from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse, HttpResponseRedirect
from django.core import serializers
from .models import Cameras, Emails, Users, Properties, Agents
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
import re
from django.utils import timezone

from app.forms import EmailForm

def index(request):
    # context = {}
    # template = loader.get_template('app/index.html')
    # return HttpResponse(template.render(context, request))
    if request.user.is_superuser:
        return HttpResponseRedirect("/ipcameras")
    else:
        return HttpResponseRedirect("/monitor")

def gentella_html(request):
    context = {}
    # The template to be loaded as per gentelella.
    # All resource paths for gentelella end in .html.

    # Pick out the html file name from the url. And load that template.
    load_template = request.path.split('/')[-1]
    template = loader.get_template('app/' + load_template)
    return HttpResponse(template.render(context, request))

@login_required(login_url='/login')
def ipcamera_html(request):
    context = {}
    template = loader.get_template('app/ipcameras.html')
    return HttpResponse(template.render(context, request))

@login_required(login_url='/login')
def monitor_html(request):
    context = {}
    template = loader.get_template('app/monitor.html')
    return HttpResponse(template.render(context, request))

def login_html(request):
    next = request.GET.get('next')
    context = {"next" : next}
    template = loader.get_template('app/login.html')
    return HttpResponse(template.render(context, request))

@login_required(login_url='/login')
def users_html(request):
    context = {}
    template = loader.get_template('app/users.html')
    return HttpResponse(template.render(context, request))

@login_required(login_url='/login')
def properties_html(request):
    context = {}
    template = loader.get_template('app/properties.html')
    return HttpResponse(template.render(context, request))

@login_required(login_url='/login')
def agents_html(request):
    context = {}
    template = loader.get_template('app/agents.html')
    return HttpResponse(template.render(context, request))

@login_required(login_url='/login')
def alerts_html(request):
    context = {}
    template = loader.get_template('app/alerts.html')
    return HttpResponse(template.render(context, request))

def cameras_asJson(request):
    object_list = Cameras.objects.all()
    for item in object_list:
        if item.online_status == False:
            continue
        last_con = item.lastConnection
        now = timezone.now()
        delta = now - last_con
        if delta.total_seconds() > 1860:
            item.online_status = False
            item.save()
    json = serializers.serialize('json', object_list)
    return HttpResponse(json, content_type='application/json')

def users_asJson(request):
    object_list = Users.objects.all()
    json = serializers.serialize('json', object_list)
    return HttpResponse(json, content_type='application/json')

def properties_asJson(request):
    object_list = Properties.objects.all()
    json = serializers.serialize('json', object_list)
    return HttpResponse(json, content_type='application/json')

def agents_asJson(request):
    object_list = Agents.objects.all()
    for item in object_list:
        if item.status == "offline":
            continue
        last_con = item.lastConnection
        now = timezone.now()
        delta = now - last_con
        if delta.total_seconds() > 3:
            item.status = "offline"
            item.save()
    object_list = Agents.objects.all()
    json = serializers.serialize('json', object_list)
    return HttpResponse(json, content_type='application/json')

def get_serial(text):
    try:
        found = re.search('Alarm Device Name: (.+?) ', text).group(1)
    except AttributeError:
        # AAA, ZZZ not found in the original string
        found = '' # apply your error handling
    return found

@csrf_exempt
def email_receiver(request):
    if request.POST.get('subject') == "Health_Test":
        serial = get_serial(re.sub(r"\s+", " ", request.POST.get('stripped-text')))
        cam = Cameras.objects.get(serial_number=serial)
        cam.online_status = True
        cam.lastConnection = timezone.now()
        cam.save()
        return HttpResponse('')
    else:
        #form = EmailForm(request.POST)
        print(request.POST)
        print(request.POST.get('stripped-text'))
        new_email = Emails()
        new_email.message_id = request.POST.get('Message-Id')
        new_email.subject = request.POST.get('Subject')
        new_email.content = request.POST.get('stripped-text')
        serial = get_serial(re.sub(r"\s+", " ", new_email.content))
        new_email.serial = serial
        cam = Cameras.objects.filter(serial_number=serial)
        if (cam[0].auth_user != None):
            new_email.notify = True
        new_email.save()
        return HttpResponse("ok")

def get_notify(request):
    alert = request.GET.get('alert')
    if alert == "1":
        agent = Agents.objects.get(username = request.user.username)
        if agent.status != "offline":
            agent.status = "offline"
            agent.save()
    else :
        agent = Agents.objects.get(username = request.user.username)
        agent.lastConnection = timezone.now()
        if agent.status != "online":
            agent.status = "online"
        agent.save()
    if request.GET.get('notify') == '0':
        object_list = Emails.objects.filter(notify=False)
        if (len(object_list) > 0):
            email = object_list[0]
            emails = Emails.objects.filter(message_id=email.message_id)
            emails.update(notify=True)
            serial = email.serial
            cam = Cameras.objects.filter(serial_number=serial)
            cam.update(auth_user = request.user.username)
            json = serializers.serialize('json', cam)
            return HttpResponse(json, content_type='application/json')
        else:
            return HttpResponse('')
    else:
        object_list = Emails.objects.filter(notify=False)
        if (len(object_list) > 0):
            email = object_list[0]
            serial = email.serial
            cam = Cameras.objects.filter(serial_number=serial)
            json = serializers.serialize('json', cam)
            return HttpResponse(json, content_type='application/json')
        else:
            return HttpResponse('')

def remove_notis(request):
    Emails.objects.filter(notify=False).update(notify=True)
    return HttpResponse('')


import trik
A = trik.constant([[1, 2], [1, 3]], name='A')
x = trik.V([[1, 0,1],[1,0,1]], name='x')
x1 =trik.V([[1, 0],[1,1],[1,0]], name='x1')
b = trik.constant([3, 4], name='b')
#~ loss = pd.reduce_sum(((A @ x@(1**x1) + b)) ** 2) / 2
loss=A(trik.MM(),x)(trik.MM(),trik.constant(1)(trik.Pow(),x1))(trik.Plus(),b)(trik.Pow(),2)(trik.ReduceSum())(trik.Div(),2)

print('loss formula =\n{}\n'.format(loss))
print('loss =\n{}\n'.format(loss.val()))

x_gradient = loss.bprop(x)
print('x grad formula =\n{}\n'.format(x_gradient))
print('x grad =\n{}\n'.format(x_gradient.val()))


def getAccessKey(filePath):
    accessKey = {}
    keyFile = open(filePath, "r", encoding='utf-8-sig')
    lines = keyFile.readlines()

    keyFile.close()
    keys = lines[0].strip().split(",")
    values = lines[1].strip().split(",")

    accessKey[keys[0].strip().replace('"', '')] = values[0].strip().replace('"', '')
    accessKey[keys[1].strip().replace('"', '')] = values[1].strip().replace('"', '')
    return accessKey

#print(returnAccessKey("accessKey.csv"))


##Jim McMahon
##DAEN 500 Final
##Problem 1

def find_nums(num1, num2):
    #First ID which number is lower
    if num1 > num2:
        clean_num1 = num2 #clean_num1 is low end
        clean_num2 = num1 #clean_num2 is high end
    elif num2 > num1:
        clean_num1 = num1 #clean_num1 is low end
        clean_num2 = num2 #clean_num2 is high end
    else:
        clean_num1 = num1 #for when nums are equal
        clean_num2 = num2 #for when nums are equal

    #Now find nums div. by 7 and but not mult. of 5
    solution_nums = []  # for storing nums that fit criteria
    if clean_num1 == clean_num2:
        if clean_num1 % 5 != 0 and clean_num1 % 7 == 0:
            solution_nums.append(clean_num1)
            return solution_nums
    elif clean_num1 != clean_num2:
        myRange = range(clean_num1, clean_num2 + 1)
        for item in myRange:
            if item % 5 !=0 and item % 7 == 0:
                solution_nums.append(item)
        return solution_nums
    else:
        print('ERROR')

if __name__ == '__main__':
    answer = find_nums(2000, 3200)
    print(answer)


import api
import braille
import config
import controlTypes
import ctypes
import NVDAHelper
import NVDAState
import speech
import textInfos
import textUtils
import UIAHandler

from comtypes import COMError
from diffHandler import prefer_difflib
from logHandler import log
from typing import (
	Any,
	Optional,
)
from UIAHandler.utils import _getConhostAPILevel, _shouldUseWindowsTerminalNotifications
from UIAHandler.constants import WinConsoleAPILevel
from . import UIA, UIATextInfo
from ..behaviors import EnhancedTermTypedCharSupport, KeyboardHandlerBasedTypedCharSupport
from ..window import Window

class ConsoleUIATextInfo(UIATextInfo):
	"A TextInfo implementation for consoles with an IMPROVED, but not FORMATTED, API level."
	def __init__(self, obj, position, _rangeObj=None):
		collapseToEnd = None
		# We want to limit  textInfos to just the visible part of the console.
		# Therefore we specifically handle POSITION_FIRST, POSITION_LAST and POSITION_ALL.
		if not _rangeObj and position in (
			textInfos.POSITION_FIRST,
			textInfos.POSITION_LAST,
			textInfos.POSITION_ALL
		):
			try:
				_rangeObj, collapseToEnd = self._getBoundingRange(obj, position)
			except (COMError, RuntimeError):
				# We couldn't bound the console.
				log.warning("Couldn't get bounding range for console", exc_info=True)
				# Fall back to presenting the entire buffer.
				_rangeObj, collapseToEnd = None, None
		super(ConsoleUIATextInfo, self).__init__(obj, position, _rangeObj)
		if collapseToEnd is not None:
			self.collapse(end=collapseToEnd)

	def _getBoundingRange(self, obj, position):
		"""Returns the UIA text range to which the console should be bounded,
		and whether the textInfo should be collapsed after instantiation."""
		# microsoft/terminal#4495: In newer consoles,
		# IUIAutomationTextRange::getVisibleRanges returns a reliable contiguous range.
		_rangeObj = obj.UIATextPattern.GetVisibleRanges().GetElement(0)
		collapseToEnd = None
		if position == textInfos.POSITION_FIRST:
			collapseToEnd = False
		elif position == textInfos.POSITION_LAST:
			# The exclusive end hangs off the end of the visible ranges.
			# Move back one character to remain within bounds.
			_rangeObj.MoveEndpointByUnit(
				UIAHandler.TextPatternRangeEndpoint_End,
				UIAHandler.NVDAUnitsToUIAUnits['character'],
				-1
			)
			collapseToEnd = True
		return (_rangeObj, collapseToEnd)

	def move(self, unit, direction, endPoint=None):
		oldInfo = None
		if self.basePosition != textInfos.POSITION_CARET:
			# Ensure we haven't gone beyond the visible text.
			# UIA adds thousands of blank lines to the end of the console.
			boundingInfo = self.obj.makeTextInfo(textInfos.POSITION_ALL)
			oldInfo = self.copy()
		res = self._move(unit, direction, endPoint)
		# Console textRanges have access to the entire console buffer.
		# However, we want to limit ourselves to onscreen text.
		# Therefore, if the textInfo was originally visible,
		# but we are now above or below the visible range,
		# Restore the original textRange and pretend the move didn't work.
		if oldInfo:
			try:
				if (
					(
						self.compareEndPoints(boundingInfo, "startToStart") < 0
						or self.compareEndPoints(boundingInfo, "startToEnd") >= 0
					)
					and not (
						oldInfo.compareEndPoints(boundingInfo, "startToStart") < 0
						or oldInfo.compareEndPoints(boundingInfo, "startToEnd") >= 0
					)
				):
					self._rangeObj = oldInfo._rangeObj
					return 0
			except (COMError, RuntimeError):
				pass
		return res

	def _move(self, unit, direction, endPoint=None):
		"Perform a move without respect to bounding."
		return super(ConsoleUIATextInfo, self).move(unit, direction, endPoint)

	def _get_text(self) -> str:
		# #14689: IMPROVED and END_INCLUSIVE UIA consoles have many blank lines,
		# which slows speech dictionary processing to a halt
		res = super()._get_text()
		stripRes = res.rstrip("\r\n")
		IGNORE_TRAILING_WHITESPACE_LENGTH = 100
		if len(res) - len(stripRes) > IGNORE_TRAILING_WHITESPACE_LENGTH:
			return stripRes
		else:
			return res

	def __ne__(self, other):
		"""Support more accurate caret move detection."""
		return not self == other

