import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.append('../../../../scripts/')
from fig_settings import configure_fig_settings
sys.path.append('../../modules_gammak24/')
from plotpsi import PlotPsi
import seaborn as sns

colors = sns.color_palette()

configure_fig_settings()

# see user_inputs.md for details on what typically goes in these inputs.
user_input = input("input string of k24,Lambda,omega values, "
                   "using comma as delimiter: ")

gammas = np.array([0.025,0.05,0.075,0.1,0.125,0.15,0.175],float)

k24,Lambda,omega = np.array(user_input.split(','),float)

fig,ax = plt.subplots()
width  = 3.487
height = width
fig.set_size_inches(width,height)

for i,gamma in enumerate(gammas):
    if i == 0:
        label = fr'$\gamma=\num{{{gamma:.2e}}}$'
    elif i == len(gammas)-1:
        label = fr'$\gamma=\num{{{gamma:.2e}}}$'
    else:
        label = None
    pl = PlotPsi(gamma,k24,fig,ax)
    pl.plot_psivsr(omega,Lambda,label=label,color=colors[i])

ax.set_xlabel(r'$r$')
ax.set_ylabel(r'$\psi(r)$')
ax.legend(frameon=False)
fig.tight_layout()
fig.savefig(pl.psivsr_sname(omega,Lambda))


def safe_pawns(pawns: set) -> int:
    columns = ' abcdefgh '
    rows = ' 12345678 '
    safe = 0
    for paw in pawns:
        check = 0
        col_num = columns.find(paw[0])
        row_num = rows.find(paw[1])
        for i in pawns:
                if ((i[0] == columns[col_num-1] or i[0] == columns[col_num+1])
                        and i[1] == rows[row_num-1]):
                    check+=1
        if check>=1:
            safe+=1
    return safe

if __name__ == '__main__':
    print(safe_pawns({"a1","b2","c3","d4","e5","f6","g7","h8"}))
    # These "asserts" using only for self-checking and not necessary for auto-testing
    assert safe_pawns({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}) == 6
    assert safe_pawns({"b4", "c4", "d4", "e4", "f4", "g4", "e5"}) == 1
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")


from requests_html import HTMLSession
from datetime import datetime
from multiprocessing import Pool
from bs4 import BeautifulSoup
import pandas as pd
import re
import os

LINKS_REGEX = r'(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?'
BASE_AVMF_URL = "https://d2ec906f9aea-003845.vbulletin.net"

def get_html_session(session=None):
    if session is None:
        print("new html session")
        return HTMLSession()
    else:
        return session

def handle_date():
    pass

def build_index(src, dst, nump):

    sub_urls = list(pd.read_csv(src)["subs"].values)
    session = get_html_session()
    df_list = []

    for sub_url in sub_urls:
        print(sub_url)

        # Gets the first page
        r = session.get(BASE_AVMF_URL + sub_url)

        # Find number of pages
        number_of_pages = int([v.text for v in r.html.find(".toolbar-pagenav-wrapper .pagetotal")][-1])

        for page_num in range(1, number_of_pages + 1, 1):
            print("Page {0}/{1}".format(page_num, number_of_pages))
            r = session.get(BASE_AVMF_URL + sub_url + "/page" + str(page_num))

            for thread in r.html.find(".js-topic-item"):
                topic_info = thread.find(".topic-info")[0].text.split(",")
                author_topic = "".join(topic_info[:-2])[11:]

                prefix_l = thread.find(".js-topic-item")[0].find(".js-prefix")
                prefix = None

                if len(prefix_l) > 0:
                    if prefix_l[0].text == "Sticky:":
                        prefix = "Sticky"
                    elif prefix_l[0].text == "Redirect:":
                        continue

                thread_dict = {
                    "prefix": prefix,
                    "title": thread.find(".js-topic-title")[0].text,
                    "link": re.findall(LINKS_REGEX,
                                       list(thread.find(".js-topic-title")[0].links)[0])[0][2],
                    "author_topic": author_topic,
                    "replies": int(re.sub("[ response(s)?|,]", "", thread.find(".posts-count")[0].text)),
                    "views": int(re.sub("[ view(s)?|,]", "", thread.find(".views-count")[0].text)),
                    "subforum": sub_url
                }

                df_list.append(thread_dict)

        df = pd.DataFrame(df_list)

        df.to_csv(dst, index=False)

build_index("./data/forums/avfm_subs.csv", "./data/forums/avfm/index.csv", None)


from xai.brain.wordbase.nouns._competency import _COMPETENCY

#calss header
class _COMPETENCIES(_COMPETENCY, ):
	def __init__(self,):
		_COMPETENCY.__init__(self)
		self.name = "COMPETENCIES"
		self.specie = 'nouns'
		self.basic = "competency"
		self.jsondata = {}


PRO_EDITION=True
NATIVE_LINES_OGL_LIKE=False
ASYNC_BACKGROUND_REFRESH=False  # devel purposes only
APP_VERSION = 1.76

try:
    import rego
except ModuleNotFoundError:
    # print("rego functionality not found")
    PRO_EDITION=False
    registered_to = ""
else:
    PRO_EDITION = rego.are_registered(APP_VERSION)
    registered_to = rego.get_stored_serial_info()["name"] if rego.get_stored_serial_info() else ""
    enter_license = lambda name, serial : rego.enter_license(name, serial, APP_VERSION)

if not PRO_EDITION:
    print("Running Community Edition")

# APP_ICON_PATH = "/home/andy/.pyenv/versions/3.7.1/lib/python3.7/site-packages/wx/py/Py.ico"
APP_ICON_PATH = "media/pynsource.ico"

LOG_TO_CONSOLE = False


# -*- coding: utf-8 -*-

from unittest import TestCase
from unittest.mock import Mock

from testProject.MainClass import Main

class TestMain(TestCase):
    def test_helloThere_Success(self):
        # Given
        main = Main()

        # When
        helloResult = main.hello()

        # Then
        self.assertEqual(helloResult, 3)

    def test_shouldAskServer_ToServe(self):
        # Given
        main = Main()
        main.httpd = Mock()

        # When
        main.run()

        # Then
        main.httpd.serve_forever.assert_called_with()


#!/usr/bin/env python3
"""Simulate an environment for testing of control algorithms"""

import time

import pybullet_data
import pybullet as p

from controller import control_vehicle

# Constants for the IDs of various joints
FRONT_SWERVE, FRONT_DRIVE, BACK_SWERVE, BACK_DRIVE = range(4)
# Time step length
DELTA_TIME = 1 / 240

# Create a client and connect to the GUI
client = p.connect(p.GUI)
# Enable loading of models included by default (the plane)
p.setAdditionalSearchPath(pybullet_data.getDataPath())
# Configure the basic parameters and load the plane
p.setGravity(0, 0, -9.81)
plane_id = p.loadURDF('plane.urdf')
# Load the bike and drop it into the scene
start_position = [0, 0, 0.475]
start_orientation = p.getQuaternionFromEuler([0, 0, 0])
bike_id = p.loadURDF('bike.xml', start_position, start_orientation)
# Remember the last tilt so we can calculate the derivative
last_tilt = 0
# Run the simulation for a defined number of steps
for i in range(100_000):
    # Get the current state of the bike
    bike_position, bike_orientation_quaternion = p.getBasePositionAndOrientation(bike_id)
    # Specifically, we want the X and Y positions
    x_pos, y_pos, _ = bike_position
    # Convert the orientation to Euler angles, and get the tilt angle and heading
    tilt, _, heading = p.getEulerFromQuaternion(bike_orientation_quaternion)
    # The heading is inverted
    heading *= -1
    # Get the current velocity of the bike (positional only)
    bike_position_speed, _ = p.getBaseVelocity(bike_id)
    # We want the X and Y speeds (but for some reason they are inverted)
    x_speed, y_speed, _ = bike_position_speed
    # For some reason the Y speed is inverted
    y_speed *= -1
    # Calculate the tilt speed numerically
    tilt_speed = (tilt - last_tilt) / DELTA_TIME
    # Update the previous tilt value
    last_tilt = tilt
    # Get the current angles of the swerve joints
    current_angle_front, _, _, _ = p.getJointState(bike_id, FRONT_SWERVE)
    current_angle_back, _, _, _ = p.getJointState(bike_id, BACK_SWERVE)
    # Get the desired control values according to the current states
    angle_front, angle_back, total_speed_front, total_speed_back = control_vehicle(x_speed, y_speed, heading, tilt, tilt_speed, current_angle_front, current_angle_back, -1, 1, 0.3)
    # Set the desired angles of the swerve motors
    p.setJointMotorControlArray(bodyUniqueId=bike_id, jointIndices=[FRONT_SWERVE, BACK_SWERVE], controlMode=p.POSITION_CONTROL, targetPositions=[angle_front, angle_back], forces=[20] * 2)
    # Set the desired speeds of the drive motors
    p.setJointMotorControlArray(bodyUniqueId=bike_id, jointIndices=[FRONT_DRIVE, BACK_DRIVE], controlMode=p.VELOCITY_CONTROL, targetVelocities=[total_speed_front, total_speed_back], forces=[10] * 2)
    # Step the physics simulation
    p.stepSimulation()
    # Wait a small amount of time before moving on to the next step
    time.sleep(DELTA_TIME)
# Disconnect from the server at the very end
p.disconnect()


