import sys
from urllib import urlencode

# Zope imports
from AccessControl import ClassSecurityInfo
from AccessControl.Permissions import view
from DocumentTemplate.sequence import sort
from Globals import InitializeClass
from OFS.Folder import Folder
import Products
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from zLOG import LOG, DEBUG

# Naaya imports
from Products.NaayaBase.constants import MESSAGE_SAVEDCHANGES, \
                                         PERMISSION_EDIT_OBJECTS
from Products.NaayaCore.managers.utils import slugify, genRandomId, genObjectId
from naaya.i18n.LocalPropertyManager import LocalPropertyManager, LocalProperty

import statistics
from statistics.BaseStatistic import manage_addStatistic

STATISTICS = dict([(statistic.meta_type, statistic) for statistic in statistics.AVAILABLE_STATISTICS])

def manage_addSurveyReport(context, id="", title="", REQUEST=None, **kwargs):
    """
    ZMI method that creates an object of this type.
    """
    if not id:
        id = slugify(title)

    idSuffix = ''
    while id+idSuffix in context.objectIds():
        idSuffix = genRandomId(p_length=4)
    id = id + idSuffix

    # Get selected language
    lang = REQUEST and REQUEST.form.get('lang', None)
    lang = lang or kwargs.get('lang', context.gl_get_selected_language())

    ob = SurveyReport(id, lang=lang, title=title)
    context.gl_add_languages(ob)
    context._setObject(id, ob)
    if REQUEST is not None:
        context.manage_main(context, REQUEST, update_menu=1)
    return id

class SurveyReport(Folder, LocalPropertyManager):
    """Survey Report"""

    meta_type = 'Naaya Survey Report'

    manage_options=(
        {'label':'Contents', 'action':'manage_main',
         'help':('OFSP','ObjectManager_Contents.stx')},
        {'label':'View', 'action':'index_html'},
        {'label':'Security', 'action':'manage_access',
         'help':('OFSP', 'Security.stx')},
        )

    _constructors = (manage_addSurveyReport,)

    _properties=()

    icon = 'misc_/NaayaSurvey/NySurveyReport.gif'

    security = ClassSecurityInfo()

    title = LocalProperty('title')
    description = LocalProperty('description')

    def __init__(self, id, lang=None, **kwargs):
        Folder.__init__(self, id=id)
        self.set_localproperty('title', 'string', lang)
        self.set_localproperty('description', 'text', lang)
        self.saveProperties(lang=lang, **kwargs)

    #
    # global methods used in naaya site context
    #
    def _object_add_language(self, language, **kwargs):
        for doc in self.objectValues():
            doc.add_language(language)

    def _object_del_language(self, language, **kwargs):
        for doc in self.objectValues():
            doc.del_language(language)

    #
    # Self edit methods
    #
    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'saveProperties')
    def saveProperties(self, REQUEST=None, **kwargs):
        """Update properties"""
        if REQUEST:
            kwargs.update(REQUEST.form)
        local_properties = self.getLocalProperties()
        local_properties = filter(None, [x.get('id', None) for x in local_properties])
        # Update local properties
        lang = kwargs.get('lang', self.get_selected_language())
        for local_property in local_properties:
            prop_value = kwargs.get(local_property, '')
            self.set_localpropvalue(local_property, lang, prop_value)
        kwargs = dict([(key, value) for key, value in kwargs.items()
                       if key not in local_properties])
        self.manage_changeProperties(**kwargs)
        if REQUEST:
            query = {'lang': lang}
            query = urlencode(query)
            REQUEST.RESPONSE.redirect('%s/edit_html?%s' % (self.absolute_url(), query))
        return True

    security.declareProtected(view, 'getStatistics')
    def getStatistics(self):
        """Return the statistics"""
        return self.objectValues()

    #security.declareProtected(view, 'getSortedStatistics')
    security.declarePublic('getSortedStatistics')
    def getSortedStatistics(self, sort_by='sortorder'):
        """Return the statistics in sorted order"""
        return sort(self.getStatistics(), ((sort_by, 'cmp', 'asc'), ))

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'deleteStatistics')
    def addStatistic(self, REQUEST, question=None, meta_type=None):
        """Add a statistic for question.

            @param question: id of the question
            @param meta_type: metatype of the statistic
        """
        err = []
        if not question:
            err.append('Please select a question')
        if not meta_type:
            err.append('Please select a statistic type')
        if err:
            self.setSessionErrorsTrans(err)
            return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)

        statistic_cls = STATISTICS[meta_type]
        question = self.getWidget(question)
        try:
            return manage_addStatistic(statistic_cls,
                                       self,
                                       genObjectId(question.title),
                                       question=question,
                                       REQUEST=REQUEST)
        except TypeError:
            if not REQUEST:
                raise
            err = sys.exc_info()
            LOG('NaayaSurvey.statistics.manage_addStatistic', DEBUG,
                'Error creating statistic %s for question %s' % (statistic_cls, question.absolute_url()), error=err)
            self.setSessionErrorsTrans('"${meta_label}" can\'t be used for question "${title}"',
                meta_label=statistic_cls.meta_label, title=question.title)
            return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'deleteStatistics')
    def deleteStatistics(self, ids=[], REQUEST=None):
        """ Delete statistics by ids"""
        if not ids:
            self.setSessionErrorsTrans('Please select one or more items to delete.')
        else:
            try: self.manage_delObjects(ids)
            except: self.setSessionErrorsTrans('Error while deleting data.')
            else: self.setSessionInfoTrans('Item(s) deleted.')
        REQUEST.RESPONSE.redirect('%s/index_html' % self.absolute_url())

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'setSortOrder')
    def setSortOrder(self, order={}, REQUEST=None):
        """Set the order of the statistics"""
        if REQUEST:
            order.update(REQUEST.form)
        for id, neworder in order.items():
            ob = self._getOb(id, None)
            if id not in self.objectIds():
                continue
            ob.sortorder = neworder
        if REQUEST:
            self.setSessionInfoTrans(MESSAGE_SAVEDCHANGES, date=self.utGetTodayDate())
            return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)

    def getAvailableStatistics(self):
        """Return the available statistics"""
        return statistics.AVAILABLE_STATISTICS

    security.declareProtected(PERMISSION_EDIT_OBJECTS, 'index_html')
    index_html = PageTemplateFile('zpt/surveyreport_index', globals())

    security.declareProtected(view, 'edit_html')
    edit_html = PageTemplateFile('zpt/surveyreport_edit', globals())

    security.declareProtected(view, 'view_report_html')
    view_report_html = PageTemplateFile('zpt/surveyreport_view_report', globals())

InitializeClass(SurveyReport)


import os
import discord
import random
from discord.ext import commands
import asyncio
from datetime import datetime
from dotenv import load_dotenv
import traceback
from discord.ext import tasks
import json

class jsonfile(object):
	"""docstring for jsonfile"""

	def __init__(self, file:str = "0"): #file is an actual argument
		super(jsonfile, self).__init__() #idk what this does but i feel like it might break if i remove
		self.file = file #makes the argument file a class var

		if file == "0": #alternate option to make it not write to file and reset on shutdown
			self.data = {} #sets the data class var up

		else: #if a file was input
			try: #attempts to load said file (will always fail if the file doesnt exist..yet)
				with open(self.file) as file: #attempts to load the file that was inputted
					self.data = json.load(file) # parses the JSON data in the file and returns a dictionary assigned to class var data
			except: #if the file doesnt exist yet
				try:
					file = file.name #IODataWrapper preventer
				except:
					file = file #throwaway except function so that except runs something

				self.data = {"null": 1} #still makes sure data exists to not error out
				self.write(self.data) #invokes the local write function to write out the file
		self.timer = {"null": 1} #initilizes the timer class var

	#overrides the json with input
	def write(self, input):
		if self.file != "0": #checks if a file was input
			with open(self.file, "w") as file: #opens up the file for writing
				file.write(json.dumps(input, indent=4)) # formats and beautifies the JSON as a string and overwrites the file contents with it
		self.data = input #updates the data var to make sure its uptodate\

	#local timer funct

	#editing function
	def edit(self, entry:str, inp):
		self.data[entry] = inp #replaces the <entry> with input
		self.update() #invokes write function

	#a simpler version of write that just writes the current state of data to the file
	def update(self):
		self.write(self.data) #write function invoked

	def append(self, inp):
		self.data[len(self.data)] = inp
		self.update()

intents = discord.Intents.default() #sets up the intents obj
intents.members = True #flips the member inperwhatever it is to true

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN') #retrieves the stuff needed from a *hidden* env file yall aint gettin

bot = commands.Bot(command_prefix='am!', intents=intents) #initilizes the bot
#bot.obj = [] #initilizes list of games
bot.obj = jsonfile('games.json')

#flavorie text to make sure its working good
@bot.event
async def on_ready(): #initilization

    guild = discord.utils.get(bot.guilds, name='bot tester') #gets the guild that i put in to kinda add some flavor text

    print(discord.utils.get(bot.guilds))

    print(
    	f'{bot.user} is connected to the following guild:\n'
        f'{guild.name}(id: {guild.id})'
    )

    await bot.change_presence(activity=discord.Game(name='amogus bot :)')) #:)

#the react-to-join section
@bot.event
async def on_reaction_add(reaction, user):
	y = {} #initilizes a dict
	for x in range(len(bot.obj.data)): #for every entry in bot.obj (counting 0 - num)
		y[bot.obj.data[x]] = bot.obj.data[x].latestmsg #store the key of the instance as the latest message of it

	if user != bot.user and reaction.emoji == u"\U0001F44D" and reaction.message in y.values(): #if not bot and reaction is thumbs up and the message is correct
		for key, value in y.items(): #for every single entry in the dictionary
			if reaction.message == value: #if the message is the same as the value
				obj = key #stores the correct instance into obj
		ctx = await bot.get_context(reaction.message) #obtains the ctx from the message sent
		await obj.add_user(ctx, user) #adds the user to the obj it belongs to

''' testing stuff
@bot.command(name='test')
async def react(ctx):
	bot.reactmsg = ctx.message
	bot.ogmsg = await ctx.send('reaction msg')
	await bot.ogmsg.add_reaction(u"\U0001F44D") #thumbs up

@bot.command(name='add')
async def add(ctx, game=0):
	game = bot.obj[game]
	await game.add_user(ctx, ctx.author)
'''

#initilizes a new instance of the game class
@bot.command(name='init')
async def init(ctx, name, code):
	bot.obj.append(gameobj(ctx, name, code)) #appends an instance to bot.obj

''' another testing thing bc im lonely
@bot.command(name='fill')
async def fill(ctx):
	for x in {"user1#9833", "user2#2383", "user3#9742", "user4#8269", "user5#1048", "user6#7862", "user7#3452", "user8#3821", "user9#3490"}:
		await bot.obj[0].add_user(ctx, x)
'''

#listing command (both overall and individual)
@bot.command(name='list')
async def list(ctx, game = -1):

	try:
		msg = 'Game listing: \n\n' #nice little flavoring text

		if game == -1 and len(bot.obj.data) > 1: #if the game var was not provided and there is more than one instance
			for x in range(len(bot.obj.data)): #for the number of entries in bot.obj
				game = bot.obj.data[x] #stores the instance of the thing
				msg += f'<game {x}>, <name \'{game.name}\'>, <players {len(game.active)}/{len(game.wait)}>, <code \'{game.code}\'>\n' #flavor text and informacione
			await ctx.send(msg) #sends the message
		elif game == -1: #if there is only one instance and the game wasnt provided
			await bot.obj.data[0].statusmsg(ctx, 1) #just gets 0
		else:
			try:
				await bot.obj.data[game].statusmsg(ctx, 1) #gets the game input
			except:
				await ctx.send('Please send a valid game number') #if the game input was invalid
	except:
		ctx.send("Please initilize a game")