class ConsoleUIATextInfoWorkaroundEndInclusive(ConsoleUIATextInfo):
	"""Implementation of various workarounds for pre-microsoft/terminal#4018
	conhost: fixes expand/collapse, uses rangeFromPoint instead of broken
	GetVisibleRanges for bounding, and implements word movement support."""
	def _getBoundingRange(self, obj, position):
		# We could use IUIAutomationTextRange::getVisibleRanges, but it seems very broken in consoles
		# once more than a few screens worth of content has been written to the console.
		# Therefore we resort to using IUIAutomationTextPattern::rangeFromPoint
		# for the top left, and bottom right of the console window.
		_rangeObj = None
		if position is textInfos.POSITION_FIRST:
			_rangeObj = self.__class__(obj, obj.location.topLeft)._rangeObj
		elif position is textInfos.POSITION_LAST:
			# Asking for the range at the bottom right of the window
			# Seems to sometimes ignore the x coordinate.
			# Therefore use the bottom left, then move   to the last character on that line.
			tempInfo = self.__class__(obj, obj.location.bottomLeft)
			tempInfo.expand(textInfos.UNIT_LINE)
			# We must pull back the end by one character otherwise when we collapse to end,
			# a console bug results in a textRange covering the entire console buffer!
			# Strangely the *very* last character is a special blank point
			# so we never seem to miss a real character.
			UIATextInfo.move(tempInfo, textInfos.UNIT_CHARACTER, -1, endPoint="end")
			tempInfo.setEndPoint(tempInfo, "startToEnd")
			_rangeObj = tempInfo._rangeObj
		elif position is textInfos.POSITION_ALL:
			first = self.__class__(obj, textInfos.POSITION_FIRST)
			last = self.__class__(obj, textInfos.POSITION_LAST)
			first.setEndPoint(last, "endToEnd")
			_rangeObj = first._rangeObj
		return (_rangeObj, None)

	def collapse(self, end=False):
		"""Works around a UIA bug on conhost versions before microsoft/terminal#4018.
		When collapsing, consoles seem to incorrectly push the start of the
		textRange back one character.
		Correct this by bringing the start back up to where the end is."""
		oldInfo = self.copy()
		super(ConsoleUIATextInfo, self).collapse(end=end)
		if not end:
			self._rangeObj.MoveEndpointByRange(
				UIAHandler.TextPatternRangeEndpoint_Start,
				oldInfo._rangeObj,
				UIAHandler.TextPatternRangeEndpoint_Start
			)

	def compareEndPoints(self, other, which):
		"""Works around a UIA bug on conhost versions before microsoft/terminal#4018.
		Even when a console textRange's start and end have been moved to the
		same position, the console incorrectly reports the end as being
		past the start.
		Compare to the start (not the end) when collapsed."""
		selfEndPoint, otherEndPoint = which.split("To")
		if selfEndPoint == "end" and self._isCollapsed():
			selfEndPoint = "start"
		if otherEndPoint == "End" and other._isCollapsed():
			otherEndPoint = "Start"
		which = f"{selfEndPoint}To{otherEndPoint}"
		return super().compareEndPoints(other, which=which)

	def setEndPoint(self, other, which):
		"""Override of L{textInfos.TextInfo.setEndPoint}.
		Works around a UIA bug on conhost versions before microsoft/terminal#4018 that means we can
		not trust the "end" endpoint of a collapsed (empty) text range
		for comparisons.
		"""
		selfEndPoint, otherEndPoint = which.split("To")
		# In this case, there is no need to check if self is collapsed
		# since the point of this method is to change its text range, modifying the "end" endpoint of a collapsed
		# text range is fine.
		if otherEndPoint == "End" and other._isCollapsed():
			otherEndPoint = "Start"
		which = f"{selfEndPoint}To{otherEndPoint}"
		return super().setEndPoint(other, which=which)

	def expand(self, unit):
		if unit == textInfos.UNIT_WORD:
			# UIA doesn't implement word movement, so we need to do it manually.
			lineInfo = self.copy()
			lineInfo.expand(textInfos.UNIT_LINE)
			offset = self._getCurrentOffsetInThisLine(lineInfo)
			start, end = self._getWordOffsetsInThisLine(offset, lineInfo)
			wordEndPoints = (
				(offset - start) * -1,
				end - offset - 1
			)
			if wordEndPoints[0]:
				self._rangeObj.MoveEndpointByUnit(
					UIAHandler.TextPatternRangeEndpoint_Start,
					UIAHandler.NVDAUnitsToUIAUnits[textInfos.UNIT_CHARACTER],
					wordEndPoints[0]
				)
			if wordEndPoints[1]:
				self._rangeObj.MoveEndpointByUnit(
					UIAHandler.TextPatternRangeEndpoint_End,
					UIAHandler.NVDAUnitsToUIAUnits[textInfos.UNIT_CHARACTER],
					wordEndPoints[1]
				)
		else:
			return super(ConsoleUIATextInfo, self).expand(unit)

	def _move(self, unit, direction, endPoint=None):
		if unit == textInfos.UNIT_WORD and direction != 0:
			# On conhost versions before microsoft/terminal#4018, UIA doesn't implement word
			# movement, so we need to do it manually.
			# Relative to the current line, calculate our offset
			# and the current word's offsets.
			lineInfo = self.copy()
			lineInfo.expand(textInfos.UNIT_LINE)
			offset = self._getCurrentOffsetInThisLine(lineInfo)
			start, end = self._getWordOffsetsInThisLine(offset, lineInfo)
			if direction > 0:
				# Moving in a forward direction, we can just jump to the
				# end offset of the current word and we're done.
				res = self.move(
					textInfos.UNIT_CHARACTER,
					end - offset,
					endPoint=endPoint
				)
			else:
				# Moving backwards
				wordStartDistance = (offset - start) * -1
				if wordStartDistance < 0:
					# We are after the beginning of a word.
					# So first move back to the start of the word.
					self.move(
						textInfos.UNIT_CHARACTER,
						wordStartDistance,
						endPoint=endPoint
					)
					offset += wordStartDistance
				# Try to move one character back before the start of the word.
				res = self.move(textInfos.UNIT_CHARACTER, -1, endPoint=endPoint)
				if res == 0:
					return 0
				offset -= 1
				# We are now positioned  within the previous word.
				if offset < 0:
					# We've moved on to the previous line.
					# Recalculate the current offset based on the new line we are now on.
					lineInfo = self.copy()
					lineInfo.expand(textInfos.UNIT_LINE)
					offset = self._getCurrentOffsetInThisLine(lineInfo)
				# Finally using the new offset,
				# Calculate the current word offsets and move to the start of
				# this word if we are not already there.
				start, end = self._getWordOffsetsInThisLine(offset, lineInfo)
				wordStartDistance = (offset - start) * -1
				if wordStartDistance < 0:
					self.move(
						textInfos.UNIT_CHARACTER,
						wordStartDistance,
						endPoint=endPoint
					)
		else:  # moving by a unit other than word
			res = super(ConsoleUIATextInfo, self).move(unit, direction, endPoint)
		if not endPoint:
			# #10191: IUIAutomationTextRange::move in consoles does not correctly produce a collapsed range
			# after moving.
			# Therefore manually collapse.
			self.collapse()
		return res

	def _getCurrentOffsetInThisLine(self, lineInfo):
		"""
		Given a caret textInfo expanded to line, returns the index into the
		line where the caret is located.
		This is necessary since Uniscribe requires indices into the text to
		find word boundaries, but UIA only allows for relative movement.
		"""
		# position a textInfo from the start of the line up to the current position.
		charInfo = lineInfo.copy()
		charInfo.setEndPoint(self, "endToStart")
		text = charInfo._rangeObj.getText(-1)
		offset = textUtils.WideStringOffsetConverter(text).wideStringLength
		return offset

	def _getWordOffsetsInThisLine(self, offset, lineInfo):
		lineText = lineInfo._rangeObj.getText(-1)
		# Convert NULL and non-breaking space to space to make sure
		# that words will break on them
		lineText = lineText.translate({0: u' ', 0xa0: u' '})
		start = ctypes.c_int()
		end = ctypes.c_int()
		# Uniscribe does some strange things when you give it a string  with
		# not more than two alphanumeric chars in a row.
		# Inject two alphanumeric characters at the end to fix this.
		lineText += "xx"
		lineTextLen = textUtils.WideStringOffsetConverter(lineText).wideStringLength
		NVDAHelper.localLib.calculateWordOffsets(
			lineText,
			lineTextLen,
			offset,
			ctypes.byref(start),
			ctypes.byref(end)
		)
		return (
			start.value,
			min(end.value, max(1, lineTextLen - 2))
		)

	def _isCollapsed(self):
		"""Works around a UIA bug on conhost versions before microsoft/terminal#4018 that means we
		cannot trust the "end" endpoint of a collapsed (empty) text range
		for comparisons.
		Instead we check to see if we can get the first character from the
		text range. A collapsed range will not have any characters
		and will return an empty string."""
		return not bool(self._rangeObj.getText(1))

	def _get_isCollapsed(self):
		# To decide if the textRange is collapsed,
		# Check if it has no text.
		return self._isCollapsed()

	def _get_text(self):
		# #10036: return a space if the text range is empty.
		# Consoles don't actually store spaces, the character is merely left blank.
		res = super()._get_text()
		if not res:
			return ' '
		else:
			return res

class consoleUIAWindow(Window):
	# This is the parent of the console text area, which sometimes gets focus after the text area.
	shouldAllowUIAFocusEvent = False

class WinConsoleUIA(KeyboardHandlerBasedTypedCharSupport):
	#: Disable the name as it won't be localized
	name = ""

	def _get_apiLevel(self) -> WinConsoleAPILevel:
		"""
		This property shows which of several console UIA workarounds are
		needed in a given conhost instance.
		See the comments on the WinConsoleAPILevel enum for details.
		"""
		self.apiLevel = _getConhostAPILevel(self.windowHandle)
		return self.apiLevel

	def _get__caretMovementTimeoutMultiplier(self):
		"On older consoles, the caret can take a while to move."
		return (
			1 if self.apiLevel >= WinConsoleAPILevel.IMPROVED
			else 1.5
		)

	def _get_windowThreadID(self):
		# #10113: Windows forces the thread of console windows to match the thread of the first attached process.
		# However, To correctly handle speaking of typed characters,
		# NVDA really requires the real thread the window was created in,
		# I.e. a thread inside conhost.
		from IAccessibleHandler.internalWinEventHandler import consoleWindowsToThreadIDs
		threadID = consoleWindowsToThreadIDs.get(self.windowHandle, 0)
		if not threadID:
			threadID = super().windowThreadID
		return threadID

	def _get_TextInfo(self):
		"""Overriding _get_TextInfo and thus the ConsoleUIATextInfo property
		on NVDAObjects.UIA.UIA
		ConsoleUIATextInfo bounds review to the visible text.
		ConsoleUIATextInfoWorkaroundEndInclusive fixes expand/collapse and implements
		word movement."""
		if self.apiLevel >= WinConsoleAPILevel.FORMATTED:
			return UIATextInfo  # No TextInfo workarounds needed
		elif self.apiLevel >= WinConsoleAPILevel.IMPROVED:
			return ConsoleUIATextInfo
		else:
			return ConsoleUIATextInfoWorkaroundEndInclusive

	def _get_devInfo(self):
		info = super().devInfo
		info.append(f"API level: {self.apiLevel} ({self.apiLevel.name})")
		return info

	def _get_diffAlgo(self):
		if self.apiLevel < WinConsoleAPILevel.FORMATTED:
			# #12974: These consoles are constrained to onscreen text.
			# Use Difflib to reduce choppiness in reading.
			return prefer_difflib()
		else:
			return super().diffAlgo

	def detectPossibleSelectionChange(self):
		try:
			return super().detectPossibleSelectionChange()
		except COMError:
			# microsoft/terminal#5399: when attempting to compare text ranges
			# from the standard and alt mode buffers, E_FAIL is returned.
			# Downgrade this to a debugWarning.
			log.debugWarning((
				"Exception raised when comparing selections, "
				"probably due to a switch to/from the alt buffer."
			), exc_info=True)

	def event_UIA_notification(self, **kwargs):
		"""
		In Windows Sun Valley 2 (SV2 M2), UIA notification events will be sent
		to announce new text. Block these for now to avoid double-reporting of
		text changes.
		@note: In the longer term, NVDA should leverage these events in place
		of the current LiveText strategy, as performance will likely be
		significantly improved and #11002 can be completely mitigated.
		"""
		log.debugWarning(f"Notification event blocked to avoid double-report: {kwargs}")