# Parser for config.txt. This will return 'machine-readable' configurations
# to the main script from a human-readable file.

class ConfigurationError(Exception):
    """Errors raised when parsing config file"""
    def __init__(self, message):
        self.message = message

try:
    with open("/home/pi/FEMTAFYESIMBOXsoftware/simbox/config.txt", "r") as cfg:
        src = cfg.read().split("::")[2::2]
except FileNotFoundError:
    raise ConfigurationError("The configuration file was not found")

configs = dict() #To be filled and outputted

# -=-=- Parse simbox frequency -=-=-
try:
    configs["frequency"] = int(src[0].strip().split()[0])
except TypeError:
    raise ConfigurationError("'Simbox Frequency' is missing or formatted incorrectly")

# -=-=- Parse virtual environment timestep -=-=-
try:
    configs["dt"] = float(src[1].strip().split()[0])
except TypeError:
    raise ConfigurationError("'Simulation Timestep' is missing or formatted incorrectly")

# -=-=- Parse simulation sensitivity -=-=-
try:
    configs["sensitivity"] = float(src[2].strip())
except TypeError:
    raise ConfigurationError("'Simulation Sensitivity' is missing or formatted incorrectly")

# -=-=- Parse event timing -=-=-
events = ["Launch", "Start of 0g", "Apogee", "End of 0g", "Landing"]
lines = src[3].strip().split("\n")

times = list()
for i in range(5):
    line = lines[i].split(";")
    if line[0] != events[i]:
        raise ConfigurationError(f"Event name for flight event #{i + 1} has been modified")

    try:
        times.append(float(line[-1].strip()))
    except TypeError:
        raise ConfigurationError(f"Non-numeric event time for event {line[0]}")

if times[0] != 0:
    raise ConfigurationError("Launch must occur at T+0")
elif len(times) != len(events):
    raise ConfigurationError("Flight event list has been modified")

flight_duration = times[4] - times[0]
configs["event_times"] = tuple(times)

# -=-=- Parse sensor failures -=-=-
sensors = ["flow0", "flow1", "uv", "pres0", "pres1", "pres2", "pres3", "therm0",
"therm1", "therm2", "therm3", "therm4", "mass0", "mass1", "ir0", "ir1"]
states = ["normal", "min", "max", "dead"]

# First, get a list of tuples of the form (name, state, time), where name and state are numeric
failures = src[4].strip().split("\n")
if len(failures) > 1 and ";" in failures[0]:
    failures = [[i.strip() for i in line.split(";")][:3] for line in failures]
else:
    failures = list()

for i in range(len(failures)):
    if failures[i][0].lower() in sensors:
        try:
            failures[i][0] = sensors.index(failures[i][0].lower())
        except ValueError:
            raise ConfigurationError("Invalid sensor name")
    elif failures[i][0].isnumeric() and int(failures[i][0]) in range(16):
        failures[i][0] = int(failures[i][0])
    else:
        raise ConfigurationError("Invalid sensor failure configuration")

    if failures[i][1].lower() in states:
        try:
            failures[i][1] = states.index(failures[i][1].lower())
        except ValueError:
            raise ConfigurationError("Invalid sensor failure state")
    elif failures[i][1].isnumeric() and int(failures[i][1]) in range(4):
        failures[i][1] = int(failures[i][1])
    else:
        raise ConfigurationError("Invalid sensor failure configuration")

    if failures[i][1] == 3 and failures[i][0] > 2:
        raise ConfigurationError(f"Only digital sensors can fail to state Dead (line {i + 1})")

    try:
        failures[i][2] = float(failures[i][2])
    except ValueError:
        raise ConfigurationError(f"Invalid time for sensor failure #{i + 1}")

    if failures[i][2] < 0:
        raise ConfigurationError(f"Invalid time for sensor failure #{i + 1} (before liftoff)")
    if failures[i][2] > flight_duration:
        raise ConfigurationError(f"Invalid time for sensor failure #{i + 1} (after landing)")

failures.sort(key=lambda x: x[2])

# Next, convert digital sensor 'dead' failures to error states
dead_failures = [failure for failure in failures if (failure[0] < 3) and (failure[1] in (0, 3))]
dig_error_states = [[0, flight_duration, 0]] #-> start_t, end_t, event state
for fail in dead_failures:
    sensor = 2 ** fail[0]
    state = bool(fail[1]) # i.e 1 if Dead, 0 if Normal
    time = fail[2]

    indx = -1
    for i in range(len(dig_error_states)):
        if (dig_error_states[i][0] < time) and (dig_error_states[i][1] == flight_duration or dig_error_states[i+1][0] > time):
            # insert a new tuple starting at transition time and taking the previous tuple's end time
            dig_error_states.insert(i + 1, [time, dig_error_states[i][1], dig_error_states[i][2]])
            # set previous tuple's end time to transition time
            dig_error_states[i][1] = time
            indx = i
            break
        elif dig_error_states[i + 1][0] == time:
            # no need for a new tuple
            indx = i
            break

    # bitwise xor with new state for each tuple, starting from the new one,
    # but only if there is a toggle to be done
    if (dig_error_states[indx][2] & sensor) != state:
        for i in range(indx + 1, len(dig_error_states)):
            dig_error_states[i][2] ^= sensor

configs["dig_error_states"] = dig_error_states

# Next, parse normal/min/max for all sensors
# outputted: list of (start_t, end_t, <state>) like above but <state> is a
# 16-list with each spot corresponding to a sensor and equal to either
# 0, 1, or 2 (being Normal, Min, and Max)

all_failures = [f for f in failures if f[1] != 3]
all_error_states = [[0, flight_duration, [0]*16]] #-> start_t, end_t, state

for fail in all_failures:
    sensor = fail[0]
    state = fail[1]
    time = fail[2]

    indx = -1
    for i in range(len(all_error_states)):
        if (all_error_states[i][0] < time) and (all_error_states[i][1] == flight_duration or all_error_states[i+1][0] > time):
            # insert a new tuple starting at transition time and taking the previous tuple's end time
            all_error_states.insert(i + 1, [time, all_error_states[i][1], all_error_states[i][2].copy()])
            # set previous tuple's end time to transition time
            all_error_states[i][1] = time
            indx = i
            break
        elif all_error_states[i + 1][0] == time:
            # no need for a new tuple
            indx = i
            break

    # update all following tuples with new state info
    for i in range(indx + 1, len(all_error_states)):
        all_error_states[i][2][sensor] = state

configs["all_error_states"] = all_error_states

if __name__ == "__main__":
    print(configs)


