import praw
import re
import random

from pymongo import Connection, DESCENDING, ASCENDING, MongoClient
global client
client = MongoClient()
global conn
conn = Connection().Bachelor
global question_database
question_database = conn.questions
global comment_database
comment_database = conn.comments

global negativeWords
f = open('negative.txt', 'r')
negativeWords = [line.strip() for line in f]
global positiveWords
g = open('positive.txt', 'r')
positiveWords = [line.strip() for line in g]

negativeSet = set(negativeWords)
positiveSet = set(positiveWords)

f.close()
g.close()

bad_question_words = ["should I", "can I", "EDIT"]
remove_words = [" of Reddit", "Redditors", "Redditor", "Reddit"]
comment_list = []

global profanity
profanity = (
'sex', 'bum', 'shitfaced', 'fucked', 'plastered', 'wasted', 'hammered', 'cheating', 'sex', 'lust', 'thrust', 'pelvic',
'breast', 'breasts', 'anus', 'arse', 'arsehole', 'ass', 'ass-hat', 'ass-jabber', 'ass-pirate', 'assbag', 'assbandit',
'assbanger', 'assbite', 'assclown', 'asscock', 'asscracker', 'asses', 'assface', 'assfuck', 'assfucker', 'assgoblin',
'asshat', 'asshead', 'asshole', 'asshopper', 'assjacker', 'asslick', 'asslicker', 'assmonkey', 'assmunch', 'assmuncher',
'assnigger', 'asspirate', 'assshit', 'assshole', 'asssucker', 'asswad', 'asswipe', 'axwound', 'bampot', 'bastard',
'beaner', 'bitch', 'bitchass', 'bitches', 'bitchtits', 'bitchy', 'blow job', 'blowjob', 'bollocks', 'bollox', 'boner',
'brotherfucker', 'bullshit', 'bumblefuck', 'butt plug', 'butt-pirate', 'buttfucka', 'buttfucker', 'camel toe',
'carpetmuncher', 'chesticle', 'chinc', 'chink', 'choad', 'chode', 'clit', 'clitface', 'clitfuck', 'clusterfuck', 'cock',
'cockass', 'cockbite', 'cockburger', 'cockface', 'cockfucker', 'cockhead', 'cockjockey', 'cockknoker', 'cockmaster',
'cockmongler', 'cockmongruel', 'cockmonkey', 'cockmuncher', 'cocknose', 'cocknugget', 'cockshit', 'cocksmith',
'cocksmoke', 'cocksmoker', 'cocksniffer', 'cocksucker', 'cockwaffle', 'coochie', 'coochy', 'coon', 'cooter', 'cracker',
'cum', 'cumbubble', 'cumdumpster', 'cumguzzler', 'cumjockey', 'cumslut', 'cumtart', 'cunnie', 'cunnilingus', 'cunt',
'cuntass', 'cuntface', 'cunthole', 'cuntlicker', 'cuntrag', 'cuntslut', 'dago', 'damn', 'deggo', 'dick', 'dick-sneeze',
'dickbag', 'dickbeaters', 'dickface', 'dickfuck', 'dickfucker', 'dickhead', 'dickhole', 'dickjuice', 'dickmilk',
'dickmonger', 'dicks', 'dickslap', 'dicksucker', 'dicksucking', 'dicktickler', 'dickwad', 'dickweasel', 'dickweed',
'dickwod', 'dike', 'dildo', 'dipshit', 'doochbag', 'dookie', 'douche', 'douchebag', 'douchewaffle', 'dumass',
'dumb ass', 'dumbass', 'dumbfuck', 'dumbshit', 'dumshit', 'dyke', 'fag', 'fagbag', 'fagfucker', 'faggit', 'faggot',
'faggotcock', 'fagtard', 'fatass', 'fellatio', 'feltch', 'flamer', 'fuck', 'fuckass', 'fuckbag', 'fuckboy', 'fuckbrain',
'fuckbutt', 'fuckbutter', 'fucked', 'fucker', 'fuckersucker', 'fuckface', 'fuckhead', 'fuckhole', 'fuckin', 'fucking',
'fucknut', 'fucknutt', 'fuckoff', 'fucks', 'fuckstick', 'fucktard', 'fucktart', 'fuckup', 'fuckwad', 'fuckwit',
'fuckwitt', 'fudgepacker', 'gay', 'gayass', 'gaybob', 'gaydo', 'gayfuck', 'gayfuckist', 'gaylord', 'gaytard', 'gaywad',
'goddamn', 'goddamnit', 'gooch', 'gook', 'gringo', 'guido', 'handjob', 'hard on', 'heeb', 'hell', 'ho', 'hoe', 'homo',
'homodumbshit', 'honkey', 'humping', 'jackass', 'jagoff', 'jap', 'jerk off', 'jerkass', 'jigaboo', 'jizz',
'jungle bunny', 'junglebunny', 'kike', 'kooch', 'kootch', 'kraut', 'kunt', 'kyke', 'lardass', 'lesbian', 'lesbo',
'lezzie', 'mcfagget', 'mick', 'minge', 'mothafucka', 'mothafuckin', 'motherfucker', 'motherfucking', 'muff',
'muffdiver', 'munging', 'nigaboo', 'nigga', 'nigger', 'niggers', 'niglet', 'nutsack', 'paki', 'panooch', 'pecker',
'peckerhead', 'penis', 'penisbanger', 'penisfucker', 'penispuffer', 'piss', 'pissed', 'pissflaps', 'polesmoker',
'pollock', 'poon', 'poonani', 'poonany', 'poontang', 'porchmonkey', 'porchmonkey', 'prick', 'punanny', 'punta',
'pussies', 'pussy', 'pussylicking', 'puto', 'queef', 'queer', 'queerbait', 'queerhole', 'renob', 'rimjob', 'ruski',
'sandnigger', 'schlong', 'scrote', 'shit', 'shitass', 'shitbag', 'shitbagger', 'shitbrains', 'shitbreath', 'shitcanned',
'shitcunt', 'shitdick', 'shitface', 'shitfaced', 'shithead', 'shithole', 'shithouse', 'shitspitter', 'shitstain',
'shitter', 'shittiest', 'shitting', 'shitty', 'shiz', 'shiznit', 'skank', 'skeet', 'skullfuck', 'slut', 'slutbag',
'smeg', 'snatch', 'spic', 'spick', 'splooge', 'spook', 'suckass', 'tard', 'testicle', 'thundercunt', 'tit', 'titfuck',
'tits', 'tittyfuck', 'twat', 'twatlips', 'twats', 'twatwaffle', 'unclefucker', 'vag', 'vagina', 'vajayjay', 'vjayjay',
'wank', 'wankjob', 'wetback', 'whore', 'whorebag', 'whoreface', 'wop')
profanitySet = set(profanity)

# remove words that shouldn't be in question (basically any variation of 'Reddit'
def removeBadWords(title):
    for word in remove_words:
        title = re.sub(word, '', title, flags=re.I)
    return title

# gives a title of a subreddit a score to rank it
def questionScore(title):
    score = 0 #low score is good
    for bad_word in bad_question_words:
        if bad_word in title:
            score += 2
    for word in remove_words:
        if word in title:
            score += 1
    if title.endswith('?'):
        score -= 1
    if len(title) > 1000:
        score += 5

    return score

#used in ranking (item[0] is score)
def getKey(item):
    return item[0]

#very basic ranking of questions
def rankSubmissions(submissions):
    scoredList = []
    finalList = []
    bestCount = 0
    goodCount = 0
    for sub in submissions:
        score = questionScore(sub.title)
        if score == -1:
            bestCount += 1
        if score == 0:
            goodCount += 1
        addition = (score,sub)
        scoredList.append(addition)
    sortedList = sorted(scoredList, key=getKey)
    for item in sortedList:
        finalList.append(item[1])
    return (finalList, bestCount, goodCount)

#returns all the comments from a subreddit (no replies to comments though)
def getComments(sub, topic):
    print("Getting comments from " + sub.title + " \nTopic: " + topic)
    sub.replace_more_comments(limit=32, threshold=1) #this takes FOREVER
    flat_comments = praw.helpers.flatten_tree(sub.comments)
    #comments = sub.comments
    for comment in flat_comments:
        # check if comments have links (remove these comments)

        new_comment = {}
        new_comment['topic'] = topic
        new_comment['text'] = str(comment.body)

        clean = new_comment['text']

        for char in ',;:!?\n\t.\(){}[]':
            clean = clean.replace(char, ' ')
        clean = clean.replace("  ", " ")

        new_comment['tokens'] = clean.split()

        swears = len(profanitySet.intersection(set(comment.body.lower().split(" "))))
        if swears > 2:
            new_comment['dirty'] = True
        else:
            new_comment['dirty'] = False

        if len(positiveSet.intersection(set(new_comment['tokens']))) > 10: #10 is just a guess...
            new_comment['positive'] = True
        else:
            new_comment['positive'] = False

        if len(negativeSet.intersection(set(new_comment['tokens']))) > 10:
            new_comment['negative'] = True
        else:
            new_comment['negative'] = False

        if len(clean) < 12 and len(clean) > 2:
            new_comment['snarky'] = True
        else:
            new_comment['snarky'] = False

        if 'http:' in new_comment['text'] or '[deleted]' in new_comment['text']:
            print("Contained link, did not insert")
        else:
            comment_database.insert(new_comment)
        '''
        try:
            print("Added comment: " + str(comment.body))
        except UnicodeEncodeError:
            print("Couldn't encode this comment.\n")
        '''

    return comment_list
'''
def getDirtyComments(comments):
    # look in database for dirty comments

    dirtyComments = []
    for comment in comments:
        swears = len(profanitySet.intersection(set(comment.lower().split(" "))))
        if swears > 0:
            dirtyComments.append(comment)
    return dirtyComments
'''

def getEmotionComments(topic, emotion):
    comments = comment_database.find({'topic': topic, emotion: True})
    if comments.count() < 3:
        comments = comment_database.find({'topic': topic})
        return comments
    return comments