def findExtraOverlayClasses(obj, clsList):
	if obj.UIAAutomationId == "Text Area":
		clsList.append(WinConsoleUIA)
	elif obj.UIAAutomationId == "Console Window":
		clsList.append(consoleUIAWindow)

class _DiffBasedWinTerminalUIA(EnhancedTermTypedCharSupport):
	"""
	An overlay class for Windows Terminal (wt.exe) that uses diffing to speak
	new text.
	"""

	def event_UIA_notification(self, **kwargs):
		"Block notification events when diffing to prevent double reporting."
		log.debugWarning(f"Notification event blocked to avoid double-report: {kwargs}")

class _NotificationsBasedWinTerminalUIA(UIA):
	"""
	An overlay class for Windows Terminal (wt.exe) that uses UIA notification
	events provided by the application to speak new text.
	"""

	#: Override the role, which is controlTypes.Role.STATICTEXT by default.
	role = controlTypes.Role.TERMINAL
	#: New line text is announced using UIA notification events
	announceNewLineText = False

	def event_UIA_notification(
			self,
			notificationKind: Optional[int] = None,
			notificationProcessing: Optional[int] = UIAHandler.NotificationProcessing_CurrentThenMostRecent,
			displayString: Optional[str] = None,
			activityId: Optional[str] = None
	):
		# Do not announce output from background terminals.
		if self.appModule != api.getFocusObject().appModule:
			return
		braille.handler.handleUpdate(self)
		# microsoft/terminal#12358: Automatic reading of terminal output
		# is provided by UIA notifications. If the user does not want
		# automatic reporting of dynamic output, suppress this notification.
		if not config.conf["presentation"]["reportDynamicContentChanges"]:
			return
		for line in displayString.splitlines():
			if line and not line.isspace():  # Don't say "blank" during autoread
				speech.speakText(line)

def __getattr__(attrName: str) -> Any:
	"""Module level `__getattr__` used to preserve backward compatibility."""
	if attrName == "WinTerminalUIA" and NVDAState._allowDeprecatedAPI():
		log.warning(
			"WinTerminalUIA is deprecated. "
			"Instead use _DiffBasedWinTerminalUIA or _NotificationsBasedWinTerminalUIA"
		)
		return (
			_NotificationsBasedWinTerminalUIA
			if _shouldUseWindowsTerminalNotifications()
			else _DiffBasedWinTerminalUIA
		)
	raise AttributeError(f"module {repr(__name__)} has no attribute {repr(attrName)}")


import string
alphabet = list(string.ascii_lowercase)

def place(letter):
    return alphabet.index(letter)
def letter(place):
    return alphabet[place % 26]

tofind = "NorthPole"

with open("4.txt") as file:
    content = file.read().split("\n")

for x in content:
    x = x.split("[")[0]
    x = x.split("-")
    sectorID = int(x[-1])
    y = ""
    for i in range(len(x)-1):
        y += x[i]
        y += " "

    z = ""
    for l in y:
        if l == " ":
            z += " "
        else:
            z += letter(place(l) + sectorID)

    # print(z)
    if tofind.lower() in z:
        print(sectorID)     # 324


def bubble_sort(t):
    if len(t) < 2:
        return

    for idx in range(len(t)):
        done = True
        for jdx in range(1, len(t) - idx):
            if t[jdx] < t[jdx - 1]:
                t[jdx], t[jdx - 1] = t[jdx - 1], t[jdx]
                done = False
        if done:
            return

t = [8, 2, 4, 1, 3]
#t = [4, 3]
bubble_sort(t)
print(t)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from flask import Flask, abort, request, jsonify
from flask_script import Manager
from flask_cors import CORS
import os
import logging
import boto3
from botocore.exceptions import ClientError
from ipfs import ipfs_hash
import urllib
import time
from log import init_log

app = Flask(__name__)
CORS(app)
app.config.from_pyfile('config.py')

manager = Manager(app)

init_log(app.config['LOGDNA_KEY'])
log = logging.getLogger('logdna')

global file_count
file_count = int(app.config['INIT_FILE_COUNT'])

def upload_file(file, bucket='dfile', object_name=None):
    """Upload a file to an S3 bucket

    :param file: File to upload
    :param bucket: Bucket to upload to
    :param object_name: S3 object name. If not specified then file_name is used
    :return: True if file was uploaded, else False
    """

    # Upload the file
    try:
        start1 = time.time()
        file_name = file.filename
        log.info('content_type: {}'.format(file.content_type))
        bytes = file.read()
        hash = ipfs_hash(bytes)
        log.info("ipfs hash: {0:.2f}s".format(time.time() - start1))
        name, ext = os.path.splitext(file_name)
        log.info('hash: {}, ext: {}'.format(hash, ext))

        # If S3 object_name was not specified, use ipfs hash
        if object_name is None:
            object_name = '{}{}'.format(hash, ext)

        session = boto3.session.Session()
        client = session.client('s3',
                                region_name=app.config['S3_REGION'],
                                endpoint_url=app.config['S3_ENDPOINT'],
                                aws_access_key_id=app.config['S3_KEY'],
                                aws_secret_access_key=app.config['S3_SECRET'])
        file.seek(0, 0)
        # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/customizations/s3.html#boto3.s3.transfer.S3Transfer.ALLOWED_UPLOAD_ARGS
        # ExtraArgs:['ACL', 'CacheControl', 'ContentDisposition', 'ContentEncoding', 'ContentLanguage', 'ContentType', 'Expires', 'GrantFullControl',
        # 'GrantRead', 'GrantReadACP', 'GrantWriteACP', 'Metadata', 'RequestPayer', 'ServerSideEncryption', 'StorageClass', 'SSECustomerAlgorithm',
        # 'SSECustomerKey', 'SSECustomerKeyMD5', 'SSEKMSKeyId', 'WebsiteRedirectLocation']
        extra_args = {'ACL': 'public-read', 'ContentType': file.content_type, 'Metadata': {'name': urllib.parse.quote(file_name, safe='')}}
        start2 = time.time()
        response = client.upload_fileobj(file, bucket, object_name, ExtraArgs=extra_args)
        log.info("s3 upload: {0:.2f}s".format(time.time() - start2))
        log.info("total: {0:.2f}s".format(time.time() - start1))
        # log.info('res: {}'.format(response))
        return {'hash': object_name}
    except ClientError as e:
        log.exception("S3 Client Error! file name:{0}, exception:{1}".format(file.filename, str(e)))
        return {'hash': '', 'error': "S3 Client Error! \n"}
    except Exception as e:
        log.exception("S3 Upload Error! file name:{0}, exception:{1}".format(file.filename, str(e)))
        return {'hash': '', 'error': "S3 Upload Error! \n"}

@app.route("/", methods=["POST", "PUT"])
@app.route("/up", methods=["POST", "PUT"])
def up():
    try:
        if "file" in request.files:
            file = request.files["file"]

            log.info("file name: {}".format(file.filename), {'app': 'dfile-up-req'})

            res = upload_file(file)

            log.info("upload res: {}".format(res), {'app': 'dfile-up-res'})
            if not res['hash']:
                return res['error']
            global file_count
            file_count += 1
            url = app.config['DOMAIN'] + '/' + str(res['hash'])
            return url

        abort(400)

    except Exception as e:
        log.exception("Upload Error! exception:{}".format(str(e)))
        return "Upload Error! \n", 503

@app.route("/stat", methods=["GET"])
def stat():
    try:
        return jsonify({'file_count': file_count})

    except Exception as e:
        log.exception("Upload Error! exception:{}".format(str(e)))
        return "Upload Error! \n", 503

def legal():
    return "451 Unavailable For Legal Reasons\n", 451

@manager.command
def debug():
    app.run(debug=True, port=5000, host="0.0.0.0")
    log.info("DFile is debugging.")

if __name__ == "__main__":
    manager.run()
    log.info("DFile is running.")


import numpy as np

def hms2dec(h, m, s):
  return 15 * (h + m/60 + s/3600)

def dms2dec(deg, arcmin, arcsec):
  val = abs(deg) + arcmin/60 + arcsec/3600

  if deg < 0:
    val = -1 * val

  return val

# haversine
def angular_dist(r1, d1, r2, d2):
  r1 = np.radians(r1)
  d1 = np.radians(d1)
  r2 = np.radians(r2)
  d2 = np.radians(d2)

  a = np.sin(np.abs(d1 - d2)/2)**2
  b = np.cos(d1)*np.cos(d2)*np.sin(np.abs(r1 - r2)/2)**2

  return np.degrees(2*np.arcsin(np.sqrt(a + b)))

def import_super():
  idx = 1
  ret = []
  data = np.loadtxt('crossmatch_data/super.csv', delimiter=',', skiprows=1, usecols=[0, 1])

  for i in data:
    coords = (idx, i[0], i[1])
    ret.append(coords)
    idx += 1

  return ret

def import_bss():
  idx = 1
  ret = []
  data = np.loadtxt('crossmatch_data/bss.dat', usecols=range(1, 7))
  for i in data:
    coords = (idx, hms2dec(i[0], i[1], i[2]), dms2dec(i[3], i[4], i[5]))
    ret.append(coords)
    idx += 1

  return ret

def find_closest(cat, ra, dec):
  smallest = None
  best = None

  for i in cat:
    dist = angular_dist(ra, dec, i[1], i[2])
    if smallest == None or dist < smallest:
      smallest = dist
      best = (i[0], dist)

  return best

def crossmatch(cat1, cat2, max_dist):
  match = []
  nomatch = []

  # small optimization to avoid doing it for dup values later
  cat1 = np.radians(cat1)
  cat2 = np.radians(cat2)

  for i in cat1:
    best, dist = find_closest(cat2, i[1], i[2])

    if dist < max_dist:
      match.append( (i[0], best, dist) )

    else:
      nomatch.append(i[0])

  return (match, nomatch)

# You can use this to test your function.
# Any code inside this `if` statement will be ignored by the automarker.
if __name__ == '__main__':
  bss_cat = import_bss()
  super_cat = import_super()

  # First example in the question
  max_dist = 40/3600
  matches, no_matches = crossmatch(bss_cat, super_cat, max_dist)
  print(matches[:3])
  print(no_matches[:3])
  print(len(no_matches))

  # Second example in the question
  max_dist = 5/3600
  matches, no_matches = crossmatch(bss_cat, super_cat, max_dist)
  print(matches[:3])
  print(no_matches[:3])
  print(len(no_matches))


# -*- coding: utf-8 -*-
import os
import sys
import time
import json
from contextlib import contextmanager

import requests

from covador.compat import bstr
from . import helpers

@contextmanager
def server(covfile, module_name, append_coverage=False):
    pid = os.fork()
    if not pid:
        import coverage
        cov = coverage.Coverage(covfile, source=['covador'])
        cov._auto_load = append_coverage
        cov.start()
        print('Server starting...')
        try:
            __import__(module_name)
            module = sys.modules[module_name]
            module.main()
            print('Server stopped')
        except:
            import traceback
            traceback.print_exc()
        sys.stdout.flush()
        sys.stderr.flush()
        cov.stop()
        cov.save()
        os._exit(0)

    for _ in range(50):
        try:
            resp = requests.get('http://127.0.0.1:5000/status/', timeout=2)
            resp.content
        except:
            time.sleep(0.1)
        else:
            break
    else:
        raise Exception('Server did not start')

    try:
        yield
    finally:
        os.kill(pid, 2)
        wait_till = time.time() + 10
        killed = False
        while time.time() < wait_till:
            if os.waitpid(pid, os.WNOHANG) == (0, 0):
                time.sleep(0.3)
                os.kill(pid, 2)
            else:
                killed = True
                break

        if not killed:
            print('Server did not stoped on SIGINT, sending SIGKILL')
            os.kill(pid, 9)