#change code funct
@bot.command(name='code')
async def chncode(ctx, game = -1, code:str = "error"):
	if game == -1 and len(bot.obj.data) > 1: ctx.send('Please specify a game') #if the game is left as default and there is more than one instance warn
	else:
		if game == -1: game = 0 #moves the default game int up one
		sudo = await chkrl(ctx, ctx.author)
		if ctx.author == bot.obj.data[game].host: sudo = 1
		if sudo == 1:
			bot.obj.data[game].code = code #sets the corresponding game's code
			bot.obj.update()
		else: await ctx.send('Sorry bud, you don\'t have the perms to do that')

#leave queue funct
@bot.command(name='leave')
async def leave(ctx, game = 0, member:discord.Member = None):
		if member == None: member = ctx.author
		if member != None:
			sudo = await chkrl(ctx, ctx.author)
			if ctx.author == bot.obj.data[game].host: sudo = 1
			if sudo == 1:
				try:
					await bot.obj.data[game].leave(ctx, member)
					await bot.obj.data[game].statusmsg(ctx)
				except Exception as e:
					print(e)
					await ctx.send('Whoops, that user isn\'t in that game')
			else:
				await ctx.send('Sorry bud, you don\'t have the perms to do that')
		elif game == -1: #very special case
			for x in bot.obj.data: #for every entry in bot.obj
				await x.leave(ctx, member) #runs leave in the instance
				await x.statusmsg(ctx, member) #updates the message
		else:
			await bot.obj.data[game].leave(ctx, member) #runs leave in the inst
			await bot.obj.data[game].statusmsg(ctx, member) #updates message

@bot.command(name='close')
async def close(ctx, game = -1):
	if game == -1:
		ctx.send('No game specified.')
	else:
		sudo = await chkrl(ctx, ctx.author)
		if ctx.author == bot.obj.data[game].host: sudo = 1
		if sudo == 1:
			try:
				bot.obj.data.pop(game)
				await ctx.send('Game successfully closed')
			except:
				await ctx.send('There was an error closing the game. Please check you are reffering to a valid game')
		else:
			await ctx.send('Sorry bud, you don\'t have the perms to do that')

class gameobj(object): #heres where like half the magic happens
	"""docstring for gameobj"""
	def __init__(self, ctx, name:str, code:str):
		super(gameobj, self).__init__()
		self.code = code #fils in all the default values
		self.active = []
		self.wait = []
		self.name = name
		self.host = ctx.author
		self.latestmsg = 0
		asyncio.ensure_future(self.statusmsg(ctx)) #triggers the status message

	#adds user
	async def add_user(self, ctx, user):
		if user not in self.active and len(self.active) <= 9: #if the user isnt already in the list of active players and there is an empty spot
			self.active.append(user) #appends the user to the list
			await self.statusmsg(ctx) #updates info msg
		else: #no room in self.active or they're already in
			if user in self.active: msg = await ctx.send("You're already in the game") #if they're already in
			elif len(self.active) >= 9:  #if theres no room left
				msg = await ctx.send('There is no room left, adding you to the waiting list..') #msg letting you know
				self.wait.append(user) #adds the user to the waiting list
				await self.statusmsg(ctx) #updates the info msg
			await asyncio.sleep(3) #wait 3 seconds
			await msg.delete() #delete the status message

	#updates/creates new status message
	async def statusmsg(self, ctx, new:int = 0):
		try:
			msg = f'Host: {self.host} \nCode: {self.code} \nGame name: {self.name} \n\n' #header flavor text

			for x in range(10): #loops through below code 10 times
				try:
					if self.active[x].nick != None: nick = f'({self.active[x].nick}) '
					else: nick = ''
					msg += f'{x + 1}: {str(self.active[x])} {nick}\n' #if theres a user in the specific spot, print it
				except:
					msg += '[Empty] \n' #if the above fails due to index out of range, print empty

			if len(self.wait) > 0: #if theres ppl in the waiting list
				msg += '\n Waiting List \n' #seperator
				for x in range(len(self.wait)): #for the number of entries in the waiting list
					if self.active[x].nick != None: nick = f'({self.active[x].nick}) '
					else: nick = ''
					msg +=  f'{x + 1}: {str(self.wait[x])} {nick}\n' #adds the user to msg
					if x == 10: #10 entry limit
						msg += "...\n" #...

						break #breaks the for loop
				msg += "\n\n"

			msg += 'React with :thumbsup: to join!' #flavor texto

			#await bot.wait_until_ready() #something something keeps the loop from breaking

			try:
				if self.latestmsg and new == 0: await self.latestmsg.edit(content=msg) #if latestmsg exists and the flag isnt set, edit content
				else: raise Exception('expected manual exception, im too lazy to rewrite this code') #i just have this here so if new isnt 0 it cancels the try
			except Exception as e:
				print(e)
				self.latestmsg = await ctx.send(msg) #creates new message

			await self.latestmsg.add_reaction(u"\U0001F44D") #adds the thumbs up reaction

		except Exception as e:
			await ctx.send('There are no games running currently, run init to start one!') #hopefully this only triggers if there isnt an init for this instance
			await ctx.send(e)

	#leave funct
	async def leave(self, ctx, member = None):
		if member == None: member = ctx.author
		if member in self.active: #if the person leaving is in the active list
			self.active.remove(member) #removes from active list
			if len(self.wait) > 0: #if there are people waiting
				new = self.wait[0] #sets the first person in the waiting list to "new"
				self.wait.remove(new) #removes them from wait
				self.active.append(new) #adds to active
				await ctx.send(f'{new.mention}, {member.mention} has given you a spot!') #flavor text
			else: #if there is nobody waiting
				await ctx.send(f'{member.mention} has left the game') #simple 'has left' message
		elif member in self.wait: #if the person is in the waiting list
			self.wait.remove(member) #removes from waiting list
			await ctx.send(f'{member} has left the queue') #message of confirmation
		else:
			x = x
			await ctx.send(f'You need to be in a queue to leave, {member}') #if the triggerer is not in any list, then just send back this

async def chkrl(ctx, user: discord.Member):
		modrl = [ #list of roles that are "elevated"
			742937828425465899
		]
		blacklist = [ #list of member roles
			"User",
			"user",
			813469324328173608
		]

		for x in modrl:
			if isinstance(x, str): x = discord.utils.find(lambda r: r.name == x, ctx.guild.roles) #if its a string, use utils.find to get the role obj
			elif isinstance(x, int): x = ctx.guild.get_role(x) #if not string, but is an int, simply use get_role to get role obj
			if x in user.roles: return 1 #checks if the input user has the role from blacklist, if yes, returns -1
		for x in blacklist: #for every entry in blacklist
			if isinstance(x, str): x = discord.utils.find(lambda r: r.name == x, ctx.guild.roles) #if its a string, use utils.find to get the role obj
			elif isinstance(x, int): x = ctx.guild.get_role(x) #if not string, but is an int, simply use get_role to get role obj
			if x in user.roles: return -1 #checks if the input user has the role from blacklist, if yes, returns -1

bot.run(TOKEN) #runs everything else


import sys
input = sys.stdin.readline

arr = list(map(int, input().rstrip().split()))
score = [100, 100, 200, 200, 300, 300, 400, 400, 500]

done = 0
for i in range(len(arr)):
    if arr[i] > score[i]:
        done = 1
        break

if done == 1:
    print('hacker')
else:
    if sum(arr) >= 100: print('draw')
    else: print('none')

백준/Bronze/21866. 추첨을 통해 커피를 받자/추첨을 통해 커피를 받자.py

추첨을 통해 커피를 받자.py


#
# @lc app=leetcode.cn id=5 lang=python3
#
# [5] 最长回文子串
#

# @lc code=start
class Solution:
    def longestPalindrome(self, s: str) -> str:
        if not s:
            return s
        answer = (0, 0) # (lenth, start_index)
        for mid in range(len(s)):
            answer = max(answer, self.get_palindrome_from(s, mid, mid))
            answer = max(answer, self.get_palindrome_from(s, mid, mid + 1))
        return s[answer[1]: answer[0] + answer[1]]

    def get_palindrome_from(self, s, left, right):
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
        return right - left -1, left + 1
    # @lc code=end


import rq
from datetime import datetime, timedelta
import settings
from sqlalchemy import engine
import pandas as pd
from typing import(
	Callable,
	List,
	Optional,
	Tuple
)
from . import rqu
from . import settings
from . import task
from multiprocessing import Process

def enqueue_process(func, func_input, task_name:str, log_filepath:str, queue, queue_type:str="rq"):
	"""
	enqueue the function process and save 'out' and 'error' logs to respective log file.

	Args:
		func: function to be executed
		func_input: parameters the above function needs
		log_file: path to the respective log file.
		queue_type: the type of task queue that the function is joining for execution

	Raises:
		OError if log file cannot be created

	Returns:
		a job object of the particular queue.
	"""

	metadata = {'progress': 0}
	try:
		if queue_type == "rq":
			job = queue.enqueue(func, func_input, meta=metadata)

	except OSError as exc:
		raise exc

	return(job)

def execute_job(func, func_input, log_filepath:str, job_name:str, task_name:str, now:datetime, queue, queue_type:str="rq"):
	"""
	Interface for running a job:
		-> launch a process
		-> write job execution log.

	Args:
		func: function to be executed
		func_input: parameters the above function needs
		log_file: path to the respective log file.
		job_name: name generated for the job.
		now: datetime.now()
		queue_type: the type of task queue that the function is joining for execution

	Returns:
		a job object of the particular queue.
	"""
	job = enqueue_process(func, func_input, log_filepath, queue, queue_type)
	return(job)

def schedule_process_job(func, func_input, job_name:str, task_name:str, start:datetime, interval_duration:timedelta, weekdays:Optional[List[str]], execution_frequency:str, execution_type:str, queue, queue_type:str="rq"):
	"""
	Launch a scheduler process that spawns job execution processes if launch conditions are met.
	Checks for current date. If date criterion is met -> start the process with command execution.

	Args:
		func: function to be executed
		func_input: parameters the above function needs
		job_name: name generated for the job.
		start: execution datetime.
		interval_duration: interval to wait before before scheduling the next job execution.
		weekdays: (optional) list with selected weekdays.
		execution_frequency: frequency of execution: "Interval" / "Daily"
		execution_type: type of execution schedule: is execution "Scheduled" or not.
		queue_type: the type of task queue that the function is joining for execution

	"""
	stdout_log_file = f"{settings.BASE_LOG_DIR}/{job_name}_stdout.txt"
	if execution_frequency == "Once":
		job = execute_job(func=func, func_input=func_input, log_filepath=stdout_log_file, job_name=job_name, task_name=task_name, now=datetime.now(), queue=queue, queue_type=queue_type)
		return(job)

	# If process must be executed now, decrease start date by interval timedelta:
	# this way 'match_duration' will return True in the 'process_should_execute' check.
	if execution_frequency == "Now":
		start -= interval_duration

	while True:
		now = datetime.now()
		if process_should_execute(now, start, interval_duration, weekdays):
			job = execute_job(func=func, func_input=func_input, log_filepath=stdout_log_file, job_name=job_name, task_name=task_name, now=datetime.now(), queue=queue, queue_type=queue_type)
			start += interval_duration
		else:
			time.sleep(1)