#returns a subreddit from AskReddit which has to be in question form
#the question is randomly selected as long as it isn't a 'bad' question
def getMoreQuestions(topic):

    user_agent = ("windows:myredditapp:1.0 (by /u/cjw)")
    r = praw.Reddit(user_agent=user_agent)
    submissions = r.search(topic, "AskReddit")
    print("Submissions found: \t" + str(submissions.__sizeof__()))

    rank_output = rankSubmissions(submissions)
    rankedQuestions = rank_output[0]
    num_best_ans = rank_output[1]
    num_good_ans = rank_output[2]
    if num_best_ans >= 1:
        # add to database
        select = random.randint(0,num_best_ans-1)
    elif num_good_ans >= 1:
        # add to database
        select = random.randint(0,num_good_ans-1)
    else:
        # do not add to database
        select = 0

    print("Good questions found: " + str(num_good_ans))
    for ii in range(0, num_good_ans-1):
        new_question = {}
        new_question['topic'] = topic
        new_question['question'] = removeBadWords(rankedQuestions[ii].title)

        getComments(rankedQuestions[ii], topic)

        question_database.insert(new_question)

if __name__ == '__main__':
    question = getMoreQuestions('dogs')
    getEmotionComments('dogs', 'dirty')
    '''
    print(removeBadWords(question.title) + "\n\n")
    a = getComments(question, "cats")
    i = 0
    if len(a) < 10:
        num = len(a)
    else:
        num = 10
    while i < num:
        print(a[i])
        i += 1
    '''


import numpy as np
import pandas as pd

x = float(input("Enter volume of gel beads (ml):\n"))

max_rep = 5
i=3
flag=0
while(i<max_rep):
    for vol in range(0,50000,1):
        dil=1/(x/(x+vol))
        wash = np.power(dil,i)
        if(wash>1000):
            flag=1
            break
    if(flag==1):
        break
    else:
        i=i+1

print("Perform " + str(i) + " washes with " + str(vol) + "ml of packaging buffer for " + str(int(wash)) + "x dilution.")

y = float(input("How many ladder points would you like to package?\n"))

targets = []
for i in range(int(y)):
    target = float(input("Enter ladder point "+ str(i+1) + " \n"))
    targets.append(target)

cols = ["tube_mass","tube_gb_mass","gb_mass","vol_gb","target_vf","target_buffer_vol","target_buffer_mass","tube_gb_buffer_mass","buffer_mass","%_error","total_volume","gb_fraction"]

df = pd.DataFrame(columns=cols)
df["target_vf"] = targets

print(df)

def calc(a,b,c):
    buff_density = 1.023
    bead_density = 1.08
    gb_mass = b-a
    vol_gb = gb_mass/bead_density
    target_buffer_vol = vol_gb*((1-c)/c)
    target_buffer_mass = target_buffer_vol*buff_density
    return target_buffer_mass , gb_mass, vol_gb , target_buffer_vol

for i in range(int(y)):
    tube_mass = float(input("Enter tare weight of falcon tube for ladder point "+str(i+1)+":\n"))
    df.iat[i,0] = tube_mass
    tube_gb_mass = float(input("Enter weight of falcon tube + gel beads for ladder point "+str(i+1)+":\n"))
    df.iat[i,1] = tube_gb_mass
    a,b,c,d = calc(tube_mass,tube_gb_mass,df.iloc[i].target_vf)
    df.iat[i,6] = a
    df.iat[i,2] = b
    df.iat[i,3] = c
    df.iat[i,5] = d
    print("\nAdd "+str(round(df["target_buffer_mass"][i],2))+"ml of packaging buffer to the tube.")

    tube_gb_buffer_mass = float(input("Enter weight of falcon tube + gel beads + buffer for ladder point "+str(i+1)+":\n"))
    df.iat[i,7] = tube_gb_buffer_mass
    buffer_mass= tube_gb_buffer_mass-tube_gb_mass
    df.iat[i,8]=buffer_mass
    error = 100*(np.abs((df["target_buffer_mass"][i]-buffer_mass)/df["target_buffer_mass"][i]))
    df.iat[i,9] = error
    df.iat[i,10] = c + buffer_mass/1.023
    df.iat[i,11] = c/df.iat[i,10]
    print("\nPercent error in adding buffer = "+ str(round(error,2)))
    print("Final volume fraction for ladder point "+str(i+1)+": "+str(round(df.iloc[i].gb_fraction,4)))

print(df)


"""
File: 03_scene.py
Author: Leah Tajon

Purpose: Prove that you can write functions with parameters
and call those functions multiple times with arguments.

"""

# Import the functions from the Draw 2-D library
# so that they can be used in this program.
# Import random to call random numbers
from draw2d import \
    start_drawing, draw_line, draw_oval, draw_arc, \
    draw_rectangle, draw_polygon, draw_text, finish_drawing
import random

def main():
    # Width and height of the scene in pixels
    scene_width = 800
    scene_height = 500

    # Call the start_drawing function in the draw2d.py
    # library which will open a window and create a canvas.
    canvas = start_drawing("Scene", scene_width, scene_height)

    # Call your drawing functions such
    # as draw_sky and draw_ground here.
    draw_grid(canvas, scene_width, scene_height, 20)
    draw_sky(canvas, scene_width, scene_height)
    draw_clouds(canvas, scene_width, scene_height)
    draw_skyscrapers(canvas, scene_width, scene_height)
    draw_ground(canvas, scene_width, scene_height)
    draw_road(canvas, scene_width, scene_height)

    # Draw pine trees on the ground
    for x in range(15):
        tree_center_x = random.randint(100, 700)
        tree_bottom = random.randint(120, 200)
        tree_height = random.randint(80, 180)

        draw_pine_tree(canvas, tree_center_x, tree_bottom, tree_height)
        x += 1

    # Call the finish_drawing function
    # in the draw2d.py library.
    finish_drawing(canvas)

# Define your functions such as
# draw_sky and draw_ground here.

def draw_grid(canvas, width, height, interval):
    # Draw vertical lines at every x interval
    label_y = 20
    for x in range(interval, width, interval):
        draw_line(canvas, x, 0, x, height)
        draw_text(canvas, x, label_y, f'{x}')

    # Draw horizontal lines at every y interval
    label_x = 20
    for y in range(interval, height, interval):
        draw_line(canvas, 0, y, width, y)
        draw_text(canvas, label_x, y, f'{y}')

def draw_sky(canvas, width, height):
    # Draw the sky
    draw_rectangle(canvas, 0, height / 2, width, height, width=0, fill="deepSkyBlue2")

def draw_clouds(canvas, width, height):
    # Draw clouds that randomly change shape
    min_diam = 50
    max_diam = 100

    for i in range(80):
        x = random.randint(0, width - max_diam)
        y = random.randint(0, height)
        diameter = random.randint(min_diam, max_diam)

        draw_oval(canvas, x, y, x + diameter, y + diameter, width=0, fill='lightCyan1')
    pass

def draw_skyscrapers(canvas, width, height):
    # Draw skyscrapers that randomly change in shape
    x = 20
    y = 250

    n = 30
    m = 300

    for i in range(80):
        diameter1 = random.randint(50, 100)
        diameter2 = random.randint(80, 180)

        draw_rectangle(canvas, x, y, x + diameter1, y + diameter2, width=0, fill='dodgerBlue4')

        x += random.randint(40, 120)
    pass

def draw_ground(canvas, width, height):
    # Draw the ground and all the objects in the ground.

    draw_rectangle(canvas, 0, 100, width, height / 2, width=0, fill='forestGreen')

    diameter = 12
    space = 2
    interval = diameter + space

    # Draw a row of flowers
    x = 10
    y = 102

    for i in range(56):
        draw_oval(canvas, x, y, x + diameter, y + diameter, outline="orangeRed1", width=3, fill="yellow")
        x += interval

def draw_pine_tree(canvas, center_x, bottom, height):
    # Draw random pine trees on the ground

    trunk_width = height / 30
    trunk_height = height / 8
    trunk_left = center_x - trunk_width / 2
    trunk_right = center_x + trunk_width / 2
    trunk_top = bottom + trunk_height

    # Draw the trunk of the flower
    draw_rectangle(canvas, trunk_left, trunk_top, trunk_right, bottom, outline="gray20",
        width=2, fill="tan3")

    # Draw the skirt
    skirt_width = height / 2
    skirt_height = height - trunk_height
    skirt_left = center_x - skirt_width / 2
    skirt_right = center_x + skirt_width / 2
    skirt_top = bottom + height

    draw_polygon(canvas,center_x, skirt_top, skirt_right, trunk_top, skirt_left, trunk_top,
        outline="darkGreen", width=2, fill="green1")

def draw_road(canvas, width, height):
    # Draw the road and all the objects in the road.
    draw_rectangle(canvas, 0, 0, width, height / 5, outline="lightBlue4", width=2, fill='gray25')

    # Draw center line
    x = 20
    y = 40
    for i in range(5):
        draw_rectangle(canvas, x, y, x + 100, y + 20, outline="lightBlue4", width=2, fill='azure')
        x += 160

# Call the main function so that
# this program will start executing.
main()


#tropopoihsh ths sthlhs zipcode wste na periexei to idio to zipcode kai oxi to onoma ths geitonias
#ta dedomena gia to zipcode prohlthan apo to pinaka neighborhood
import csv #no header edition
import collections

ZC={} #neighname,zipcode
def createTable(fnamer):
    with open(fnamer,encoding="utf8") as csv_file: #readfile
        csvreader = csv.reader(csv_file, delimiter=",")
        line_count = 0
        for row in csvreader:
            if(line_count==0):#header
                line_count += 1
            else:
                ZC[str(row[0])]=row[1]
                line_count += 1