def do_tests():
    # qs
    resp = requests.get('http://127.0.0.1:5000/qs/?boo=boo', timeout=2)
    assert resp.content == b'boo'

    # form
    resp = requests.post('http://127.0.0.1:5000/form/', timeout=2,
                         data={'p1': bstr(u'буу', 'utf-8'), 'p2': 10})
    assert resp.content == bstr(u'буу.10', 'utf-8')

    resp = requests.post('http://127.0.0.1:5000/form/', timeout=2,
                         data='p1=boo&p2=10')
    assert resp.status_code == 400
    assert resp.json() == {'details': {'p1': 'Required item',
                                       'p2': 'Required item'},
                           'error': 'bad-request'}

    # mform
    resp = requests.post('http://127.0.0.1:5000/form/', timeout=2,
                         data=helpers.mform,
                         headers={'Content-Type': helpers.mct})
    assert resp.content == bstr(u'буу.10', 'utf-8')

    # params
    resp = requests.post('http://127.0.0.1:5000/params/', timeout=2,
                         params={'p2': 10}, data={'p1': 'boo'})
    assert resp.content == b'boo.10'

    # args
    resp = requests.get('http://127.0.0.1:5000/args/boo/', timeout=2)
    assert resp.content == b'boo'

    # error
    resp = requests.get('http://127.0.0.1:5000/qs/', timeout=2)
    assert resp.status_code == 400
    assert resp.json() == {'details': {'boo': 'Required item'},
                           'error': 'bad-request'}

    # json body
    data = {'boo': 'утф'}
    resp = requests.post('http://127.0.0.1:5000/json/', timeout=2, json=data)
    assert resp.content == bstr(u'утф', 'utf-8')

    resp = requests.post('http://127.0.0.1:5000/json/', timeout=2,
                         data=json.dumps(data))
    assert resp.status_code == 400
    assert resp.json() == {'details': {'boo': 'Required item'},
                           'error': 'bad-request'}

def test_flask():
    with server('flask.cov', 'integration.flask_server'):
        do_tests()

def test_tornado():
    with server('tornado.cov', 'integration.tornado_server'):
        do_tests()

def test_django():
    with server('django.cov', 'integration.django_server'):
        do_tests()

    with server('django.cov', 'integration.django_cbv_server', True):
        do_tests()

def test_aiohttp_async():
    with server('aiohttp_async.cov', 'integration.aiohttp_server'):
        do_tests()

    with server('aiohttp_async.cov', 'integration.aiohttp_cbv_server', True):
        do_tests()

def test_aiohttp_yield():
    with server('aiohttp_yield.cov', 'integration.aiohttp_yield_server'):
        do_tests()

def test_sanic():
    with server('sanic.cov', 'integration.sanic_server'):
        do_tests()

        resp = requests.get('http://127.0.0.1:5000/qs-multi/?boo=boo&boo=foo',
                            timeout=2)
        assert resp.content == b'boo,foo'


# split trex bed files, reformat correctly in order to re-aligned
# build a uniq identifier for each motif
import sys
tr={}
prefix = sys.argv[2] # where to put all fasta files

# reading bed file
with open (sys.argv[1], 'r' ) as bedfile:
    for line in bedfile:
        if line.startswith('#'):
            continue
        fld = line.strip().split()
        gid, aln = (fld[0], fld[5])
        if gid not in tr:
            tr[gid] = [aln]
        else:
            tr[gid].append(aln)
# dump each tr in a separate fasta file
for gid in tr.keys():
    trs=tr[gid]
    for i,t in enumerate(trs):
        # for each TR in gene gid
        outfn = 'TR%d_%s.fasta' % (i,gid)
        fd = open (prefix+"/" +outfn,'w')
        motifs = t.split(',')
        # for each motif in TR
        for pos, m in enumerate(motifs):
            m = m.translate(None, '-')
            head = '>motif_%d_TR%d_%s\n' % (pos,i, gid)
            fd.write(head)
            fd.write(m+'\n')
        fd.close()


"""main"""
def main():
    """main"""
    txt = input()
    alpha = [i for i in txt if i.isalpha()]
    tmp, digit, get, keep = [], [], "", ""
    for i in txt:
        if not i.isdigit():
            tmp.append(get)
            get = ""
        get += i
    for i in tmp:
        for j in i:
            if j.isdigit():
                keep += j
        digit.append(keep)
        keep = ""
    print(*list(map(lambda txt, num: txt * int(num), alpha, digit)), sep="")

main()


# Objects which are divisible, ie we can take fraction
import pprint
def knapsack_divisible(bag_wt,wt_profit_dict):
    import collections
    profit_per_wt_dict = {}
    for obj,value_tup in wt_profit_dict.items():
        profit_per_wt_dict[obj] = round(value_tup[1]/value_tup[0],2)
    profit_per_wt_dict = collections.OrderedDict(sorted\
        (profit_per_wt_dict.items(), key=lambda x:x[1],reverse=True))
    knapsack_dict = {}
    profit = 0
    for obj, kg_price in profit_per_wt_dict.items():
        if bag_wt <= 0 :
            break
        else:
            wt = wt_profit_dict[obj][0]
            if wt > bag_wt:
                wt = bag_wt
            knapsack_dict[obj] = wt
            profit += kg_price*wt
            bag_wt -= wt
    return knapsack_dict, profit

obj_wt_profit = {'A':(2,10),'B':(3,5),'C':(5,15),
                'D':(7,7),'E':(1,6),'F':(4,18),'G':(1,3)}
#print(knapsack_divisible(15,obj_wt_profit))

# dp by tabulation method
def knapsack(bag_wt, wt_profit_dict):
    # dp table, width - bag wt from 0,
    # height - from 0 to len(list)
    # dp table is filled with profit values
    wt_profit_list = sorted(wt_profit_dict.items(),key=lambda x: x[1][0])
    wt_profit_list.insert(0,(0,(0,0)))
    dp_dict ={}
    # for profit=0, bag_wt=0
    for col in range(bag_wt+1):
        dp_dict[(0,col)]=0
    # when bag_wt=0, profit=0
    for row in range(len(wt_profit_list)):
        dp_dict[(row,0)] = 0
    # table: height=i, width = bag_wt starts from 0
    for row in range(1,len(wt_profit_list)):
        wt,profit = wt_profit_list[row][1]
        for b_wt in range(bag_wt+1):
            if wt > b_wt:
            # just copy the above value of the table
                dp_dict[(row,b_wt)] = dp_dict[(row-1,b_wt)]
            else:
                dp_dict[(row,b_wt)] = max(dp_dict[(row-1,b_wt)],
                # in the previous row bag_wt-wt of object + profit
                    dp_dict[(row-1, b_wt-wt)] + profit)
    max_profit = dp_dict[len(wt_profit_list)-1,bag_wt]
    find = max_profit
    knapsack_list = []
    # if the find element is from the previous row,
    # then skip current row
    for row in range(len(wt_profit_list)-1,0,-1):
        find_status = False
        # check whether the element is in the current row
        for col in range(bag_wt+1):
            if find == dp_dict[(row,col)]:
                find_status = True
                break
        # check whether the element is in the previous row
        for col in range(bag_wt+1):
            if find == dp_dict[(row-1,col)]:
                find_status = False
                break
        # find in which row the element is first appears
        if find_status:
            find -= wt_profit_list[row][1][1]
            knapsack_list.append(wt_profit_list[row][0])
    return max_profit,knapsack_list
    #return max_profit

obj_wt_profit_1 = {'A':(2,1),'B':(3,2),'C':(4,5),'D':(5,6)}
#print(knapsack(15,obj_wt_profit))
#print(knapsack(8,obj_wt_profit_1))

#TODO
# This wont work if the profit is not in the sorted form
# same as that of wt.
def knapsack_other(bag_wt, wt_profit_dict):
    # dp table, width - bag wt from 0,
    # height - from 0 to len(list)
    # dp table is filled with profit values
    wt_profit_list = sorted(wt_profit_dict.items(),key=lambda x: x[1][0])
    wt_profit_list.insert(0,(0,(0,0)))
    dp_dict ={}
    # for profit=0, bag_wt=0
    for col in range(bag_wt+1):
        dp_dict[(0,col)]=0
    # when bag_wt=0, profit=0
    for row in range(len(wt_profit_list)):
        dp_dict[(row,0)] = 0
    # table: height=i, width = bag_wt starts from 0
    for row in range(1,len(wt_profit_list)):
        wt,profit = wt_profit_list[row][1]
        track = 0
        for b_wt in range(bag_wt+1):
            check_wt,check_profit = wt_profit_list[track][1]
            if wt > b_wt:
            # just copy the above value of the table
                dp_dict[(row,b_wt)] = dp_dict[(row-1,b_wt)]
            else:
                if wt+check_wt <= b_wt and track<row:
                    dp_dict[(row,b_wt)] = profit + check_profit
                    track +=1
                else:
                    dp_dict[(row,b_wt)] = dp_dict[(row,b_wt-1)]
    max_profit = dp_dict[len(wt_profit_list)-1,bag_wt]
    return max_profit

def knapsack_set(bag_wt,wt_profit_dict):
    obj_wt_profit_list = sorted(wt_profit_dict.items(),key=lambda x: x[1][0])
    import collections
    import copy
    #list_dict = collections.defaultdict(list)
    list_dict= {'list_0':[(0,0)]}

    for index in range(len(obj_wt_profit_list)):
        wt_obj,profit_obj = obj_wt_profit_list[index][1]
        temp_list = []
        for wt_temp, profit_temp in list_dict[f'list_{index}']:
            temp_list.append((wt_obj+wt_temp,profit_obj+profit_temp))

        list_dict[f'list_{index+1}'] = copy.deepcopy(list_dict[f'list_{index}'])
        p_wt,p_profit = list_dict[f'list_{index+1}'][-1]
        for wt, profit in temp_list:
            if wt > p_wt and wt<=bag_wt:
                list_dict[f'list_{index+1}'].append((wt,profit))
                p_wt,p_profit = wt, profit
            else:
                if profit > p_profit and wt<=bag_wt:
                    list_dict[f'list_{index+1}'].pop()
                    list_dict[f'list_{index+1}'].append((wt,profit))
                    p_wt,p_profit = wt, profit
                else:
                    continue
    max_profit = list_dict[f'list_{len(wt_profit_dict)}'][-1][1]
    find = list_dict[f'list_{len(wt_profit_dict)}'][-1]
    knapsack_list = []
    # if the find (wt,profit) is from the previous list,
    # then skip current list

    # list_dict index and obj_wt_profit_list index are different
    for index in range(len(wt_profit_dict)-1,-1,-1):
        find_status = False
        # check whether the element is in the current list
        if find in list_dict[f'list_{index+1}']:
            find_status = True
        # check whether the element is in the previous row
        if find in list_dict[f'list_{index}']:
            find_status = False
        # find in which row the element is first appears
        if find_status:
            find = (find[0]-obj_wt_profit_list[index][1][0],\
                find[1]-obj_wt_profit_list[index][1][1])
            knapsack_list.append(obj_wt_profit_list[index][0])
    #
    return max_profit,knapsack_list
#print(knapsack_set(15,obj_wt_profit))
#print(knapsack(15,obj_wt_profit))

