from copy import deepcopy
from typing import List

class Solution:
    def findContinuousSequence(self, target: int) -> List[List[int]]:
        left, right = 1, 1
        ans, res, sums = [], [], 0
        while right < target:
            sums += right
            while sums > target:
                sums -= left
                res.pop(0)
                left += 1
            res.append(right)
            right += 1
            if sums == target:  # 如果找到一个符合条件的区间
                ans.append(deepcopy(res))
        return ans

LeetCode/Problems/57 - II. 和为s的连续正数序列/python.py


import os
import pandas as pd
import pymysql.cursors

conn = pymysql.connect(host='localhost',
                       user='root',
                       password='',
                       db='albert',
                       charset='utf8mb4',
                       cursorclass=pymysql.cursors.DictCursor)
'''
class row:
	#ignore class status, session, start/end date (add sem/year ), description,
	#component = class_type
	#min/max units = credits
	#building room = room_num/building
	#primary instructor = first_name, last_name
	def __init__(self, catalog_num, class_section, title, classnbr, days,
		timest, sem, year, class_type, credits, consent, course_id, location,
		room_num, building, room_cap, enroll_cap, enroll_tot, waitlist_cap, waitlist_tot,
		combined, class_topic, first_name, last_name):
		self.catalog_num = catalog_num
		self.class_section = class_section
		self.title = title
		self.classnbr = classnbr
		self.days = days
		self.timest = timest
		self.sem = sem
		self.year = year
		self.class_type = class_type
		self.credits = credits
		self.consent = consent
		self.course_id = course_id
		self.location = location
		self.room_num = room_num
		self.building = building
		self.room_cap = room_cap
		self.enroll_cap = enroll_cap
		self.enroll_tot = enroll_tot
		self.waitlist_cap = waitlist_cap
		self.waitlist_tot = waitlist_tot
		self.combined = combined
		self.class_topic = class_topic
		self.first_name = first_name
		self.last_name = last_name

def readFile():
    rows = []
    excel_file = "data.xlsx"
    data = pd.read_excel(excel_file)
    j = 2;
    for index, row in data.iterrows():
      print("row" + str(j))
      #add sem/year
      if (row["Start/End Date"][1] == "9"):
          sem = "Fall"
      else:
          sem = "Spring"

      year = row["Start/End Date"][-4:]

      #add building

      #if empty
      if (pd.isnull(row["Building Room"])):
          building = ""
          room_num = ""
      #if online
      elif(row["Building Room"] == "On-Line"):
          building = "Online"
          room_num = "N/A"
      else:
          build = row["Building Room"].split(" Rm ")
          building = build[0]
          room_num = build[1]

      #add Instructors

      #No instructor
      if(pd.isnull(row["Primary Instructor"])):
          first_name = ""
          last_name = ""
          x = addRow(row, sem, year, room_num, building, first_name, last_name)
          rows.append(x)
     #2 instructors
      elif ("&" in row["Primary Instructor"]):
          names = row["Primary Instructor"].split("& ")
          for i in names:
              name = i.split(",")
              x = addRow(row, sem, year, room_num, building, name[0], name[1])
              rows.append(x)
     #1 instructor
      else:
          name = row["Primary Instructor"].split(",")
          x = addRow(row, sem, year, room_num, building, name[0], name[1])
          rows.append(x)
      j+=1

    course_sheet(rows)
def addRow(line, sem, year, room_num, building, first_name, last_name):
       x = row(line["Subject/Catalog#"], line["Class Section"], line["Class Title"],
                line["Class Nbr"], line["Days"], line["Time"], sem, year ,line["Component"],
                line["Min/Max Units"], line["Consent"], line["Course ID"], line["Location"],
                room_num, building, line["Room Cap"], line["Enrollment Capacity"],
                line["Enrollment Total"], line["Class Wait List Cap"], line["Wait List Total"],
                line["Combined Status"], line["Class Topic"], first_name, last_name)
       return x
'''

def course_sheet(data):

    cursor = conn.cursor()

    df = pd.DataFrame({"Course ID":data["Course ID"], "Class Title":data["Class Title"],
                  "Subject/Catalog#":data["Subject/Catalog#"],
                  "Credits":data["Min/Max Units"], "Consent":data["Consent"], "Location":data["Location"]})
    df = df.drop_duplicates("Course ID")

    for index, row in df.iterrows():
        if(row["Consent"] != "Dept"):
            df.set_value(index, "Consent", "No")

    for index, row in df.iterrows():
        query = 'INSERT INTO course(course_id, title, catalog_num, credits, consent, location) VALUES (%s, %s, %s, %s,%s,%s) ON DUPLICATE KEY UPDATE title = VALUES(title), catalog_num = VALUES(catalog_num), credits = VALUES(credits), consent = VALUES(consent), location = VALUES(location)'
        cursor.execute(query, (row["Course ID"], row["Class Title"], row["Subject/Catalog#"], row["Credits"], row["Consent"], row["Location"]))

    conn.commit()
    cursor.close()