def createCSV(fnamer,fnamew):
    with open(fnamer,encoding="utf8") as csv_file:
        with open(fnamew, mode='w', encoding="utf8",newline='') as z:
            z = csv.writer(z, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
            csvreader = csv.reader(csv_file, delimiter=",")
            line_count = 0
            for row in csvreader:
                if(line_count==0):#header
                    line_count += 1
                else:
                    line_count += 1
                    if row[4] in ZC:
                        row[4]=ZC[str(row[4])]
                        z.writerow(row)
                    else:
                        row[4]=''
                        z.writerow(row)

#createTable('portland_normalizedCSVs\\neighborhood.csv')
#createCSV('portland_normalizedCSVs\\summary_listing.csv','portland_normalizedCSVs\\summary_listingNEWP.csv');

#createTable('denver_normalizedCSVs\\neighborhood.csv')
#createCSV('denver_normalizedCSVs\\summary_listing.csv','denver_normalizedCSVs\\summary_listingNEWP.csv');

#createTable('boston_normalizedCSVs\\neighborhood.csv')
#createCSV('boston_normalizedCSVs\\summary_listing.csv','boston_normalizedCSVs\\summary_listingNEWP.csv');


import sys
import os

ships = set()
hits = set()
misses = set()

def usage():
	print("USAGE:")
	print(os.path.basename(sys.argv[0]), "[filename]")

def parse_coord(coord):
	return ord(coord[0]) - ord('a'), int(coord[1:]) - 1

def print_board():
	print("  1 2 3 4 5 6 7 8 9 10")
	for row in range(10):
		l = chr(ord("a") + row)
		for col in range(10):
			if (row, col) in misses:
				l += ' o'
			elif (row, col) in hits:
				l += ' x'
			else:
				l += ' .'
		print(l)

if __name__ == "__main__":
	try:
		fname = sys.argv[1]
		with open(fname) as f:
			for row in range(10):
				l = f.readline()
				for col in range(10):
					if l[col] != '.':
						ships.add((row, col))

	except IndexError:
		usage()
	except OSError:
		print("Invalid file format")
	else:
		print(ships)
		while True:
			i = input('-->')
			if i == "quit":
				break
			if len(i) == 2 or len(i) == 3:
				try:
					c = parse_coord(i)
				except ValueError:
					print(i, "is invalid")
					continue
				print(c)
				if c in ships:
					hits.add(c)
					print("HIT!")
					print('-->hits shps', hits, ships)
					if hits == ships:
						print("YOU WIN")
						break
				else:
					print("MISS!")
					misses.add(c)
			if i == 'p':
				print_board()


from __future__ import absolute_import

import os
import sys
import warnings

from .exceptions import (  # noqa
    ProcessError,
    BufferTooShort,
    TimeoutError,
    AuthenticationError,
    TimeLimitExceeded,
    SoftTimeLimitExceeded,
    WorkerLostError,
)
from .process import Process, current_process, active_children
from .util import SUBDEBUG, SUBWARNING

VERSION = (3, 3, 0, 23)
__version__ = '.'.join(map(str, VERSION[0:4])) + "".join(VERSION[4:])
__author__ = 'R Oudkerk / Python Software Foundation'
__author_email__ = 'python-dev@python.org'
__maintainer__ = 'Ask Solem'
__contact__ = "ask@celeryproject.org"
__homepage__ = "http://github.com/celery/billiard"
__docformat__ = "restructuredtext"

# -eof meta-

__all__ = [
    'Process', 'current_process', 'active_children', 'freeze_support',
    'Manager', 'Pipe', 'cpu_count', 'log_to_stderr', 'get_logger',
    'allow_connection_pickling', 'BufferTooShort', 'TimeoutError',
    'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition',
    'Event', 'Queue', 'JoinableQueue', 'Pool', 'Value', 'Array',
    'RawValue', 'RawArray', 'SUBDEBUG', 'SUBWARNING', 'set_executable',
    'forking_enable', 'forking_is_enabled'
]

def ensure_multiprocessing():
    from ._ext import ensure_multiprocessing
    return ensure_multiprocessing()

W_NO_EXECV = """\
force_execv is not supported as the billiard C extension \
is not installed\
"""

#
# Definitions not depending on native semaphores
#

def Manager():
    '''
    Returns a manager associated with a running server process

    The managers methods such as `Lock()`, `Condition()` and `Queue()`
    can be used to create shared objects.
    '''
    from .managers import SyncManager
    m = SyncManager()
    m.start()
    return m

def Pipe(duplex=True, rnonblock=False, wnonblock=False):
    '''
    Returns two connection object connected by a pipe
    '''
    from billiard.connection import Pipe
    return Pipe(duplex, rnonblock, wnonblock)

def cpu_count():
    '''
    Returns the number of CPUs in the system
    '''
    if sys.platform == 'win32':
        try:
            num = int(os.environ['NUMBER_OF_PROCESSORS'])
        except (ValueError, KeyError):
            num = 0
    elif 'bsd' in sys.platform or sys.platform == 'darwin':
        comm = '/sbin/sysctl -n hw.ncpu'
        if sys.platform == 'darwin':
            comm = '/usr' + comm
        try:
            with os.popen(comm) as p:
                num = int(p.read())
        except ValueError:
            num = 0
    else:
        try:
            num = os.sysconf('SC_NPROCESSORS_ONLN')
        except (ValueError, OSError, AttributeError):
            num = 0

    if num >= 1:
        return num
    else:
        raise NotImplementedError('cannot determine number of cpus')

def freeze_support():
    '''
    Check whether this is a fake forked process in a frozen executable.
    If so then run code specified by commandline and exit.
    '''
    if sys.platform == 'win32' and getattr(sys, 'frozen', False):
        from .forking import freeze_support
        freeze_support()

def get_logger():
    '''
    Return package logger -- if it does not already exist then it is created
    '''
    from .util import get_logger
    return get_logger()

def log_to_stderr(level=None):
    '''
    Turn on logging and add a handler which prints to stderr
    '''
    from .util import log_to_stderr
    return log_to_stderr(level)

def allow_connection_pickling():
    '''
    Install support for sending connections and sockets between processes
    '''
    from . import reduction  # noqa

#
# Definitions depending on native semaphores
#

def Lock():
    '''
    Returns a non-recursive lock object
    '''
    from .synchronize import Lock
    return Lock()

def RLock():
    '''
    Returns a recursive lock object
    '''
    from .synchronize import RLock
    return RLock()

def Condition(lock=None):
    '''
    Returns a condition object
    '''
    from .synchronize import Condition
    return Condition(lock)

def Semaphore(value=1):
    '''
    Returns a semaphore object
    '''
    from .synchronize import Semaphore
    return Semaphore(value)

def BoundedSemaphore(value=1):
    '''
    Returns a bounded semaphore object
    '''
    from .synchronize import BoundedSemaphore
    return BoundedSemaphore(value)

def Event():
    '''
    Returns an event object
    '''
    from .synchronize import Event
    return Event()

def Queue(maxsize=0):
    '''
    Returns a queue object
    '''
    from .queues import Queue
    return Queue(maxsize)

def JoinableQueue(maxsize=0):
    '''
    Returns a queue object
    '''
    from .queues import JoinableQueue
    return JoinableQueue(maxsize)

def Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None,
         timeout=None, soft_timeout=None, lost_worker_timeout=None,
         max_restarts=None, max_restart_freq=1, on_process_up=None,
         on_process_down=None, on_timeout_set=None, on_timeout_cancel=None,
         threads=True, semaphore=None, putlocks=False, allow_restart=False):
    '''
    Returns a process pool object
    '''
    from .pool import Pool
    return Pool(processes, initializer, initargs, maxtasksperchild,
                timeout, soft_timeout, lost_worker_timeout,
                max_restarts, max_restart_freq, on_process_up,
                on_process_down, on_timeout_set, on_timeout_cancel,
                threads, semaphore, putlocks, allow_restart)

def RawValue(typecode_or_type, *args):
    '''
    Returns a shared object
    '''
    from .sharedctypes import RawValue
    return RawValue(typecode_or_type, *args)

def RawArray(typecode_or_type, size_or_initializer):
    '''
    Returns a shared array
    '''
    from .sharedctypes import RawArray
    return RawArray(typecode_or_type, size_or_initializer)

def Value(typecode_or_type, *args, **kwds):
    '''
    Returns a synchronized shared object
    '''
    from .sharedctypes import Value
    return Value(typecode_or_type, *args, **kwds)

def Array(typecode_or_type, size_or_initializer, **kwds):
    '''
    Returns a synchronized shared array
    '''
    from .sharedctypes import Array
    return Array(typecode_or_type, size_or_initializer, **kwds)

#
#
#

def set_executable(executable):
    '''
    Sets the path to a python.exe or pythonw.exe binary used to run
    child processes on Windows instead of sys.executable.
    Useful for people embedding Python.
    '''
    from .forking import set_executable
    set_executable(executable)

def forking_is_enabled():
    '''
    Returns a boolean value indicating whether billiard is
    currently set to create child processes by forking the current
    python process rather than by starting a new instances of python.

    On Windows this always returns `False`.  On Unix it returns `True` by
    default.
    '''
    from . import forking
    return forking._forking_is_enabled

def forking_enable(value):
    '''
    Enable/disable creation of child process by forking the current process.

    `value` should be a boolean value.  If `value` is true then
    forking is enabled.  If `value` is false then forking is disabled.
    On systems with `os.fork()` forking is enabled by default, and on
    other systems it is always disabled.
    '''
    if not value:
        from ._ext import supports_exec
        if supports_exec:
            from . import forking
            if value and not hasattr(os, 'fork'):
                raise ValueError('os.fork() not found')
            forking._forking_is_enabled = bool(value)
            if not value:
                os.environ["MULTIPROCESSING_FORKING_DISABLE"] = "1"
        else:
            warnings.warn(RuntimeWarning(W_NO_EXECV))
if os.environ.get("MULTIPROCESSING_FORKING_DISABLE"):
    forking_enable(False)