"""yuanquan URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from . import home
import user, article, comment
from django.conf import settings
from django.conf.urls.static import static
import notifications.urls

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home.home, name='home'),
    path('article/', include('article.urls')),
    path('user/', include('user.urls')),
    path('like/', include('comment.urls')),
    path('login/', user.views.login, name='login'),
    path('logout/', user.views.logout, name='logout'),
    path('register/', user.views.register, name='register'),
    path('error404/', home.error404, name='error404'),
    path('search/', home.search, name='search'),
    path('test/', home.test, name='test'),
    path('classify/<int:classify_id>', article.views.article_type, name='classify_type'),
    path('add_comment/<int:article_id>', comment.views.add_comment, name='add_comment'),
    path('info/', home.info, name='info'),
    path('record/', home.record, name='record'),
    path('load_file/', home.load_file, name='load_file'),
    path('notifications/', include(notifications.urls, namespace='notifications')),
    path('delete_all_notification', home.delete_all_notification, name='delete_all_notification'),
    path('delete_notification', home.delete_notification, name='delete_notification'),
    path('mdeditor/', include('mdeditor.urls')),

] + static('/pic', document_root=settings.MEDIA_ROOT)


from __future__ import print_function, absolute_import, division
from . import get_doxygen_root

def flatten(xmlnode):
    # <xmlnode>this.text<child0>child0.text</child0>child0.tail...</xmlnode>

    t = ''

    # text of this node
    if xmlnode.text is not None:
        t += xmlnode.text

    # process all children recursively
    for n in xmlnode:
        t += ' '
        t += flatten(n)
        if n.tail is not None:
            t += ' '
            t += n.tail

    return t

def format_xml_paragraph(xmlnode):
    """Format an Doxygen XML segment (principally a detaileddescription)
    as a paragraph for inclusion in the rst document

    Parameters
    ----------
    xmlnode

    Returns
    -------
    lines
        A list of lines.
    """
    return [l.rstrip() for l in _DoxygenXmlParagraphFormatter().generic_visit(xmlnode).lines]

class _DoxygenXmlParagraphFormatter(object):
    # This class follows the model of the stdlib's ast.NodeVisitor for tree traversal
    # where you dispatch on the element type to a different method for each node
    # during the traverse.

    # It's supposed to handle paragraphs, references, preformatted text (code blocks), and lists.

    def __init__(self):
        self.lines = ['']
        self.continue_line = False

    def visit(self, node):
        method = 'visit_' + node.tag
        visitor = getattr(self, method, self.generic_visit)
        return visitor(node)

    def generic_visit(self, node):
        for child in node.getchildren():
            self.visit(child)
        return self

    def visit_ref(self, node):
        # find target node
        refid = node.get('refid')
        kind = None

        if node.get('kindref') == 'member':
            ref = get_doxygen_root().find('./compounddef/sectiondef/memberdef[@id="%s"]' % refid)
            # only set the kind if we find a function, otherwise it might be
            # a documentation reference
            if ref is not None:
                kind = 'func'
        elif node.get('kindref') == 'compound':
            ref = get_doxygen_root().find('./compounddef[@id="%s"]' % refid)
            if ref is not None:
                if ref.get('kind') == 'namespace':
                    kind = 'mod'
                elif ref.get('kind') == 'type':
                    kind = 'type'
        else:
            # we probably don't get here
            print('warning: slow ref search!')
            ref = get_doxygen_root().find('.//*[@id="%s"]' % refid)

        # get name of target
        if ref is not None:
            name_node = None

            if kind == 'func':
                name_node = ref.find('./name')
            elif kind == 'mod' or kind == 'type':
                name_node = ref.find('./compoundname')

            if name_node is not None:
                real_name = name_node.text.split('::')[-1]
            else:
                self.lines[-1] += '(unimplemented link)' + node.text
                return
        else:
            # couldn't find link
            real_name = None

        if kind is None:
            # section link, we hope!
            val = ['`']
        else:
            val = [':f:%s:`' % kind]

        val.append(node.text)
        if real_name is not None:
            val.extend((' <', real_name, '>`'))
        else:
            val.append('`')

        if kind is None:
            # convert into a proper link
            val.append('_')

        self.lines[-1] += ''.join(val)

    def visit_ulink(self, node):
        self.para_text('`%s <%s>`_' % (node.text, node.get('url')))

    def visit_emphasis(self, node):
        self.para_text('*%s*' % node.text)

    def role_text(self, node, role):
        # XXX we should probably escape preceeding whitespace...
        # but there's no backward equivalent of `tail`
        text = ' :%s:`%s`' % (role, node.text)

        if node.tail is not None and not node.tail.startswith(' '):
            # escape following whitespace
            text += '\\'

        text += ' ' # interpretered text needs surrounding whitespace
        self.para_text(text)

    def visit_image(self, node):
        if len(node.text.strip()):
            type = 'figure'
        else:
            type = 'image'

        self.lines.append('.. %s:: /images/%s' % (type, node.get('name')))

        if type == 'figure':
            self.lines.extend(['', node.text])

    def visit_superscript(self, node):
        self.role_text(node, 'superscript')

    def visit_subscript(self, node):
        self.role_text(node, 'subscript')

    def para_text(self, text):
        if text is not None:
            if self.continue_line:
                self.lines[-1] += text
            else:
                self.lines.append(text.lstrip())

    def visit_para(self, node):
        self.para_text(node.text)

        # visit children and append tail
        for child in node.getchildren():
            self.visit(child)
            self.para_text(child.tail)
            self.continue_line = True

        self.lines.append('')
        self.continue_line = False

    def visit_formula(self, node):
        text = node.text.strip()

        # detect inline or block math
        if text.startswith('\\[') or not text.startswith('$'):
            if text.startswith('\\['):
                text = text[2:-2]

            self.lines.append('')
            self.lines.append('.. math:: ' + text)
            self.lines.append('')
            self.continue_line = False
        else:
            inline = ':math:`' + node.text.strip()[1:-1].strip() + '`'
            if self.continue_line:
                self.lines[-1] += inline
            else:
                self.lines.append(inline)

            self.continue_line = True

    def visit_parametername(self, node):
        if 'direction' in node.attrib:
            direction = '[%s] ' % node.get('direction')
        else:
            direction = ''

        #self.lines.append('**%s** -- %s' % (
            #node.text, direction))
        self.lines.append(':param %s: %s' % (node.text, direction))
        self.continue_line = True

    def visit_parameterlist(self, node):
        lines = [l for l in type(self)().generic_visit(node).lines if l is not '']
        self.lines.extend([''] + lines + [''])

    def visit_simplesect(self, node):
        if node.get('kind') == 'return':
            self.lines.append(':returns: ')
            self.continue_line = True
        self.generic_visit(node)

    def visit_sect(self, node, char):
        """Generic visit section"""
        title_node = node.find('title')
        if title_node is not None:
            title = title_node.text
            self.lines.append(title)
            self.lines.append(len(title) * char)
            self.lines.append('')

        self.generic_visit(node)

    def visit_sect1(self, node):
        self.visit_sect(node, '=')

    def visit_sect2(self, node):
        self.visit_sect(node, '-')

    def visit_sect3(self, node):
        self.visit_sect(node, '^')

    def visit_sect4(self, node):
        self.visit_sect(node, '"')

    def visit_listitem(self, node):
        char = '*' if node.getparent().tag == 'itemizedlist' else '#'
        self.lines.append('')
        self.lines.append(char + ' ')
        self.continue_line = True
        self.generic_visit(node)

    def preformat_text(self, lines):
        self.lines.extend(('::', ''))
        self.lines.extend(['  ' + l for l in lines])
        self.lines.append('')

    def visit_preformatted(self, node):
        segment = [node.text if node.text is not None else '']
        for n in node.getchildren():
            segment.append(n.text)
            if n.tail is not None:
                segment.append(n.tail)

        lines = ''.join(segment).split('\n')
        self.preformat_text(lines)

    def visit_programlisting(self, node):
        lines = []
        for n in node.getchildren():
            lines.append(flatten(n))
        self.preformat_text(lines)

    def visit_verbatim(self, node):
        self.visit_preformatted(node)

    def visit_computeroutput(self, node):
        c = node.find('preformatted')
        if c is not None:
            return self.visit_preformatted(c)

        # I don't think we can put links inside
        # computeroutput text...
        self.lines[-1] += '``' + flatten(node) + '``'

    def visit_xrefsect(self, node):
        title = node.find('xreftitle').text
        sublines = type(self)().generic_visit(node).lines
        self.lines.extend(['.. admonition:: %s' % title] + ['   ' + s for s in sublines])

    def visit_subscript(self, node):
        self.lines[-1] += '\ :sub:`%s` %s' % (node.text, node.tail)

    def visit_table(self, node):
        # save the number of columns
        cols = int(node.get('cols'))
        table = []
        # save the current output
        lines = self.lines

        # get width of each column
        widths = [0] * cols

        # build up the table contents
        for row_node in node.findall('row'):
            row = []
            for i, entry in enumerate(row_node.getchildren()):
                self.lines = ['']
                self.generic_visit(entry)
                row.append(self.lines)

                # find width of this entry (including leading and trailing space)
                widths[i] = max(widths[i], max([len(line) for line in self.lines]) + 2)

            table.append(row)

        def append_row(row):
            # find number of lines in row
            num_lines = max([len(e) for e in row])
            lines = []

            for k in range(num_lines):
                line = '|'
                for i, e in enumerate(row):
                    if k < len(e):
                        # this is a valid line
                        line += ' ' + e[k]
                        # pad rest of line
                        line += ' ' * (widths[i] - len(e[k]) - 1)
                    else:
                        # invalid line, just fill with spaces
                        line += ' ' * widths[i]

                    line += '|'

                lines.append(line)

            return lines

        self.lines = lines
        # start with a blank
        self.lines.append('')

        # usual separator line
        sep = '+'
        for width in widths:
            sep += '-' * width
            sep += '+'

        self.lines.append(sep)

        # header row
        self.lines.extend(append_row(table[0]))
        # header separator uses '=' instead of '-'
        self.lines.append(sep.replace('-', '='))

        # loop over body rows
        for row in table[1:]:
            self.lines.extend(append_row(row))
            self.lines.append(sep)

        # end with a blank
        self.lines.append('')


import re
from eunjeon import Mecab
from wordcloud import WordCloud
from collections import Counter
import matplotlib.pyplot as plt

def read_txt(fname):
    f = open(f'./{fname}', 'r', encoding='UTF8')
    lines = f.readlines()
    f.close()

    p = re.compile(r'(\d+[:]\d+)')
    time = 0
    talk_dic = {}
    for line in lines:
        m = p.search(line)
        if line.startswith('---------------'):
            time = line[16:line.find('---------------', 1)]
        elif m is not None and line.find('[') == 0:
            talker = line[1:line.find(']')]
            talk = line[m.end() + 1:].strip()
            hour = line[line.find('[', line.find('[')+1)+1 : line.find(']', line.find(']')+1)]
            if talker not in talk_dic:
                talk_dic[talker] = [(time+hour, talk)]
            else:
                talk_dic[talker].append((time+hour, talk))
    return talk_dic

def message_cleaning(docs):
    '''
    1. Photo, Emoticon은 내용 알 수 없으므로 제거
    2. 자음/모음 표현 처리
    3. http://로 시작하는 하이퍼링크 제거
    4. 특수문자 제거
    '''

    pattern1 = re.compile("이모티콘")
    docs = pattern1.sub("", docs)

    pattern2 = re.compile("[ㄱ-ㅎ]*|[ㅏ-ㅢ]*")
    docs = pattern2.sub("", docs)

    pattern3 = re.compile(r"\b(https?:\/\/)?([\w.]+){1,2}(\.[\w]{2,4}){1,2}(.*)")
    docs = pattern3.sub("", docs)

    pattern4 = re.compile("[\{\}\[\]\/?.,;:|\)*-`!^\-_+<>@\#$&\\\=\(\'\"]")
    docs = pattern4.sub("", docs)

    return docs

def define_stopwords(path):
    SW = set()
    # 불용어 추가 방법 Sw.add("있다") or stopwords-ko.txt에 직접 추가
    with open(path, encoding='utf-8') as f:
        for word in f:
            SW.add(word)
    words = ['이랑', '웅웅', '아서', '시반']
    for word in words:
        SW.add(word)
    return SW

def tokenize(filename):
    talk_dic = read_txt(filename)
    SW = define_stopwords("./stopwords-ko.txt")
    mecab= Mecab()
    total = {}
    for k, v in talk_dic.items():
        total_sub = []
        for idx, talk_set in enumerate(v):
            time, talk = talk_set
            clean_talk = message_cleaning(talk)
            tokenized_talk = [word for word in mecab.morphs(clean_talk) if word not in SW and len(word) > 1]
            talk_dic[k][idx] = (time, talk, tokenized_talk)
            total_sub.extend(tokenized_talk)
        total[k] = total_sub
    return talk_dic, total

def get_wordcloud(filename):
    talk_dic, total = tokenize(filename)
    word_counts = []
    for k, v in total.items():
        count = Counter(v)
        wc = count.most_common(100)
        wordcloud = WordCloud(font_path = './static/malgun.ttf',
                        relative_scaling=0.2,
                        background_color = 'white',
                        ).generate_from_frequencies(dict(wc))
        wc = [(idx, w) for idx, w in enumerate(wc)]
        word_counts.append(wc)
        fig = plt.figure(figsize=(16,8))
        plt.imshow(wordcloud)
        plt.axis("off")
        plt.show()
        fig.savefig(f'./static/wordcloud_{k}.png')
    return talk_dic, word_counts

#talk_dic, total = tokenize('kakao.txt')
#print(total['조성빈'][:3])


#!/usr/bin/env python
# -*- coding: utf-8 -*-
from Humano import *

## Funciones

## Función principal
def main():
    angel = Humano()
    angel.setEdad(21)
    angel.setNombre("Angel")
    angel.setEstadoCerebro("Buen estado")

    print("El nombre del individuo es: " + angel.getNombre())
    print("La edad del individuo es: " + str(angel.getEdad()))
    print("El cerebro de " + angel.getNombre() + " esta en " + angel.getEstadoCerebro())

if __name__ == '__main__':
    main()


# coding: utf-8
import os
import shutil
import sqlite3
import pathlib
from jinjaql.cache import test as test_cache
from jinjaql.factory import JinJAQL
from jinjaql.engine import sqlite_test

try:
    import unittest2 as unittest
except ImportError:
    import unittest

class TestIntegration(unittest.TestCase):

    def setUp(self):
        self.sql_root = os.path.abspath(os.path.dirname(__file__))
        self.jinjaql_engine = JinJAQL(pathlib.Path(self.sql_root, 'queries'), engine=sqlite_test)
        self.jinjaql_engine_cache = JinJAQL(pathlib.Path(self.sql_root, 'queries'), engine=sqlite_test, cache=test_cache)
        self.sqlite_folder = os.path.join(self.sql_root, 'data')
        self.sqlite_path = os.path.join(self.sqlite_folder, 'test_db.sqlite')
        if not os.path.exists(self.sqlite_folder):
            os.makedirs(self.sqlite_folder)
        if not os.path.exists(self.sqlite_path):
            open(self.sqlite_path, 'a').close()

    def tearDown(self):
        shutil.rmtree(self.sqlite_folder)

    def test_engine(self):
        queries = self.jinjaql_engine.load_queries('integration.sql')
        try:
            queries.create_artists()
        except:
            pass
        query = queries.insert_artist(**{
            'id': 1,
            'name': 'Lana Del Rey',
            'age': 30,
            'instrument': 'voice',
            'creation_date': '2015-10-13',
        })
        result = queries.get_artists(id=1)

        self.assertEqual(result, [('Lana Del Rey', 30, 'voice')])

    def test_engine_cache(self):
        queries = self.jinjaql_engine_cache.load_queries('integration.sql')
        try:
            queries.create_artists()
        except:
            pass
        query = queries.insert_artist(**{
            'id': 1,
            'name': 'Lana Del Rey',
            'age': 30,
            'instrument': 'voice',
            'creation_date': '2015-10-13',
        })
        result = queries.get_artists(id=1)

        self.assertEqual(result, [('Lana Del Rey', 30, 'voice'), ('Lana Del Rey', 32, 'voice')])


from django.conf.urls import url
from . import views
from django.views.generic.base import TemplateView

app_name = 'blogg'

urlpatterns = [
	url(r'^signup$', views.signup, name='signup'),
	url(r'^profile/$', views.profile, name='profile'),
	url(r'^$', views.post_list, name = 'post_list'),
	url(r'^post/(?P<pk>\d+)/$', views.post_detail, name = 'post_detail'),
	url(r'^post/new/$', views.post_new, name = 'post_new'),
	url(r'^post/(?P<pk>\d+)/edit/$', views.post_edit, name='post_edit'),
	url(r'^post/(?P<pk>\d+)/delete/$', views.post_delete, name='post_delete'),
]


#!/usr/bin/env python
"""A smoke test for containers"""

import json
import logging
import os
import pytest
import requests
import time

from kubetest_stdlib import testutils
from requests.packages.urllib3.exceptions import InsecureRequestWarning

# Supress warnings
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

logger = logging.getLogger(__name__)

class TestSmoke():
    """ Use pytest to execute rest api operations against a container. """

    @classmethod
    def setup_class(cls):
        """
        Setup environment for the upcoming tests. This is basically the constructor for
        this test class. Its used to create the KubeUtils API instance used by some
        tests, retrieve environment variables from the testconfig.yaml and set up any
        structures and variables that might be used by All of the test methods below.

        """
        # Initial setup
        test_target = "configuratn"
        test_vars = testutils.k8s_test_setup(test_target)
        # Expose variables to test functions
        cls.TARGET_BASE_NAME = test_target
        cls.TARGET_POD_NAME = test_vars.get("target_pod_name")
        cls.NAMESPACE = test_vars.get("namespace")
        cls.kubeutilobj = test_vars.get("kubeutilobj")

    def test_01_pod_user_not_root(self):
        """
        Check user not root
        """
        time.sleep(1)
        cmd = "exec {} whoami".format(self.TARGET_POD_NAME)
        status,result = self.kubeutilobj.kubectl(cmd, self.NAMESPACE)
        error_flag = False
        if "failure" in status.lower() or b"root" in result["output"]:
            error_flag = True
        assert error_flag == False

    def test_02_hostname(self):
        """
        Check consul in hostname
        """
        cmd = "exec {} hostname".format(self.TARGET_POD_NAME)
        status, result = self.kubeutilobj.kubectl(cmd, self.NAMESPACE)
        assert self.TARGET_BASE_NAME in result["output"].decode("utf-8")

    def test_03_agent_self_no_tls(self):
        '''
        Ensure agent member name contains pod name
        http://consul.kubeworker1.sas.com/v1/agent/self

        '''
        url = "http://localhost:8500/v1/agent/self"
        cmd = 'exec {} -- curl -s -o /dev/null -w '.format(self.TARGET_POD_NAME) + \
               str('"%{http_code}"') + ' {}'.format(url)
        status, result = self.kubeutilobj.kubectl(cmd, self.NAMESPACE)
        print(result)
        assert b"200" in result["output"]

    def test_04_agent_member_no_tls(self):
        '''
        http://consul.kubeworker1.sas.com/v1/agent/peers
        '''
        url = "http://localhost:8500/v1/agent/members"
        cmd = 'exec {} -- curl -s -o /dev/null -w '.format(self.TARGET_POD_NAME) + \
               str('"%{http_code}"') + ' {}'.format(url)
        status, result = self.kubeutilobj.kubectl(cmd, self.NAMESPACE)
        print(result)
        assert b"200" in result["output"]


import gamera.core as gc
import matplotlib.pyplot as plt
import itertools

import numpy as np

from gamera.plugins.image_utilities import union_images

class textUnit(object):

    gap_ignore = 10
    line_step = 4

    letters_path = './letters/'
    letter_list = (
        'cae cre est rex sti tet tri'.split() +
        'ae am an be bo ca ch ci co cu de do ec em en es et fa fe fi fo gr pe po om on ra sa se si sp sr ss st su sy ta te ti tu us um un vo xs'.split() +
        'a b c d e f g h i j l m n o p q r s t u v x y ae_2 r_2 e_2 d_2 v_2 m_2 b_2 ._1'.split()
        )

    prototypes = {}

    # necessary to use a helper function to load images into a dictionary comprehension because
    # python does strange things to scope in the expression part of a comprehension (????????)
    def _dict_helper(A, B):
        return {x: gc.load_image(A + x + '.png').to_onebit() for x in B}

    chunk_images = _dict_helper(letters_path, letter_list)

    def __init__(self, image=None, text=None, is_wildcard=None):

        if not (bool(text) ^ bool(image)):
            raise ValueError('Supply an image or text, but not both')

        self.is_wildcard = is_wildcard

        if text:
            self.is_synthetic = True
            self.text = text
            self.image = textUnit.chunk_images[text].trim_image()

        if image:
            self.is_synthetic = False
            self.image = image
            self.text = None

        self.box_index = None
        self._extract_features()

        self.ul = gc.Point(self.image.offset_x, self.image.offset_y)
        self.lr = gc.Point(
            self.image.offset_x + self.image.ncols,
            self.image.offset_y + self.image.nrows
            )

        self.nrows = self.image.nrows
        self.ncols = self.image.ncols
        self.offset_x = self.image.offset_x
        self.offset_y = self.image.offset_y

    def _index_in_seq(self, subseq, seq):
        i, n, m = -1, len(seq), len(subseq)
        try:
            while True:
                i = seq.index(subseq[0], i + 1, n - m + 1)
                if subseq == seq[i:i + m]:
                    return i
        except ValueError:
            return -1

    def _runs_line(self, ind, vertical=False, gap_ignore=gap_ignore, line_step=line_step):

        if vertical:
            cross_line = [self.image[ind, x] for x in range(self.image.nrows)]
        else:
            cross_line = [self.image[x, ind] for x in range(self.image.ncols)]

        switch_points = [i for i, x in enumerate(cross_line) if cross_line[i-1] != x]

        for i in reversed(range(len(switch_points)-2)):

            gap_size = switch_points[i+1] - switch_points[i]
            if gap_size >= gap_ignore:
                continue
            del switch_points[i+1]

        return len(switch_points)

    def _extract_features(self):
        res = {}

        # res['volume'] = self.image.volume()[0]
        res['black_area'] = self.image.black_area()[0]
        res['aspect_ratio'] = self.image.aspect_ratio()[0]
        # res['diagonal_projection'] = self.image.diagonal_projection()[0]

        # skeleton_feats = self.image.skeleton_features()
        # for i, f in enumerate(skeleton_feats):
        #     res['skeleton_' + str(i)] = f

        # before taking region volume features, pad image out to a square
        temp_img = self.image.image_copy()
        if temp_img.nrows > temp_img.ncols:
            temp_img.pad_image(0, temp_img.nrows - temp_img.ncols, 0, 0)
        elif temp_img.nrows < temp_img.ncols:
            temp_img.pad_image(0, 0, temp_img.ncols - temp_img.nrows, 0)

        volume_feats = temp_img.volume64regions()
        for i, f in enumerate(volume_feats):
            res['volume_region_' + str(i)] = f

        # moments_feats = self.image.moments()
        # for i, f in enumerate(moments_feats):
        #     res['moments_' + str(i)] = f

        self.features = res

def knn_search(train_set, test_syl, k=5):
    '''
    given a list of textUnits as a train set and a single textUnit to search for, returns the
    nearest textUnit to the test textUnit in the feature space.
    '''

    feature_keys = train_set[0].features.keys()
    closest = [(None, np.inf)]
    max_val = np.inf

    for train_syl in train_set:
        dist = 0

        for fk in feature_keys:
            df = test_syl.features[fk] - train_syl.features[fk]
            dist += df * df

            # break out early if possible
            if dist > max_val:
                break

        if dist > max_val:
            continue

        # if we didn't break out early, this is a candidate for entry
        # key with max value
        if len(closest) >= k:
            max_key = max(closest, key=lambda x: x[1])
            closest.remove(max_key)

        closest.append((train_syl, dist))
        max_val = max(closest, key=lambda x: x[1])[1]

    closest.sort(key=lambda x: x[1])
    return closest

def get_prototypes():
    res = {}

    for l in textUnit.letter_list:
        res[l] = textUnit(text=l)

    res['*'] = textUnit(is_wildcard=True, text='a')

    return res

def compare_units(a, b):
    feature_keys = a.features.keys()

    if a.is_wildcard or b.is_wildcard:
        return 0

    sum = 0

    for fk in feature_keys:
        sum += (a.features[fk] - b.features[fk]) * (a.features[fk] - b.features[fk])

    return sum

class unitSequence(object):
    def __init__(self, seq=None, skip_edges=None, used_edges=None,
            char_index=None, cost_arr=None, predicted_string=None):
        self.cost_arr = cost_arr if cost_arr else []
        self.seq = seq if seq else []
        self.skip_edges = skip_edges if skip_edges else []
        self.used_edges = used_edges if used_edges else []
        self.char_index = char_index if char_index else 0
        self.predicted_string = predicted_string if predicted_string else []

    def head(self):
        return self.seq[-1]

    def cost(self, moving_avg=False):
        if not moving_avg:
            return np.mean(self.cost_arr)

        res = []
        for i in range(len(self.cost_arr)):
            res.append(np.mean(self.cost_arr[0:i]))

        return res

    def equivalent(self):
        return [self.char_index, self.seq[-1][0], self.seq[-1][1]]

    def __repr__(self):
        return 'cost: {3}, index: {0.char_index}, len: {1}, ' \
            'base:{2}'.format(self, len(self.used_edges), self.seq[0], self.cost())

if __name__ == "__main__":
    gc.init_gamera()
    asdf = get_prototypes()


from tkinter import Canvas,Label,Tk
import threading
import random
import time

class map_generator():
    '''This class provides level creation.
    '''
    def __init__(self):
        '''Info about level`s obstacles and their coords
        '''
        self.map_size = 16
        self.map0 = [[1,4],[1,9],
             [2,1],[2,2],[2,4],[2,5],[2,6],[2,9],[2,12],[2,13],[2,14],
             [3,9],[3,12],
             [4,4],[4,5],[4,12],
             [5,2],[5,4],[5,7],[5,8],[5,9],
             [6,1],[6,2],[6,7],[6,12],[6,13],[6,14],
             [7,5],[7,6],[7,7],[7,8],[7,9],[7,10],[7,13],
             [8,7],
             [9,7],[9,11],
             [10,4],[10,7],[10,9],[10,10],[10,11],[10,12],[10,13],[10,14],
             [11,1],[11,2],[11,3],[11,4],[11,9],[11,13],
             [13,2],[13,3],[13,4],[13,5],[13,6],[13,7],[13,9],[13,11],[13,12],[13,13],
             [14,6],[14,9],[14,13]
             ]

    def make_canvas(self):
        '''creating level`s canvas
        '''
        can = []
        for y in range(self.map_size):
            for x in range(self.map_size):
                mc = move_cell()
                mc.position_y = y
                mc.position_x = x
                can.append(mc)
        return can

    def make_border(self):
        '''returns arr of perimeter with obstacles
        '''
        mb = []
        for _ in range(self.map_size):
            w = wall()
            w.position_x = 0
            w.position_y = _
            mb.append(w)
        for _ in range(self.map_size + 1):
            w = wall()
            w.position_x = self.map_size
            w.position_y = _
            mb.append(w)
        for _ in range(self.map_size):
            w = wall()
            w.position_x = _
            w.position_y = 0
            mb.append(w)
        for _ in range(self.map_size):
            w = wall()
            w.position_x = _
            w.position_y = self.map_size
            mb.append(w)
        for _ in range(self.map_size):
            w = wall()
            w.position_x = 0
            w.position_y = _
            mb.append(w)
        return mb

    def make_inside(self, inside_poligon):
        '''returns arr with inside parts of level
        inside_poligon - arr with obstacles coords
        '''
        arr = []
        for _ in inside_poligon:
            w = wall()
            w.position_y = _[0]
            w.position_x = _[1]
            arr.append(w)
        return arr

    def make_decorations(self):
        '''returns arr with special elements of level
        like target
        '''
        t = target()
        arr = []
        arr.append(t)
        return arr

    def generate_map1(self):
        '''returns summary map arr for map1:
        map1 - map with obstacles inside level
        '''
        full_map = self.make_canvas() + self.make_border() + self.make_inside(self.map0) + self.make_decorations()
        return full_map

    def generate_map0(self):
        '''returns summary map arr for map0:
        map0 - map with obstacles only on the level` perimeter
        '''
        full_map = self.make_canvas() + self.make_border() + self.make_decorations()
        return full_map

class move_cell():
    '''class for moving cell creation
    '''
    def __init__(self, target_position_y = 0, target_position_x = 0, marker = 0):
        '''position of cell in coords x and y
        marker is using for noneGUI or debugging
        '''
        self.position_x = target_position_x
        self.position_y = target_position_y
        self.marker = marker

class target():
    '''class for target creation
    '''
    def __init__(self, target_position_y = 1, target_position_x = 14, marker = 3):
        '''position of target point in coords x and y
        marker is using for noneGUI or debugging
        '''
        self.position_x = target_position_x
        self.position_y = target_position_y
        self.marker = marker

class wall():
    '''class for wall(obstacle) creation
    '''
    def __init__(self, marker = 5, wall_position_x = 0, wall_position_y = 0):
        '''position of wall point in coords x and y
        marker is using for noneGUI or debugging
        '''
        self.marker = marker
        self.position_x = wall_position_x
        self.position_y = wall_position_y

class Q_agent():
    '''class for Q agent creation
    '''
    def __init__(self, marker = 1, agent_position_y = 14, agent_position_x = 1, trip_marker = 8):
        '''position of wall point in coords x and y
        marker is using for noneGUI or debugging
        trip_marker is using for tracering the way
        that agent went
        '''
        #reward dict provides get reward for every state
        self.reward0 = {
            (11, 16): -1, (16, 6): -1, (16, 16): -1, (1, 16): -1,
            (16, 9): -1, (0, 14): -1, (4, 16): -1, (8, 0): -1,
            (16, 2): -1, (0, 7): -1, (0, 16): -1, (7, 16): -1,
            (0, 10): -1, (12, 16): -1, (16, 14): -1, (0, 3): -1,
            (16, 7): -1, (4, 0): -1, (9, 0): -1, (16, 10): -1,
            (0, 15): -1, (0, 6): -1, (16, 3): -1, (15, 0): -1,
            (14, 1): 100, (13, 16): -1, (3, 0): -1, (0, 11): -1,
            (5, 0): -1, (0, 4): -1, (3, 16): -1, (10, 0): -1,
            (8, 16): -1, (2, 16): -1, (16, 11): -1, (0, 0): -1,
            (16, 15): -1, (16, 4): -1, (6, 0): -1, (0, 12): -1,
            (11, 0): -1, (9, 16): -1, (16, 0): -1, (0, 5): -1,
            (16, 5): -1, (1, 0): -1, (0, 8): -1, (16, 12): -1,
            (0, 1): -1, (7, 0): -1, (14, 16): -1, (5, 16): -1,
            (12, 0): -1, (10, 16): -1, (16, 8): -1, (0, 13): -1,
            (6, 16): -1, (16, 1): -1, (2, 0): -1, (0, 9): -1,
            (15, 16): -1, (16, 13): -1, (0, 2): -1, (13, 0): -1,
             (14, 0): -1
             }
        self.reward1 = {}
        m = map_generator()

        for obj in m.generate_map1():
            if obj.marker == 5:
                x = obj.position_x
                y = obj.position_y
                self.reward1[(x,y)] =- 506
            if obj.marker == 3:
                x = obj.position_x
                y = obj.position_y
                self.reward1[(x,y)] = 300
        self.marker = marker
        self.position_x = agent_position_x
        self.position_y = agent_position_y
        self.trip_marker = trip_marker
        #reward
        self.r = 0
        self.size = 15
        #how much powerful agent`s fate into a new info
        self.gamma = 0.9
        #possible actions
        self.actions = (1, 2, 3, 4)
        #coords
        self.coordinates = []
        #state
        self.s = None
        self.s_ = None
        #start action
        self.a = 1
        self.a_ = None
        self.choice = ''
        self.Q = {}
        #for epsilon greedy algorithm
        self.epsilon = 1
        self.epsilon_min = 0.1
        self.epsilon_decay = 0.995
        self.eps_bool = False
        #learning rate alfa - less digit and agent will think less about future step`s advantages
        self.alfa = 0.95
    def get_reward(self):
        '''generate reward from state
        '''
        reward =- 10
        coord = (self.position_x, self.position_y)
        if coord in self.reward1:
            reward = self.reward1[coord]
        return reward

    def Q_init(self):
        '''generate Q dict randomly
        '''
        for y in range(0, self.size + 1 + 1):
            for x in range(0, self.size + 1 + 1):
                self.coordinates.append((y,x))
        for _ in self.coordinates:
            for a in self.actions:
                self.Q[_, a] = random.random()

    # methods for move
    def move_right(self):
        self.position_x += 1

    def move_left(self):
        self.position_x -= 1

    def move_up(self):
        self.position_y -= 1

    def move_down(self):
        self.position_y += 1
    #methods for taking position
    def get_pos_x(self):
        return self.position_x

    def get_pos_y(self):
        return self.position_y

    def make_move(self):
        '''generates move depending on
        current action
        '''
        if self.a == 1:
            self.move_up()
        if self.a == 2:
            self.move_right()
        if self.a == 3:
            self.move_down()
        if self.a == 4:
            self.move_left()

    def look_around(self):
        '''for taking current state
        '''
        return (self.position_y, self.position_x)

    def epsilon_greedy_algoritm(self):
        '''for generating randomly move
        with epsilon rate
        '''
        self.eps_bool = False
        if random.random() <= self.epsilon:
            self.a = random.randint(1, 4)
            self.make_move()
            self.s = self.look_around()
            self.eps_bool = True
        if self.epsilon > self.epsilon_min:
            self.epsilon *= self.epsilon_decay

    def init(self):
        '''init Q and current state
        '''
        self.Q_init()
        self.s = self.look_around()

    def run(self):
        '''main method for Q algorithm
        1). getting state S
        2). chose (a)ction from Q by (s)tate
        3). getting r(eward) after (a)ction realisation
        4). getting new current (s_)tate
        5). updating Q
        6). set s = s_
        7). repeat from 2).
        '''
        buff = []
        for keys in self.Q.keys():
            if keys[0] == self.s:
                buff.append((keys[1], self.Q[keys]))
        subbuff = []
        for i in buff:
            subbuff.append(i[1])
        index = subbuff.index(max(subbuff))
        self.a = buff[index][0]
        self.make_move()
        self.r = self.get_reward()
        self.s_ = self.look_around()
        key = (self.s,self.a)

        buff = []
        for keys in self.Q.keys():
            if keys[0] == self.s_:
                buff.append((keys[1], self.Q[keys]))
        subbuff = []
        for i in buff:
            subbuff.append(i[1])
        index = subbuff.index(max(subbuff))
        tipa_a = buff[index][0]
        key_plus = (self.s_, tipa_a)
        self.Q[key] += self.alfa * (self.r + self.gamma * self.Q[key_plus] - self.Q[key])
        self.s = self.s_

class graphics():
    '''class for GUI creation
    '''
    def __init__(self):
        self.agent_image = None
        self.m_generator = map_generator()
        self.m1 = self.m_generator.generate_map1()
        self.m0 = self.m_generator.generate_map0()
        self.start_x = 1
        self.start_y = 14
        self.q_agent = Q_agent(agent_position_x = self.start_x, agent_position_y = self.start_y)
        self.game_finish = False
        self.reward = {}
        self.walls = []
        self.target = None
        self.rectangle_size = 50
        self.oval_size = 50
        self.width = self.rectangle_size * (self.m_generator.map_size + 1)
        self.height = self.width
        self.score = 0
        self.steps = 0
        self.local_steps = 0
        self.num_games = 0
        self.root = Tk()
        self.can = Canvas(self.root, width=self.width, height=self.height, bg='lightblue')
        self.can.pack()
        self.label = Label(self.root)
        self.label.pack(side = 'bottom')
        self.init()

    def init(self):
        '''inits map, agent, reward
        '''
        self.create_map()
        self.init_agent()
        for obj in self.m0:
            if type(obj) == type(target()):
                    self.target = obj
                    self.reward[(obj.position_x, obj.position_y)] = 100
            if type(obj) == type(wall()):
                    self.walls.append(obj)
                    self.reward[(obj.position_x, obj.position_y)] =- 1

    def write_score_steps(self,score,steps,local_steps,num_games):
        '''writing info on GUI
        '''
        info = 'SCORE: ' + str(score) + ' ;' + '\n' + 'STEPS: ' + str(steps) + ' ;'
        info1 = 'STEPS IN THIS GAME:  ' + str(local_steps) + ' ;' + '\n' + 'GAMES: ' + str(num_games) + ' ;'
        sum_info = info + info1
        self.label.config(text = sum_info)

    def create_map(self):
        '''creating graphical content
        '''
        fill = ''
        for _ in self.m1:
            if _.marker == 0:
                fill = 'white'
            if _.marker == 3:
                fill = 'green'
            if _.marker == 5:
                fill = 'black'
            self.can.create_rectangle(self.rectangle_size * _.position_x,
                                      _.position_y * self.rectangle_size,
                                      (_.position_x * self.rectangle_size) + self.rectangle_size,
                                      (_.position_y * self.rectangle_size) + self.rectangle_size,
                                      fill = fill,outline='blue')

    def init_agent(self):
        '''inits agent on level
        '''
        a=self.q_agent
        self.q_agent.init()
        self.agent_image = self.can.create_oval(self.oval_size * a.position_x,
                             a.position_y * self.oval_size,
                             (a.position_x * self.oval_size) + self.oval_size,
                             (a.position_y * self.oval_size) + self.oval_size,
                             fill = 'yellow', outline = 'blue')
        self.can.pack()

    def move_agent(self):
        '''moves agent on level
        '''
        self.can.coords(self.agent_image,
                        self.q_agent.position_x * self.oval_size,
                        self.q_agent.position_y * self.oval_size,
                        (self.q_agent.position_x * self.oval_size) + self.oval_size,
                        (self.q_agent.position_y * self.oval_size) + self.oval_size)
        self.local_steps += 1

    def restart(self):
        '''resets agent coords to start position
        '''
        self.q_agent.position_x = self.start_x
        self.q_agent.position_y = self.start_y

    def check_rules(self):
        '''checking for finish
        '''
        for w in self.walls:
            if self.q_agent.get_pos_y() == w.position_y and self.q_agent.get_pos_x() == w.position_x:
                self.restart()
                break
        if  self.q_agent.position_y == self.target.position_y and self.q_agent.position_x == self.target.position_x:
            self.game_finish = True
            self.restart()
            self.num_games += 1
            self.local_steps = 0

    def run(self):
        '''main method with all math
        and mechanics
        '''
        self.write_score_steps(self.score, self.steps, self.local_steps, self.num_games)
        self.check_rules()
        self.q_agent.run()
        self.move_agent()
        #for watching ability
        time.sleep(0.02)

    def core_loop(self):
        while True:
            self.run()

    def loop(self):
        while True:
            self.root.mainloop()

g=graphics()
g.init()
t=threading.Thread(target=g.core_loop)
t.start()
g.root.mainloop()


from django.views import generic
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django_tables2 import RequestConfig
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.db.models import Sum, Count
from django.db import models
from .tables import ExpenseTable
from .models import Expense
from .forms import ExpenseTableHelper
from .filters import ExpenseFilter
from .utils import AmountUnitUtil
import random
from calendar import monthrange
import datetime

class IndexView(generic.ListView):
    template_name = "tracker/index.html"
    context_object_name = "records"
    model = Expense
    table_class = ExpenseTable
    filter_class = ExpenseFilter
    formhelper_class = ExpenseTableHelper

    def get_queryset(self):
        return Expense.objects.filter(created_by=self.request.user)

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        filter = ExpenseFilter(self.request.GET, queryset=self.get_queryset(**kwargs))
        filter.form.helper = ExpenseTableHelper()
        table = ExpenseTable(filter.qs)
        table.order_by = '-date'
        RequestConfig(self.request, paginate={'per_page': 10}).configure(table)
        context['filter'] = filter
        context['table'] = table
        return context

class ExpenseCreate(CreateView):
    # TODO: add datepicker

    model = Expense
    fields = [
        'date',
        'description',
        'type',
        'payment',
        'amount'
    ]

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.created_by = self.request.user
        obj.created_at = datetime.datetime.now()
        obj.save()
        return HttpResponseRedirect(reverse_lazy('tracker:expense'))

class ExpenseUpdate(UpdateView):
    model = Expense
    fields = [
        'date',
        'description',
        'type',
        'payment',
        'amount'
    ]

# obsolete
class ExpenseDelete(DeleteView):
    model = Expense
    success_url = reverse_lazy('tracker:expense')

class AnalyticsView(generic.ListView):
    template_name = "analytics/index.html"
    context_object_name = "records"
    model = Expense

    def statistic(request):
        # init
        avg_year = 0
        avg_month = 0
        avg_day = 0

        # get user expense objects
        exp = Expense.objects.filter(created_by=request.user)

        # count total record
        total_records = exp.count()

        # sum up all the expenses
        total_expenses = exp.aggregate(amount=Sum('amount'))['amount']
        if total_expenses is None:
            total_expenses = 0

        # categories count
        categories = exp.values('type').annotate(the_count=Count('type')).count()

        # list out dates for the following processing.
        dates = list(exp.values('date')
                     .values_list('date', flat=True))

        # avg amount per year, per month and per day
        year_arr = []
        month_arr = []
        day_arr = []

        for date in dates:
            if date.year not in year_arr:
                year_arr.append(date.year)
            if date.year not in month_arr:
                month_arr.append(date.month)
            if date.year not in day_arr:
                day_arr.append(date.day)

        if total_expenses > 0 :
            avg_year = AmountUnitUtil.convertToMills(total_expenses / year_arr.__len__())
            avg_month = AmountUnitUtil.convertToMills(total_expenses / month_arr.__len__())
            avg_day = AmountUnitUtil.convertToMills(total_expenses / day_arr.__len__())
            total_expenses = AmountUnitUtil.convertToMills(total_expenses)

        now = datetime.datetime.now()

        context = {
            'context_type': 'statistic',
            'total_records': total_records,
            'total_expenses': total_expenses,
            'categories': categories,
            'avg_year': avg_year,
            'avg_month': avg_month,
            'avg_day': avg_day,
            'current_year': now.year,
            'current_month': now.month,
            'current_day': now.day

        }

        return render(request, "analytics/index.html", context)

    def annually(request, year):
        # get user expense objects
        exp = Expense.objects.filter(created_by=request.user)

        # retrieve distinct types
        expense_type = list(exp.filter(date__year=year).values('type').distinct().order_by()
                                 .values_list('type', flat=True))

        datasets = []
        months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October",
                  "November", "December"]

        for type in expense_type:
            # expense
            arr = list(exp.filter(date__year=year).filter(type=type).distinct().order_by('date'))

            # expense month by type
            month_tmp_arr = list(exp.filter(date__year=year).filter(type=type).values('date').distinct()
                            .order_by('date')
                            .values_list('date', flat=True))

            # expense amount by type
            expense_tmp_arr = list(exp.filter(date__year=year).filter(type=type)
                .values('date').distinct().order_by('date')
                .annotate(amount=Sum('amount')).values_list('amount', flat=True))

            # init array with size 12 with value 0
            monthly_expense_cnt = [0] * 12

            for i, m in enumerate(arr):
                monthly_expense_cnt[m.date.month-1] += m.amount

            total_amount = []

            for j, k in enumerate(monthly_expense_cnt):
                o = {}
                o['x'] = months[j];
                o['y'] = monthly_expense_cnt[j];
                total_amount.append(o)

            # generate random color
            r = lambda: random.randint(0, 255)
            color = '#%02X%02X%02X' % (r(), r(), r())

            # construct dataset
            dataset = {
                'label': type,
                'backgroundColor': color,
                'borderColor': color,
                'data': total_amount,
                'fill': 'false'
            }

            datasets.append(dataset)

        # fetch available years for menu labels
        dates = list(exp.values('date')
             .values_list('date', flat=True))
        year_arr = []
        for date in dates:
            if date.year not in year_arr:
                year_arr.append(date.year)
        year_arr.sort()

        # construct submenu
        expense_per_month = []
        month_not_none = []
        for i, month in enumerate(months):
            amount = exp.filter(date__year=year).filter(date__month=(i+1)).values('date').distinct().order_by('date').aggregate(amount=Sum('amount'))['amount']
            if amount is not None:
                expense_per_month.append(float("{0:.2f}".format(amount)))
                month_not_none.append((months[i]))

        if expense_per_month:
            submenu = zip(month_not_none, expense_per_month)
        else:
            submenu = False

        context = {
            'context_type': 'annually',
            'datasets': datasets,
            'labels': months,
            'title': 'Annual Report in ' + str(year),
            'report_type': 'line',
            'menu_labels': year_arr,
            'x_axis_label': 'Month',
            'submenu': submenu
        }

        return render(request, "analytics/index.html", context)

    def monthly(request, year, month):
        # get user expense objects
        exp = Expense.objects.filter(created_by=request.user)

        months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October",
                  "November", "December"]
        months_reverse = dict(January=1, February=2, March=3, April=4)
        datasets = []

        # retrieve distinct types
        expense_type = list(exp.filter(date__year=year).filter(date__month=month).values('type').distinct().order_by()
                            .values_list('type', flat=True))

        lastday = monthrange(year, month)[1]
        days = list(range(1,lastday+1))

        for type in expense_type:
            # expense
            arr = list(exp.filter(date__year=year).filter(date__month=month).filter(type=type).distinct().order_by('date'))

            # expense month by type
            month_tmp_arr = list(exp.filter(date__year=year).filter(date__month=month).filter(type=type).values('date').distinct()
                                 .order_by('date')
                                 .values_list('date', flat=True))

            # expense amount by type
            expense_tmp_arr = list(exp.filter(date__year=year).filter(date__month=month).filter(type=type)
                                   .values('date').distinct().order_by('date')
                                   .annotate(amount=Sum('amount')).values_list('amount', flat=True))

            # init array
            daily_expense_cnt = [0] * lastday

            for i, m in enumerate(arr):
                daily_expense_cnt[m.date.day] += m.amount

            total_amount = []

            for j, k in enumerate(daily_expense_cnt[1:]):
                o = {}
                o['x'] = days[j];
                o['y'] = daily_expense_cnt[j+1];
                total_amount.append(o)

            # generate random color
            r = lambda: random.randint(0, 255)
            color = '#%02X%02X%02X' % (r(), r(), r())

            # construct dataset
            dataset = {
                'label': type,
                'backgroundColor': color,
                'borderColor': color,
                'data': total_amount,
                'fill': 'false'
            }

            datasets.append(dataset)

        # fetch available months for menu labels
        dates = list(exp.values('date')
                     .values_list('date', flat=True))
        month_arr = []
        month_labels = []
        for date in dates:
            if date.month not in month_arr:
                month_arr.append(date.month)
                month_arr.sort()

        for single_month in month_arr:
            month_labels.append(months[single_month - 1])
        # construct submenu
        expense_per_day = []
        day_not_none  = []
        for i, d in enumerate(days):
            amount = exp.filter(date__year=year).filter(date__month=month).filter(date__day=(i+1)).values('date').distinct().order_by(
                'date').aggregate(amount=Sum('amount'))['amount']
            if amount is not None:
                expense_per_day.append(float("{0:.2f}".format(amount)))
                day_not_none.append((i+1))

        if expense_per_day:
            submenu = zip(day_not_none, expense_per_day)
        else:
            submenu = False

        context = {
            'context_type': 'monthly',
            'datasets': datasets,
            'monthly_expense': expense_type,
            'labels': days,
            'title': 'Monthly Report on ' + str(months[month-1]) + ' ' + str(year),
            'report_type': 'bar',
            'selected_year':year ,
            'menu_labels': month_arr,
            'month_labels': month_labels,
            'x_axis_label': 'Day',
            'submenu': submenu,
            'months': months
        }
        return render(request, "analytics/index.html", context)

    def daily(request, year, month, day):
        # get user expense objects
        exp = Expense.objects.filter(created_by=request.user)

        type =[]
        # retrieve distinct types
        expense_type = list(
            exp.filter(date__year=year).filter(date__month=month)
            .filter(date__day=day).values('type').distinct().order_by()
            .values_list('type', flat=True))

        datasets = []
        expense_arr = []
        color_arr = []
        for type in expense_type:
            # expense amount by type
            expense_tmp_arr = list(exp.filter(date__year=year).filter(date__month=month).filter(date__day=day)
                                   .filter(type=type)
                                   .values('date').distinct().order_by('date')
                                   .annotate(amount=Sum('amount')).values_list('amount', flat=True))
            # get the sum
            expense_arr.append(expense_tmp_arr[0])

            # generate random color
            r = lambda: random.randint(0, 255)
            color = '#%02X%02X%02X' % (r(), r(), r())
            color_arr.append(color)

        # construct dataset
        if color_arr and expense_arr:
            dataset = {
                'label': type,
                'backgroundColor': color_arr,
                'borderColor': color_arr,
                'data': expense_arr
            }
            datasets.append(dataset)

        # construct submenu
        expense_per_type = []
        for i, type in enumerate(expense_type):
            amount = exp.filter(date__year=year).filter(date__month=month).filter(date__day=day).filter(type=type).values('date').distinct().order_by('date').aggregate(amount=Sum('amount'))['amount']
            if amount is not None:
                expense_per_type.append(float("{0:.2f}".format(amount)))

        if expense_per_type:
            submenu = zip(expense_type, expense_per_type)
        else:
            submenu = False

        context = {
            'context_type': 'daily',
            'datasets': datasets,
            'daily_expense': expense_type,
            'labels': expense_type,
            'title': 'Daily Report on ' + str(day) + '/' + str(month) + '/' + str(year) ,
            'x_axis_label': 'Type',
            'report_type': 'pie',
            'submenu': submenu
        }
        return render(request, "analytics/index.html", context)

class landingView():
    def landing(request):
        context = {}
        return render(request, "landing/index.html", context)


parameters = open("parameters.py", 'r').read()
exec(parameters)

# Trying to scrape Ronny J's soundcloud links
# End goal: Get all tracks and info about tracks by just giving the link to his soundcloud.

chrome_options = Options()
chrome_options.add_argument("--headless")

driver = webdriver.Chrome(executable_path='../chromedriver_win32/chromedriver.exe', chrome_options = chrome_options)

artists_urls = list(pd.read_csv(artist_repository, index_col = 0)['artist_url'])

def scrape_artist_page(artist_extension):

    url = 'https://soundcloud.com' + artist_extension + '/tracks'

    #Start Driver
    driver.get(url)
    WebDriverWait(driver, 2).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "ul.lazyLoadingList__list")))

    # scrolling to the bottom of the page
    lazy_soundList_loaded = 0
    loaded_songs = len(driver.find_elements_by_class_name('soundList__item'))
    except_count = 0

    while lazy_soundList_loaded == 0:  # waits for the "paging-eof" class to appear when list is loaded
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        try:
            WebDriverWait(driver, 2).until((lambda x: len(driver.find_elements_by_class_name('soundList__item'))!= loaded_songs))

     # couldn't figure out how to get it to break when it finds the eof element, just catching timeout instead
        except TimeoutException:
            except_count += 1
            if except_count == 2:
                break
        loaded_songs = len(driver.find_elements_by_class_name('soundList__item'))
        lazy_soundList_loaded = len(driver.find_elements_by_class_name('paging-eof'))

    #Grab elements in the page
    item_path = "//*[@class='userMain__content']//li[@class='soundList__item']"
    song_name_path = "//*[@class='userMain__content']//div[@class='soundTitle__usernameTitleContainer']/a[1]/span"
    artist_name_path = "//*[@class='userMain__content']//span[@class='soundTitle__usernameText']"
    publish_date_path = "//*[@class='userMain__content']//time[@class='relativeTime']"
    plays_path = "//*[@class='userMain__content']//div[@class='sound__soundStats']/ul/li[1]"
    comment_path = "//div[@class='sound__soundStats']/ul/li[2]"
    likes_path = "//*[@class='userMain__content']//button[@class='sc-button-like sc-button sc-button-small sc-button-responsive']"
    repost_path = "//*[@class='userMain__content']//button[@class='sc-button-repost sc-button sc-button-small sc-button-responsive']"
    followers_path = "//a[@class='infoStats__statLink sc-link-light']"

    song_list = [item.text for item in driver.find_elements_by_xpath(song_name_path)]

    artist_list = [item.text for item in driver.find_elements_by_xpath(artist_name_path)]

    publish_date_list = [
            datetime.datetime.strptime(item.get_attribute('datetime').replace('T',':')[0:-5],'%Y-%m-%d:%H:%M:%S')
            for item in driver.find_elements_by_xpath(publish_date_path)]

    comment_list = []
    plays_list = []

    for item in  driver.find_elements_by_xpath(item_path):
        stats = item.find_elements_by_class_name('sc-ministats-item')
        num_stats = len(stats)

        if num_stats == 0:
            plays, comments = 0, 0

        elif num_stats == 1:
            plays = int((re.split(" " ,stats[0].get_attribute('title'))[0]).replace(',',''))
            comments = 0

        else:
            for stat in stats:
                 plays = int((re.split(" " ,stats[0].get_attribute('title'))[0]).replace(',',''))
                 comments = int((re.split(" " ,stats[1].get_attribute('title'))[0]).replace(',',''))

        plays_list.append(plays)
        comment_list.append(comments)

    likes_list = [item.text for item in driver.find_elements_by_xpath(likes_path)]

    repost_list = [item.text for item in driver.find_elements_by_xpath(repost_path)]

    artist_followers = int((re.split(" " ,driver.find_element_by_xpath(followers_path)\
                                     .get_attribute('title'))[0]).replace(',',''))

    run_time = datetime.datetime.now()

    artist_data = {'song_name': song_list,
                   'artist_name': artist_list,
                   'publish_date': publish_date_list,
                   'plays': plays_list,
                   'comments':comment_list,
                   'likes': likes_list,
                   'repost': repost_list,
                   'artist_followers': artist_followers,
                   'run_date': run_time}

    pd.set_option('display.max_columns', None)

    artist_df = pd.DataFrame(artist_data)

    return(artist_df)

appended_data = pd.DataFrame()

for url in artists_urls:
    data = scrape_artist_page(url)
    appended_data = pd.concat([appended_data, data])

driver.quit()

appended_data = appended_data\
.reset_index(drop = True)\
.rename_axis('index')

data = Catalogue(appended_data)

Catalogue.save_data(data, song_metrics_data)


#from flask import Flask, render_template, request
from chatterbot import ChatBot
from chatterbot.response_selection import get_random_response
from chatterbot.trainers import ChatterBotCorpusTrainer

#For getting the spreadsheets
import requests
import gspread
from oauth2client.service_account import ServiceAccountCredentials

import logging
logging.basicConfig(level=logging.INFO)

##Try to download the spreadsheet from Google to retrain from
scope = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']

credentials = ServiceAccountCredentials.from_json_keyfile_name('googleapi.json', scope)

gc = gspread.authorize(credentials)

worksheet = gc.open("ChatBot Knowledge Base").sheet1

all_cells = worksheet.get_all_values()

with open('data/trainingdata.yml', 'w') as f:
    f.write("categories:\r\n")
    f.write("- Conversations")
    f.write("\r\nconversations:")
    for i in range(len(all_cells)):
        if i != 0:
            f.write("\r\n- - " + all_cells[i][0])
            f.write("\r\n  - " + all_cells[i][1])
            #print("- - " + all_cells[i][0])
            #print("  - " + all_cells[i][1])

print("I have successfully imported " + str(len(all_cells)) + " rows of data and will now retrain...")

bot = ChatBot(
    "Chatbot",
    logic_adapters=[
        {
            'import_path': 'chatterbot.logic.BestMatch'
        },
        {
            'import_path': 'chatterbot.logic.LowConfidenceAdapter',
            'threshold': 0.65,
            'default_response': 'I don\'t have a response for that. What else can we talk about?'
        }
    ],
    response_selection_method=get_random_response, #Comment this out if you want best response
    input_adapter="chatterbot.input.VariableInputTypeAdapter",
    output_adapter="chatterbot.output.OutputAdapter",
    storage_adapter="chatterbot.storage.SQLStorageAdapter",
    database="botdata.sqlite3"
)

bot.read_only=True #Comment this out if you want the bot to learn based on experience
print("Bot Learn Read Only:" + str(bot.read_only))

#You can comment these out for production later since you won't be training everytime:
bot.set_trainer(ChatterBotCorpusTrainer)
bot.train("data/trainingdata.yml")

print("I am all trained up and ready to chat!")


newfile = open('foo.txt')

print('file1 ===> :')
for line in newfile:

    print(line.rstrip())

###############################################
newfile.seek(0)  # moving the cursor to the beginging of the file
lines = newfile.readlines()  # return an array with text
print('file2 ===>:  ', lines)

newfile.close()
###################################### file is closed

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

with open('bar.txt', 'w') as newfile2:
    newfile2.write('hello word \nhow is everything \nthank you')

with open('bar.txt', 'a') as newfile2:
    newfile2.write('\nhello hello , how is everything going thank you so much')

quote = [
    '\n helllllllllllllollllllllll',
    '\n babbabababbabbababababbabab',
    '\n iizizziziiziziziiziizizizizizi'
]

with open('bar.txt', 'a') as newfile3:
    newfile3.writelines(quote)


import sendgrid
from app import sg

def send_email(to, subject, body):
    message = sendgrid.Mail()
    message.add_to(to)
    message.set_subject(subject)
    message.set_html(body)
    message.set_text(body)
    message.set_from('admin@budokai-arena.com')
    status, msg = sg.send(message)