def split_classroom(data):
    room_num = []
    building = []
    for index, row in data.iterrows():
      if (pd.isnull(row["Building Room"])):
          building.append("N/A")
          room_num.append("N/A")
      #if online
      elif(row["Building Room"] == "On-Line"):
          building.append("Online")
          room_num.append("N/A")
      elif(row["Building Room"] == "No Room Required"):
          building.append("No Room")
          room_num.append("N/A")
      elif(row["Building Room"] == "Dibner , Pfizer Auditorium"):
          building.append("Dibner")
          room_num.append("Pfizer Auditorium")
      elif("Rm" in row["Building Room"]):
          build = row["Building Room"].split(" Rm ")
          room_num.append(build[1])
          if("," in build[0]):
              building.append(build[0].rstrip(","))
          else:
              building.append(build[0])
      else:
          building.append("Unknown")
          room_num.append("Unknown")

    return room_num, building

def split_instructor(data):
    first_name = []
    last_name = []

    #add Instructors
    #No instructor
    for index, row in data.iterrows():
        if(pd.isnull(row["Primary Instructor"])):
            first_name.append("N/A")
            last_name.append("N/A")
        #2 instructors
        elif ("&" in row["Primary Instructor"]):
            names = row["Primary Instructor"].split(" & ")
            for i in names:
                name = i.split(",")
                if(len(name) > 1):
                    first_name.append(name[1])
                else:
                    first_name.append("N/A")
                if(name[0]):
                    last_name.append(name[0])
                else:
                    last_name.append("N/A")
         #1 instructor
        else:
            name = row["Primary Instructor"].split(",")
            first_name.append(name[1])
            last_name.append(name[0])
    return first_name, last_name
def classroom_sheet(data):
    #go through the data frame and add it in two separate dictionaries, add that in with room Cap
    cursor = conn.cursor()

    room_num, building = split_classroom(data)

    df = pd.DataFrame({"room_num":room_num, "building":building, "room_cap":data["Room Cap"]})
    df = df.drop_duplicates(subset=["room_num", "building"])

    df["room_cap"] = df["room_cap"].astype(str)
    for index, row in df.iterrows():
        if(row["room_cap"] == "nan"):
          df.set_value(index, "room_cap", "N/A")

    for index, row in df.iterrows():
        query = 'INSERT INTO classroom(room_num, building, room_cap) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE room_num = VALUES(room_num), building = VALUES(building), room_cap = VALUES(room_cap)'
        cursor.execute(query, (row["room_num"], row["building"], row["room_cap"]))

    conn.commit()
    cursor.close()

def instructor_sheet(data):
    #go through data frame, parse instructor and add dictionaries and write it back in
    cursor = conn.cursor()

    first_name, last_name = split_instructor(data)

    df = pd.DataFrame({"first_name":first_name, "last_name":last_name})
    df = df.drop_duplicates(subset=["first_name", "last_name"])

    for index, row in df.iterrows():
        query = 'INSERT INTO instructor(first_name, last_name) VALUES (%s, %s) ON DUPLICATE KEY UPDATE first_name = VALUES(first_name), last_name = VALUES(last_name)'
        cursor.execute(query, (row["first_name"], row["last_name"]))

    conn.commit()
    cursor.close()

def time_sheet(data):

    cursor = conn.cursor()

    df = pd.DataFrame({"days":data["Days"], "timest":data["Time"]})
    df = df.drop_duplicates(subset=["days","timest"])

    for index, row in df.iterrows():
        if(pd.isnull(row["days"])):
            df.set_value(index, "days", "N/A")
        if(pd.isnull(row["timest"])):
            df.set_value(index, "timest", "N/A")

    for index, row in df.iterrows():
        query = 'INSERT INTO class_time(days, timest) VALUES (%s, %s) ON DUPLICATE KEY UPDATE days = VALUES(days), timest = VALUES(timest)'
        cursor.execute(query, (row["days"], row["timest"]))

    conn.commit()
    cursor.close()

def teaches_sheet(data):
    #class_section, sem, year, course_id, first_name, last_name
    cursor = conn.cursor()

    class_section = []
    sem = []
    year = []
    course_id = []
    first_name = []
    last_name = []

    #checking month/year
    if (data["Start/End Date"][0][1] == "9"):
        sems = "Fall"
    else:
        sems = "Spring"
    years = data["Start/End Date"][0][-4:]

    for index, row in data.iterrows():
      if(pd.isnull(row["Primary Instructor"])):
          class_section.append(row["Class Section"])
          course_id.append(row["Course ID"])
          sem.append(sems)
          year.append(years)
          first_name.append("N/A")
          last_name.append("N/A")
      elif("&" in row["Primary Instructor"]):
          names = row["Primary Instructor"].split(" & ")
          for i in names:
              class_section.append(row["Class Section"])
              course_id.append(row["Course ID"])
              sem.append(sems)
              year.append(years)
              name = i.split(",")
              if(len(name) > 1):
                  first_name.append(name[1])
              else:
                  first_name.append("N/A")
              if(name[0]):
                  last_name.append(name[0])
              else:
                  last_name.append("N/A")
      else:
          class_section.append(row["Class Section"])
          course_id.append(row["Course ID"])
          sem.append(sems)
          year.append(years)
          #add instructor
          name = row["Primary Instructor"].split(",")
          first_name.append(name[1])
          last_name.append(name[0])

    df = pd.DataFrame({"class_section":class_section, "sem":sem, "year":year, "course_id":course_id, "first_name":first_name, "last_name":last_name})
    for index, row in df.iterrows():
        query = 'INSERT INTO teaches(class_section, sem, year, course_id, first_name, last_name) VALUES (%s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE class_section = VALUES(class_section), sem = VALUES(sem), year = VALUES(year), course_id = VALUES(course_id), first_name = VALUES(first_name), last_name = VALUES(last_name)'
        cursor.execute(query, (row["class_section"], row["sem"], row["year"], row["course_id"], row["first_name"], row["last_name"]))

    conn.commit()
    cursor.close()