import tensorflow as tf
import config as cfg
from anchor import Anchor
from detection import Detect
class PredictionModule(tf.keras.layers.Layer):

  def __init__(self, out_channels, num_anchors, num_class, num_mask):
      super(PredictionModule, self).__init__()
      self.num_anchors = num_anchors
      self.num_class = num_class
      self.num_mask = num_mask

      self.Conv = tf.keras.layers.Conv2D(out_channels, (3, 3), 1, padding="same",
                        kernel_initializer=tf.keras.initializers.glorot_uniform(),
                        activation="relu")

      self.classConv = tf.keras.layers.Conv2D(self.num_class * self.num_anchors, (3, 3), 1, padding="same",
                           kernel_initializer=tf.keras.initializers.glorot_uniform())
      self.boxConv = tf.keras.layers.Conv2D(4 * self.num_anchors, (3, 3), 1, padding="same",
                          kernel_initializer=tf.keras.initializers.glorot_uniform())
      # activation of mask coef is tanh
      self.maskConv = tf.keras.layers.Conv2D(self.num_mask * self.num_anchors, (3, 3), 1, padding="same",
                          kernel_initializer=tf.keras.initializers.glorot_uniform())

  def call(self, p):
      p = self.Conv(p)
      pred_class = self.classConv(p)
      pred_box = self.boxConv(p)
      pred_mask = self.maskConv(p)

      # pytorch input  (N,Cin,Hin,Win)
      # tf input (N,Hin,Win,Cin)
      # so no need to transpose like (0, 2, 3, 1) as in original yolact code
      # reshape the prediction head result for following loss calculation
      pred_class = tf.reshape(pred_class, [tf.shape(pred_class)[0], -1, self.num_class])
      pred_box = tf.reshape(pred_box, [tf.shape(pred_box)[0], -1, 4])
      pred_mask = tf.reshape(pred_mask, [tf.shape(pred_mask)[0], -1, self.num_mask])

      # add activation for conf and mask coef
      # pred_class = tf.nn.softmax(pred_class, axis=-1)
      pred_mask = tf.keras.activations.tanh(pred_mask)

      return pred_class, pred_box, pred_mask
class ProtoNet(tf.keras.layers.Layer):
  """
      Creating the component of ProtoNet
      Arguments:
      num_prototype
  """

  def __init__(self, num_prototype):
      super(ProtoNet, self).__init__()
      self.Conv1 = tf.keras.layers.Conv2D(256, (3, 3), 1, padding="same",
                          kernel_initializer=tf.keras.initializers.glorot_uniform(),
                          activation="relu")
      self.Conv2 = tf.keras.layers.Conv2D(256, (3, 3), 1, padding="same",
                          kernel_initializer=tf.keras.initializers.glorot_uniform(),
                          activation="relu")
      self.Conv3 = tf.keras.layers.Conv2D(256, (3, 3), 1, padding="same",
                          kernel_initializer=tf.keras.initializers.glorot_uniform(),
                          activation="relu")
      self.upSampling = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear')
      self.Conv4 = tf.keras.layers.Conv2D(256, (3, 3), 1, padding="same",
                          kernel_initializer=tf.keras.initializers.glorot_uniform(),
                          activation="relu")

      self.finalConv = tf.keras.layers.Conv2D(num_prototype, (1, 1), 1, padding="same",
                          kernel_initializer=tf.keras.initializers.glorot_uniform(),
                          activation='relu')

  def call(self, p3):
      # (3,3) convolution * 3
      proto = self.Conv1(p3)
      proto = self.Conv2(proto)
      proto = self.Conv3(proto)

      # upsampling + convolution
      proto = tf.keras.activations.relu(self.upSampling(proto))
      proto = self.Conv4(proto)
       # final convolution
      proto = self.finalConv(proto)
      return proto

class FPN(tf.keras.layers.Layer):
  def __init__(self,num_fpn_filters):
      super(FPN,self).__init__()
      self.upSample = tf.keras.layers.UpSampling2D(size=(2, 2), interpolation='bilinear')

      # no Relu for downsample layer
      # Pytorch and tf differs in conv2d when stride > 1
      # https://dmolony3.github.io/Pytorch-to-Tensorflow.html
      # Hence, manually adding padding
      self.pad1 = tf.keras.layers.ZeroPadding2D(padding=(1,1))
      self.downSample1 = tf.keras.layers.Conv2D(num_fpn_filters, (3, 3), 2, padding="valid",
                            kernel_initializer=tf.keras.initializers.glorot_uniform())

      self.pad2 = tf.keras.layers.ZeroPadding2D(padding=(1,1))
      self.downSample2 = tf.keras.layers.Conv2D(num_fpn_filters, (3, 3), 2, padding="valid",
                            kernel_initializer=tf.keras.initializers.glorot_uniform())

      self.lateralCov1 = tf.keras.layers.Conv2D(num_fpn_filters, (1, 1), 1, padding="same",
                            kernel_initializer=tf.keras.initializers.glorot_uniform())
      self.lateralCov2 = tf.keras.layers.Conv2D(num_fpn_filters, (1, 1), 1, padding="same",
                            kernel_initializer=tf.keras.initializers.glorot_uniform())
      self.lateralCov3 = tf.keras.layers.Conv2D(num_fpn_filters, (1, 1), 1, padding="same",
                            kernel_initializer=tf.keras.initializers.glorot_uniform())

      # predict layer for FPN
      self.predictP5 = tf.keras.layers.Conv2D(num_fpn_filters, (3, 3), 1, padding="same",
                            kernel_initializer=tf.keras.initializers.glorot_uniform(),
                            activation="relu")
      self.predictP4 = tf.keras.layers.Conv2D(num_fpn_filters, (3, 3), 1, padding="same",
                            kernel_initializer=tf.keras.initializers.glorot_uniform(),
                            activation="relu")
      self.predictP3 = tf.keras.layers.Conv2D(num_fpn_filters, (3, 3), 1, padding="same",
                             kernel_initializer=tf.keras.initializers.glorot_uniform(),
                             activation="relu")

  def call(self, c3, c4, c5):
      # lateral conv for c3 c4 c5
      # pytorch input  (N,Cin,Hin,Win)
      # tf input (N,Hin,Win,Cin)
      p5 = self.lateralCov1(c5)
      # _, h, w, _ = tf.shape(c4)
      p4 = tf.add(tf.image.resize(p5, [tf.shape(c4)[1],tf.shape(c4)[2]]), self.lateralCov2(c4))
      # _, h, w, _ = tf.shape(c3)
      p3 = tf.add(tf.image.resize(p4, [tf.shape(c3)[1],tf.shape(c3)[2]]), self.lateralCov3(c3))
      # print("p3: ", p3.shape)

      # smooth pred layer for p3, p4, p5
      p3 = self.predictP3(p3)
      p4 = self.predictP4(p4)
      p5 = self.predictP5(p5)

      # downsample conv to get p6, p7
      p6 = self.downSample1(self.pad1(p5))
      p7 = self.downSample2(self.pad2(p6))

      return [p3, p4, p5, p6, p7]

  """
    if training:
        pred = {
            'pred_cls': pred_cls,
            'pred_offset': pred_offset,
            'pred_mask_coef': pred_mask_coef,
            'proto_out': protonet_out,
            'seg': seg,
            'priors': self.priors
        }
        # Following to make both `if` and `else` return structure same
        result = {
            'detection_boxes': tf.zeros((self.max_output_size, 4)),
            'detection_classes': tf.zeros((self.max_output_size)),
            'detection_scores': tf.zeros((self.max_output_size)),
            'detection_masks': tf.zeros((self.max_output_size, 30, 30, 1)),
            'num_detections': tf.constant(0)}
        pred.update(result)
    else:
        pred = {
            'pred_cls': pred_cls,
            'pred_offset': pred_offset,
            'pred_mask_coef': pred_mask_coef,
            'proto_out': protonet_out,
            'seg': seg,
            'priors': self.priors
        }

        pred.update(self.detect(pred))

    return pred
  """


from rest_framework import serializers

from vet_sys.pacientes.models import Paciente
from ...models import Cliente

class ClienteSerializer(serializers.ModelSerializer):
    from vet_sys.pacientes.api.serializers.paciente_serializer import PacienteLookupSerializer

    paciente = serializers.PrimaryKeyRelatedField(queryset=Paciente.objects.all(), many=True)

    paciente_detail = PacienteLookupSerializer(source='paciente', read_only=True, many=True)

    class Meta:
        model = Cliente
        fields = (
            'id', 'uuid', 'nome', 'cpf', 'sexo', 'paciente', 'paciente_detail', 'tipo_logradouro', 'logradouro',
            'numero', 'bairro', 'complemento', 'cep', 'ddd',
            'telefone', 'ddd_segundo_telefone', 'segundo_telefone', 'data_de_nascimento', 'email', 'descricao', 'criado_em'
        )

class ClienteLookupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Cliente
        fields = (
            'id', 'uuid', 'nome', 'cpf', 'sexo', 'tipo_logradouro', 'logradouro', 'numero', 'bairro', 'complemento',
            'cep', 'ddd',
            'telefone', 'ddd_segundo_telefone', 'segundo_telefone', 'data_de_nascimento', 'email', 'descricao'
        )


class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        dp = [[0 for i in range(len(text2)+1)] for i in range(len(text1)+1)]
        '''
        def find(x,y):
            if(dp[x][y]!=-1):
                return dp[x][y]
            if(x==0 or y==0):
                return 0
            if(text1[x-1]==text2[y-1]):
                return 1+find(x-1,y-1)
            dp[x][y] = max(find(x-1,y),find(x,y-1))
            return dp[x][y]
        return find(len(text1),len(text2))
        '''
        for i in range(len(text1)+1):
            for j in range(len(text2)+1):
                if(i==0 or j==0):
                    continue
                if(text1[i-1]==text2[j-1]):
                    dp[i][j] = 1+dp[i-1][j-1]
                else:
                    dp[i][j] = max(dp[i-1][j],dp[i][j-1])
        l1,l2 = len(text1),len(text2)
        def find(l1,l2):
            if(l1==0 or l2==0):
                return
            if(text1[l1-1]==text2[l2-1]):
                self.ans+=text1[l1-1]
                find(l1-1,l2-1)
            else:
                if(dp[l1-1][l2]<=dp[l1][l2-1]):
                    find(l1,l2-1)
                else:
                    find(l1-1,l2)
        self.ans = ""
        find(l1,l2)
        print(self.ans)

        return dp[l1][l2]