def start_scheduler_process(func, func_input, job_name:str, task_name:str, start: datetime, interval_duration:timedelta, weekdays: Optional[List[str]], execution_frequency: str, execution_type:str, queue_type:str="rq") -> (int, int):
	"""
	Run a process with the selected parameters.

	Args:
		func: function to be executed
		func_input: parameters the above function needs
		job_name: name generated for the job.
		start: execution datetime.
		interval_duration: interval to wait before before scheduling the next job execution.
		weekdays: (optional) list with selected weekdays.
		execution_frequency: frequency of execution: "Interval" / "Daily"
		execution_type: type of execution schedule: is execution "Scheduled" or not.
		queue_type: the type of task queue that the function is joining for execution

	Returns:
		ID of the started process and the job

	"""
	log_filepath = f"{settings.BASE_LOG_DIR}/{job_name}_redis_server_log.txt"
	conn, q = rq.start_redis_queue(log_filepath)
	job = schedule_process_job(func, func_input, job_name, task_name, start, interval_duration, weekdays, execution_frequency, execution_type, q, queue_type)
	process = Process(target=run_worker, kwargs=dict(conn=conn, q=q))
	process.start()
	return(q, process, job)

def submit_job(func, func_input, job_name:str, task_name:str, start:datetime, interval_duration:timedelta, weekdays:Optional[List[str]], execution_type:str, task_id:int, sql_engine:engine, queue_type:str="rq", execution_frequency:str="Once"):
	"""
	Run a process job and save related process information to an SQL alchemy file.

	Args:
		func: function to be executed
		func_input: parameters the above function needs
		job_name: name generated for the job.
		start: execution datetime.
		interval_duration: interval to wait before before scheduling the next job execution.
		weekdays: (optional) list with selected weekdays.
		execution_frequency: frequency of execution: "Interval" / "Daily"
		execution_type: type of execution schedule: is execution "Scheduled" or not.
		task_id: task ID
		sql_engine: sql engine to use for saving DF information to sql.
		queue_type: the type of task queue that the function is joining for execution

	"""
	return(start_scheduler_process(func, func_input, job_name, task_name, start, interval_duration, weekdays, execution_frequency, execution_type, queue_type))

def create_process_info_dataframe(func, func_input, job_name: str, pid: int, task_id: int) -> pd.DataFrame:
	"""
	Generate a dataframe with process information in the following format:

	{
		'task_id': [],
		'created': [],
		'process id': [],
		'job name': [],
		'task': [],
		'last update': [],
		'running': []
	}

	Args:
		func: function to be executed
		func_input: parameters the above function needs
		job_name: name generated for the job.
		pid: process ID.
		task_id: task ID.

	Returns:
		pandas DF with process related information.
	"""
	created = datetime.now()
	return pd.DataFrame(
		{
			'task_id': [task_id],
			'created': [created],
			'process id': [pid],
			'job name': [job_name],
			'task': [func.__str__()],
			'last update': [None],
			'running': [None]
		}
	)

def save_df_to_sql(df: pd.DataFrame, sql_engine: engine) -> None:
	"""
	Save dataframe with process information to a local sql alchemy DB file.
	Args:
		df: process information df.
		sql_engine:  sql alchemy engine to use.

	Raises:
		OperationalError: if any sqlalchemy errors have been thrown.
	"""
	try:
		df.to_sql("processes", con=sql_engine, if_exists="append", index=False)
	except OperationalError as exc:
		raise exc

def read_log(filename: str) -> List[str]:
	"""
	Utility function to read a logfile.

	Args:
		filename: name of the log file to be read.
	Raises:
		FileNotFoundError if respective log file is missing.

	Returns:
		list of strings, with each string representing a line.
	"""
	try:
		with open(filename, "r", encoding="utf-8") as reader:
			return reader.readlines()
	except FileNotFoundError as exc:
		raise exc

def write_job_execution_log(job_name: str, command:str, now: datetime, msg: str) -> None:
	"""
	Save job execution information to a log file.
	Args:
		func: function to be executed
		func_input: parameters the above function needs
		job_name: name of the job for which to write the log.
		now: datetime object with current timestamp.
		msg: message to be logged.

	Raises:
		OSError if log file creation fails.
	"""
	now_str = now.strftime(settings.DATE_FORMAT)
	for suffix in [".txt", "_stdout.txt"]:
		try:
			with open(f"{settings.BASE_LOG_DIR}/{job_name}{suffix}", "a") as file:
				if suffix == "_stdout.txt" and command != "":
					file.write(f"\n{'=' * 70} \n")
				file.write(f"{now_str} {msg} {command}\n")
		except OSError as exc:
			raise exc


import re
from datetime import datetime

from django import forms
from django.utils import timezone

class BaseForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setup_bootstrap_class()

    def setup_bootstrap_class(self):
        for field_name, field in self.fields.items():
            if "class" in field.widget.attrs:
                class_list = [field.widget.attrs["class"]]
            elif (
                isinstance(field.widget, forms.RadioSelect)
                or isinstance(field.widget, forms.CheckboxInput)
                or isinstance(field.widget, forms.CheckboxSelectMultiple)
            ):
                class_list = ["custom-control-input"]
            else:
                class_list = ["form-control"]

            if self.has_error(field_name):
                class_list.append("is-invalid")

            field.widget.attrs["class"] = " ".join(class_list)

class SplitDateTimeWidget(forms.SplitDateTimeWidget):
    def value_from_datadict(self, data, files, name):
        date_str, time_str = super().value_from_datadict(data, files, name)

        if not date_str and not time_str:
            return

        value = (date_str or "") + (time_str or "")
        try:
            if self.is_HMS(time_str):
                return datetime.strptime(value, "%Y-%m-%d%H:%M:%S").astimezone(timezone.get_default_timezone())
            elif self.is_HM(time_str):
                return datetime.strptime(value, "%Y-%m-%d%H:%M").astimezone(timezone.get_default_timezone())
            return value
        except:
            return value

    def is_HMS(self, time_str):
        pattern = r"^((0?|1)[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$"
        return re.compile(pattern).match(time_str)

    def is_HM(self, time_str):
        pattern = r"^((0?|1)[0-9]|2[0-3]):[0-5][0-9]$"
        return re.compile(pattern).match(time_str)

    def decompress(self, value):
        try:
            return super().decompress(value.replace(second=0) if value else value)
        except:
            return value


# https://www.codewars.com/kata/extract-the-domain-name-from-a-url-1/train/python

import re
def domain_name(url):
    regex = re.compile(r'''
    ^(http://|https://|http://www.|https://www.|www.)  # http + wwww
    ([a-zA-Z0-9\-]+)                                   # domain
    (\.[a-z0-9/]+)$                                    # .com
    ''', re.VERBOSE)
    mo = regex.findall(url)
    return mo[0][1]

print(domain_name("http://zombie-bites.com"))# == "zombie-bites"
print(domain_name("http://github.com/carbonfive/raygun"))# == "github"
print(domain_name("http://www.zombie-bites.com"))# == "zombie-bites"
print(domain_name("https://www.cnet.com"))# == "cnet"


import re, os
from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
    help = 'trans tag wrapper. Input the module names you want to modify./ Modules template folder will be scanned and modified recursively'

    def add_arguments(self, parser):
        parser.add_argument('module', nargs='+', type=str)

    def exclude_this(self, text_obj):
        exclude_patterns = ['http:','https:','ftp:']
        for a in exclude_patterns:
            if re.match(a, text_obj) :
                # print('false', text_obj)
                return False

        return True

    def include_this(self, text_obj):
        include_patterns = ['.jpg','.png','.svg','gif','.css','.js']
        for a in include_patterns:
            if text_obj.endswith(a):
                return True

        return False

    def trans_tag(self, matchobj):
        # print(matchobj.groups())
        if matchobj.group(2):
            textobj = matchobj.group(2)
            if self.exclude_this(textobj):
                replace_line = ">{{% trans '{}' %}}<".format(textobj)
            else :
                replace_line = matchobj.group(0)
        elif matchobj.group(4) != None:
            textobj = matchobj.group(4)
            if self.exclude_this(textobj):
                replace_line = 'alt="{{% trans \'{}\' %}}"'.format(textobj)
            else :
                # print('group 4')
                replace_line = matchobj.group(0)
        else:
            # print('empty')
            replace_line = matchobj.group(0)
        self.stdout.write(replace_line )
        return replace_line

    def static_tag(self, matchobj):
        if matchobj.group(2):
            if self.exclude_this(matchobj.group(2)) and self.include_this(matchobj.group(2)):
                replace_line = '{}=\"{{% static \'{}\' %}}\"'.format(matchobj.group(1) ,matchobj.group(2))
            else :
                replace_line = matchobj.group(0)
        self.stdout.write(replace_line)
        return replace_line

    def handle(self, *args, **options):
        for url in options['module']:
            self.stdout.write(url, )
            module_url = url+'/templates/'
            if os.path.exists(module_url):
                PATH = os.path.join(module_url)
                for root,d_names,f_names in os.walk(PATH):
                    print( root, d_names, f_names)
                    for file in f_names:
                        if file.endswith(".html"):
                            file_path = root+'/'+file
                            with open (file_path, 'r' ) as f:
                                content = f.read()
                            content_new = re.sub('(>([^{}<>()]+\S)<)|(alt="(\w*)")', self.trans_tag, content, flags = re.M)
                            content_new = re.sub('(href|src|img)=\"([^{%].*?)\"', self.static_tag, content_new, flags = re.M)
                            f.close()
                            with open (file_path, 'w' ) as g:
                                g.write(content_new)
                            g.close()
                            self.stdout.write(self.style.SUCCESS('Successfully wrapped "%s"' % file_path))
            else:
                er_message = "module {} doesn't exist".format(url)
                self.stdout.write(er_message, )


#!/usr/bin/env python
import os
import sys

from django.core.management.templates import TemplateCommand
from django.core.management.utils import get_random_secret_key

CURRENT_PYTHON = sys.version_info[:2]
REQUIRED_PYTHON = (3, 7)

if CURRENT_PYTHON < REQUIRED_PYTHON:
    sys.stderr.write(
        "This version of CjkCMS requires Python {}.{} or above - you are running {}.{}\n".format(
            *(REQUIRED_PYTHON + CURRENT_PYTHON)
        )
    )
    sys.exit(1)

class CreateProject(TemplateCommand):
    """
    Based on django.core.management.startproject
    """

    help = (
        "Creates the directory structure for a new CjkCMS project. "
        "Provide a slug-styled project name as an argument."
    )
    missing_args_message = "You must provide a project name."

    def add_arguments(self, parser):
        parser.add_argument(
            "--sitename",
            help='Human readable name of your website or brand, e.g. "Nano Corp Inc."',
        )
        parser.add_argument(
            "--domain",
            help='Domain that will be used for your website in production, e.g. "www.nanocorp.com"',
        )
        super().add_arguments(parser)

    def handle(self, **options):
        # pop standard args
        project_name = options.pop("name")
        target = options.pop("directory")

        # create Uppercase-first and full uppercase versions of project name
        options["uf_project"] = project_name[0].upper() + project_name[1:]
        options["uc_project"] = project_name.upper()
        options["lc_project"] = project_name.lower()

        # Make sure given name is not already in use by another python package/module.
        try:
            __import__(project_name)
        except ImportError:
            pass
        else:
            sys.exit(
                "'%s' conflicts with the name of an existing "
                "Python module and cannot be used as a project "
                "name. Please try another name." % project_name
            )

        # Create a random SECRET_KEY to put it in the main settings.
        options["secret_key"] = get_random_secret_key()

        # Handle custom template logic
        import cjkcms

        cms_path = os.path.dirname(cjkcms.__file__)
        if not options["template"]:
            options["template"] = "basic"
        template_path = os.path.join(
            os.path.join(cms_path, "project_template"), options["template"]
        )

        # Check if provided template is built-in to the cms,
        # otherwise, do not change it.
        if os.path.isdir(template_path):
            options["template"] = template_path

        # Treat these files as Django templates to render the boilerplate.
        options["extensions"] = ["py", "md", "txt"]
        options["files"] = ["Dockerfile"]

        # Set options
        message = "Creating a CjkCMS project called %(project_name)s"

        if options.get("sitename"):
            message += " for %(sitename)s"
        else:
            options["sitename"] = project_name

        if options.get("domain"):
            message += " (%(domain)s)"
            # Strip protocol out of domain if it is present.
            options["domain"] = options["domain"].split("://")[-1]
            # Figure out www logic.
            if options["domain"].startswith("www."):
                options["domain_nowww"] = options["domain"].split("www.")[-1]
            else:
                options["domain_nowww"] = options["domain"]
        else:
            options["domain"] = "localhost"
            options["domain_nowww"] = options["domain"]

        # Add additional custom options to the context.
        options["cjkcms_version"] = cjkcms.VERSION  # type: ignore

        # Print a friendly message
        print(
            message
            % {
                "project_name": project_name,
                "sitename": options.get("sitename"),
                "domain": options.get("domain"),
            }
        )

        # Run command
        super().handle("project", project_name, target, **options)

        # Be a friend once again.
        print(
            "Success! %(project_name)s has been created"
            % {"project_name": project_name}
        )

        nextsteps = """
Next steps:
    1. cd %(directory)s/
    2. python manage.py migrate
    3. python manage.py createsuperuser
    4. python manage.py runserver
    5. Go to http://localhost:8000/backend/ and start editing!
"""
        print(nextsteps % {"directory": target or project_name})