def cross_listed_sheet(data):
    #class_section_u, sem_u, year_u, course_id_u, class_section_g, sem_g, year_g, course_id_g
    #match with title, professor
    cursor = conn.cursor()

    class_section_u =[]
    sem_u = []
    year_u = []
    course_id_u = []
    class_section_g = []
    sem_g = []
    year_g = []
    course_id_g = []

    undergrad = []

    #checking month/year
    if (data["Start/End Date"][0][1] == "9"):
        sems = "Fall"
    else:
        sems = "Spring"
    years = data["Start/End Date"][0][-4:]

    #grab data that is crosslisted
    for index, row in data.iterrows():
        if(row["Combined Status"] == "Combin" and "UY" in row["Subject/Catalog#"]):
            undergrad.append(row)

    #go through each data and find the crosslisted part
    for under in undergrad:
        for index, row in data.iterrows():
            if(under["Class Title"].lower() == "computer security" and row["Class Title"].lower() == "information security & privacy" and under["Primary Instructor"] == row["Primary Instructor"] and "GY" in row["Subject/Catalog#"] and under["Days"] == row["Days"] and under["Time"] == row["Time"]):
                class_section_u.append(under["Class Section"])
                sem_u.append(sems)
                year_u.append(years)
                course_id_u.append(under["Course ID"])

                class_section_g.append(row["Class Section"])
                sem_g.append(sems)
                year_g.append(years)
                course_id_g.append(row["Course ID"])

            elif(under["Class Title"].lower() == "interactive computer graphics" and row["Class Title"].lower() == "interact comp graphics" and under["Primary Instructor"] == row["Primary Instructor"] and "GY" in row["Subject/Catalog#"] and under["Days"] == row["Days"] and under["Time"] == row["Time"]):
                class_section_u.append(under["Class Section"])
                sem_u.append(sems)
                year_u.append(years)
                course_id_u.append(under["Course ID"])

                class_section_g.append(row["Class Section"])
                sem_g.append(sems)
                year_g.append(years)
                course_id_g.append(row["Course ID"])
            elif(under["Class Title"].lower() == row["Class Title"].lower() and under["Primary Instructor"] == row["Primary Instructor"] and "GY" in row["Subject/Catalog#"] and under["Days"] == row["Days"] and under["Time"] == row["Time"]):

                class_section_u.append(under["Class Section"])
                sem_u.append(sems)
                year_u.append(years)
                course_id_u.append(under["Course ID"])

                class_section_g.append(row["Class Section"])
                sem_g.append(sems)
                year_g.append(years)
                course_id_g.append(row["Course ID"])

    df = pd.DataFrame({"class_section_u":class_section_u, "sem_u":sem_u, "year_u":year_u, "course_id_u":course_id_u, "class_section_g": class_section_g, "sem_g":sem_g, "year_g":year_g, "course_id_g":course_id_g})
    for index, row in df.iterrows():
        query = 'INSERT INTO crosslisted(class_section_u, sem_u, year_u, course_id_u, class_section_g, sem_g, year_g, course_id_g) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE class_section_u = VALUES(class_section_u), sem_u = VALUES(sem_u), year_u = VALUES(year_u), course_id_u = VALUES(course_id_u), class_section_g = VALUES(class_section_g), sem_g = VALUES(sem_g), year_g = VALUES(year_g), course_id_g = VALUES(course_id_g)'
        cursor.execute(query, (row["class_section_u"], row["sem_u"], row["year_u"], row["course_id_u"], row["class_section_g"], row["sem_g"], row["year_g"], row["course_id_g"]))

    conn.commit()
    cursor.close()