def generate_dict(num):
    import random
    char = ['A','B','C','D','E','F','G','H','I','J','K','L','M',
            'N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
    d = {}
    for i in range(num):
        n = i
        char_selection = []
        while True:
            x,y=divmod(n,26)
            char_selection.append(y)
            if x==0:
                break
            elif x<26:
                char_selection.append(x-1)
                break
            else:
                n=x
        c = ''
        for i in char_selection:
            c = char[i]+c
        d[c] = (random.randint(1,50),random.randint(10,100))
        #val = random.randint(1,50)
        #d[c] = (val, 2*val)
    # dict with profit increases with weight
    dd = {}
    p_wt,p_profit = 1,1
    i = 1
    while len(dd) < num:
        wt,profit = random.randint(p_wt,p_wt * 2), random.randint(p_profit*2,p_profit*3)
        if wt > p_wt and profit > p_profit:
            dd[i] = (wt,profit)
            i +=1
            p_wt, p_profit = wt, profit
    return dd
#print(generate_dict(5))

import unittest
import random
from hypothesis import Verbosity
class Test_knapsack(unittest.TestCase):
    known_values = [(15,{'A':(2,10),'B':(3,5),'C':(5,15),
                'D':(7,7),'E':(1,6),'F':(4,18),'G':(1,3)}),
                (8,{'A':(2,1),'B':(3,2),'C':(4,5),'D':(5,6)})]

    true_value = {'A':(2,1),'B':(3,2),'C':(4,5),'D':(5,6)}

    def test_known_values(self):
        for wt, d in self.known_values:
            self.assertEqual(knapsack(wt,d),knapsack_set(wt,d))
    def test_known_values_1(self):
        for wt, d in self.known_values:
            self.assertEqual(knapsack(wt,d)[0],knapsack_other(wt,d))
    def test_known_values_2(self):
        for num in range(5,100):
            d = generate_dict(num)
            result = knapsack(random.randint(1,100),d)
            self.assertEqual(type(result),tuple)
    def test_true_value(self):
        self.assertEqual(knapsack(8,self.true_value)[0],knapsack_other(8,self.true_value))

    def test_knapsack_knapsackSet(self):
        for num in range(5,100):
            d = generate_dict(num)
            w = random.randint(10,100)
            self.assertEqual(knapsack(w,d),knapsack_set(w,d))


def getdata():
    empId = input("Enter Emp.Id : ")
    empName = input("Enter Name : ")
    emailId = input("Enter Email.Id : ")
    dept = input("Enter Department : ")
    designation = input("Enter Designation : ")
    basic = int(input("Enter BASIC salary : "))
    DA = int(input("Enter DA : "))
    HRA = int(input("Enter HRA : "))

    file1 = open('Emp_info.txt','a')
    file1.write(empId + " " + empName + " " +" "+ emailId + "\n")
    file1.close()

    file2 = open('Department_info.txt','a')
    file2.write(empId + " " + dept + " " + designation + "\n")
    file2.close()

    file3 = open('Empsal.txt','a')
    file3.write(empId + " " + str(basic) + " " + str(DA) + " " + str(HRA) + "\n")
    file3.close

def searchdata():
    key = input("Enter Name to search : ")
    file1 = open('Emp_info.txt','r')
    readlines = file1.readlines()
    for line in readlines:
        if key in line:
            list1 = line.split()

    empyoid = list1[0]
    file2 = open('Department_info.txt','r')
    readlines = file2.readlines()
    for line in readlines:
        if empyoid in line:
            list2 = line.split()

    file3 = open('Empsal.txt','r')
    readlines = file3.readlines()
    for line in readlines:
        if empyoid in line:
            list3 = line.split()
    print("Employee details : ")
    print(f'{"Emp.Id":^20}{"Name":^20}{"Email.Id":^20}{"Department":^20}{"Designation":^20}{"Basic salary":^20}{"DA":^20}{"HRA":^20}')
    print(f'{list1[0]:^20}{list1[1]:^20}{list1[2]:^20}{list2[1]:^20}{list2[2]:^20}{list3[1]:^20}{list3[2]:^20}{list3[3]:^20}')

flag = True
print("==========MENU============")
print("1.Enter data\n2.Search data\n3.Exit")
print("==========================")
while (flag):
    choice = int(input("\nEnter choice : "))
    if choice == 1:
        getdata()
    elif choice == 2:
        searchdata()
    else:
        flag = False


from trading.get_account_info import get_all_stat, get_my_order, get_all_currency, get_all_securities, get_my_operations
from main import dp, bot
from aiogram.types import Message
from aiogram.dispatcher.filters import Text
from trading.get_securities import security_name_by_figi
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from trading.place_order import cancel_order
from config.personal_data import get_account_access

"""

    Здесь собраны все хэндлеры, которые отвечают за вывод информации о счёте

"""

"""

    Баланс

"""

@dp.message_handler(Text(contains="баланс", ignore_case=True))
async def get_balance(message: Message):
    currency_df = get_all_currency(message.from_user.id)

    await message.answer(f"💸Доступная валюта💸")

    text = ""

    for i in currency_df.index:

        if currency_df['exchange_rate'][i] != 0.0 and currency_df['exchange_rate'][i] != 1.0:
            text += (
                f"{currency_df['name'][i]}\n"
                f"{round(currency_df['sum'][i], 2)}{currency_df['sign'][i]} ({round(currency_df['sum_in_ruble'][i], 2)}₽)\n\n")
        else:
            text += (
                f"{currency_df['name'][i]}\n"
                f"{round(currency_df['sum'][i], 2)}{currency_df['sign'][i]}\n\n")

    if text:
        await message.answer(text=text)
    else:
        await message.answer(text="У Вас нет средств!")

"""

    Бумаги

"""

@dp.message_handler(Text(contains="бумаги", ignore_case=True))
async def get_share(message: Message):
    security_df = get_all_securities(message.from_user.id)

    empty_portfolio = True
    await message.answer(f"💼Ценные бумаги в портфеле💼")

    for i in security_df.index:

        inst = ""

        if security_df['instrument'][i] == "share":
            inst = "Акции"
            empty_portfolio = False

        elif security_df['instrument'][i] == "bond":
            inst = "Бонды"
            empty_portfolio = False

        elif security_df['instrument'][i] == "etf":
            inst = "ETF"
            empty_portfolio = False

        elif security_df['instrument'][i] == "currency":
            continue

        elif security_df['instrument'][i] == "future":
            inst = "Фьючерсы"
            empty_portfolio = False

        if security_df['exp_yield'][i] >= 0:
            exp_yield = f"Ожидаемый доход: {round(security_df['exp_yield'][i], 2)}₽"
        else:
            exp_yield = f"Ожидаемая убыль: {round(security_df['exp_yield'][i], 2)}₽"

        await message.answer(
            f"🧾{inst} {security_df['security_name'][i]}\n"
            f"FIGI: {security_df['figi'][i]}\n\n"
            f"Лотов: {int(security_df['lots'][i])}\n"
            f"Всего: {round(security_df['quantity'][i], 2)}\n\n"
            f"Средняя цена: {security_df['average_price'][i]}{security_df['currency_sign'][i]}\n"
            f"Средняя цена FIFO: {security_df['average_price_fifo'][i]}{security_df['currency_sign'][i]}\n"
            f"Текущая цена: {round(security_df['current_price'][i], 6)}{security_df['currency_sign'][i]}\n\n"
            f"НКД: {security_df['nkd'][i]}{security_df['currency_sign'][i]}\n"
            f"{exp_yield}{security_df['currency_sign'][i]}\n"
        )

    if empty_portfolio:
        await message.answer(f"У Вас нет ценных бумаг в портфеле!")

"""

    Статистика по счёту

"""

@dp.message_handler(Text(contains="статистика", ignore_case=True))
async def get_stat(message: Message):
    await message.answer(f"📈Статистика по счёту📉 ")

    stat = get_all_stat(message.from_user.id)

    # Посчитаем сумму всех бумаг
    sum = stat['sum_total'][0]

    # Переведём доход/убыток из процентов в рубли
    dif = round(sum - (sum / (100 + stat['exp_yield'][0])) * 100, 2)

    if dif >= 0:
        dif_text = f"Прибыль: {dif}₽ ({stat['exp_yield'][0]}%)"
    else:
        dif_text = f"Убыль: {dif}₽ ({stat['exp_yield'][0]}%)"

    await message.answer(
        f"Акции на сумму: {stat['sum_shares'][0]}₽\n"
        f"Бонды на сумму: {stat['sum_bonds'][0]}₽\n"
        f"ETF на сумму: {stat['sum_etf'][0]}₽\n"
        f"Валюта на сумму: {stat['sum_curr'][0]}₽\n"
        f"Фьючерсы на сумму: {stat['sum_fut'][0]}₽\n\n"
        f"Итого: {round(sum, 2)}₽\n"
        f"{dif_text}\n"

    )

'''
    Открытые ордера
'''

@dp.message_handler(Text(contains="ордер", ignore_case=True))
async def get_orders(message: Message):
    order_df = get_my_order(message.from_user.id)

    await message.answer(f"📋Открытые ордера📋")

    no_orders = True

    for i in order_df.index:

        no_orders = False

        cancel_order_keyboard = InlineKeyboardMarkup()
        if get_account_access(user_id=message.from_user.id) == 1:
            cancel_order_keyboard.add(InlineKeyboardButton(text=f"Отменить ордер", callback_data=f"cancel_order:{order_df['order_id'][i]}"))

        if order_df['direction'][i] == 2:
            direction = "Продажа"
        else:
            direction = "Покупка"

        await message.answer(
            f"✅{direction} бумаг {security_name_by_figi(order_df['figi'][i], message.from_user.id)}\n"
            f"Открыт: {order_df['order_date'][i]}\n\n"
            f"ID: {order_df['order_id'][i]}\n\n"
            f"FIGI: {order_df['figi'][i]}\n\n"
            f"Лотов запрошено: {order_df['lots_req'][i]}\n"
            f"Лотов исполнено: {order_df['lots_ex'][i]}\n\n"
            f"Сумма запрошена: {order_df['sum_req'][i]}{order_df['currency_sign'][i]}\n"
            f"Сумма исполнено: {order_df['sum_ex'][i]}{order_df['currency_sign'][i]}\n\n"
            f"Цена одной акции: {round(order_df['price_one'][i], 6)}{order_df['currency_sign'][i]}\n\n"
            f"Комиссия: {round(order_df['commission'][i], 3)}{order_df['currency_sign'][i]}\n"
            f"Комиссия сервиса: {round(order_df['serv_commission'][i], 3)}{order_df['currency_sign'][i]}\n\n"
            f"Итого: {order_df['sum_total'][i]}{order_df['currency_sign'][i]}\n",
            reply_markup=cancel_order_keyboard
        )
    if no_orders:
        await message.answer(text="У Вас нет открытых ордеров!")

'''
    Закрытие ордера по id
'''

@dp.callback_query_handler(lambda c: c.data and c.data.startswith('cancel_order'))
async def close_order(callback_query):
    data = callback_query.data.split(":")
    order_id = data[1]

    await cancel_order(order_id=order_id, user_id=callback_query.from_user.id)

    await bot.edit_message_text(chat_id=callback_query.from_user.id, message_id=callback_query.message.message_id,
                                text="❌Ордер отменён❌")

'''
    Операции
'''

@dp.message_handler(Text(contains="операции", ignore_case=True))
async def get_operations(message: Message):

    try:
        operations = get_my_operations(user_id=message.from_user.id)
    except:
        await message.answer("Ошибка!")

    else:
        if operations:
            await message.answer(f"Ваши операции:")

            with open(f"img/operations/all_operations_{message.from_user.id}.png", "rb") as operations_img:
                await bot.send_photo(chat_id=message.from_user.id, photo=operations_img)

        else:
            await message.answer(f"У Вас пока не было операций!")


from flask import Flask, jsonify, request, render_template
import requests
import pymongo
import time

app = Flask(__name__)

client = pymongo.MongoClient()

mydb = client['final']
webcol = mydb['webcol']

# Get document id in string format
def get_data(data):
    data['_id'] = str(data['_id'])
    return data

# Get last mongo collection document
def get_last_doc(col):
    try:
        last_doc = col.find().sort([('_id', -1)]).limit(1)[0]
    except:
        last_doc = 'error'

    return last_doc

# Get morse code
def get_morse(decimal):

    total = ''
    for num in decimal:
        if num == 0:
            morse = '11111'
        elif num == 1:
            morse = '01111'
        elif num == 2:
            morse = '00111'
        elif num == 3:
            morse = '00011'
        elif num == 4:
            morse = '00001'
        elif num == 5:
            morse = '00000'
        elif num == 6:
            morse = '10000'
        elif num == 7:
            morse = '11000'
        elif num == 8:
            morse = '11100'
        else:
            morse = '11110'

        total = total + morse

    return total

# receive get action from pi and return response based on form page
@app.route("/", methods=['GET', 'POST'])
def index():
    if(request.method == 'GET'):
        # Wait until form() updates webcol
        aux_doc = get_last_doc(webcol)
        while True:
            last_doc = get_last_doc(webcol)
            try:
                if last_doc['_id'] != aux_doc['_id']:
                    break
            except:
                print('cannot get last_doc')

        last_doc = get_last_doc(webcol)
        decimal = last_doc['decimal']
        morse = get_morse(decimal)
        return jsonify({'morse':morse})

# receive post action from html page, insert to db and return response
@app.route("/form", methods=['GET', 'POST'])
def form():

    if(request.method == 'POST'):
        # get and insert input into webcol
        webpost = request.form.get('inputval')
        #if len(webpost) > 10:
        #    last_webpost = 'input is longer than 10'
        #    return render_template('final.html', data=last_webpost)
        #elif webpost.isdigit():
        #    last_webpost = 'has letters'
        #    return render_template('final.html', data=last_webpost)

        webcol.insert_one({'decimal':webpost})
        # get last webcol document
        try:
            last_webpost = webcol.find().sort([('_id', -1)]).limit(1)[0]['decimal']
        except:
            last_webpost = 'error'
            print('cannot get last_webpost')

        return render_template('final.html', data=last_webpost)
    else:
        # get form with last_webpost
        try:
            last_webpost = webcol.find().sort([('_id', -1)]).limit(1)[0]['decimal']
        except:
            last_webpost = 'error'
            print('cannot get last_webpost')
        return render_template('final.html', data=last_webpost)

# query webcol-JSON
@app.route('/webson', methods=['GET'])
def get_webson():
    reg_data = [get_data(i) for i in webcol.find()]
    return jsonify(reg_data)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)