COMMANDS = {
    "start": CreateProject(),
}

def prog_name():
    return os.path.basename(sys.argv[0])

def help_index():
    print(
        "Type '%s help <subcommand>' for help on a specific subcommand.\n" % prog_name()
    )
    print("Available subcommands:\n")
    for name, cmd in sorted(COMMANDS.items()):
        print(f"    {name.ljust(20)}{cmd.help}")

def unknown_command(command):
    print(f"Unknown command: '{command}'")
    print(f"Type '{prog_name()} help' for usage.")
    sys.exit(1)

def main():
    try:
        command_name = sys.argv[1]
    except IndexError:
        help_index()
        return

    if command_name == "help":
        try:
            help_command_name = sys.argv[2]
        except IndexError:
            help_index()
            return

        try:
            command = COMMANDS[help_command_name]
        except KeyError:
            unknown_command(help_command_name)
            return

        command.print_help(prog_name(), help_command_name)
        return

    try:
        command = COMMANDS[command_name]
    except KeyError:
        unknown_command(command_name)
        return

    command.run_from_argv(sys.argv)

if __name__ == "__main__":
    main()


from django.urls import path

from . import views

app_name='peak_numbers'
urlpatterns=[

    path('num',views.num,name="peaknum"),
    path('leaders',views.leaders,name="leaders"),
    path('common',views.common_num,name="common")
]


import re
import os

def cpuCelsius():
    with open('/sys/class/thermal/thermal_zone0/temp', 'r') as cpuCelsiusFile:
        cpuCelsius = str(round(int(cpuCelsiusFile.readline())/1000))
        return cpuCelsius

def gpuCelsius():
    gpuCelsius = ''
    if os.path.isfile('/opt/vc/bin/vcgencmd'):
        stream = os.popen('/opt/vc/bin/vcgencmd measure_temp')
        gpuCelsius = str(int(re.sub('[^0-9]', '', stream.read())) / 10)
    return gpuCelsius

def cpuLoad():
    with open('/proc/loadavg', 'r') as cpuLoadFile:
        load = cpuLoadFile.readline()[:4]
        return load

def memoryUsed():
    freeMemoryStream = os.popen('cat /proc/meminfo | grep MemFree')
    totalMemoryStream = os.popen('cat /proc/meminfo | grep MemTotal')
    freeMemory = int(re.sub('[^0-9]', '', freeMemoryStream.read()))
    totalMemory = int(re.sub('[^0-9]', '', totalMemoryStream.read()))
    usedMemory = totalMemory - freeMemory
    usedMemoryReadable = str(round(usedMemory/1024))
    return usedMemoryReadable

def memoryFree():
    freeMemoryStream = os.popen('cat /proc/meminfo | grep MemFree')
    freeMemory = int(re.sub('[^0-9]', '', freeMemoryStream.read()))
    freeMemoryReadable = str(round(freeMemory/1024))
    return freeMemoryReadable


#-*- coding: utf-8 -*-
from contextlib import closing
from flask import Flask, render_template, g, url_for, redirect, request, abort
from models import Post, PostRoot
from datetime import datetime, timedelta
import time

app = Flask(__name__)
app.config.from_object('config')

def getMessage():
	heekPost = PostRoot(key_name='heek', version=2)

	query = Post.all()
	query.ancestor(heekPost)
	query.order('-datetime')

	for post in query.run(limit=1):
        	return post.text

def getSatTimedelta():
	now = datetime.now()
	sat = datetime(2017, 11, 16, 8, 40)
	interval = sat - now

	# if interval < timedelta(0):
	# 	sat = datetime(2016, 11, 17, 8, 40)
	# 	interval = sat - now

	return interval

def formatTime(interval):
	days = interval.days
	hours = interval.seconds / 60 / 60
	minutes = interval.seconds / 60 % 60
	seconds = interval.seconds % 60
	ms = interval.microseconds / 1000

	return u"%d일 %d시간 %d분 %d초 %d" % (days, hours, minutes, seconds, ms)

@app.route('/')
def index():
	msg = getMessage()

	interval = getSatTimedelta()
	time = formatTime(interval)

	blue = interval.total_seconds() / (365 * 24 * 60 * 60) * 255
	red = 255 - blue
	theme_color = '#%02x%02x%02x' % (red, blue, 0)

	return render_template('index.html',
						   entry=msg,
						   time=time,
						   theme_color=theme_color)

@app.route('/submit_entry', methods=['POST'])
def submit_entry():
	heekPost = PostRoot(key_name='heek', version=2)

	post = Post(parent=heekPost)
	post.text = request.form['message'][0:128]
	post.datetime = datetime.now()

	post.put()

	return redirect(url_for('index'))

@app.route('/history', methods=['GET'])
def history():
	show_count = 50
	startPage = int(request.args.get('page', 1))

	prevpage = startPage - 1
	if prevpage <= 0:
		prevpage = None
	nextpage = startPage + 1

	startOffset = startPage * show_count - show_count
	nextOffset = nextpage * show_count - show_count

	heekPost = PostRoot(key_name='heek', version=2)
	query = Post.all()
	query.ancestor(heekPost)
	query.order('-datetime')

	rows = [dict(text=post.text) for post in query.run(offset=startOffset, limit=show_count)]

	next_cnt = query.count(offset=nextOffset, limit=show_count)
	if next_cnt == 0:
		nextpage = None

	return render_template('history.html', contents=rows, prevpage=prevpage, nextpage=nextpage)


import os
import numpy as np
from sklearn.preprocessing import MinMaxScaler, StandardScaler

import torch
from torch.utils.data import TensorDataset, DataLoader, random_split

def load():

	# Load files
	path = '../../data/rsd_processed/undersampled/mfcc_40_delta_split_05_0125'

	data = np.load(os.path.join(path, 'rsd_s0.5_mfcc_40_d.npy'), allow_pickle=True)
	labels = np.load(os.path.join(path, 'labels_rsd.npy'))

	# Obtain a list of spectrograms
	arr_flattened = []
	labels_new = []
	for i, obj in enumerate(data):
		for spec in obj:
			arr_flattened.append(spec)
			labels_new.append(labels[i])

	# Label distubution
	hist = np.histogram(np.argmax(labels_new, axis=1), bins=8)
	#print("Label distribution:", hist, '\nTotal (label/data):', len(labels_new), len(arr_flattened))

	# Normalize (Per-image normalization)
	for i, spect in enumerate(arr_flattened):
		arr_flattened[i] = (spect-np.mean(spect))/np.std(spect)

	# Convert to numpy, add channel axis
	data = np.array(arr_flattened, dtype=np.float16)
	data = np.expand_dims(data, axis=1)

	# Convert to Pytorch DataLoader
	tensor_x = torch.from_numpy(data)
	tensor_x = tensor_x.float()
	tensor_y = torch.FloatTensor(labels_new)
	tensor_y = torch.argmax(tensor_y, dim=1)

	# Dataset
	full_dataset = TensorDataset(tensor_x, tensor_y)

	# Split to train-test sets
	len_train = int(0.9*len(tensor_x))
	len_test = len(tensor_x) - len_train
	train_dataset, test_dataset = random_split(full_dataset, [len_train, len_test])

	# Create dataloaders
	train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=32)
	test_dataloader = DataLoader(test_dataset, shuffle=True, batch_size=32)

	return [train_dataloader, test_dataloader]


import pygame
import sys
from random import randint

"""----------------------------------FLAPPY BIRD-----------------------------------------
------------------------------------BY: DANIEL SAGI-----------------------------------"""
Score = 0
exit = False
FrameRate = 0
#
pygame.font.init()
score_font = pygame.font.SysFont('Comic Sans MS', 30)
game_over_font = pygame.font.SysFont('Comic Sans MS', 45)
background = pygame.image.load("images/bg.png")

gameDisplay = None
Clock = None
#
BLACK = (0,0,0)
WHITE = (255,255,255)
SKY_BLUE = (0, 153, 204)
#
H = 650
W = 800
#
BLOCKS_WIDTH = 60
BLOCKS_SPACE = 350
PIPE_HEAD_HEIGHT = 30
PIPE_HEAD_OFFSET = 4
PIPE_HEAD_WIDTH = BLOCKS_WIDTH + PIPE_HEAD_OFFSET
#

"""-----------Control Panel------------"""
FPS = 120
BLOCKS_SPEED = 3
BACK_MOVIE_SPEED = 1
BIRD_ANDGLE_FACTOR = 3.1
BIRD_FLAP_FORCE = 5
MIN_PIPE_OPENING = 135
MAX_PIPE_OPENING = 160
"""------------------------------------"""

class Bird:
    def __init__(self):
        self.bird_image = pygame.image.load("images/flappybird.png")
        self.flap_force = BIRD_FLAP_FORCE
        self.speed = 0
        self.tilt = 0
        self.rect = pygame.Rect(W/3, H/4, 36, 28)

    def do_flap(self):
        self.speed = self.flap_force

    def draw(self):
        picture = pygame.transform.scale(self.bird_image, (self.rect.width,self.rect.height))
        picture = pygame.transform.rotate(picture, self.tilt)
        gameDisplay.blit(picture, (self.rect.x, self.rect.y, self.rect.width, self.rect.height))

    def is_collided_with_blocks(self, pipeSet):
        return

class Pipe:
    def __init__(self, height, isUp):
        self.body_height = height - PIPE_HEAD_HEIGHT

        # loading images and resizing them
        self.body = pygame.image.load("images/pipeBody.png")
        self.body = pygame.transform.scale(self.body, (BLOCKS_WIDTH, height))

        self.head = pygame.image.load("images/pipeHead.png")
        self.head = pygame.transform.scale(self.head, (BLOCKS_WIDTH + PIPE_HEAD_OFFSET, PIPE_HEAD_HEIGHT))

        self.isUp = isUp

    def draw(self, x):
        if self.isUp:
            gameDisplay.blit(self.body, (x, 0, BLOCKS_WIDTH, self.body_height))
            gameDisplay.blit(self.head, (x - PIPE_HEAD_OFFSET /2,
                                         self.body_height,
                                         PIPE_HEAD_WIDTH,
                                         PIPE_HEAD_HEIGHT))
        else:
            gameDisplay.blit(self.body, (x, H - self.body_height, BLOCKS_WIDTH, self.body_height))
            gameDisplay.blit(self.head, (x - (PIPE_HEAD_OFFSET/2),
                                         H-self.body_height-PIPE_HEAD_HEIGHT,
                                         PIPE_HEAD_WIDTH,
                                         PIPE_HEAD_HEIGHT))