def section_sheet(data):
    #class_section, sem, year course_id, room_num, building, day, timest, classnbr, class_type, enroll_cap, enroll_tot, waitlist_cap, class_topic, waitlist_tot, consent
    cursor = conn.cursor()

    sem = []
    year = []

    room_num, building = split_classroom(data)

    #checking month/year
    for index, row in data.iterrows():
        if (data["Start/End Date"][0][1] == "9"):
            sem.append("Fall")
        else:
            sem.append("Spring")
        year.append(data["Start/End Date"][0][-4:])

        data["Enrollment Capacity"] = data["Enrollment Capacity"].astype(str)
        data["Enrollment Total"] = data["Enrollment Total"].astype(str)
        data["Class Wait List Cap"] = data["Class Wait List Cap"].astype(str)
        data["Class Topic"] = data["Class Topic"].astype(str)
        data["Wait List Total"] = data["Wait List Total"].astype(str)
        data["Consent"] = data["Consent"].astype(str)

        if(row["Enrollment Capacity"] == "nan"):
            data.set_value(index, "Enrollment Capacity", "N/A")
        if(row["Enrollment Total"] == "nan"):
            data.set_value(index, "Enrollment Total", "N/A")
        if(pd.isnull(row["Class Wait List Cap"])):
            data.set_value(index, "Class Wait List Cap", "N/A")
        if(pd.isnull(row["Class Topic"])):
            data.set_value(index, "Class Topic", "N/A")
        if(pd.isnull(row["Wait List Total"])):
            data.set_value(index, "Wait List Total", "N/A")
        if(row["Consent"] == "nan"):
            data.set_value(index, "Consent", "No")
        if(pd.isnull(row["Days"])):
            data.set_value(index, "Days", "N/A")

    df = pd.DataFrame({"class_section":data["Class Section"], "sem":sem, "year":year, "course_id":data["Course ID"], "room_num":room_num, "building":building, "day":data["Days"], "timest":data["Time"], "classnbr":data["Class Nbr"],
                       "class_type":data["Component"], "enroll_cap":data["Enrollment Capacity"], "enroll_tot":data["Enrollment Total"], "waitlist_cap":data["Class Wait List Cap"],
                       "class_topic":data["Class Topic"], "waitlist_tot":data["Wait List Total"], "consent":data["Consent"]})
    for index, row in df.iterrows():
        query = 'INSERT INTO section(class_section, sem, year, course_id, room_num, building, days, timest, classnbr, class_type, enroll_cap, enroll_tot, waitlist_cap, waitlist_tot, class_topic, consent) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE class_section = VALUES(class_section), sem = VALUES(sem), year = VALUES(year), course_id = VALUES(course_id), room_num = VALUES(room_num), building = VALUES(building), days = VALUES(days), timest = VALUES(timest), classnbr = VALUES(classnbr), class_type = VALUES(class_type), enroll_cap = VALUES(enroll_cap), enroll_tot = VALUES(enroll_tot), waitlist_cap = VALUES(waitlist_cap), waitlist_tot = VALUES(waitlist_tot), class_topic = VALUES(class_topic), consent = VALUES(consent)'
        cursor.execute(query, (row["class_section"], row["sem"], row["year"], row["course_id"], row["room_num"], row["building"], row["day"], row["timest"], row["classnbr"], row["class_type"], row["enroll_cap"], row["enroll_tot"], row["waitlist_cap"], row["waitlist_tot"], row["class_topic"], row["consent"]))

    conn.commit()
    cursor.close()

def run_sheets(data):
    course_sheet(data)
    classroom_sheet(data)
    instructor_sheet(data)
    time_sheet(data)
    section_sheet(data)
    teaches_sheet(data)
    cross_listed_sheet(data)

def main():
    print("Select 1 to run all files")
    print("Select 2 to run latest file")
    choice = input("What would you like to do? ")

    dirs = os.listdir(os.getcwd()) #get current directory and list
    if(choice == "1"):
        for file in dirs:
            if(file != "automate.py"):
                print(file)
                data = pd.read_excel(file)
                run_sheets(data)
                print("done")
    elif(choice == "2"):
        latest_file = max(dirs, key=os.path.getctime)
        print(latest_file)
        data = pd.read_excel(latest_file)
        run_sheets(data)
        print("done")

main()


"""
isort:skip_file
"""
from __future__ import annotations

from typing import TYPE_CHECKING, Generator

import pytest
import logging
from pathlib import Path

from barney.BarneyApp import Barney
from barney.Utilities.PathMapper import pathToQUrl, qUrlToPath  # noqa: F401

if TYPE_CHECKING:
    from pytestqt import qtbot
    from barney.views.MainWindow import MainWindow

logger = logging.getLogger()

@pytest.fixture(scope="session")
def app() -> Generator[Barney, None, None]:
    barney = Barney()
    yield barney
    barney.qtapp.processEvents()
    logger.removeHandler(barney.qtapp.handler)
    barney.qtapp.quit()

@pytest.fixture
def viewer(app: Barney, qtbot: qtbot) -> MainWindow:
    app.qtapp.startBarney()
    viewer = app.qtapp.mainView
    qtbot.addWidget(viewer)
    qtbot.waitExposed(viewer)
    yield viewer
    viewer.clear()
    viewer._model.fileProxyModel.setSourceModel(None)
    viewer.close()

@pytest.fixture(scope="function")
def dbPath_relativeEntries():
    dbPath = Path(__file__).parents[1] / "data" / "relative_paths.db"
    return pathToQUrl(dbPath)

@pytest.fixture(scope="function")
def wavPath():
    wavPath = Path(__file__).parents[1] / "data" / "speech-mwm.wav"
    return pathToQUrl(wavPath)