from graphene_django.types import DjangoObjectType
from capitania.apps.core.models import User

class UserType(DjangoObjectType):
    class Meta:
        model = User
        only_fields = (
            'id',
            'username',
            'first_name',
            'last_name',
            'genre',
            'email',
            'date_joined',
            'is_active',
            'first_login',
            'is_superuser'
        )


import asyncio
import aiodns

async def do():
    for i in range(10):
        print('doing...')
        await asyncio.sleep(1)

loop = asyncio.get_event_loop()
resolver = aiodns.DNSResolver(loop=loop)
f = resolver.query('eventbus', 'A')
f2 = do()
result = loop.run_until_complete(
    asyncio.wait([f, f2], return_when=asyncio.FIRST_COMPLETED)
)
print(result)


from discord.ext import commands
import asyncio
from pretty_help import PrettyHelp
from json import load, dump
from datetime import datetime, timezone

### Configuration and loging methods ###
def console_log(message, level: int = 0):
    offset = datetime.now() - datetime.utcnow()
    tz = timezone(offset)
    date = datetime.now(tz)
    if level == 0:
        print(date.strftime('[%Y-%M-%d %H:%M:%S.%f UTC%z]'), '[INFO]', message)
    elif level == 1:
        print(date.strftime('[%Y-%M-%d %H:%M:%S.%f UTC%z]'), '[WARNING]', message)
    elif level == 0:
        print(date.strftime('[%Y-%M-%d %H:%M:%S.%f UTC%z]'), '[ERROR]', message)

class BotConfig:
    """The basic config settings for the bot
    """
    def __init__(self, configpath='config.json'):
        """The basic config settings for the bot

        Args:
            configpath (str, optional): The path to the config file. Defaults to 'config.json'.
        """
        self.configpath = configpath
        self.extensions = None
        self.owner_id = None
        self.command_prefix = '/'
        self.token = ''
        self.debug = False

        with open(self.configpath, 'r') as fp:
            cfg = load(fp)
            self.extensions = cfg['extensions']
            self.owner_id = cfg['owner_id']
            self.command_prefix = cfg['command_prefix']
            self.token = cfg['token']
            self.debug = cfg['debug']
            fp.close()

    def save(self):
        with open(self.configpath, 'w') as fp:
            cfg = load(fp)
            self.extensions = cfg['extensions']
            self.owner_id = cfg['owner_id']
            self.command_prefix = cfg['command_prefix']
            self.token = cfg['token']
            self.debug = cfg['debug']
            fp.close()

### Bot setup ###
config = BotConfig()

bot = commands.Bot(command_prefix=config.command_prefix, owner_id=config.owner_id, help_command=PrettyHelp())

def check_owner(ctx):
    return bot.is_owner(ctx.author)

### Events ###
@bot.event
async def on_connect():
    console_log('Logged in as ' + str(bot.user))
    console_log('Latency: ' + str(bot.latency*1000) + 'ms')
    print('==============================\n')

@bot.event
async def on_ready():
    console_log('Loading extensions...')

    for extension in config.extensions:
        try:
            bot.load_extension(extension['name'])
        except ExtensionNotFound:
            console_log('Extension\'' + extension['name'] + '\' could not be found', 1)
        except ExtensionAlreadyLoaded:
            console_log('Extension\'' + extension['name'] + '\' already loaded', 1)
        except ExtensionFailed:
            console_log('Extension\'' + extension['name'] + '\' failed during setup', 2)
            if config.debug:
                raise
        else:
            console_log('Extension\'' + extension['name'] + '\'loaded')

    console_log('Bot ready!')
    print('\n==============================\n')

### Commands ###
# Extension management
@bot.command(hidden=True)
@commands.check(check_owner)
async def load(ctx, extension: str):
    """Loads the specified extension

    Args:
        ctx (commands.Context): The invocation context
        extension (str): The name of the extension to load
    """
    try:
        bot.load_extension(extension)
    except ExtensionNotFound:
        await ctx.send(':x: Extension \'' + extension +'\' could not be found!')
        console_log('Extension\'' + extension + '\' could not be found', 1)
    except ExtensionAlreadyLoaded:
        await ctx.send(':x: Extension \'' + extension +'\' already loaded!')
        console_log('Extension\'' + extension + '\' already loaded', 1)
    except ExtensionFailed:
        await ctx.send(':x: Extension \'' + extension +'\' failed during setup!')
        console_log('Extension\'' + extension + '\' failed during setup', 2)
        if config.debug:
            raise
    else:
        await ctx.send(':white_check_mark: Extension \'' + extension +'\' loaded successfully!')
        console_log('Extension' + extension + 'loaded')

@bot.command(hidden=True)
@commands.check(check_owner)
async def unload(ctx, extension: str):
    """Unloads the specified extension

    Args:
        ctx (commands.Context): The invocation context
        extension (str): The name of the extension to unload
    """
    try:
        bot.unload_extension(extension)
    except ExtensionNotLoaded:
        await ctx.send(':x: Extension \'' + extension +'\' was not loaded!')
        console_log('Extension \'' + extension +'\' was not loaded', 1)
    else:
        await ctx.send(':white_check_mark: Extension \'' + extension + '\' unloaded successfully!')
        console_log('Extension' + extension + 'unloaded')

@bot.command(hidden=True)
@commands.check(check_owner)
async def reload(ctx, extension: str):
    """Reloads the specified extension

    Args:
        extension (str): The name of the extension to reload
    """
    try:
        bot.reload_extension(extension)
    except ExtensionNotFound:
        await ctx.send(':x: Extension \'' + extension +'\' could not be found!')
        console_log('Extension \'' + extension +'\' could not be found!', 1)
    except ExtensionNotLoaded:
        await ctx.send(':x: Extension \'' + extension +'\' was not loaded!')
        console_log('Extension \'' + extension +'\' was not loaded!', 1)
    except ExtensionFailed:
        await ctx.send(':x: Extension \'' + extension +'\' failed during setup!')
        console_log('Extension \'' + extension +'\' failed during setup', 2)
        if config.debug:
            raise
    else:
        await ctx.send(':white_check_mark: Extension \'' + extension +'\' reloaded successfully!')
        console_log('Extension' + extension + 'reloaded')

bot.run(config.token)


from collections import defaultdict
from sys import stdin

readline = stdin.readline
n, q = map(int, readline().split())
query = [tuple(map(lambda x: int(x) - 1, readline().split())) for _ in [0] * q]
groups = n
cnt = [0] * n
graph = defaultdict(set)
for que in query:
    if que[0] == 0:
        u = que[1]
        v = que[2]
        if cnt[u] == 0:
            groups -= 1
        if cnt[v] == 0:
            groups -= 1
        cnt[u] += 1
        cnt[v] += 1
        graph[u].add(v)
        graph[v].add(u)
        print(groups)
    else:
        v = que[1]
        if cnt[v] != 0:
            groups += 1
        cnt[v] = 0
        for u in graph[v]:
            graph[u].discard(v)
            cnt[u] -= 1
            if cnt[u] == 0:
                groups += 1
        graph[v].clear()
        print(groups)


import random
import math
from PIL import Image

class RandomErasing(object):
    '''
    Class that performs Random Erasing in Random Erasing Data Augmentation by Zhong et al.
    -------------------------------------------------------------------------------------
    probability: The probability that the operation will be performed.
    sl: min erasing area
    sh: max erasing area
    r1: min aspect ratio
    mean: erasing value
    -------------------------------------------------------------------------------------
    '''
    def __init__(self, probability = 0.5, sl = 0.02, sh = 0.4, r1 = 0.3, mean=[0.4914, 0.4822, 0.4465]):
        self.probability = probability
        self.mean = mean
        self.sl = sl
        self.sh = sh
        self.r1 = r1

    def __call__(self, img):

        if random.uniform(0, 1) > self.probability:
            return img

        for attempt in range(100):
            area = img.shape[1] * img.shape[2]
            target_area = random.uniform(self.sl, self.sh) * area
            aspect_ratio = random.uniform(self.r1, 1/self.r1)

            h = int(round(math.sqrt(target_area * aspect_ratio)))
            w = int(round(math.sqrt(target_area / aspect_ratio)))

            if w < img.shape[2] and h < img.shape[1]:
                x1 = random.randint(0, img.shape[1] - h)
                y1 = random.randint(0, img.shape[2] - w)
                if img.shape[0] == 3:
                    img[0, x1:x1+h, y1:y1+w] = self.mean[0]
                    img[1, x1:x1+h, y1:y1+w] = self.mean[1]
                    img[2, x1:x1+h, y1:y1+w] = self.mean[2]
                else:
                    img[0, x1:x1+h, y1:y1+w] = self.mean[0]
                return img

        return img

class MixingImages(object):
    '''
    Class that performs Random mixing of images.
    -------------------------------------------------------------------------------------
    probability: The probability that the operation will be performed.
    -------------------------------------------------------------------------------------
    '''
    def __init__(self, probability = 0.5, alpha=0.5):
        self.probability = probability
        self.alpha = alpha

    def __call__(self, img, i, batch_x, batch_y):

        if random.uniform(0, 1) > self.probability:
            return img

        options = [im for im, label in zip(batch_x, batch_y) if label == batch_y[i]]
        img_to_blend = random.choice(options)
        blended_img = Image.blend(img, img_to_blend, self.alpha)

        return blended_img


from flask import Blueprint, jsonify, request, redirect, render_template
from app.models import db, Community, User, Post, Comment
from sqlalchemy import or_

search_routes = Blueprint("search", __name__)