class PipeSet:
    def __init__(self):
        self.opening_size = randint(MIN_PIPE_OPENING, MAX_PIPE_OPENING)
        self.behind_bird = False

        # calculating random opening, Both of down block and up block.
        self.up_height = randint(0, H-self.opening_size)
        self.down_height = H - self.up_height - self.opening_size

        # creating pipes
        self.up_pipe = Pipe(self.up_height, True)
        self.down_pipe = Pipe(self.down_height, False)

        #starting from edge
        self.X = W + PIPE_HEAD_WIDTH

        self.up_pipe_rect = pygame.Rect(self.X, 0, BLOCKS_WIDTH, self.up_height)
        self.down_pipe_rect = pygame.Rect(self.X, H - self.down_height, BLOCKS_WIDTH, self.down_height)

    def draw_blocks(self):
        self.up_pipe.draw(self.X)
        self.down_pipe.draw(self.X)

    def move_block(self, offset):
        self.X -= offset
        self.up_pipe_rect.x -= offset
        self.down_pipe_rect.x -= offset

    def is_colliding_bird(self, bird):
        return self.up_pipe_rect.colliderect(bird.rect) or self.down_pipe_rect.colliderect(bird.rect)

    def is_behind_bird(self, bird):
        if self.X + BLOCKS_WIDTH < bird.rect.x and self.behind_bird == False:
            self.behind_bird = True
            return True
        else:
            return False

class Movie:
    def __init__(self, image):
        self.source_image = image
        self.source_rect = image.get_rect(y=H-image.get_rect().height)
        self.tape = []
        self.tape.append(self.source_rect)
    def roll_display(self):
        for image_rect in self.tape:
            # adding image to back when first starts to go off screen
            if image_rect.x < 0 and len(self.tape) < 2:
                # new_rect = self.source_image.get_rect(x=self.source_image.get_rect().width)
                new_rect = pygame.Rect(self.source_rect.width-1, self.source_rect.y, self.source_rect.width, self.source_rect.height)
                self.tape.append(new_rect)

            if image_rect.x < 0 - image_rect.width:
                self.tape.remove(image_rect)

            image_rect.x -= BACK_MOVIE_SPEED
            gameDisplay.blit(self.source_image, image_rect)

def events(bird):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            return "QUIT"
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                bird.do_flap()
                return "CLAP"

def do_physics(bird):
    velocity = 0.15

    # bird falling and flapping physics
    bird.speed -= velocity
    bird.rect.y -= bird.speed

    if bird.speed > -90:
        bird.tilt = bird.speed * BIRD_ANDGLE_FACTOR

def game_over_stall(bird):
    global Score
    while True:
        gameover_surface = game_over_font.render("Game Over!", False, (0, 255, 0))
        gameDisplay.blit(gameover_surface, (W/2 - 120, H/3))
        pygame.display.update()
        event = events(bird)
        if event == "QUIT":
            pygame.quit()
            sys.exit()
        elif event == "CLAP":
            Score = 0
            bird.y = H/3
            break

def init_pygame():
    global gameDisplay, Clock
    gameDisplay = pygame.display.set_mode((W, H))
    Clock = pygame.time.Clock()
    pygame.display.set_caption("Flappy Bird - Daniel Sagi")
    icon = pygame.image.load("images/icon.png")
    pygame.display.set_icon(icon)

    pygame.init()

"""------------ MAIN --------------"""
def main():
    global Score, FrameRate
    init_pygame()
    bird = Bird()
    back_movie = Movie(background)

    pipeSets = []
    while True:
        FrameRate += 1
        if events(bird) == "QUIT": break
        elif FrameRate % 99 == 0:
            pipeSets.append(PipeSet())

        # if bird is out of boundaries of screen
        if bird.rect.y >= H + bird.rect.height:
            game_over_stall(bird)
            pipeSets = []

        gameDisplay.fill(SKY_BLUE)

        back_movie.roll_display()
        do_physics(bird)

        bird.draw()

        score_surface = score_font.render(" " +str(Score), False, (0, 0, 0))
        gameDisplay.blit(score_surface, (0, 0))

        for pipeSet in pipeSets:
            if pipeSet.is_behind_bird(bird):
                Score += 1
            if pipeSet.X <= 0 - BLOCKS_WIDTH:
                pipeSets.remove(pipeSet)
            else:
                pipeSet.move_block(BLOCKS_SPEED)
                pipeSet.draw_blocks()
                if pipeSet.is_colliding_bird(bird):
                    game_over_stall(bird)
                    pipeSets = []

        pygame.display.update()
        Clock.tick(FPS)

    pygame.quit()
    sys.exit()

main()


#%matplotlib notebook
import warnings
warnings.filterwarnings('ignore')

import numpy as np
import random
import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score, mean_squared_error
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

def generate_set(size):
    return 6 * np.random.rand(size, 1) - 2

m = 50
x = generate_set(m)

noise =  np.random.randn(m, 1)

theta = [0.7, 2]

y = theta[0]*x**2 - theta[1]*x + 3 + noise

def get_preds(x, y, degree):
    poly_feats = PolynomialFeatures(degree=degree, include_bias=False)
    x_poly = poly_feats.fit_transform(x)
    lr = LinearRegression()
    lr.fit(x_poly, y)
    return lr.predict(x_poly)

degrees = [2,   4,   8,   16,   32]
colors      = ['r', 'g', 'c', 'y', 'k']

plt.figure(figsize=(22, 6))
plt.scatter(x, y, marker='+', s=100, c='b' )

for degree, c in zip(degrees, colors):
    y_preds = get_preds(x, y, degree)

    plt.plot(
        sorted(x[:, 0]),
        y_preds[np.argsort(x[:, 0])],
        c,
        label= f'Model: {c}'
    )

#     print(
#     f'Degree: {degree}\n'
#     f'RMSE:   {np.sqrt(mean_squared_error(y, y_preds)):.3f}\n'
#     f'R2:     {r2_score(y, y_preds):.3f}'
#     '\n''-------------'
# )

plt.legend()
plt.grid(True)
plt.show()


import cv2
import os
import numpy as np
import torch
import math
import random

from detectron2.structures.boxes import Boxes
from detectron2.structures.instances import Instances
from detectron2.engine import DefaultPredictor
import detectron2.data.transforms as T
from detectron2.structures import ImageList

def get_images_from_dir(path):

    extensions = ['jpg', 'png', 'bmp']
    contents = os.listdir(path)
    contents.sort()
    image_contents = [imgpath for imgpath in contents if imgpath.split('.')[-1] in extensions and 'Annotated' not in imgpath]

    return image_contents

def draw_bboxes(img, cars_indices, BBOX_WIDTH):

    for r, c in zip(cars_indices[0], cars_indices[1]):
        start_point = (c - BBOX_WIDTH, r - BBOX_WIDTH)
        end_point = (c + BBOX_WIDTH, r + BBOX_WIDTH)
        img = cv2.rectangle(img, start_point, end_point, (0, 0, 255), 1)

def calculate_image_slices(img, patch_size):

    height = img.shape[0]
    width = img.shape[1]
    h_grid = int(np.floor(height/patch_size))
    w_grid = int(np.floor(width/patch_size))
    patch_coords = [0]*h_grid*w_grid

    i = 0
    for row in range(h_grid):
        for col in range(w_grid):
            patch_coords[i] = (row*patch_size, col*patch_size)
            i += 1

    return patch_coords

def get_instances(cars_img, neg_img, bbox_width, patch_coords, patch_size):

        h_start = patch_coords[0]
        w_start = patch_coords[1]
        cars_patch = cars_img[h_start : h_start+patch_size, w_start : w_start+patch_size]
        # cv2.imshow('cars', cars_patch)
        neg_patch = neg_img[h_start : h_start+patch_size, w_start : w_start+patch_size]
        cars_indices = np.where(cars_patch[:, :, 2] == 255)
        neg_indices = np.where(neg_patch[:, :, 0] == 255)
        pos_bboxes = [[c - bbox_width, r - bbox_width, c + bbox_width, r + bbox_width] for r, c in zip(cars_indices[0], cars_indices[1])]
        neg_bboxes = [[c - bbox_width, r - bbox_width, c + bbox_width, r + bbox_width] for r, c in zip(neg_indices[0], neg_indices[1])]
        pos_classes = [1]*len(pos_bboxes)
        neg_classes = [0]*len(neg_bboxes)

        #crop bboxes to patch
        for b in range(len(pos_bboxes)):
            for c in range(len(pos_bboxes[b])):
                if pos_bboxes[b][c] < 0:
                    pos_bboxes[b][c] = 0
                if pos_bboxes[b][c] >= patch_size:
                    pos_bboxes[b][c] = patch_size

        for b in range(len(neg_bboxes)):
            for c in range(len(neg_bboxes[b])):
                if neg_bboxes[b][c] < 0:
                    neg_bboxes[b][c] = 0
                if neg_bboxes[b][c] >= patch_size:
                    neg_bboxes[b][c] = patch_size

        boxes = Boxes(torch.tensor(pos_bboxes + neg_bboxes).to(torch.device('cuda:0')) )
        gt_classes = torch.tensor(pos_classes + neg_classes).to(torch.device('cuda:0') )

        return boxes, gt_classes