@pytest.fixture(scope="function")
def dirPath():
    dirPath = Path(__file__).parents[1]
    return pathToQUrl(dirPath)


#!../dependencies/python/Python32/python3
import os
import sys
import shutil
from argparse import ArgumentParser
from analyze_juliet import AnalyzeJuliet

def main():
    """
    Analyze all juliet test cases with pmd.
    :return: None
    """
    # define, parse, and validate arguments
    parser = ArgumentParser('main.py')
    parser.add_argument('--juliet_dir', help='path/to/juliet/test/cases', type=str, default='..\juliet_test_cases')
    parser.add_argument('--cwe_mappings_file', help='path/to/cwe/mapping/file', type=str, default='cwe_mappings.txt')
    parser.add_argument('--ruleset_template_file', help='path/to/ruleset/template/file', type=str,
                        default='ruleset_template.xml')
    parser.add_argument('--pmd_exec', help='path/to/pmd/exec', type=str,
                        default='..\..\pmd\pmd-dist\\target\pmd-bin-6.13.0-SNAPSHOT\\bin\pmd.bat')
    parser.add_argument('--outdir', help='path/to/outdir', type=str, default='outdir')
    parser.add_argument('--mp', help='max number of pmd processes to spawn at one time', type=int, default=25)
    parser.add_argument('--keep_copied_source', help='keep copied source files', action='store_true')
    parser.add_argument('--use_multifile_tests', help='include tests with multiple files', action='store_true')
    parser.add_argument('-q', '--quiet', help='supress terminal output', action='store_true')
    args = validate_args(parser.parse_args())

    # analyze
    AnalyzeJuliet(
        args.juliet_dir,
        parse_cwe_mappings_file(args.cwe_mappings_file),
        args.ruleset_template_file,
        args.pmd_exec,
        args.outdir,
        args.mp,
        not args.keep_copied_source,
        not args.use_multifile_tests,
        args.quiet)

def validate_args(args):
    """
    Validate command line arguments. Calls sys.exit if error is found.

    :param args: ArgumentParser arguments
    :return: None
    """
    check_exists(args.juliet_dir, 'juliet_dir', False, args.quiet)
    if not os.path.isdir(os.path.join(args.juliet_dir, 'src', 'testcases')):
        sys.exit('invalid argument "juliet_dir", make sure it is a path to the juliet test cases')

    check_exists(args.cwe_mappings_file, 'cwe_mappings_file', True, args.quiet)

    check_exists(args.ruleset_template_file, 'ruleset_template_file', True, args.quiet)

    check_exists(args.pmd_exec, 'pmd_exec', True, args.quiet)

    if os.path.isdir(args.outdir):
        shutil.rmtree(args.outdir)
    os.makedirs(args.outdir)  # TODO verify we can make ruleset outdir

    return args

def check_exists(path, desc, check_file=True, quiet=False):
    """
    Check if a path exists as a dir or file. Calls sys.exit if error is found.

    :param path: desired/path
    :param desc: description for printing
    :param check_file: True to check for file, False to check for dir
    :param quiet: supress output
    :return: None
    """
    tmp_str = '"%s" -> "%s"' % (desc, path)
    if os.path.exists(path):
        type_ = 'dir'
        if check_file:
            type_ = 'file'
        if (check_file and os.path.isfile(path)) or (not check_file and os.path.isdir(path)):
            if quiet:
                print('found argument: %s.' % tmp_str)
            return

        sys.exit('invalid argument: %s, should be a %s.' % (tmp_str, type_))
    else:
        sys.exit('invalid argument: %s, doesnt exist.' % tmp_str)

def parse_cwe_mappings_file(cwe_mappings_file):
    """
    Parse the cwe mappings file. Call sys exit if file is invalid

    :param cwe_mappings_file: path/to/cwe/mappings/file
    :return: cwe_mappings list
    """
    cwe_mappings = []
    with open(cwe_mappings_file, 'r') as fin:
        for idx, line in enumerate(fin.readlines()):
            error = False
            line = line.replace(" ", "")
            if len(line) > 0:
                if line[:1] == "#":
                    continue
            line = line.split(',')
            cwe = 0
            priority = 0
            pmd_rule = ''
            if len(line) == 2:
                try:
                    cwe = int(line[0])
                except:
                    error = True
                pmd_rule = line[1]
                if len(pmd_rule) == 0:
                    error = True
            else:
                error = True
            if error:
                sys.exit('error in cwe_mappings file: "%s", line: "%d", must be in the following format:'
                         '"cwe_number,pmd_rule_path,priority"' % (cwe_mappings_file, idx))
            cwe_mappings.append([cwe, pmd_rule])

    if len(cwe_mappings) == 0:
        sys.exit('error in cwe_mappings file: "%s", empty file.' % cwe_mappings_file)

    return cwe_mappings

if __name__ == '__main__':
    main()


import osmnx as ox
import pandas as pd
import matplotlib.pyplot as plt