# SEARCH ALL COMMUNITIES AND USERS
@search_routes.route("/<query>")
def search(query):
    """
    Query for searching all communities and users
    """

    formatted_query = " ".join(query.split('+'))

    queried_communities = Community.query.filter(Community.name.ilike(f"%{formatted_query}%")).all()
    queried_users = User.query.filter(User.username.ilike(f"%{formatted_query}%")).all()
    queried_posts = Post.query.filter(or_(Post.title.ilike(f"%{formatted_query}%"), Post.content.ilike(f"%{formatted_query}%"))).all()
    queried_comments = Comment.query.filter(Comment.content.ilike(f"%{formatted_query}%")).all()
    combined_query = queried_users + queried_communities + queried_posts + queried_comments

    print({"query": [query.to_dict() for query in combined_query]})
    return {"query": [query.to_dict() for query in combined_query]}


import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score

def train_and_predict_category(data_file, new_data):
    # Load the category dataset
    category = pd.read_csv(data_file)

    # Split dataset into features and target variable
    X = category.iloc[:, :-1].values
    y = category.iloc[:, -1].values

    # Split the dataset into the Training set and Test set
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)

    # Feature Scaling
    sc = StandardScaler()
    X_train = sc.fit_transform(X_train)
    X_test = sc.transform(X_test)

    # Training the Decision Tree Classification model
    classifier = DecisionTreeClassifier(criterion='entropy', random_state=0)
    classifier.fit(X_train, y_train)

    # Predicting the category for new data
    new_result = classifier.predict(new_data)

    # Predicting the Test set results
    y_pred = classifier.predict(X_test)

    # Calculate accuracy
    accuracy = accuracy_score(y_test, y_pred)

    return new_result[0], accuracy

# Example usage:
# data_file = 'category.csv'
# new_data = [[Marketing, Labor, Utilities, Personnel, Venue, Material, Ticket, Sales, Sponsor]]
# result, accuracy = train_and_predict_category(data_file, new_data)
# print("New Result:", result)
# print("Accuracy:", accuracy)


'''
Author: your name
Date: 2021-05-15 12:35:30
LastEditTime: 2021-05-16 13:46:00
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: /ml/draw.py
'''

'''
Author: your name
Date: 2021-05-12 05:51:37
LastEditTime: 2021-05-15 04:34:13
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: /kg-mtl/utils/draw.py
'''
from matplotlib import pyplot as plt
import numpy as np
from numpy.core.fromnumeric import size
from matplotlib.backends.backend_pdf import PdfPages
pdf=PdfPages('redundant_drugbank.pdf')
fig=plt.figure(figsize=(5,3))
neodti=[0.89, 0.95, 0.93]
neodti_std=[0.002, 0.002, 0.003]
mean=[0.92,0.96,0.95]
mean_kg=[0.93,0.96,0.95]
std = [0.022,0.013,0.019]
std_kg=[0.012,0.002,0.003]
env=['ACC','AUC','AUPR']
kg_entity=[0.92, 0.95, 0.95]
kg_entity_std=[0.012, 0.005, 0.009]
total_width,n=0.3, 3
width=total_width/n
x=np.arange(3)

#rect=plt.bar(left=range(len(mean)),height=mean,align="center")

plt.ylabel(u'Average Metrics',fontsize=12)
x=x-(total_width)/n
# plt.xlabel(u'')
plt.bar(x, height=neodti, width=width, label='NeoDTI',color='lightgreen')
plt.bar(x+width, height=mean, width=width, label='KG-MTL$^\#$',color='lightsteelblue')
plt.bar(x+2*width,mean_kg,width=width, label='KG-MTL',color='lightcoral')
plt.ylim((0.85,1))
plt.xticks(range(len(env)),env,FontSize=12)
plt.legend(fontsize=12)

k=8
for i in range(len(env)):

    z = [x[i]+width,x[i]+width]

    #w = [kg_entity[i]-kg_entity_std[i]/k,kg_entity[i]+kg_entity_std[i]/k]
    w = [mean[i]-std[i]/k,mean[i]+std[i]/k]
    z_ = [x[i]+2*width,x[i]+2*width]

    w_ = [mean_kg[i]-std_kg[i]/k,mean_kg[i]+std_kg[i]/k]
    z_neodti = [x[i],x[i]]

    w_neodti = [neodti[i]-neodti_std[i]/k,neodti[i]+neodti_std[i]/k]
    plt.plot(z_neodti,w_neodti, color='black')
    plt.plot(z,w,color='black')
    plt.plot(z_,w_,color='black')
plt.tight_layout()
#plt.savefig('utils/fig.png')
pdf.savefig(fig)
plt.show()
plt.close()
pdf.close()


"""
给你一个由 n 个节点（下标从 0 开始）组成的无向加权图，该图由一个描述边的列表组成，其中 edges[i] = [a, b] 表示连接节点 a 和 b 的一条无向边，且该边遍历成功的概率为 succProb[i] 。

指定两个节点分别作为起点 start 和终点 end ，请你找出从起点到终点成功概率最大的路径，并返回其成功概率。

如果不存在从 start 到 end 的路径，请 返回 0 。只要答案与标准答案的误差不超过 1e-5 ，就会被视作正确答案。

示例 1：

输入：n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2
输出：0.25000
解释：从起点到终点有两条路径，其中一条的成功概率为 0.2 ，而另一条为 0.5 * 0.5 = 0.25
示例 2：

输入：n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2
输出：0.30000
示例 3：

输入：n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2
输出：0.00000
解释：节点 0 和 节点 2 之间不存在路径

提示：

2 <= n <= 10^4
0 <= start, end < n
start != end
0 <= a, b < n
a != b
0 <= succProb.length == edges.length <= 2*10^4
0 <= succProb[i] <= 1
每两个节点之间最多有一条边

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/path-with-maximum-probability
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
"""
import heapq
from collections import defaultdict
from typing import List

class Solution:
    def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:
        """
        思路：地杰斯特拉+堆优化
        1. 涉及到乘法和最大值，考虑到heapq为小顶堆，所以存负数
        """
        visited = [False] * n
        graph = defaultdict(dict)
        for ix, (i, j) in enumerate(edges):
            graph[i][j] = succProb[ix]
            graph[j][i] = succProb[ix]
        queue = [(-1, start)]
        ans = 0
        while queue:
            p, u = heapq.heappop(queue)
            if u == end:
                ans = -p
                break
            visited[u] = True
            for v in graph[u]:
                if not visited[v]:
                    heapq.heappush(queue, (p*graph[u][v], v))
        return ans

if __name__ == '__main__':
    n = 3
    edges = [[0, 1], [1, 2], [0, 2]]
    succProb = [0.5, 0.5, 0.3]
    start = 0
    end = 2
    print(Solution().maxProbability(n, edges, succProb, start, end))


from typing import List
'''
    给两个整数数组 A 和 B ，返回两个数组中公共的、长度最长的子数组的长度。
'''
'''
    解法 dp  状态  当前数字是否能够与上个数字组成最长子数组 (子串)
            状态转移  dp[i][j] = dp[i-1][j-1] + 1 if A[i] == B[j] else 0
            0 代表当前字符不在最长公共子数组(串)内
            随后记录下这个二维表的最大值即为所求的最长长度。
            ans 为这个最长子数组。
            方法记录最长子数组末尾的的那个index 然后倒退最大长度。
'''

class Solution:
    def findLength(self, A: List[int], B: List[int]) -> int:
        lA, lB = len(A), len(B)
        dp = [[0 for i in range(lA + 1)] for _ in range(lB + 1)]
        res = 0
        index = 0
        for i in range(1, lA + 1):
            for j in range(1, lB + 1):
                if A[i - 1] == B[j - 1]:
                    dp[i][j] = dp[i - 1][j - 1] + 1
                    index = i
                    res = max(dp[i][j], res)
        ans = A[index - res:index]
        print(ans)
        return res

S = Solution()
print(S.findLength([1, 2, 3, 2, 1], [3, 2, 1, 4, 7, 8, 7]))


import os
import numpy as np
import math

#Method will be used to distribute data to allocated areas
def distributeData(f, train, test):
    line_count = 0
    writeToTest = False
    for line in f:
        #reset line_count one we have iterated over values
        if line_count == 3:
            line_count = 0
        #Check to see if we are at sentence, keyword, or sentiment analysis
        if (line_count == 0):
            split_decision = np.random.randint(low=1, high=100, size=1)
            if (split_decision[0] <= 20):
                test.writelines(line)
                writeToTest = True
            else:
                train.writelines(line)
                writeToTest = False
        elif (line_count == 1) or (line_count == 2):
            if writeToTest:
                test.writelines(line)
            else:
                train.writelines(line)
        line_count += 1

if __name__ == '__main__':
    #Open the files, train and test will hold data to pass into attenion-based lstm
    #Note: Change created to create test and training data for each category type
    f1 = open('abs.txt', 'r')
    train = open('./datasets/semeval14/ABS_Train.xml.seg', 'w')
    test = open('./datasets/semeval14/ABS_Test_Gold.xml.seg', 'w')
    #Function will allocate a 80/20 split train/test for data
    distributeData(f1, train, test)

    f2 = open("airbag.txt", 'r')
    train = open('./datasets/semeval14/Airbag_Train.xml.seg', 'w')
    test = open('./datasets/semeval14/Airbag_Test_Gold.xml.seg', 'w')
    distributeData(f2, train, test)

    f3 = open("airconditioner.txt", 'r')
    train = open('./datasets/semeval14/AirConditioner_Train.xml.seg', 'w')
    test = open('./datasets/semeval14/AirConditioner_Test_Gold.xml.seg', 'w')
    distributeData(f3, train, test)

    f4 = open("balljoint.txt", 'r')
    train = open('./datasets/semeval14/Balljoint_Train.xml.seg', 'w')
    test = open('./datasets/semeval14/Balljoint_Test_Gold.xml.seg', 'w')
    distributeData(f4, train, test)

    f5 = open('cabinairfilter.txt', 'r')
    train = open('./datasets/semeval14/CabinAirFilter_Train.xml.seg', 'w')
    test = open('./datasets/semeval14/CabinAirFilter_Test_Gold.xml.seg', 'w')
    distributeData(f5, train, test)

    f6 = open("oil.txt", 'r')
    train = open('./datasets/semeval14/Oil_Train.xml.seg', 'w')
    test = open('./datasets/semeval14/Oil_Test_Gold.xml.seg', 'w')
    distributeData(f6, train, test)