class CowcDataloaderOld():

    def __init__(self, config, DATASET_DIR):

        self.IMG_PATCH_SIZE = config.INPUT.MIN_SIZE_TEST
        self.BATCH_SIZE = 100
        self.BBOX_WIDTH = 18
        self.DATASET_DIR = DATASET_DIR
        self.config = config
        self.predictor = DefaultPredictor(config)
        self.backbone = self.predictor.model.backbone
        self.box_pooler = self.predictor.model.roi_heads.box_pooler
        self.box_head = self.predictor.model.roi_heads.box_head

        self.batches_per_img = []
        print("Loading dataset...")
        imgnames = get_images_from_dir(self.DATASET_DIR)
        for imgname in imgnames:
            print(imgname)
            self.batches_per_img.append(self.get_batches_from_img(imgname))
        print('Dataset loaded.')

    def preprocess_image(self, original_image):

        device = torch.device(self.config.MODEL.DEVICE)
        transform_gen = T.ResizeShortestEdge(
            [self.config.INPUT.MIN_SIZE_TEST, self.config.INPUT.MIN_SIZE_TEST], self.config.INPUT.MAX_SIZE_TEST
        )
        pixel_mean = torch.Tensor(self.config.MODEL.PIXEL_MEAN).to(device).view(-1, 1, 1)
        pixel_std = torch.Tensor(self.config.MODEL.PIXEL_STD).to(device).view(-1, 1, 1)
        height, width = original_image.shape[:2]
        image = transform_gen.get_transform(original_image).apply_image(original_image)
        image = torch.as_tensor(image.astype("float32").transpose(2, 0, 1))
        inputs = {"image": image, "height": height, "width": width}
        batched_inputs = [inputs]

        images = [x["image"].to(device) for x in batched_inputs]
        images = [(x - pixel_mean) / pixel_std for x in images]
        images = ImageList.from_tensors(images, self.backbone.size_divisibility)
        return images

    def get_instances(self, cars_img, neg_img, bbox_width, patch_coords, patch_size):

        h_start = patch_coords[0]
        w_start = patch_coords[1]
        cars_patch = cars_img[h_start : h_start+patch_size, w_start : w_start+patch_size]
        # cv2.imshow('cars', cars_patch)
        neg_patch = neg_img[h_start : h_start+patch_size, w_start : w_start+patch_size]
        cars_indices = np.where(cars_patch[:, :, 2] == 255)
        neg_indices = np.where(neg_patch[:, :, 0] == 255)
        pos_bboxes = [[c - bbox_width, r - bbox_width, c + bbox_width, r + bbox_width] for r, c in zip(cars_indices[0], cars_indices[1])]
        neg_bboxes = [[c - bbox_width, r - bbox_width, c + bbox_width, r + bbox_width] for r, c in zip(neg_indices[0], neg_indices[1])]
        pos_classes = [1]*len(pos_bboxes)
        neg_classes = [0]*len(neg_bboxes)

        #crop bboxes to patch
        for b in range(len(pos_bboxes)):
            for c in range(len(pos_bboxes[b])):
                if pos_bboxes[b][c] < 0:
                    pos_bboxes[b][c] = 0
                if pos_bboxes[b][c] >= patch_size:
                    pos_bboxes[b][c] = patch_size - 1

        for b in range(len(neg_bboxes)):
            for c in range(len(neg_bboxes[b])):
                if neg_bboxes[b][c] < 0:
                    neg_bboxes[b][c] = 0
                if neg_bboxes[b][c] >= patch_size:
                    neg_bboxes[b][c] = patch_size - 1

        boxes = Boxes(torch.tensor(pos_bboxes + neg_bboxes).to(torch.device('cuda:0')) )
        gt_classes = torch.tensor(pos_classes + neg_classes).to(torch.device('cuda:0') )

        return boxes, gt_classes

    def get_batches_from_img(self, imgname):

        cars_imgname = imgname.split('.')[0] + '_Annotated_Cars.png'
        neg_imgname = imgname.split('.')[0] + '_Annotated_Negatives.png'
        cars_img = cv2.imread(os.path.join(self.DATASET_DIR, cars_imgname))
        neg_img = cv2.imread(os.path.join(self.DATASET_DIR, neg_imgname))
        bigimg = cv2.imread(os.path.join(self.DATASET_DIR, imgname))
        patches_startpoints = calculate_image_slices(bigimg, self.IMG_PATCH_SIZE)
        train_features = None
        train_classes = None

        for patch_coords in patches_startpoints:
            h_start = patch_coords[0]
            w_start = patch_coords[1]
            img_patch = bigimg[h_start : h_start+self.IMG_PATCH_SIZE, w_start : w_start+self.IMG_PATCH_SIZE]
            boxes, gt_classes = get_instances(cars_img, neg_img, self.BBOX_WIDTH, patch_coords, self.IMG_PATCH_SIZE)
            if len(gt_classes) > 0:
                with torch.no_grad():
                    batched_input = self.preprocess_image(img_patch)
                    features = self.backbone(batched_input.tensor)
                    features = [features[f] for f in self.config.MODEL.ROI_HEADS.IN_FEATURES]
                    roi_features = self.box_pooler(features, [boxes])
                    conv_roi_features = self.box_head(roi_features)
                if train_features is None:
                    train_features = conv_roi_features.cpu()
                    train_classes = gt_classes.cpu()
                else:
                    train_features = torch.cat([train_features, conv_roi_features.cpu()], 0)
                    train_classes = torch.cat([train_classes, gt_classes.cpu()], 0)

        pos_indices = torch.where(train_classes == 1)[0]
        neg_indices = torch.where(train_classes == 0)[0]
        num_pos = len(pos_indices)
        num_neg = len(neg_indices)
        paired_num = min(num_pos, num_neg)
        num_samples = int(self.BATCH_SIZE/2)
        num_batches = math.floor(paired_num / num_samples)

        batches_list = []
        for batch_idx in range(num_batches):

            batch_pos_indices = pos_indices[batch_idx*num_samples : (batch_idx+1)*num_samples]
            batch_neg_indices = neg_indices[batch_idx*num_samples : (batch_idx+1)*num_samples]
            pos_features = train_features[batch_pos_indices]
            neg_features = train_features[batch_neg_indices]
            batch_train_features = torch.cat([pos_features, neg_features], 0)
            batch_train_labels = torch.tensor([1]*num_samples + [0]*num_samples)
            batches_list.append( (batch_train_features, batch_train_labels) )

        return batches_list

class CowcDataloader():

    def __init__(self, config, DATASET_DIR):

        self.IMG_PATCH_SIZE = config.INPUT.MIN_SIZE_TEST
        self.BATCH_SIZE = 100
        self.BBOX_WIDTH = 18
        self.IMAGES_PER_BATCH = 2
        self.DATASET_DIR = DATASET_DIR
        self.config = config
        self.imgnames = get_images_from_dir(self.DATASET_DIR)
        self.current_img = None
        self.current_cars_img = None
        self.current_patches_startpoints = None
        self.current_instances_per_patch = None

    def preprocess_image(self, original_image):

        device = torch.device(self.config.MODEL.DEVICE)
        transform_gen = T.ResizeShortestEdge(
            [self.config.INPUT.MIN_SIZE_TEST, self.config.INPUT.MIN_SIZE_TEST], self.config.INPUT.MAX_SIZE_TEST
        )
        pixel_mean = torch.Tensor(self.config.MODEL.PIXEL_MEAN).to(device).view(-1, 1, 1)
        pixel_std = torch.Tensor(self.config.MODEL.PIXEL_STD).to(device).view(-1, 1, 1)
        height, width = original_image.shape[:2]
        image = transform_gen.get_transform(original_image).apply_image(original_image)
        image = torch.as_tensor(image.astype("float32").transpose(2, 0, 1))
        inputs = {"image": image, "height": height, "width": width}
        batched_inputs = [inputs]

        images = [x["image"].to(device) for x in batched_inputs]
        images = [(x - pixel_mean) / pixel_std for x in images]
        images = ImageList.from_tensors(images, self.backbone.size_divisibility)
        return images

    def load_img(self, imgname):

        cars_imgname = imgname.split('.')[0] + '_Annotated_Cars.png'
        self.current_img = cv2.imread(os.path.join(self.DATASET_DIR, imgname) )
        self.current_cars_img = cv2.imread(os.path.join(self.DATASET_DIR, cars_imgname) )
        self.current_patches_startpoints = calculate_image_slices(self.current_img, self.IMG_PATCH_SIZE)
        self.current_instances_per_patch = {}
        for patch_coords in self.current_patches_startpoints:
            h_start = patch_coords[0]
            w_start = patch_coords[1]
            img_patch = self.current_img[h_start : h_start+self.IMG_PATCH_SIZE, w_start : w_start+self.IMG_PATCH_SIZE]
            cars_patch = self.current_cars_img[h_start : h_start+self.IMG_PATCH_SIZE, w_start : w_start+self.IMG_PATCH_SIZE]
            cars_indices = np.where(cars_patch[:, :, 2] == 255) # tuple of two arrays
            if len(cars_indices[0]) > 0:
                patch_instances = Instances( (self.IMG_PATCH_SIZE, self.IMG_PATCH_SIZE) )
                pos_bboxes = [[c - self.BBOX_WIDTH, r - self.BBOX_WIDTH, c + self.BBOX_WIDTH, r + self.BBOX_WIDTH] for r, c in zip(cars_indices[0], cars_indices[1])]
                classes = [0]*len(pos_bboxes)
                for b in range(len(pos_bboxes)):
                    for c in range(len(pos_bboxes[b])):
                        if pos_bboxes[b][c] < 0:
                            pos_bboxes[b][c] = 0
                        if pos_bboxes[b][c] >= self.IMG_PATCH_SIZE:
                            pos_bboxes[b][c] = self.IMG_PATCH_SIZE - 1
                gt_boxes = Boxes(torch.tensor(pos_bboxes).to(torch.device('cuda:0')) )
                gt_classes = torch.tensor(classes).to(torch.device('cuda:0') )
                patch_instances._fields['gt_boxes'] = gt_boxes
                patch_instances._fields['gt_classes'] = gt_classes
                self.current_instances_per_patch[patch_coords] = patch_instances

    def get_batch(self):

        batch = []
        for i in range(self.IMAGES_PER_BATCH):
            print(patches_startpoints)

    # def get_imgdict(self, patch_coords):


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 19 09:49:02 2018