# Rough map of Rochester
rochester_city = ox.geocode_to_gdf('Rochester, NY, USA')
ax = ox.project_gdf(rochester_city).plot()
_ = ax.axis('off')

# Node visibility
rochester_graph = ox.graph_from_place('Rochester, NY, USA', network_type='drive')
ox.plot_graph(rochester_graph)

# Setting background and edge colours in the map
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
ox.plot.plot_graph(rochester_graph, bgcolor='#FFFFFF', node_color=colors[0], edge_color='gray', node_size=5)

# Sample bounding box in Rochester, NY - River Bend Shelter - Highland park boxed area
north, south, east, west = 43.12671,43.13403,-77.63630,-77.60385

# create a network from the above bounded box
G = ox.graph_from_bbox(north, south, east, west, network_type="drive_service")
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
ox.plot.plot_graph(G, bgcolor='#FFFFFF', node_color=colors[0], edge_color='gray', node_size=5)

# Number of nodes within the selected area
count=0
for i in G.nodes:
    count=count+1
print("The number of nodes within the selected location: River Bend Shelter - Highland park boxed area")
print(count)

# Storing nodes in dataframe
cords = pd.DataFrame()
loc= []
for i in G.nodes:
    loc.append(i)

# Create a column name Location in the dataframe for nodes where
loc_data=pd.DataFrame(loc)
loc_data.rename(columns = {0:'Locations'}, inplace = True)

# Appending lats and longitudes
latitude = []
longitude = []
for i in loc:
    latitude.append(G.nodes[i].get('y'))
    longitude.append(G.nodes[i].get('x'))

# create 2 columns in the dataframe latitude and longitude and add the respective lists to the dataframe
loc_data['Latitudes'] = latitude
loc_data['Longitudes'] = longitude

# Print updated dataframe
print(loc_data)


import logging
from typing import List

from cmdb.database.managers import DatabaseManagerMongo
from cmdb.database.errors.database_errors import NoDocumentFound
from cmdb.framework.cmdb_base import CmdbManagerBase, ManagerGetError, ManagerInsertError, ManagerUpdateError, \
    ManagerDeleteError
from cmdb.user_management.models.user import UserModel
from cmdb.user_management.models.group import UserGroupModel
from cmdb.user_management.models.right import BaseRight
from cmdb.utils.error import CMDBError
from cmdb.security.security import SecurityManager

LOGGER = logging.getLogger(__name__)