from bs4 import BeautifulSoup
from django.db.models import QuerySet
from urllib.parse import urljoin
from .exceptions import DiscoveryError
import feedparser
import requests

class SubscriptionQuerySet(QuerySet):
    def discover(self, topic):
        response = requests.head(topic, allow_redirects=True)
        rel_topic = topic

        if response.status_code == 200:
            hub = response.links.get('hub')
            rel_self = response.links.get('self')

            if rel_self:
                rel_topic = rel_self['url']

            if hub is not None:
                obj, created = self.get_or_create(
                    hub=urljoin(topic, hub['url']),
                    topic=urljoin(topic, rel_topic)
                )

                return obj

        content_type = response.headers['Content-Type']

        if 'text/html' in content_type:
            response = requests.get(topic)
            soup = BeautifulSoup(response.content, 'html.parser')
            head = soup.find('head')

            if head is not None:
                for link in head.find_all('link'):
                    rel = link.get('rel')
                    if 'self' in rel:
                        rel_topic = link.get('href')
                        break

                for link in head.find_all('link'):
                    rel = link.get('rel')
                    if 'hub' in rel:
                        obj, created = self.get_or_create(
                            hub=urljoin(topic, link.get('href')),
                            topic=urljoin(topic, rel_topic)
                        )

                        return obj

        if (
            'text/xml' in content_type or
            'application/atom+xml' in content_type or
            'application/rss+xml' in content_type or
            'application/xml' in content_type
        ):
            response = requests.get(topic)
            feed = feedparser.parse(response.content)

            for link in feed.feed.links:
                if link.rel == 'self':
                    rel_topic = link.href
                    break

            for link in feed.feed.links:
                if link.rel == 'hub':
                    obj, created = self.get_or_create(
                        hub=urljoin(topic, link.get('href')),
                        topic=urljoin(topic, rel_topic)
                    )

                    return obj

        raise DiscoveryError('Unable to discover WebSub hub URL.')


import gym
from gym import spaces
from gym.utils import seeding

import autograd.numpy as np
from autograd import jacobian
from autograd.tracer import getval

def wrap_angle(x):
    # wraps angle between [-pi, pi]
    return ((x + np.pi) % (2. * np.pi)) - np.pi

class Pendulum(gym.Env):

    def __init__(self):
        self.dm_state = 2
        self.dm_act = 1

        self.dt = 0.01

        self.sigma = 1e-4 * np.eye(self.dm_state)

        # g = [th, thd]
        self.g = np.array([0., 0.])
        self.gw = np.array([1e0, 1e-1])

        # x = [th, thd]
        self.xmax = np.array([np.inf, np.inf])
        self.observation_space = spaces.Box(low=-self.xmax,
                                            high=self.xmax)

        self.slew_rate = False
        self.uw = 1e-3 * np.ones((self.dm_act, ))
        self.umax = 10. * np.ones((self.dm_act, ))
        self.action_space = spaces.Box(low=-self.umax,
                                       high=self.umax, shape=(1,))

        self.x0 = np.array([np.pi, 0.])
        self.sigma0 = 1e-4 * np.eye(self.dm_state)

        self.periodic = False

        self.state = None
        self.np_random = None

        self.seed()

    @property
    def xlim(self):
        return self.xmax

    @property
    def ulim(self):
        return self.umax

    def dynamics(self, x, u):
        _u = np.clip(u, -self.ulim, self.ulim)

        g, m, l, k = 9.81, 1., 1., 1e-3

        def f(x, u):
            th, dth = x
            return np.hstack((dth, - 3. * g / (2. * l) * np.sin(th + np.pi) +
                              3. / (m * l ** 2) * (u - k * dth)))

        k1 = f(x, _u)
        k2 = f(x + 0.5 * self.dt * k1, _u)
        k3 = f(x + 0.5 * self.dt * k2, _u)
        k4 = f(x + self.dt * k3, _u)

        xn = x + self.dt / 6. * (k1 + 2. * k2 + 2. * k3 + k4)
        xn = np.clip(xn, -self.xlim, self.xlim)

        return xn

    def inverse_dynamics(self, x, u):
        _u = np.clip(u, -self.ulim, self.ulim)

        g, m, l, k = 9.81, 1., 1., 1e-3

        def f(x, u):
            th, dth = x
            return np.hstack((dth, - 3. * g / (2. * l) * np.sin(th + np.pi) +
                              3. / (m * l ** 2) * (u - k * dth)))

        k1 = f(x, _u)
        k2 = f(x - 0.5 * self.dt * k1, _u)
        k3 = f(x - 0.5 * self.dt * k2, _u)
        k4 = f(x - self.dt * k3, _u)

        xn = x - self.dt / 6. * (k1 + 2. * k2 + 2. * k3 + k4)
        xn = np.clip(xn, -self.xlim, self.xlim)

        return xn

    def features(self, x):
        return x

    def features_jacobian(self, x):
        J = jacobian(self.features, 0)
        j = self.features(x) - J(x) @ x
        return J, j

    def noise(self, x=None, u=None):
        _u = np.clip(u, -self.ulim, self.ulim)
        _x = np.clip(x, -self.xlim, self.xlim)
        return self.sigma

    def cost(self, x, u, u_last, a):
        c = 0.

        if self.slew_rate:
            c += (u - u_last).T @ np.diag(self.uw) @ (u - u_last)
        else:
            c += u.T @ np.diag(self.uw) @ u

        if a:
            y = np.hstack((wrap_angle(x[0]), x[1])) if self.periodic else x
            J, j = self.features_jacobian(getval(y))
            z = J(getval(y)) @ y + j
            c += a * (z - self.g).T @ np.diag(self.gw) @ (z - self.g)

        return c

    def seed(self, seed=None):
        self.np_random, seed = seeding.np_random(seed)
        return [seed]

    def step(self, u):
        # state-action dependent noise
        _sigma = self.noise(self.state, u)
        # evolve deterministic dynamics
        self.state = self.dynamics(self.state, u)
        # add noise
        self.state = self.np_random.multivariate_normal(mean=self.state, cov=_sigma)
        return self.state, [], False, {}

    def init(self):
        return self.x0, self.sigma0

    def reset(self):
        # self.state = self.np_random.multivariate_normal(mean=self.x0, cov=self.sigma0)
        low, high = np.array([np.pi - np.pi / 10., -0.75]), \
                    np.array([np.pi + np.pi / 10., 0.75])
        x0 = self.np_random.uniform(low=low, high=high)
        self.state = np.hstack((wrap_angle(x0[0]), x0[1]))
        return self.state

class PendulumWithCartesianCost(Pendulum):

    def __init__(self):
        super(PendulumWithCartesianCost, self).__init__()

        # g = [cs_th, sn_th, dth]
        self.g = np.array([1., 0., 0.])
        self.gw = np.array([1e4, 1e4, 1e0])

    def features(self, x):
        return np.array([np.cos(x[0]), np.sin(x[0]), x[1]])


"""
This python script
- takes a GeoJSON file as input
- creates a HTML output file with a map
- the includes several basemap/tile options
- the map renders the GeoJSON FeatureCollection

The script is based on the python folium library,
which is based on the Javascript leaflet.js library

Joerg Kummer 8. Oct 2023
"""

import folium
import folium.plugins
import json
import pyproj
import random
from os.path import expanduser

# The following variables are made global and are set prior to
# exececuting ImportSchweizmobil()
# Because of this, the importer can overwrite these values
# and the values defined here are defaults

# debug levels
# 0 - no console outputs
# 1 - filenames, API calls
debug=1

# some defaults, which are likely to be overwritten by main
infile=expanduser('~')+'/Documents/TrackMapper/GeoJSON/schweizmobil.GeoJSON'
outfileo =expanduser('~')+'/Documents/TrackMapper/PMoutput/map.html'

# OpenTopoMap - gutes Shading, Höhenlinien
otattr = (
    '© OpenStreetMap '
    'Contributors, © SRTM'
    'Map style: © OpenTopoMap'
    '(CC-BY-SA)'
)
ottiles = "https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png"

# ESRI Worldimagery
attr= 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
tiles='https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'

# OpenStreetMap.CH, Höhenlinien und gutes Shading aber nur Schweiz
osmchattr= '© OpenStreetMap contributors',
osmchtiles="https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png"

#SwissFederalGeoportal_SWISSIMAGE
tiles='https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.swissimage/default/current/3857/{z}/{x}/{y}.jpeg'
attr='© swisstopo'
# minZoom: 2,
# maxZoom: 19,
#	bounds: [[45.398181, 5.140242], [48.230651, 11.47757]]

#SwissFederalGeoportal_NationalMap
#	minZoom: 2,
#	maxZoom: 18,
#	bounds: [[45.398181, 5.140242], [48.230651, 11.47757]]
attr='© swisstopo'
# From https://www.geo.admin.ch/en/wmts-available-services-and-data
# https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.pixelkarte-farbe/default/{Time}/3857/{TileMatrix}/{TileCol}/{TileRow}.jpeg
tilesCHCol='https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.pixelkarte-farbe/default/current/3857/{z}/{x}/{y}.jpeg'
tilesCHBW='https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.landeskarte-grau-10/default/current/3857/{z}/{x}/{y}.png'