@author: MarioAntao
"""
import pickle
import random
import numpy as np
import pandas as pd
class Review(object):
    """Class represents tweet from Twitter.

    Attributes:
        reviewer_id: A unique identifier.
        product_id : A unique identifier.
        ReviewTime: A date-time, describing when the review was created.
        reviewText: A string, containing the text of the review.
        overall: A float, stating the rating of the product.
        summary: A string, containing the summary of the review.
        helpful: An integer, stating the number of favorites.
        category: A list, containing the helpfulness rating of the review.
    """

    def __init__(self, reviewer_id, product_id, ReviewTime, reviewText, overall, summary, helpful, category):
        """Initialzes Review class with defined content."""
        self.reviewer_id = reviewer_id
        self.product_id = product_id
        self.ReviewTime = ReviewTime
        self.reviewText = reviewText
        self.overall = overall
        self.summary = summary
        self.helpful = helpful
        self.category = category
        self.cleaning_log = dict()
    def __str__(self):
        """Creates user-friendly string representation of review."""

        return "reviewer_id: {}\nProduct_id: {}\nReviewTime: {}\nreviewText: {}\noverall: {}\nsummary: {}\nhelpful: {}\ncategory: {}".\
            format(self.reviewer_id, self.product_id, self.ReviewTime, self.reviewText, self.overall,
                   self.summary, self.helpful, self.category)

    def __eq__(self, other):
        """
        Determines if review is equal to other review.

        Compares the reviewer_id value. Returns True if reviewer_ids are equal.
        """
        return self.reviewer_id == other.reviewer_id

    def __hash__(self):
        """
        Returns a unique hash value.
        """
        return hash(self.reviewer_id)

    def count_number_of_words(self):
        """
        Counts the words in the review.

        Retrieves the text from the week_3.tweet, splits it by spaces and counts
        the length of the list.

        Returns:
            An interger value, corresponding to the number of words in the week_3.tweet.
        """
        word_list = self.reviewText.split()
        return len(word_list)

def create_review_from_dict(review_dict):
    """
    Creates a review object from dictionary.

    Extracts reviewer_id, helpful, reviewText, overall,
    summary,unixReviewTime, product_id and category from dictionary.

    Args:
        review_dict: A dictionary, containing review information.

    Returns:
        A review object.
    """

    # Extract parameters from dictionary
    reviewer_id = review_dict.get('reviewer_id')
    helpful = review_dict.get('helpful')
    reviewText = review_dict.get('reviewText')
    overall = review_dict.get('overall')
    summary = review_dict.get('summary')
    ReviewTime = review_dict.get('unixReviewTime')
    category = review_dict.get('category')
    product_id = review_dict.get('product_id')

    # Create review object
    review = Review(reviewer_id, product_id, ReviewTime, reviewText, overall, summary, helpful, category)

    return review

def make_review_set(filename):
    """
    Creates set of tweets from week_3.data/01_raw/trump_tweets.json.
    Returns:
        Set of week_3.tweet objects.
    """

    # Create set and review.Review objects.
    review_set = set()

    for revieww in sample_review:
        review = create_review_from_dict(revieww)
        review_set.add(review)

    return review_set

import pickle
import pandas as pd

merged_dic=pd.read_pickle('merged_dic.pickle')

sample_review=random.sample(merged_dic,1000)

review_set=make_review_set(merged_dic)

review_train_set=make_review_set(review_train)
review_test_set=make_review_set(review_test)

review_sample_set=make_review_set(sample_review)

l= list(review_train_set)

from sklearn.cross_validation import train_test_split

review_train,review_test=train_test_split(merged_dic,test_size=0.3)

"""Export Data with pickle"""
with open('review_test_set.pickle', 'wb') as handle:
    pickle.dump(review_test_set, handle, protocol=pickle.HIGHEST_PROTOCOL)

"""Export Data with pickle"""
with open('merged_test.pickle', 'wb') as handle:
    pickle.dump(merged_test, handle, protocol=pickle.HIGHEST_PROTOCOL)

review_test_set=pd.read_pickle('review_test_set.pickle')
review_train_set=pd.read_pickle('review_train_set.pickle')
review_sample_set=pd.read_pickle('review_sample_set.pickle')

calculate_average_reviews_per_day(review_sample_set)

calculate_average_word_count(review_test_set)

get_top_mentions(review_set)

review_sample_set['overall']

#Convert set to List
test_list = list(review_sample_set)

#Flat List
test_list = [" ".join(item) for Review in test_list for item in Review.text_cleaned]

flat_list = [item for sublist in test_list for item in sublist]
#Merge List String

test_list_merge = ' '.join([word for word in review_sample_list])


'''
Navigation Screen
=================
Display a Navigation drawer

-------- ----------------------------------
        | =    PyCon India 2017            |
        |__________________________________
        |                                  |
        |                                  |
        |                                  |
But1    |                                  |
        |     Logo Here                    |
But2    |                                  |
        |                                  |
But3    |       ----------------------     |
        |     [ Workshop + Dev Sprints ]   |
But4    |       ----------------------     |
        |                                  |
But5    |       ----------------------     |
        |     [ Conference Days        ]   |
But6    |       ----------------------     |
        |                                  |
        |                                  |
'''

# from kivy.factory import Factory
# Factory.register('NavigationDrawer', module='uix.navigationdrawer')
from uix.navigationdrawer import NavigationDrawer
from kivy.uix.screenmanager import Screen
from kivy.properties import (ObjectProperty, NumericProperty, OptionProperty,
                             BooleanProperty, StringProperty)
from kivy.factory import Factory
from kivy.lang import Builder
from kivy.app import App

from uix.buttons import ImageButton

import json

class NavButton(Factory.ButtonBehavior, Factory.BoxLayout):
    menu_item_text = StringProperty('')
    icon_source = StringProperty('')
    navigate_to = StringProperty('')

class LeftPanel(Factory.BoxLayout):
    Builder.load_string('''
<LeftPanel>
    orientation: 'vertical'
    canvas:
        Color:
            rgba: 1, 1, 1, 1
        Rectangle:
            size: self.size
            pos: self.pos
    Image
        id: img_back
        source: "data/images/background.png"
        allow_stretch: True
        keep_ratio: False
        size_hint: 1, None
        height: self.width/2
        Image
            source: 'data/images/logo.png'
            size: img_back.width, img_back.height/3.
            center: img_back.center

    RelativeLayout
        size_hint: 1, 1
        BoxLayout
            id: menu_buttons_container
            size_hint: 1, .8
            pos_hint: {'center_y': .55}
            orientation: 'vertical'

    ''')

class TopBar(Factory.BoxLayout):

    #this part of code loads data from event.json for event title
    with open('eventsapp/data/jsonfiles/event.json') as data_file:
        data = json.load(data_file)
    event_items = data.get("0.0.2")
    for items in event_items:
        event_name=items['name']

    back_button_image = StringProperty('data/images/hamburger.png')
    title = StringProperty(event_name)
    navigate_back = BooleanProperty(False)

    def on_menu_press(self):
        app = App.get_running_app()
        if self.navigate_back:
            manager = app.navigation_screen.ids.nav_manager
            manager.transition.direction = 'right'
            manager.current = 'ScheduleScreen'
        else:
            app.navigationdrawer.toggle_state()

    Builder.load_string('''
<TopBar>
    size_hint: 1, None
    height: dp(50)
    width: dp(45)
    spacing: dp(15)
    canvas.before:
        Color:
            rgba: 69/255., 132/255., 182/255., 1
        Rectangle:
            size: self.size
            pos: self.pos
    ImageButton:
        source: root.back_button_image
        on_release: root.on_menu_press()
    Label:
        text: root.title
        shorten: True
        text_size: self.size
        font_size: dp(22)
        halign: 'left'
        valign: 'center'
    ''')

class NavigationScreen(Screen):

    Builder.load_string('''
<NavButton>
    padding: dp(10)
    spacing: dp(10)
    on_release:
        app.navigation_screen.ids.drawer.toggle_state()
        app.load_screen(root.navigate_to,
        manager=app.navigation_screen.ids.nav_manager)
    Image:
        source: root.icon_source
        size_hint_x: None
        width: self.height
    Label:
        text: root.menu_item_text
        text_size: self.size
        halign: 'left'
        valign: 'center'
        font_size: dp(18)
        color: 0, 0, 0, 1

<NavigationScreen>
    name: 'NavigationScreen'
    on_parent: app.navigation_screen = self
    NavigationDrawer
        id: drawer
        anim_type: 'slide_above_simple'
        side_panel_width: max(dp(250), 0.8 * self.width)
        on_parent: if self.parent: app.navigationdrawer = self
        LeftPanel
            id: leftpanel
            on_right: nav_manager.opacity = 1.15 - (self.right/drawer.side_panel_width)
        ScreenManager
            id: nav_manager
            on_parent: if self.parent: app.load_screen('WelcomeScreen', manager=self)

    ''')

    def on_pre_enter(self, onsuccess = False):
        menu_container = self.ids.leftpanel.ids.menu_buttons_container
        menu_container.clear_widgets()
        with open('eventsapp/data/jsonfiles/menuitems.json') as data_file:
            data = json.load(data_file)
        menuitems = data.get("0.0.1")
        for item in menuitems:
            bl = Factory.NavButton(navigate_to=item['navigate_to'],
                                   menu_item_text=item['menu_item_text'],
                                   icon_source=item['icon_source'])
            menu_container.add_widget(bl)


from PIL import ImageFont, ImageDraw
import PIL
import datetime
import os
import tkinter
from tkinter import filedialog, messagebox

class Application:

    def __init__(self):

        self.date_font = ImageFont.truetype('./conf/OpenSans-Bold.ttf', 150) # ustawienie czcionki dla daty

        self.okno = tkinter.Tk()  # tworzenie okna głównego
        self.okno.geometry("600x200") # ustawienie wymiarów okna
        self.okno.title("Date2JPG")  # ustawienie tytułu okna głównego

        self.naglowek = tkinter.Label(self.okno, text = "Program nanosi na zdjęcie datę wyciągniętą z jego EXIF.\n"
                                                        "Zdjęcia są pobierane z katalogu źródłowego i po naniesieniu\n"
                                                        "daty zapisywane w katalogu docelowym.\n")
        self.naglowek.pack()

        self.kz = os.getcwd()  # katalog źródłowy
        self.kd = os.getcwd()  # katalog docelowy

        self.ramka1 = tkinter.Frame(self.okno)
        self.ramka1.pack(fill=tkinter.BOTH, expand=True)

        self.wkz_button = tkinter.Button(self.ramka1, width=20, text="Wybierz katalog źródłowy:",
                                    command=self.wybierz_katalog_zrodlowy)
        self.wkz_button.pack(side=tkinter.LEFT)
        self.wkz_label = tkinter.Label(self.ramka1, text=self.kz)
        self.wkz_label.pack(side=tkinter.LEFT)

        self.ramka2 = tkinter.Frame(self.okno)
        self.ramka2.pack(fill=tkinter.BOTH, expand=True)

        self.wkd_button = tkinter.Button(self.ramka2, width=20, text="Wybierz katalog docelowy:",
                                    command=self.wybierz_katalog_docelowy)
        self.wkd_button.pack(side=tkinter.LEFT)

        self.wkd_label = tkinter.Label(self.ramka2, text=self.kd)
        self.wkd_label.pack(side=tkinter.LEFT)

        self.ramka3 = tkinter.Frame(self.okno)
        self.ramka3.pack(fill=tkinter.BOTH, expand=True)

        self.uruchom_button = tkinter.Button(self.ramka3, width=20, text="Uruchom!",
                                    command=self.wykonaj_dzialania)
        self.uruchom_button.pack(side=tkinter.LEFT)

        self.uruchom_label = tkinter.Label(self.ramka3, text="")
        self.uruchom_label.pack(side=tkinter.LEFT)

        self.etykieta = tkinter.Label(self.okno, text="by AdrianSo")
        self.etykieta.pack()

        self.okno.mainloop()

    def wybierz_katalog_zrodlowy(self):

        katalog = tkinter.filedialog.askdirectory()
        if katalog:
            self.kz = katalog
            self.wkz_label.configure(text=self.kz)

    def wybierz_katalog_docelowy(self):

        katalog = tkinter.filedialog.askdirectory()
        if katalog:
            self.kd = katalog
            self.wkd_label.configure(text=self.kd)

    def wykonaj_dzialania(self):

        if self.kd == self.kz:
            tkinter.messagebox.showinfo("Info", "Katalog docelowy musi być inny niż źródłowy.")  # info o błędzie
            return
        else:
            lista = list(os.listdir(self.kz))
            lista.sort()
            for i in lista:
                if os.path.isfile("{}/{}".format(self.kz,i)) and os.path.splitext(i)[1].upper()[1:] == "JPG":
                    self.uruchom_label.configure(text = "Przetwarzam {}".format(i))
                    self.uruchom_label.update_idletasks()
                    self.date2img(i)
                self.uruchom_label.configure(text = "Skończyłem przetwarzać")

    def date2img(self,i):

        # otwieranie zdjęcia i konwertowanie do RGBA

        self.img = PIL.Image.open("{}/{}".format(self.kz,i)).convert("RGBA")

        # wyciąganie daty z EXIF zdjęcia i formatowanie jej

        self.img_exif = dict(self.img.getexif())
        self.img_date = str(self.img_exif[36867])
        self.img_date_obj = datetime.datetime.strptime(self.img_date, "%Y:%m:%d %H:%M:%S")
        self.img_date_obj = self.img_date_obj.strftime("%d-%m-%Y")

        # tworzenie obrazu z datą

        self.img_text = PIL.Image.new('RGBA', self.img.size, (255, 255, 255, 0))
        self.img_text_draw = PIL.ImageDraw.Draw(self.img_text)
        self.img_text_draw.text(
            (self.img.size[0] - 1000,
            self.img.size[1] - 300),
            self.img_date_obj,
            font=self.date_font,
            fill=(255, 255, 255, 255)
        )

        # łączenie zdjęcia z obrazem z datą i konwertowanie do RGB

        self.img_with_date = PIL.Image.alpha_composite(self.img, self.img_text).convert("RGB")

        # zapisywanie zdjęcia z datą

        self.img_with_date.save("{}/{}".format(self.kd,i), quality=98)

app = Application()


class Ziemniak:
    def __init__(self, sort_name, dimension, price):
        self.sort_name = sort_name
        self.dimension = dimension
        self.price = price

    def calculate_order_value(self, amount):
        order_value = amount * self.price
        print(f"Całkowita wartość zamówienia na {amount} kg ziemniaków {self.sort_name} wynosi {order_value} zł.")

ziemniak_1 = Ziemniak(sort_name="Niwa", dimension=5, price=1.5)
ziemniak_2 = Ziemniak(sort_name="Luga", dimension=8, price=1.0)
ziemniak_3 = Ziemniak(sort_name="Luksusowy", dimension=15, price=2.4)

ziemniak_3.calculate_order_value(amount=3)
ziemniak_2.calculate_order_value(amount=10)
ziemniak_1.calculate_order_value(amount=25)


'''
#### Name:  Rearrange the array in alternating positive and negative items
Link: [link]()

#### Sub_question_name: Without Extra Space and Stable
Link: [gfg](https://www.geeksforgeeks.org/rearrange-array-alternating-positive-negative-items-o1-extra-space/)

**O(n) O(1) stable**
'''

def rearrange(arr):
    n = len(arr)

    i = -1

    for j in range(n):
        if arr[j] < 0:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]

    neg, pos = 0, i+1
    print(arr)

    # Make order into alternate
    if (n-pos) > (pos-neg):          # [1, -3, 7, -1, 5, -2, 6] if no of positive numbers are more
        pass
    else:                    # [-1, 7, -2, 1, -3, 6, -5] if no_of_negatives numbers are more
        neg = 1

    while pos < n and neg < pos and arr[neg] < 0:
        arr[neg], arr[pos] = arr[pos], arr[neg]
        pos += 1
        neg += 2

    print(arr)

arr = [1, -1, -3, -2, 7, 5, 6]   # [1, -3, 7, -1, 5, -2, 6]
arr = [1, -1, -3, -2, -7, 5, 6]   # [-1, 1, -2, 5, -3, 6, -7]
rearrange(arr)

Data/Arrays/Rearrange the array in alternating positive and negative items/Without Extra Space and Stable.py


""" A message dispatcher.