class UserManager(CmdbManagerBase):

    def __init__(self, database_manager: DatabaseManagerMongo):
        self.scm = SecurityManager(database_manager)
        self.rights = self._load_rights()
        super(UserManager, self).__init__(database_manager)

    def get_new_id(self, collection: str) -> int:
        return self.dbm.get_next_public_id(collection)

    def get_users(self) -> List[UserModel]:
        """Get all users"""
        user_list = []
        for founded_user in self._get_many(collection=UserModel.COLLECTION):
            try:
                user_list.append(UserModel.from_data(founded_user))
            except CMDBError:
                continue
        return user_list

    def get_users_by(self, sort='public_id', **requirements) -> List[UserModel]:
        """Get a list of users by requirement"""
        user_list = []
        users_in_database = self._get_many(collection=UserModel.COLLECTION, sort=sort, **requirements)
        for user in users_in_database:
            try:
                user_ = UserModel.from_data(user)
            except CMDBError as err:
                LOGGER.error(f'[UserManager] Error while inserting database user into return list: {err}')
                continue
            user_list.append(user_)
        return user_list

    def get_user_by(self, **requirements) -> UserModel:
        """Get user by requirement"""
        try:
            return UserModel.from_data(self._get_by(collection=UserModel.COLLECTION, **requirements))
        except NoDocumentFound:
            raise UserManagerGetError(f'UserModel not found')

    def get_user_by_name(self, user_name) -> UserModel:
        """Get a user by his user_name"""
        return self.get_user_by(user_name=user_name)

    def update_user(self, public_id, update_params: dict):
        try:
            return self._update(collection=UserModel.COLLECTION, public_id=public_id, data=update_params)
        except (CMDBError, Exception):
            raise UserManagerUpdateError(f'Could not update user with ID: {public_id}')

    def update_users_by(self, query: dict, update: dict):
        try:
            return self._update_many(collection=UserModel.COLLECTION, query=query, update=update)
        except Exception as err:
            raise UserManagerUpdateError(err)

    def delete_user(self, public_id: int) -> bool:
        try:
            return self._delete(collection=UserModel.COLLECTION, public_id=public_id)
        except Exception:
            raise UserManagerDeleteError(f'Could not delete user with ID: {public_id}')

    def delete_users_by(self, query: dict):
        try:
            return self._delete_many(collection=UserModel.COLLECTION, filter_query=query).acknowledged
        except Exception as err:
            raise UserManagerDeleteError(err)

    def get_groups(self) -> list:
        group_list = []
        for founded_group in self._get_many(collection=UserGroupModel.COLLECTION):
            try:
                group_list.append(UserGroupModel(**founded_group))
            except CMDBError:
                LOGGER.debug("Error while group parser: {}".format(founded_group))
                continue
        return group_list

    def get_group(self, public_id: int) -> UserGroupModel:
        try:
            founded_group = self._get(collection=UserGroupModel.COLLECTION, public_id=public_id)
            return UserGroupModel(**founded_group)
        except NoDocumentFound as e:
            raise UserManagerGetError(e)

    def get_group_by(self, **requirements) -> UserGroupModel:
        try:
            return UserGroupModel(**self._get_by(collection=UserGroupModel.COLLECTION, **requirements))
        except NoDocumentFound:
            raise UserManagerGetError(f'Group not found')

    def update_group(self, public_id, update_params: dict) -> bool:
        try:
            ack = self._update(collection=UserGroupModel.COLLECTION, public_id=public_id,
                               data=update_params)
        except (CMDBError, Exception) as e:
            LOGGER.error(e)
            raise UserManagerUpdateError(e)
        return ack

    def insert_group(self, insert_group: UserGroupModel) -> int:
        try:
            return self.dbm.insert(collection=UserGroupModel.COLLECTION, data=insert_group.__dict__)
        except Exception:
            raise UserManagerInsertError(insert_group.name)

    def delete_group(self, public_id, user_action: str = None, options: dict = None) -> bool:
        try:
            delete_group: UserGroupModel = self.get_group(public_id)
        except UserManagerGetError:
            raise UserManagerDeleteError(f'Could not find group with ID: {public_id}')

        try:
            ack = self.dbm.delete(collection=UserGroupModel.COLLECTION, public_id=public_id).acknowledged
        except Exception:
            raise UserManagerDeleteError(f'Could not delete group')

        # Cleanup user
        users_in_group: [UserModel] = self.get_users_by(**{'group_id': delete_group.get_public_id()})
        if len(users_in_group) > 0:
            if user_action == 'move':
                if not options.get('group_id'):
                    raise UserManagerDeleteError(f'Not move group was provided!')
                self.update_users_by(query={'group_id': delete_group.get_public_id()},
                                     update={'$set': {'group_id': int(options.get('group_id'))}})
            elif user_action == 'delete':
                self.delete_users_by({'group_id': delete_group.get_public_id()})
            else:
                raise UserManagerDeleteError(f'No valid user action was provided')
        return ack

    def get_right_names_with_min_level(self, min_level):
        selected_levels = []
        for right in self.rights:
            if right.get_level() <= min_level:
                selected_levels.append(right.get_display_name())
        return selected_levels

    def get_all_rights(self):
        return self.rights

    def _load_rights(self):
        from cmdb.user_management.rights import __all__
        return self._load_right_tree(__all__)

    def _load_right_tree(self, right_list) -> list:
        rights = list()
        for right in right_list:
            if isinstance(right, tuple) or isinstance(right, list):
                rights = rights + self._load_right_tree(right)
            else:
                rights.append(right)
        return rights

    def get_right_by_name(self, name) -> BaseRight:
        try:
            return next(right for right in self.rights if right.name == name)
        except Exception:
            raise UserManagerGetError(name)

    def group_has_right(self, group_id: int, right_name: str) -> bool:
        right_status = False
        try:
            selected_right = self.get_right_by_name(right_name)
            chosen_group = self.get_group(group_id)
        except UserManagerGetError:
            return right_status

        right_status = chosen_group.has_right(right_name=right_name)
        if not right_status:
            right_status = chosen_group.has_extended_right(right_name=right_name)
        return right_status

class UserManagerGetError(ManagerGetError):

    def __init__(self, err):
        super(UserManagerGetError, self).__init__(err)

class UserManagerInsertError(ManagerInsertError):

    def __init__(self, err):
        super(UserManagerInsertError, self).__init__(err)

class UserManagerUpdateError(ManagerUpdateError):

    def __init__(self, err):
        super(UserManagerUpdateError, self).__init__(err)

class UserManagerDeleteError(ManagerDeleteError):

    def __init__(self, err):
        super(UserManagerDeleteError, self).__init__(err)


from flask.globals import g
from flask_jwt_extended.view_decorators import jwt_required
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from app.models import RankingListTest, Task
from app.models.RankingListModel import RankingList
from app.Responses import ApiErrorResponse, ApiResponse

class RankingListsResource(Resource):
    def __init__(self):
        self.reqparse = RequestParser()
        self.reqparse.add_argument('listname', type=str, required=True, location='json')
        self.reqparse.add_argument('shortname', type=str, required=True, location='json')
        self.reqparse.add_argument('resultsValidDays', type=str, required=False, location='json')

    @RankingList.from_request(many=True)
    def get(self):
        return ApiResponse(g.rankinglists).response()

    @jwt_required
    def post(self):
        args = self.reqparse.parse_args()

        rankinglist = RankingList(args['listname'], args['shortname'])

        rankinglist.update(self.reqparse)

        try:
            rankinglist.save()
        except Exception as e:
            return ApiErrorResponse(str(e)).response()

        return ApiResponse(rankinglist).response()