def Prepare_Map():
    # Create a Map instance
    m = folium.Map(tiles=None,location=[47.278106, 7.820381],
                       zoom_start=9, crs="EPSG3857",control_scale=True)
    if (debug>0): print (f"folium.Map done")

    folium.TileLayer(tilesCHCol,attr=attr,name='Swisstopo Color',overlay=False,show=True).add_to(m)
    folium.TileLayer(tiles=tilesCHBW,attr=attr,name='Swisstopo Gray',overlay=False,show=False).add_to(m)
    folium.TileLayer(tiles=tiles,attr=attr,name='Swisstopo Swissimage',overlay=False,show=False).add_to(m)
    folium.TileLayer(tiles=ottiles,attr=otattr,name='OSM OpenTopo',overlay=False,show=False).add_to(m)
    folium.TileLayer(tiles=osmchtiles,attr=osmchattr,name='OSM CH',overlay=False,show=False).add_to(m)

    if (debug>0): print (f"folium.TileLayers added")

    # styles : https://leafletjs.com/reference.html#path-option
    # red color variations
    stl=lambda feature: {
        'weight':'5','color':"#ff"+hex(random.randrange(255))[2:]+"80",'opacity':'0.7'}

    # blue color variations
    stl=lambda feature: {
        'weight':'5','color':"#"+hex(random.randrange(255))[2:]+"40ff",'opacity':'0.6'}

    # green for highlight
    hlf=lambda feature: {'fillColor': 'green','weight':'8','color':'#ff0000','opacity':1.0}

    fields=['Name','Track type','Duration','Length',
            'Total up','Total down','Min elevation','Max elevation','User date','Track modified','URL']

    folium.GeoJson(infile,
                   name="Schweizmobil.ch Tracks",
                   tooltip=folium.GeoJsonTooltip(fields=['Name']),
                   popup=folium.GeoJsonPopup(fields=fields,localize=False),
                   style_function=stl,
                   highlight_function=hlf,
                   zoom_on_click=True
                   ).add_to(m)

    if (debug>0): print (f"folium.GeoJSON added")

    folium.plugins.Geocoder().add_to(m)
    folium.FeatureGroup("test",overlay=True)
    folium.LayerControl().add_to(m)

    # Save the map
    m.save(outfile)
    if (debug>0): print (f"Written HTML {outfile}")


#!/usr/bin/env python

def assign(service, arg):
    if service == 'phpmyadmin':
        return True, arg

def audit(arg):
    code, head, res, errcode, _ = curl.curl(arg + 'main.php')
    if code == 200 and res and res.find('MySQL client version') != -1 and res.find('root@localhost') != -1:
        security_hole(arg)

if __name__ == '__main__':
    from dummy import *
    audit(assign('phpmyadmin', 'http://union.fxaa.cc/old/')[1])


from django.conf.urls import url

from . import views
app_name = 'professors'
urlpatterns = [
    url(r'^$', views.professors, name='index'),
    url(r'professors$', views.professors, name='professors'),
    url(r'^(?P<professor_id>[0-9]+)/$', views.detail, name='detail'),
    url(r'^(?P<professor_id>[0-9]+)/add_section$', views.add_section, name='add_section'),
    url(r'^(?P<professor_id>[0-9]+)/create_section$', views.create_section, name='create_section'),
]


import requests
import re

"""
Let's start with simple function specifications:

1. if apikey is required, use "api_" before the plugin name:

	api_service.py

2. the function name must be "get" and take as parameter "domain":

	def get(domain):
		foo

3. the function must return a possibly unique list of subdomains:

	['sub1.domain.com', 'sub2.domain.com']

4. to parse the results it is recommended to use the standard modules such as:

	requests, json, bs4, re
"""

# author: Gianni Amato
# plugin: archive
# version: 1.0

def get(domain):
	# webarchive -> TEXT URL LIST -> match subdomain
	url = "https://web.archive.org/cdx/search/cdx?url=*.{domain}/*&output=txt&fl=original&collapse=urlkey".format(domain=domain)
	resp = requests.get(url, timeout=5).text

	result = []
	pattern = "http(s)?:\/\/(.*\.%s)" % domain
	for item in resp.split('\n'):
		match = re.match(pattern, item)

		if match and re.match("^[a-zA-Z0-9-\.]*$", match.groups()[1]):
			subdomain = match.groups()[1]
			if subdomain not in result:
				result.append(subdomain)

	return result


from collections import defaultdict
from math import ceil

def getTime(time):
    h, m = time.split(":")
    return int(h) * 60 + int(m)

def calcFee(time, baseTime, baseFee, unitTime, unitFee):
    extraTime = max(0, time - baseTime)
    extraFee = baseFee + ceil(extraTime / unitTime) * unitFee
    return extraFee

def solution(fees, records):
    answer = []

    baseTime, baseFee, unitTime, unitFee = fees

    parkRecord = defaultdict(int)
    parkLot = dict()

    for record in records:
        time, carNum, type = record.split(" ")
        time = getTime(time)
        if type == "IN":
            parkLot[carNum] = time
        else:
            parkRecord[carNum] += time - parkLot[carNum]
            del parkLot[carNum]

    for carNum in parkLot:
        parkRecord[carNum] += getTime("23:59") - parkLot[carNum]

    for carNum in parkRecord:
        parkFee = calcFee(parkRecord[carNum], baseTime, baseFee, unitTime, unitFee)
        answer.append([carNum, parkFee])
    answer.sort()
    answer = [x[1] for x in answer]
    return answer

# 문제풀이 : https://sooleeandtomas.tistory.com/97


#경사로
def solution(n, l, roads):
    row_flags = [True] * n
    col_flags = [True] * n
    #가로 check
    for i in range(n):
        row_ramps = [False] * n
        for j in range(n-1):
            if roads[i][j] < roads[i][j+1]: #낮 -> 높
                if roads[i][j+1] - roads[i][j] > 1:
                    row_flags[i] = False
                    break
                if j - l + 1 < 0 or any(roads[i][k] != roads[i][j] for k in range(j-l+1, j)) or any(row_ramps[k] for k in range(j-l+1, j+1)):
                    row_flags[i] = False
                    break
                for k in range(j-l+1, j+1):
                    row_ramps[k] = True
            elif roads[i][j] > roads[i][j+1]: #높 -> 낮
                if roads[i][j] - roads[i][j+1] > 1:
                    row_flags[i] = False
                    break
                if j + l >= n or any(roads[i][k] != roads[i][j+1] for k in range(j+1, j+l+1)):
                    row_flags[i] = False
                    break
                for k in range(j+1, j+l+1):
                    row_ramps[k] = True
    #세로 check
    for j in range(n):
        col_ramps = [False] * n
        for i in range(n-1):
            if roads[i][j] < roads[i+1][j]: #낮 -> 높
                if roads[i+1][j] - roads[i][j] > 1:
                    col_flags[j] = False
                    break
                if i - l + 1 < 0 or any(roads[k][j] != roads[i][j] for k in range(i-l+1, i)) or any(col_ramps[k] for k in range(i-l+1, i+1)):
                    col_flags[j] = False
                    break
                for k in range(i-l+1, i+1):
                    col_ramps[k] = True
            elif roads[i][j] > roads[i+1][j]: #높 -> 낮
                if roads[i][j] - roads[i+1][j] > 1:
                    col_flags[j] = False
                    break
                if i + l >= n or any(roads[k][j] != roads[i+1][j] for k in range(i+1, i+l+1)):
                    col_flags[j] = False
                    break
                for k in range(i+1, i+l+1):
                    col_ramps[k] = True
    return row_flags.count(True) + col_flags.count(True)

n, l = map(int, input().split())
roads = [list(map(int, input().split())) for _ in range(n)]
print(solution(n, l, roads))


# coding=utf-8

from vk_api.longpoll import VkLongPoll, VkEventType

import requests
import vk_api

from Data import Data
from Duty import Duty
from Bot import Bot
from private import private_key
from User import User

class MyLongPoll(VkLongPoll):
    def listen(self):
        while True:
            try:
                for event in self.check():
                    yield event
            except Exception as e:
                print(e)

if __name__ == "__main__":
    session = requests.Session()
    vk_session = vk_api.VkApi(token=private_key)

    longpoll = MyLongPoll(vk_session)
    vk = vk_session.get_api()

    users = []
    current_user = 0
    current_duty = Data.getTmpDuty()

    # bot.send()
    print('starting...')
    for event in longpoll.listen():

        current_user = User.isInUsers(event.peer_id, users)
        if current_user == 0:
            users.append(User(vk, '', event.peer_id))
            users[-1].updateDuty(current_duty)
            current_user = users[-1]

        if event.type == VkEventType.MESSAGE_NEW and event.to_me and event.text:
            current_user.Bot.send(event.text)


#!/usr/bin/env python

import sys
import json
import re

name_re = re.compile(r'^([a-zA-Z_][a-zA-Z0-9_]*)=(.*)$')
option_re = re.compile(r'^\+([a-zA-Z_]+)$')
long_option_re = re.compile(r'^\+\+([a-zA-Z_][a-zA-Z0-9_]*)$')

def decode_s(s):
    try:
        return json.loads(s)
    except:
        try:
            return json.loads('"%s"' % s)
        except:
            return encode_b(s)

def encode_b(s):
    return u''.join([
        unichr(ord(c) if ord(c) >= 128 else ord(c))
        for c in s
    ])

def nclf(argv):
    args_pos = []
    args_named = {}

    literal = False
    for arg in argv:
        name_m = name_re.match(arg)
        option_m = option_re.match(arg)
        long_option_m = long_option_re.match(arg)
        if literal:
            args_pos.append(encode_b(arg))
        elif arg == '=':
            literal = True
        elif option_m is not None:
            x = option_m.groups()
            for name in x[0]:
                args_named[name] = True
        elif long_option_m is not None:
            x = long_option_m.groups()
            name = x[0]
            args_named[name] = True
        elif name_m is not None:
            x = name_m.groups()
            name = x[0]
            value = x[1]
            args_named[name] = decode_s(value)
        else:
            value = decode_s(arg)
            args_pos.append(value)

    return [args_pos, args_named]

if __name__ == '__main__':
    args = nclf(sys.argv[1:])
    print(json.dumps(args))