This is a module for a message dispatcher
for both incoming messages and outgoing messages.
However, the outgoing message dispatcher is not in used.

@author: Thanakorn Sueverachai
"""

import logging
import threading
import zmq

from NetworkSearch2.QuerySubsystem.echoMessage import ECHOMessage

# for profiling
from NetworkSearch2.ProfileTools.myProfiler import Profiler
import time

#############################
# read a configuration file #
#############################
from ConfigParser import SafeConfigParser
from sys import path

confparser = SafeConfigParser()
confparser.read([str(path[0])+'/config.cfg'])

# get values
DISPATCHER_PORT = confparser.getint('Dispatcher','dispatcher_port')

del confparser

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

class IncomingDispatcher(threading.Thread):
    """ A thread that receives incoming messages, multiplexes
    and load-balances to workers (echoProcesses)."""

    def __init__(self,process_queue_list):
        # base class initialization
        super(IncomingDispatcher,self).__init__()

        self.process_queue_list = process_queue_list
        self.Nprocess = len(process_queue_list)

        # open message receiving socket.
        self.context = zmq.Context()
        self.receiver = self.context.socket(zmq.PULL)
        self.receiver.bind("tcp://*:"+str(DISPATCHER_PORT))

        logging.info("Incoming dispatcher initiated Successfully.")

    def run(self):
        """ Override method run() in a Thread"""

        #assign function addresses locally
        dispatch = self.dispatch
        receiver = self.receiver

        while 1:
            #receive a digested message from other nodes
            digested_message = receiver.recv()

            dispatch(ECHOMessage.deserialize(digested_message))

    def dispatch(self, echoMessage):
        """ dispatch a message to a echoProcess worker based on load-balancing scheme."""

        if Profiler.enabled:
            Profiler.send_data(('transmission_of_msg_type_%i' % echoMessage.get_type()),time.time()-echoMessage.t0)
            # re-measure t0 for queuing time
            echoMessage.t0 = time.time()

        #TODO: add proper load balancing. For now, use id%Nprocess
        invoke_id = echoMessage.get_id()
        # send to a queue
        self.process_queue_list[invoke_id%self.Nprocess].put(echoMessage)

        #print "{}".format(self.process_queue_list[0].qsize())

        #Correct load balance
#         #TODO: need a capped dict, reduce CPU usage or come up with the new idea to LB
#         try:
#             # send to the queue in case of its invoke id has been visited before
#             self.process_queue_list[self.multiplex_table[invoke_id]].put(echoMessage)
#         except KeyError:
#             # send to a queue by apply load balancing
#             #TODO: what if all queue empty all the time
#             min_queue = min(self.process_queue_list, key=lambda x: x.qsize())
#             min_queue.put(echoMessage)
#             self.multiplex_table[invoke_id] = self.process_queue_list.index(min_queue)
#
#         #print "{} {} {}".format(self.process_queue_list[0].qsize(),self.process_queue_list[1].qsize(),self.process_queue_list[2].qsize())

#TODO: not in used
# class OutgoingDispatcher(threading.Thread):
#     """ It receives outgoing messages from workers (echoProcesses) and transmits to destinations."""
#
#     def __init__(self,neighbor_list):
#         # base class initialization
#         super(OutgoingDispatcher,self).__init__()
#
#         self.context = zmq.Context()
#         self.receiver = self.context.socket(zmq.PULL)
#         self.receiver.bind("ipc:///tmp/outgoing") # ipc : local inter-process communication
#
#         #setup queues and outgoing_socket_thread
#         self.setup_outgoing_queue_and_socket(neighbor_list)
#
#         logging.info("Outgoing dispatcher initiated Successfully.")
#
#     def setup_outgoing_queue_and_socket(self,neighbor_list):
#         """ initialize outgoing queues and sockets"""
#
#         #setup queues and outgoing_socket_thread
#         self.outgoing_queues = {}
#         for neighbor in neighbor_list:
#             self.outgoing_queues[neighbor] = Queue.Queue()
#             threading.Thread(target=self.outgoing_socket_thread,
#                              args=(self.outgoing_queues[neighbor],neighbor,DISPATCHER_PORT)).start()
#
#         #add a special outgoing_socket_thread for sending a return message
#         self.outgoing_queues['localhost'] = Queue.Queue()
#         threading.Thread(target=self.outgoing_socket_thread,
#                         args=(self.outgoing_queues['localhost'],'localhost',INTERFACE_PORT)).start()
#
#     def outgoing_socket_thread(self,queue,neighbor_address,port):
#         """ a thread for getting a message from the queue and send it to destination """
#
#         sender = self.context.socket(zmq.PUSH)
#         sender.connect("tcp://{0}:{1}".format(neighbor_address,port))
#
#         while 1:
#             sender.send(queue.get())
#
#
#     #override method run() in a Thread
#     def run(self):
#         #assign function addresses locally
#         dispatch = self.dispatch
#         receiver = self.receiver
#
#         while 1:
#             #receive a message tuple from echoProcess
#             message_tuple = receiver.recv_multipart()
#             dispatch(message_tuple)
#
#
#     def dispatch(self, message_tuple):
#         """ dispatch a message from a echoProcess worker and place in outgoing queue."""
#         message_content = message_tuple[0]
#         destination_list = message_tuple[1:]
#
#         for destination_name in destination_list:
#             try:
#                 self.outgoing_queues[destination_name].put(message_content)
#             except KeyError:
#                 logging.error("Can't find destination to {0} for sending a message".format(destination_name))
#


"""

46. Permutations
Medium

6035

135

Add to List

Share
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Example 1:

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Example 2:

Input: nums = [0,1]
Output: [[0,1],[1,0]]
Example 3:

Input: nums = [1]
Output: [[1]]

Constraints:

1 <= nums.length <= 6
-10 <= nums[i] <= 10
All the integers of nums are unique.
Accepted
815,191
Submissions
1,207,578

"""

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        if len(nums) < 2:
            return [nums]
        result = []
        for i in range(len(nums)):
            temp_nums = nums[:]
            num = temp_nums.pop(i)
            crazy_shit = self.permute(temp_nums)
            for crazy in crazy_shit:
                result.append([num] + crazy)

        return result


"""
    Simple resources monitoring script

    Author: L1ttl3S1st3r
    Date: 14 April 2020
"""
from psutil import cpu_percent
from psutil import cpu_count
from psutil import virtual_memory

OUTPUT_DELAY = 0.4

def format_columns(columns):
    formatted_columns = ["{0:^23}".format(column) for column in columns]
    return '|'.join(formatted_columns)

def resources_header():
    columns = [f'cpu {number+1} usage (%)' for number in range(cpu_count())]
    columns += ['memory occupied (%)']

    return format_columns(columns)

def resourses_row():
    columns = cpu_percent(interval=OUTPUT_DELAY, percpu=True)
    columns += [virtual_memory().percent]

    return format_columns(columns)

if __name__ == '__main__':
    print(resources_header())
    while True:
        print(resourses_row())


# 1 Design Linked List
'''
Find the predecessor of the node to insert, if the node is to be inserted at head, its predecessor is a sentinel head
If the node is to be inserted at tail, its predecessor is the last node
'''

class ListNode:
    def __init__(self,x):
        self.val = x
        self.next = None
class MyLinkedList:
    def __init__(self):
        self.size = 0
        self.head = ListNode(0)

    def get(self, index):
        if index<0 or index >= self.size:
            return -1
        curr = self.head
        for i in range(index+1):
            curr = curr.next
        return curr.val
    def addAtHead(self,val):
        self.addAtIndex(0,val)
    def addAtTail(self,val):
        self.addAtIndex(self.size,val)
    def addAtIndex(self,index,val):
        if index > self.size:
            return
        if index<0:
            index = 0
        self.size += 1
        pred = self.head
        for i in range(index):
            pred = pred.next
        to_add = ListNode(val)

        to_add.next = pred.next
        pred.next = to_add
    def deleteAtIndex(self,index):
        if index < 0 or index > self.size:
            return
        self.size -= 1
        pred = self.head
        for i in range(index):
            pred = pred.next

        pred.next = pred.next.next


from os import path
from setuptools import setup, find_packages

with open('requirements.txt') as reqs_file:
    requirements = reqs_file.read().splitlines()

with open('test-requirements.txt') as reqs_file:
    test_requirements = reqs_file.read().splitlines()

# Get the long description from the relevant file
long_description = 'PyDriller is a Python framework that helps developers on ' \
                   'mining software repositories. With PyDriller' \
                   ' you can easily extract information from any Git ' \
                   'repository, such as commits, developers, ' \
                   'modifications, diffs, and source codes, and ' \
                   'quickly export CSV files.'

def get_version():
    with open(path.join(path.dirname(__file__), 'pydriller', '__init__.py')) as f:
        for line in f:
            if line.startswith('__version__'):
                delim = '"' if '"' in line else "'"
                return line.split(delim)[1]
        raise RuntimeError("Unable to find version string.")

setup(
    name='PyDriller',
    description='Framework for MSR',
    long_description=long_description,
    author='Davide Spadini',
    author_email='spadini.davide@gmail.com',
    version=get_version(),
    packages=find_packages('.', exclude=['tests*']),
    url='https://github.com/ishepard/pydriller',
    license='Apache License',
    package_dir={'pydriller': 'pydriller'},
    python_requires='>=3.5',
    install_requires=requirements,
    tests_require=requirements + test_requirements,
    classifiers=[
            # How mature is this project? Common values are
            #   3 - Alpha
            #   4 - Beta
            #   5 - Production/Stable
            'Development Status :: 5 - Production/Stable',
            'Environment :: Console',
            'Intended Audience :: Developers',
            'Intended Audience :: Science/Research',
            'License :: OSI Approved :: Apache Software License',
            'Programming Language :: Python :: 3.6',
            'Programming Language :: Python :: 3.7',
            'Programming Language :: Python :: 3.8',
            'Programming Language :: Python :: 3.9',
            'Topic :: Software Development :: Libraries :: Python Modules',
            "Operating System :: OS Independent",
            "Operating System :: POSIX",
            "Operating System :: Microsoft :: Windows",
            "Operating System :: MacOS :: MacOS X",
            ]
)


class Solution:
    def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:
        # 当两种方案的efficiency相等时,speed之和更大的方案显然更优
        # 题目的输入决定了最多有 n 种 efficiency
        # 对于每种 efficiency 肯定都会存在最优的方案
        # 最终答案肯定就是这个n种方案里面最优的那个
        # 问题转化成了如何快速求出每种 efficiency 的最优方案
        arr = [(speed[i],efficiency[i]) for i in range(n)]
        arr.sort(key = lambda x:-x[1])  # 高效率的排在前面
        #print(arr)
        q = []  # speed的小根堆
        ans = 0
        _sum = 0    # 当前speed的和
        for s,e in arr:
            if len(q) == k:
                minSpeed = heapq.heappop(q)    # 当前speed的最小值
                _sum -= minSpeed
            else:
                minSpeed = 0
            heapq.heappush(q,max(minSpeed,s))   # 找一个speed更高的员工加入
            _sum += max(minSpeed,s)
            ans = max(ans,e * _sum)
        return ans % (10 ** 9 + 7)