class RankingListResource(Resource):
    def __init__(self):
        self.reqparse = RequestParser()
        self.reqparse.add_argument('listname', type=str, required=False, location='json')
        self.reqparse.add_argument('shortname', type=str, required=False, location='json')
        self.reqparse.add_argument('resultsValidDays', type=str, required=False, location='json')

    @RankingList.from_request
    def get(self, id):
        return ApiResponse(g.rankinglist).response()

    @jwt_required
    @RankingList.from_request
    def patch(self, id):
        g.rankinglist.update(self.reqparse)

        try:
            g.rankinglist.save()
        except Exception as e:
            return ApiErrorResponse(str(e)).response()

        return ApiResponse(g.rankinglist).response()

    @jwt_required
    @RankingList.from_request
    def delete(self, id):
        try:
            g.rankinglist.delete()
        except Exception as e:
            return ApiErrorResponse(str(e)).response()

        return ApiResponse(response_code=204).response()

class RankingListTestsResource(Resource):
    def __init__(self):
        self.reqparse = RequestParser()
        self.reqparse.add_argument('testcode', type=str, required=True, location='json')
        self.reqparse.add_argument('includedMarks', type=int, required=True, location='json')
        self.reqparse.add_argument('order', type=str, required=True, location='json')
        self.reqparse.add_argument('grouping', type=str, required=True, location='json')
        self.reqparse.add_argument('minMark', type=float, required=True, location='json')
        self.reqparse.add_argument('roundingPrecision', type=int, required=True, location='json')
        self.reqparse.add_argument('markType', type=str, required=True, location='json')

    @RankingList.from_request
    def get(self, id):
        try:
            tests = RankingListTest.load_many(g.rankinglist.tests)
        except ApiErrorResponse as e:
            return e.response()

        return ApiResponse(tests).response()

    @jwt_required
    @RankingList.from_request
    def post(self, id):
        test = RankingListTest()
        test.update(self.reqparse)

        try:
            g.rankinglist.add_test(test)
            test.save()
        except ApiErrorResponse as e:
            return e.response()
        except Exception as e:
            return ApiErrorResponse(str(e)).response()

        return ApiResponse(test).response()

class RankingListTasksResource(Resource):
    @RankingList.from_request
    def get(self, id):
        try:
            tasks = Task.load_many(g.rankinglist.tasks)
        except ApiErrorResponse as e:
            return e.response()

        return ApiResponse(tasks).response()


import numpy as np
from collections import deque

class Graph:

    def __init__(self, n):

        self.n = n
        self.adj_list = [[] for i in range(n)]

    def add_edge(self, u, v):

        self.adj_list[u].append(v)

    def add_node(self):

        self.n += 1
        self.adj_list.append([])

        return self.n - 1

    def compute_indegrees(self):

        indeg_list = [0] * self.n

        for node in range(self.n):
            for out_nbr in self.adj_list[node]:
                indeg_list[out_nbr] += 1

        return indeg_list

    def compute_outdegrees(self):

        return [len(self.adj_list[i]) for i in range(self.n)]

    def compute_indegree_distribution(self):

        indeg_list = self.compute_indegrees()
        indeg_dist = [0] * self.n

        for deg in indeg_list:
            indeg_dist[deg] += 1

        return indeg_dist

    def compute_outdegree_distribution(self):

        outdeg_list = self.compute_outdegrees()
        outdeg_dist = [0] * self.n

        for deg in outdeg_list:
            outdeg_dist[deg] += 1

        return outdeg_dist

    def compute_diameter(self, check_inf=False):

        dp = np.full((self.n, self.n), np.inf)

        for node in range(self.n):
            for nbr in self.adj_list[node]:
                dp[node, nbr] = 1

        for k in range(self.n):
            dp = np.minimum(
                dp, np.expand_dims(dp[:, k], axis=1)
                + np.expand_dims(dp[k, :], axis=0))

        diameter = np.max(dp) if not check_inf else np.max(dp[dp != np.inf])

        return 'infinity' if diameter == np.inf else diameter

    def dfs_rev(self, adj_rev, u, visited, dq):
        visited[u] = True

        for v in adj_rev[u]:
            if not visited[v]:
                self.dfs_rev(adj_rev, v, visited, dq)

        dq.appendleft(u)

    def dfs(self, u, visited, comp):
        visited[u] = True
        comp.append(u)

        for v in self.adj_list[u]:
            if not visited[v]:
                self.dfs(v, visited, comp)

    def scc(self):

        adj_rev = [[] for _ in range(self.n)]

        for node in range(self.n):
            for nbr in self.adj_list[node]:
                adj_rev[nbr].append(node)

        dq = deque()
        visited = [False for _ in range(self.n)]

        for u in range(self.n):
            if not visited[u]:
                self.dfs_rev(adj_rev, u, visited, dq)

        visited = [False for _ in range(self.n)]
        comp_list = []
        for u in list(dq):
            if not visited[u]:
                comp = []
                comp_list.append(comp)
                self.dfs(u, visited, comp)

        return comp_list

    def get_edge_list(self):

        edge_list = []
        for node in range(self.n):
            for nbr in self.adj_list[node]:
                edge_list.append((node, nbr))

        return edge_list