import random
from flask import Flask, render_template, jsonify

# Load quotes with authors from a file
with open("quotes.txt", "r") as file:
    quotes = [line.strip() for line in file]

# Flask web app to serve the HTML
app = Flask(__name__, template_folder="templates", static_folder="static")

# Function to get a random quote and author
def get_random_quote_with_author():
    random_quote = random.choice(quotes)
    quote, author = random_quote.split(" - ", 1)
    return quote, author

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/get_quote")
def get_quote():
    quote, author = get_random_quote_with_author()
    return jsonify({"quote": quote, "author": author})

if __name__ == "__main__":
    app.debug = True  # Enable debug mode
    app.run()


"""
Challenge: Given the triangle of consecutive odd numbers:

             1
          3     5
       7     9    11
   13    15    17    19
21    23    25    27    29
...
Calculate the row sums of this triangle from the row index (starting at index 1).
"""

#The solution can also be obtained by the mathematical insight which reveals the sum to be n**3.

def starting(i):  #Calculate first number of row recursively
	if i==1:
		return 1
	return starting(i-1)+(i-1)*2

def row_sum_odd_numbers(n):
    firstNumberInRow=starting(n) 	#Initalize the first number in the row
    rowSum=0  						#Initialize the rowSum

    for i in range(0,n):			#Add element for each number in row
    	rowSum+=firstNumberInRow+2*i

    return rowSum


import datetime
import os
import time
import uuid

import amri.utils.constants as utils_constants
from amri.usernode.google_stt import google_stt
from amri.usernode.google_tts import google_tts
from amri.utils import log_utils

audio_file_path = os.path.dirname(os.path.abspath(__file__))
audio_file_path = os.path.normpath(os.path.join(audio_file_path, 'output.mp3'))

def main():
    """
    Returns:
    --------
    subject_info : list
        List of subject parameter information; first entry in the list is timestamp
    """
    # Initialize Google TTS and Google STT
    google_stt_obj = google_stt()
    google_tts_obj = google_tts()

    text = 'Welcome, let us begin the self-administered M R exam.'
    log_utils.log(text)
    google_tts_obj.speak(text)

    text = '\nWhat is your last name?'
    log_utils.log(text)
    google_tts_obj.speak(text)
    last_name = google_stt_obj.listen()

    text = '\nWhat is your gender?'
    log_utils.log(text)
    google_tts_obj.speak(text)
    while True:
        gender = google_stt_obj.listen()
        gender = 'male' if gender == 'mail' else gender
        gender = 'male' if gender == 'men' else gender
        if gender != 'male' and gender != 'female' and gender != 'other':
            text = 'Sorry, I couldn\'t understand that, let us try again. What is your gender?'
            google_tts_obj.speak(text)
        else:
            break

    text = '\nWhat is your age?'
    log_utils.log(text)
    google_tts_obj.speak(text)
    while True:
        age = google_stt_obj.listen()
        if not age.isnumeric() or int(age) > 100 or int(age) < 1:
            text = 'Sorry, I couldn\'t understand that, let us try again. What is your age?'
            google_tts_obj.speak(text)
        else:
            break
    current_year = datetime.datetime.now().year
    dob = '1/1/{}'.format(current_year - int(age))

    text = '\nWhat is your height in centimeters?'
    log_utils.log(text)
    google_tts_obj.speak(text)
    while True:
        height_cms = google_stt_obj.listen()
        if not height_cms.isnumeric() or int(height_cms) < 121 or int(height_cms) > 213:
            text = 'Sorry, I couldn\'t understand that, let us try again. What is your height in centimeters?'
            google_tts_obj.speak(text)
        else:
            break

    text = '\nWhat is your weight in pounds?'
    log_utils.log(text)
    google_tts_obj.speak(text)
    while True:
        weight_lbs = google_stt_obj.listen()
        if not weight_lbs.isnumeric() or int(weight_lbs) < 88 or int(weight_lbs) > 286:
            text = 'Sorry, I couldn\'t understand that, let us try again. What is your weight in pounds?'
            google_tts_obj.speak(text)
        else:
            break

    text = '\nAlright. Now, please state your application.'
    log_utils.log(text)
    google_tts_obj.speak(text)
    application = google_stt_obj.listen()

    text = '\nHow many minutes would you like to spend on this exam?'
    log_utils.log(text)
    google_tts_obj.speak(text)
    while True:
        time_mins = google_stt_obj.listen()
        if ' ' in time_mins:
            time_mins = time_mins.split(' ')[0]
        if float(time_mins) < 0:
            text = 'Sorry, I couldn\'t understand that, let us try again. How many minutes would you like to spend on ' \
                   'this exam?'
            google_tts_obj.speak(text)
        else:
            time_mins = float(time_mins)
            break
    time_seconds = int(time_mins * 60)

    # Re-instantiate Google STT object
    del google_stt_obj
    text = '\nThank you. Now, please set yourself up in the scanner. When you are good to go, please say \'Start\'.'
    log_utils.log(text)
    google_tts_obj.speak(text)
    while True:
        try:
            google_stt_obj = google_stt()
            ready = google_stt_obj.listen(single_utterance=False)
        except Exception:
            log_utils.log(msg='.', endline='')
            del google_stt_obj
            continue
        if ready.lower() == 'start':
            break

    text = '\nAlright, we will begin momentarily...'
    log_utils.log(text)
    google_tts_obj.speak(text)

    os.remove(audio_file_path)

    patient_uuid = str(uuid.uuid4().int)
    patient_info = [time.time(), last_name, patient_uuid, dob, gender, height_cms, weight_lbs, application,
                    time_seconds]
    patient_info = dict(zip(utils_constants.PATIENT_PARAMS_KEYS, patient_info))

    del google_tts_obj
    return patient_info


import requests
from lxml import etree
from DataTools.tools import MysqlHelper

# 抓取微博找人下关键词搜索50页用户数据并存入数据库

def write_data(nickname, uid, kw):
    mysqlHelper = MysqlHelper('localhost', 'root', '123456', 'weibo_userinfo')
    mysqlHelper.connect()
    params = [nickname, uid, kw]
    sql = 'insert into User(nickname,uid,kw) values(%s,%s,%s) '
    count = mysqlHelper.insert(sql, params)
    if count > 0:
        print('成功写入数据库')

headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en',
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0',
}
# 设置关键词
kw = '创始人'

for page in range(1, 51):
    url = 'https://s.weibo.com/user?q=' + kw + '&Refer=weibo_user&page=' + str(page)

    response = requests.get(url, headers=headers)
    html = etree.HTML(response.content)
    user_list = html.xpath('//div[@id="pl_user_feedList"]//div[@class="card card-user-b s-pg16 s-brt1"]')
    for userinfo in user_list:
        userName = userinfo.xpath('.//div[@class="info"]//a[@class="name"]')[0].xpath('string(.)')
        userId = userinfo.xpath('.//div[@class="info"]//a[@class="s-btn-c"]/@uid')[0]
        print('用户昵称：', userName, '用户ID：', userId)

        count = write_data(userName, userId, kw)


'''
find the repeated items of a tuple
'''
import collections

# Method 1
# Convert to list and count the variables
tuple1 = (34, 45, 72, 18, 72, 92, 63, 72, 92, 18)

def ele_counter(tup):
    l1 = []
    for i in tup:
        if tup.count(i) > 1:
            if i in l1:
                pass
            else:
                l1.append(i)
    return l1

print(f'Repeated Elements in tuple1 - {ele_counter(tuple1)}')
print()

# Method- 2
tuple2 = [45, 72, 8, 'hyd', 45, True, 92, 72 ]
tuple3 = [True, 34, 'abc', 48, 24]

def rep_ele(tup):
    flag = False
    val = collections.Counter(tup)
    # print('val - ', val)
    unique_list = list(set(tup))
    # print(f'Unique list - {unique_list}')
    repeated_elements = []
    for i in unique_list:
        if val[i] >= 2:
            flag = True
            repeated_elements.append(i)
    if not flag:
        return 'Duplicates do not exist'
    return repeated_elements

print(f'Repeated elements in tuple2 - {rep_ele(tuple2)}')
print(f'Repeated elements in tuple3 - {rep_ele(tuple3)}')


import sys
import asyncio
import websockets
import json
from pytube import Playlist
from pytube import YouTube
import speedtest

WSS_HOST = "127.0.0.1"
WSS_PORT = 5678

# list of all topics
CONNECTION_SUCCEEDED = "CONNECTION_SUCCEEDED"
PLAYLIST_CONTENTS = "PLAYLIST_CONTENTS"
SEED_VIDEO_SIZE = 'SEED_VIDEO_SIZE'

# download progression status
DOWNLOAD_FAILED = "DOWNLOAD_FAILED"
DOWNLOAD_PROCESSING = "DOWNLOAD_PROCESSING"
DOWNLOAD_FINISHED = "DOWNLOAD_FINISHED"

args = sys.argv

speed_test = speedtest.Speedtest()

async def connection():
    async with websockets.connect("ws://%s:%d" % (WSS_HOST, WSS_PORT)) as websocket:
        await websocket.send(json.dumps({
            "topic": CONNECTION_SUCCEEDED,
            "value": "Connected successfully",
            "success": True
        }))

async def get_playlist_contents():
    async with websockets.connect("ws://%s:%d" % (WSS_HOST, WSS_PORT)) as websocket:
        try:
            playlist_link = args[2]
            playlist = Playlist(playlist_link)
            output = {
                "playlist_id": playlist.playlist_id,
                "playlist_url": playlist.playlist_url,
                "title": playlist.title,
                "videos": []
            }

            try:
                output["owner"] = playlist.owner
            except:
                output["owner"] = ""

            for video in playlist.videos:
                video_details = video.vid_info['videoDetails']
                # description contains not escaped characters
                del video_details["shortDescription"]
                output["videos"].append(video_details)
            await websocket.send(json.dumps({
                "topic": PLAYLIST_CONTENTS,
                "value": output,
                "success": True
            }, default=str))
        except:
            await websocket.send(json.dumps({
                "topic": PLAYLIST_CONTENTS,
                "value": "Failed to fetch playlist",
                "success": False
            }, default=str))

async def videos_seeding():
    async with websockets.connect("ws://%s:%d" % (WSS_HOST, WSS_PORT)) as websocket:
        try:
            videos_ids = json.loads(args[2])
            output = []
            for video_id in videos_ids:
                video = YouTube(f"https://youtube.com/watch?v={video_id}")
                # video_stream = video.streams.get_by_resolution('480p')
                # if video_stream == None:
                video_stream = video.streams.get_by_resolution('360p')
                if video_stream == None:
                    video_stream = video.streams.get_by_resolution('240p')
                video_size = video_stream.filesize
                download_url = video_stream.url
                expires_at = video_stream.expiration
                output.append({
                    "video_id": video_id,
                    "video_size": video_size,
                    "download_url": download_url,
                    "expires_at": expires_at
                })
            await websocket.send(json.dumps({
                "topic": SEED_VIDEO_SIZE,
                "value": output,
                "success": True
            }, default=str))
        except:
            await websocket.send(json.dumps({
                "topic": SEED_VIDEO_SIZE,
                "value": "Failed to seed the playlist videos",
                "success": False
            }, default=str))

def main():
    if len(args) > 1:
        if args[1] == PLAYLIST_CONTENTS:
            asyncio.run(get_playlist_contents())
        elif args[1] == SEED_VIDEO_SIZE:
            asyncio.run(videos_seeding())
    else:
        asyncio.run(connection())

main()


import base64
import subprocess
import time
from collections import defaultdict
from functools import partial
import os
from examples.useful_python.examples.spiders.utils.tools import MyAES

subprocess.Popen = partial(subprocess.Popen, encoding="utf-8")
import execjs
import requests

common_headers = {
    "Host": "match.yuanrenxue.com",
    "Connection": "keep-alive",
    "sec-ch-ua": '" Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"',
    "Accept": "application/json, text/javascript, */*; q=0.01",
    "X-Requested-With": "XMLHttpRequest",
    "sec-ch-ua-mobile": "?0",
    "User-Agent": "yuanrenxue.project",
    "sec-ch-ua-platform": "Windows",
    "Sec-Fetch-Site": "same-origin",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Dest": "empty",
    "Referer": "https://match.yuanrenxue.com/match/5",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh,zh-HK;q=0.9,ru;q=0.8,en;q=0.7,en-US;q=0.6,zh-CN;q=0.5",
}

common_cookies = {
    'sessionid': 'c9jqi35m9wa3k16kzd63h1jzsljy332f',
}
proxies = {
    'http': '127.0.0.1:8888',
    'https': '127.0.0.1:8888',
}

total = defaultdict(int)

session = requests.session()
session.headers = common_headers
session.cookies.update({
    "sessionid": "q9mzvylmp1p61z3xbkoyanr7cs3v20l9",
})
t = int(time.time() * 1000)
f = open("sdk.js", "r+", encoding='utf8', )
js_file = f.read()
js_compile = execjs.compile(js_file)
temp1 = js_compile.call("getCookie")
m = temp1[2]
t = temp1[0]
text = temp1[3]

# t = 1641287390884
sec_key = base64.b64encode(str(t).encode()).decode()[0:16]
print('sec_key', sec_key, t)
myAes = MyAES(sec_key)

print("加密文本:", text)
# text = '2c19c45fe56c91072c0eff540547b553,10b0395acfe3e66f0c14649561d1f3fe,6ab5e43cbee9e88be053f49d1f69ee83,e29ff5852aee529eff2f72473a097bc4,e10f123fa9ab8a2524512376eef09010'
aes_text = myAes.aes_encrypt_ecb(text, True)
print("加密后结果:", aes_text)
print(t)
session.cookies.update({
    "m": m,
    "RM4hZBv0dDon443M": aes_text,
})
print(session.cookies)
for i in range(1, 6):

    ret = session.get(
        url=f'https://match.yuanrenxue.com/api/match/5?page={i}&m={t}&f={int(t / 1000) * 1000}',
        proxies=proxies, verify=False)

    print(ret.text, 'olkk')
    json_content = ret.json()
    items = json_content.get("data")
    for item in items:
        total[str(item.get("value"))] += 1

total_list = []
for k, v in total.items():
    total_list.append((k, v))

total_list.sort(key=lambda x: x[0], reverse=True)
print(total_list)
total = 0
for i in range(0, 5):
    total += int(total_list[i][0])

print(total)


from jinja2 import Environment
import nltk
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer
from flask import Flask, request, render_template
import csv
import os

app = Flask(__name__, static_url_path='/static')

# Import the zip filter
env = Environment()
env.filters['zip'] = zip
def jinja2_enumerate(iterable):
    return enumerate(iterable)

def stemmer(documents):
    punc = ['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}', "%", "'", "``"]
    stpwrd = nltk.corpus.stopwords.words('english')
    stpwrd.extend(punc)
    porter = PorterStemmer()
    filtered_docs = []
    for doc in documents:
        tokens = word_tokenize(doc)
        tmp = ""
        for word in tokens:
            if word.lower() not in stpwrd:
                tmp += porter.stem(word.lower()) + " "
        filtered_docs.append(tmp)

    return (filtered_docs)

def stemmer_query(query):
    punc = ['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}', "%", "'", "``"]
    stpwrd = nltk.corpus.stopwords.words('english')
    stpwrd.extend(punc)
    stemmer = PorterStemmer()
    title_tokens = [stemmer.stem(token) for token in query.split() if token.lower() not in stpwrd]
    return(title_tokens)

def build_inverted_index(documents):
    inverted_index = {}
    filtered_docs = stemmer(documents)
    # Tokenize each document and count the term frequency
    for idx, doc in enumerate(filtered_docs):
        tokens = doc.split()
        term_freq = {}
        for token in tokens:
            if token in term_freq:
                term_freq[token] += 1
            else:
                term_freq[token] = 1
        for token, tf in term_freq.items():
            if token in inverted_index:
                inverted_index[token][idx] = tf
            else:
                inverted_index[token] = {idx: tf}
    return (inverted_index)

def process_query(query, inverted_index):
    qdocs = set()
    filtered_query = stemmer_query(query)
    df = {}
    tf_idf = {}
    for j in range(len(filtered_query)):
        if filtered_query[j] in inverted_index:
            qdocs = qdocs.union(inverted_index[filtered_query[j]].keys())
            print(qdocs)
            df[filtered_query[j]] = len(inverted_index[filtered_query[j]])
            N = len(qdocs)
            for i, tf in inverted_index[filtered_query[j]].items():
                if i in tf_idf:
                    tf_idf[i] += tf * (N / df[filtered_query[j]])
                else:
                    tf_idf[i] = tf * (N / df[filtered_query[j]])
    sorted_tf_idf = sorted(tf_idf, key=lambda k: tf_idf[k] * -1)
    return (sorted_tf_idf)

filename = "result_papers.csv"
script_dir = os.path.dirname(os.path.abspath(__file__))
csv_path = os.path.join(script_dir, filename)

with open(csv_path, mode="r") as csvfile:
    papers = []
    reader = csv.DictReader(csvfile)
    for row in reader:
        papers.append(row)

corpus = []
for paper in papers:
    f = ""
    f = paper['title'] + " " + paper['cov_authors'] +  " " + paper['non_cov_authors'] +  " " + paper['abstract'] + \
        paper['date']
    f = ((f.replace('[','')).replace(']','')).replace("'",'')
    corpus.append(f)

inverted_index = build_inverted_index(corpus)

@app.route("/")
def index():
    return render_template("home.html")

@app.route("/search", methods=['GET', 'POST'])

def search():
    # Get the query
    query = request.form.get("query")
    sorted_tf_idf = process_query(query, inverted_index)
    print(sorted_tf_idf)
    results = []
    for i in sorted_tf_idf:
        paper = {}
        paper = papers[i]
        results.append({
            "title": paper["title"],
            "title_link": paper["title_link"],
            "date": paper["date"],
            "authors_cov": paper["cov_authors"].replace('[','').replace(']','').split("'"),
            "author_links": paper["author_links"].replace('[','').replace(']','').split("'"),
            "authors_noncov": paper["non_cov_authors"].replace('[','').replace(']','').split("'"),
            "abstract": paper["abstract"]
        })

    return render_template("search.html", query=query, papers=results, zip = zip, enumerate = enumerate)

if __name__ == "__main__":
    app.run(debug=True)


import openpyxl

def delete_columns_with_specific_text(file_path, sheet_name, text_to_match):
    """
    删除Excel工作表中列名包含特定文本的列

    :param file_path: Excel文件的路径
    :param sheet_name: 要操作的工作表名称
    :param text_to_match: 要匹配的文本
    """
    # 加载工作簿和工作表
    workbook = openpyxl.load_workbook(file_path)
    sheet = workbook[sheet_name]

    # 获取第一行（标题行）的值
    header_row = list(sheet.iter_rows(min_row=1, max_row=1, values_only=True))[0]

    # 查找包含特定文本的列索引
    columns_to_delete = [index for index, value in enumerate(header_row, start=1) if value and text_to_match in str(value)]

    # 按降序排列列索引，以便在删除时保持正确的索引
    columns_to_delete.sort(reverse=True)

    for col_index in columns_to_delete:
        # 删除指定的列
        sheet.delete_cols(col_index)

    # 保存更改后的工作簿
    workbook.save(file_path)
    print(f"删除了{len(columns_to_delete)}列")

# # 示例用法
# file_path = "your_excel_file.xlsx"  # 你的Excel文件路径
# sheet_name = "Sheet1"  # 你要操作的工作表名称
# text_to_match = "example"  # 要匹配的文本

# delete_columns_with_specific_text(file_path, sheet_name, text_to_match)


# encoding: utf8

import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.utils.data as Data
import os
from models.RF import getRF
import const_rf as const

EPOCH = 30
BATCH_SIZE = 200
LR = 0.0005
if_use_gpu = 1
num_classes = const.num_classes

def load_data(fpath):
    train = np.load(fpath, allow_pickle=True).item()
    train_X, train_y = train['dataset'], train['label']

    return train_X, train_y

def adjust_learning_rate(optimizer, echo):
    lr = LR * (0.2 ** (echo / EPOCH))
    for para_group in optimizer.param_groups:
        para_group['lr'] = lr

def val(cnn, test_x, test_y, result_file, test_file):
    cnn.eval()
    test_result = open(test_file, 'w+')
    test_data = Data.TensorDataset(test_x, test_y)
    test_loader = Data.DataLoader(dataset=test_data, batch_size=BATCH_SIZE, shuffle=True)
    for step, (tr_x, tr_y) in enumerate(test_loader):
        test_output = cnn(tr_x)
        if if_use_gpu:
            test_output = test_output.cpu()
        pred_y, accuracy = get_result(test_output, tr_y)
        resultfile = open(result_file, 'w+')
        for i in range(len(tr_y)):
            resultfile.write(str(tr_y[i].numpy()) + ',' + str(pred_y[i]) + '\n')
        resultfile.close()
        test_result.write(str(accuracy) + '\n')
        print(accuracy)
    test_result.close()

def get_result(output, true_y):
    pred_y = torch.max(output, 1)[1].data.numpy().squeeze()
    accuracy = (pred_y == true_y.numpy()).sum().item() * 1.0 / float(true_y.size(0))
    return pred_y, accuracy

def control(feature_file):
    x, y = load_data(feature_file)
    cnn = getRF(num_classes)

    if if_use_gpu:
        cnn = cnn.cuda()

    optimizer = torch.optim.Adam(cnn.parameters(), lr=LR, weight_decay=0.001)
    loss_func = nn.CrossEntropyLoss()
    train_x = torch.unsqueeze(torch.from_numpy(x), dim=1).type(torch.FloatTensor)
    train_x = train_x.view(train_x.size(0), 1, 2, -1)
    train_y = torch.from_numpy(y).type(torch.LongTensor)

    train_data = Data.TensorDataset(train_x, train_y)
    train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE, shuffle=True)

    cnn.train()

    for epoch in range(EPOCH):

        adjust_learning_rate(optimizer, epoch)
        for step, (tr_x, tr_y) in enumerate(train_loader):
            batch_x = Variable(tr_x.cuda())
            batch_y = Variable(tr_y.cuda())
            output = cnn(batch_x)
            _, accuracy = get_result(output.cpu(), tr_y.cpu())

            del batch_x
            loss = loss_func(output, batch_y)
            del batch_y
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

            del output

            if step % 100 == 0:
                print(epoch, step, accuracy, loss.item())

    torch.save(cnn.state_dict(), os.path.join(const.model_path, method + '.pth'))

if __name__ == '__main__':
    # TODO: change the data file path
    defense = 'Undefended'
    feature_file = '../countermeasure/dataset/' + defense + '.npy'
    method = defense
    control(feature_file)


#!/usr/bin/env python
# coding: utf-8

# In[4]:

import pandas as pd
import numpy as np
import os
os.chdir('C:\DSBD project\Streamlit_Bank_Loan_Prediction-master\Streamlit_Bank_Loan_Prediction-master')

# In[5]:

train=pd.read_csv('./Loan_Data/train.csv')
train.Loan_Status=train.Loan_Status.map({'Y':1,'N':0})

# # Checking missing data

# In[6]:

train.isnull().sum()

# # Preprocessing

# In[7]:

Loan_status=train.Loan_Status
train.drop('Loan_Status',axis=1,inplace=True)
test=pd.read_csv('./Loan_Data/test.csv')
Loan_ID=test.Loan_ID
data=train.append(test)
data.head()

# In[8]:

data.shape

# In[9]:

data.describe()

# In[10]:

data.isnull().sum()

# In[11]:

data.Dependents.dtypes

# In[ ]:


"""AoC [[day]], [[year]][% if puzzle_name %]: [[puzzle_name]][% endif %]"""

# Standard library imports
import pathlib
import sys
import re
from itertools import repeat
import math

def parse(puzzle_input):
    """Parse input"""
    return puzzle_input.splitlines()

def part1(data):
    """Solve part 1"""
    highest = find_highest(data)
    the_array = create_2d_array(highest)

    for line in data:
        regex = r"^(\d+),(\d+) -> (\d+),(\d+)"
        match = re.search(regex, line)

        x0 = int(match.group(1))
        y0 = int(match.group(2))
        x1 = int(match.group(3))
        y1 = int(match.group(4))

        if x0 == x1:
            if y0 < y1 + 1:
                for y in range(y0, y1 + 1):
                    the_array[x0][y] += 1
            else:
                for y in range(y1, y0 + 1):
                    the_array[x0][y] += 1
        elif y0 == y1:
            if x0 < x1 + 1:
                for x in range(x0, x1 + 1):
                    the_array[x][y0] += 1
            else:
                for x in range(x1, x0 + 1):
                    the_array[x][y0] += 1

    return calc_result(the_array)

def find_highest(data):
    max_width = 0
    for line in data:
        regex = r"^(\d+),(\d+) -> (\d+),(\d+)"
        match = re.search(regex, line)

        for i in range(1, 5):
            if int(match.group(i)) > max_width:
                max_width = int(match.group(i))
    return max_width

def create_2d_array(max_width):
    the_array = []

    for i in range(0, max_width + 1):
        the_array.append(list(repeat(0, max_width + 1)))

    return the_array

def part2(data):
    """Solve part 2"""
    highest = find_highest(data)
    the_array = create_2d_array(highest)

    for line in data:
        regex = r"^(\d+),(\d+) -> (\d+),(\d+)"
        match = re.search(regex, line)

        x0 = int(match.group(1))
        y0 = int(match.group(2))
        x1 = int(match.group(3))
        y1 = int(match.group(4))

        if x0 == x1:
            if y0 < y1 + 1:
                for y in range(y0, y1 + 1):
                    the_array[x0][y] += 1
            else:
                for y in range(y1, y0 + 1):
                    the_array[x0][y] += 1
        elif y0 == y1:
            if x0 < x1 + 1:
                for x in range(x0, x1 + 1):
                    the_array[x][y0] += 1
            else:
                for x in range(x1, x0 + 1):
                    the_array[x][y0] += 1
        elif abs(x1 - x0) - abs(y1 - y0) == 0:
            x_sign = int(math.copysign(1, x1 - x0))
            y_sign = int(math.copysign(1, y1 - y0))
            for i in range(0, abs(x1 - x0) + 1):
                the_array[x0 + x_sign * i][y0 + y_sign * i] += 1

    return calc_result(the_array)

def calc_result(the_array):
    result = 0
    for x in the_array:
        for xy in x:
            if xy > 1:
                result += 1

    return result

def solve(puzzle_input):
    """Solve the puzzle for the given input"""
    data = parse(puzzle_input)
    solution1 = part1(data)
    solution2 = part2(data)

    # 8111
    # 22088

    return solution1, solution2

if __name__ == "__main__":
    for path in sys.argv[1:]:
        print(f"{path}:")
        solutions = solve(pathlib.Path(path).read_text().strip())
        print("\n".join(str(solution) for solution in solutions))


import os
import shutil
import imageio
import matplotlib
from matplotlib.figure import Figure
from matplotlib.axes import Axes
import matplotlib.pyplot as plt
from awpy.visualization import plot
from awpy.data import NAV
import networkx as nx
from tqdm import tqdm
import models
import mathing

CT_COLOR: str = "xkcd:azure"
T_COLOR: str = "xkcd:orange"
BOMB_COLOR: str = "yellow"
CT_TILE_COLOR: str = "xkcd:lightblue"
T_TILE_COLOR: str = "darkorange"
SMOKE_COLOR: str = "grey"
FIRE_COLOR: str = "red"
DEFAULT_COLOR: str = "black"

def plot_navigation_mesh(map_name: str, map_type: str, dark: bool) -> tuple[Figure, Axes]:
    """
    Plots the map's navigation mesh
    """

    f: Figure
    ax: Axes

    f, ax = plot.plot_map(map_name = map_name, map_type = map_type, dark = dark)

    for a in NAV[map_name]:
        tile = NAV[map_name][a]
        x_se = plot.position_transform(map_name, tile["southEastX"], "x")
        x_nw = plot.position_transform(map_name, tile["northWestX"], "x")
        y_se = plot.position_transform(map_name, tile["southEastY"], "y")
        y_nw = plot.position_transform(map_name, tile["northWestY"], "y")
        width = (x_se - x_nw)
        height = (y_nw - y_se)
        southwest_x = x_nw
        southwest_y = y_se
        rect = matplotlib.patches.Rectangle((southwest_x,southwest_y), width, height, linewidth=0.2, edgecolor="yellow", facecolor="None")
        ax.add_patch(rect)

    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)

    return f, ax

def plot_rounds(demo_file_data, output_file_directory: str) -> None:
    """
    Given a parsed demo file, plot all rounds of the demo and save it to a file
    Output file name shouldn't contain extensions
    """
    total_rounds = len(demo_file_data["gameRounds"])
    for index, round in enumerate(demo_file_data["gameRounds"]):
        # TODO: Make sure that the output is sent to the right place
        print(f"Creating .gif for round {index}/{total_rounds}:")
        plot_round(f"{output_file_directory}/round{index}.gif", round["frames"], map_name=demo_file_data["mapName"])

def plot_round(
    image_directory: str,
    round_number: int,
    round: models.Round,
    vision_graphs: list[nx.Graph],
    vision_traces: list[dict[int, mathing.VisionTraceResults]],
    map_name: str,
    map_type: str = "simpleradar",
    dark: bool = False,
    show_tiles: bool = True,
    gif_frame_rate: int = 2
    ) -> bool:
    """Plots a round and saves as a .gif. CTs are blue, Ts are orange, and the bomb is an octagon. Only use untransformed coordinates.

    Args:
        folder_name (string): folder name to save the frame images and the round gif
        round (list): the round to plot
        map_name (string): Map to search
        map_type (string): "original" or "simpleradar"
        dark (boolean): Only for use with map_type="simpleradar". Indicates if you want to use the SimpleRadar dark map type
        show_tiles: (boolean): The round images will have the outlines of each map tile displayed
        gif_frame_rate (int): The frames per second at which the GIF will play

    """
    image_files: list[str] = []
    frames = round.frames
    grenade_throwers: dict[tuple[float, float, float], str] = {
        (g.grenade_x, g.grenade_y, g.grenade_z): g.thrower_side for g in round.grenades
    }
    with tqdm(total=len(frames), desc = "Drawing frames: ") as progress_bar:
        for index, frame in enumerate(frames):
            vision_graph = vision_graphs[index]
            vision_trace_results = vision_traces[index]
            f, a = plot_frame(
                frame=frame,
                grenade_throwers=grenade_throwers,
                map_graph=vision_graph,
                vision_trace_results=vision_trace_results,
                map_name=map_name,
                map_type=map_type,
                dark=dark,
                show_tiles=show_tiles
            )
            image_files.append(f"{image_directory}/frame_{index+1}.png")
            f.tight_layout(pad=0)
            f.savefig(image_files[-1], dpi=300, bbox_inches="tight", pad_inches=0)
            plt.close()
            progress_bar.update()
    images = []
    for file in image_files:
        images.append(imageio.imread(file))
    imageio.mimsave(f"{image_directory}/round_{round_number}.gif", images, fps=gif_frame_rate)
    return True

def plot_frame(
    frame: models.Frame,
    grenade_throwers: dict[int, str],
    map_graph: nx.Graph,
    vision_trace_results: dict[int, mathing.VisionTraceResults],
    map_name: str,
    map_type: str,
    dark: bool,
    show_tiles: bool = True
    ) -> tuple[Figure, Axes]:
    """
    Plots a frame and returns the figure, axes, and the map graph (containing area controlled information).
    CTs are blue, Ts are orange, and the bomb is an octagon.
    """
    if show_tiles is True:
        f, a = plot_navigation_mesh(map_name, map_type, dark)
    else:
        f, a = plot.plot_map(map_name, map_type, dark)

    x_transform = lambda x: plot.position_transform(map_name, x, "x")
    y_transform = lambda y: plot.position_transform(map_name, y, "y")

    if frame.bomb is not None:
        bomb_x = x_transform(frame.bomb.x)
        bomb_y = y_transform(frame.bomb.y)
        a.scatter(x=bomb_x, y=bomb_y, c=BOMB_COLOR, marker="8")

    team: models.TeamFrameState
    color: str
    for team, color in [(frame.ct, CT_COLOR), (frame.t, T_COLOR)]:
        player_group: list[models.PlayerFrameState] = team.players
        for index, player in enumerate(player_group):

            player_x: float = x_transform(player.x)
            player_y: float = y_transform(player.y)

            if player.hp <= 0:
                a.scatter(x=player_x, y=player_y, c=color, marker="x")
                continue

            a.scatter(x=player_x, y=player_y, c=color, marker=".")

            # Draw lines between this player and other alive players
            for player2 in [p for p in player_group[index:] if p.hp > 0]:
                player2_x = x_transform(player2.x)
                player2_y = y_transform(player2.y)
                x_values = [player_x, player2_x]
                y_values = [player_y, player2_y]
                a.plot(x_values, y_values, c=color, linestyle="dotted", linewidth="0.7")

            aim_end_point = vision_trace_results[player.steam_id].end_points[0]
            # Draw a line to where the player is aiming
            a.scatter(x=x_transform(aim_end_point[0]), y=y_transform(aim_end_point[1]), c=color, marker="2")
            a.plot([player_x, x_transform(aim_end_point[0])], [player_y, y_transform(aim_end_point[1])], c=color, linestyle="solid", linewidth=0.85)

            # Draw lines for every view vector cast
            for end_point in vision_trace_results[player.steam_id].end_points[1:]:
                view_vector_end_point_x = x_transform(end_point[0])
                view_vector_end_point_y = y_transform(end_point[1])
                x_values = [player_x, view_vector_end_point_x]
                y_values = [player_y, view_vector_end_point_y]
                # a.scatter(x=end_point[0], y=end_point[1], c=color, marker="2")
                a.plot(x_values, y_values, c=color, linestyle="dotted", linewidth="0.4", alpha=0.2)

    # Color tiles!
    for node in map_graph.nodes(data=True):
        node_data: dict = node[1]
        controlling_side = node_data.get("controlling_side", None)
        if controlling_side is None:
            continue
        elif controlling_side == "CT":
            color = CT_TILE_COLOR
        elif controlling_side == "T":
            color = T_TILE_COLOR

        area_id: int = node_data["areaID"]
        tile = NAV[map_name][area_id]

        x_se = x_transform(tile["southEastX"])
        x_nw = x_transform(tile["northWestX"])
        y_se = y_transform(tile["southEastY"])
        y_nw = y_transform(tile["northWestY"])
        width = (x_se - x_nw)
        height = (y_nw - y_se)
        southwest_x = x_nw
        southwest_y = y_se

        rect = matplotlib.patches.Rectangle((southwest_x,southwest_y), width, height, linewidth=0.4, edgecolor=color, facecolor=color, alpha=0.2)
        a.add_patch(rect)

    # TODO: Resize markers to match how big they are in game if necessary

    marker_size: int = 400

    def get_thrower_of_closest_grenade(x: float, y: float, z: float) -> str:
        """
        Given a grenade's x, y, z coordinates, find the thrower of the closest grenade
        """
        closest_grenade_id = min(grenade_throwers, key=lambda g: (g[0] - x)**2 + (g[1] - y)**2 + (g[2] - z)**2)
        return grenade_throwers[closest_grenade_id]

    for smoke in frame.smokes:
        smoke_x: float = plot.position_transform(map_name, smoke.x, "x")
        smoke_y: float = plot.position_transform(map_name, smoke.y, "y")
        owner = get_thrower_of_closest_grenade(smoke.x, smoke.y, smoke.z)
        outline_color = CT_COLOR if owner == "CT" else T_COLOR if owner == "T" else SMOKE_COLOR
        a.scatter(x=smoke_x, y=smoke_y, c=SMOKE_COLOR, marker=".", edgecolors=outline_color, s=marker_size,)

    for fire in frame.fires:
        fire_x: float = plot.position_transform(map_name, fire.x, "x")
        fire_y: float = plot.position_transform(map_name, fire.y, "y")
        owner = get_thrower_of_closest_grenade(fire.x, fire.y, fire.z)
        outline_color = CT_COLOR if owner == "CT" else T_COLOR if owner == "T" else FIRE_COLOR
        a.scatter(x=fire_x, y=fire_y, c=FIRE_COLOR, marker=".", edgecolors=outline_color, s=marker_size,)

    return f, a