# Adjacency List

class AdjacencyList:

    def __init__(self):
        self.internal_dict = {}

    def num_vertices(self):
        return len(self.internal_dict)

    def add_vertex(self, u):
        self.internal_dict[u] = []

    def add_edge(self, u, v):
        self.internal_dict[u].append(v)

    def print_adjacency(self):
        for u, v in self.internal_dict.items():
            print(u, ':', v)

    def vertices(self):
        return self.internal_dict.keys()

    def get_neighbors(self, u):
        return self.internal_dict[u]

# Path between Nodes using a Breadth First Search
def path_between_nodes(s, t, graph):

    queue = [s]
    visited = []
    while queue:
        temp_vertex = queue.pop(0)

        if temp_vertex == t:
            return True

        for neighbor in graph.get_neighbors(temp_vertex):
            if neighbor not in visited:
                queue.append(neighbor)
                visited.append(neighbor)

    return False

if __name__ == '__main__':
    test = AdjacencyList()

    test.add_vertex(0)
    test.add_vertex(1)
    test.add_vertex(2)
    test.add_vertex(3)
    test.add_vertex(4)
    test.add_vertex(5)

    test.add_edge(0, 1)
    test.add_edge(0, 4)
    test.add_edge(0, 5)

    test.add_edge(1, 4)
    test.add_edge(1, 3)

    test.add_edge(2, 1)

    test.add_edge(3, 2)
    test.add_edge(3, 4)

    test.print_adjacency()
    print()
    print(path_between_nodes(0, 3, test))
    print(path_between_nodes(2, 4, test))
    print(path_between_nodes(1, 5, test))


import sqlite3
import time

DATABASE_PATH = "prices.sqlite"

def db_connection(path: str):
    connection = None
    try:
        connection = sqlite3.connect(path)
    except sqlite3.Error as e:
        print("Error:", e)
    return connection

connection = db_connection(DATABASE_PATH)
cur = connection.cursor()

for row in cur.execute("SELECT * FROM prices"):
    print(row)

time.sleep(20)

connection.close()


class Solution:
    def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:
        painting = [0] * (10 ** 5 + 1)
        ends = set()

        for start, end, color in segments:
            painting[start] += color
            painting[end] -= color
            ends.add(end)

        for i in range(1, 10 ** 5 + 1):
            painting[i] += painting[i - 1]

        res = []
        currentStart = -1
        currentColor = 0

        for i, x in enumerate(painting):
            if i in ends or currentColor != x:
                if currentColor > 0:
                    res.append([currentStart, i, currentColor])
                currentStart = i
                currentColor = x

        return res


import argparse
import torch

import models_torch as models
import utils

def inference(parameters, verbose=True):

    # resolve device
    device = torch.device(
        "cuda:{}".format(parameters["gpu_number"]) if parameters["device_type"] == "gpu"
        else "cpu"
    )

    # load input images
    datum_l_cc = utils.load_images(parameters['image_path'], 'L-CC')
    datum_r_cc = utils.load_images(parameters['image_path'], 'R-CC')
    datum_l_mlo = utils.load_images(parameters['image_path'], 'L-MLO')
    datum_r_mlo = utils.load_images(parameters['image_path'], 'R-MLO')

    # construct models and prepare data
    if parameters["model_type"] == 'cnn':
        model = models.BaselineBreastModel(device, nodropout_probability=1.0, gaussian_noise_std=0.0).to(device)
        model.load_state_dict(torch.load(parameters["model_path"]))
        x = {
            "L-CC": torch.Tensor(datum_l_cc).permute(0, 3, 1, 2).to(device),
            "L-MLO": torch.Tensor(datum_l_mlo).permute(0, 3, 1, 2).to(device),
            "R-CC": torch.Tensor(datum_r_cc).permute(0, 3, 1, 2).to(device),
            "R-MLO": torch.Tensor(datum_r_mlo).permute(0, 3, 1, 2).to(device),
        }
    elif parameters["model_type"] == 'histogram':
        model = models.BaselineHistogramModel(num_bins=parameters["bins_histogram"]).to(device)
        model.load_state_dict(torch.load(parameters["model_path"]))
        x = torch.Tensor(utils.histogram_features_generator([
            datum_l_cc, datum_r_cc, datum_l_mlo, datum_r_mlo
        ], parameters)).to(device)
    else:
        raise RuntimeError(parameters["model_type"])

    # run prediction
    with torch.no_grad():
        prediction_density = model(x).cpu().numpy()

    if verbose:
        # nicely prints out the predictions
        print('Density prediction:\n'
              '\tAlmost entirely fatty (0):\t\t\t' + str(prediction_density[0, 0]) + '\n'
              '\tScattered areas of fibroglandular density (1):\t' + str(prediction_density[0, 1]) + '\n'
              '\tHeterogeneously dense (2):\t\t\t' + str(prediction_density[0, 2]) + '\n'
              '\tExtremely dense (3):\t\t\t\t' + str(prediction_density[0, 3]) + '\n')

    return prediction_density[0]

if __name__ == "__main__":

    parser = argparse.ArgumentParser(description='Run Inference')
    parser.add_argument('model_type')
    parser.add_argument('--bins-histogram', default=50)
    parser.add_argument('--model-path', default=None)
    parser.add_argument('--device-type', default="cpu")
    parser.add_argument('--image-path', default="images/")
    args = parser.parse_args()

    parameters_ = {
        "model_type": args.model_type,
        "bins_histogram": args.bins_histogram,
        "model_path": args.model_path,
        "device_type": args.device_type,
        "image_path": args.image_path,
    }

    if parameters_["model_path"] is None:
        if args.model_type == "histogram":
            parameters_["model_path"] = "saved_models/BreastDensity_BaselineHistogramModel/model.p"
        if args.model_type == "cnn":
            parameters_["model_path"] = "saved_models/BreastDensity_BaselineBreastModel/model.p"

    inference(parameters_)

"""
python density_model_torch.py histogram
python density_model_torch.py cnn
"""


import requests

session = requests.Session()

def get_jobs():
    url = 'https://api.github.com/search/repositories?q=machine+learning+language:python'
    first_page = session.get(url).json()
    yield first_page
    num_pages = first_page['last_page']

    for page in range(2, num_pages + 1):
        next_page = session.get(url, params={'page': page}).json()
        yield next_page['page']

for page in get_jobs():

    np = page
    x = 0

x = 0


import asyncio

class AsyncQueue(asyncio.Queue):
    """
    asyncio.Queue with a peek method added.
    """

    async def peek(self):
        while self.empty():
            getter = self._loop.create_future()
            self._getters.append(getter)
            try:
                await getter
            except BaseException:
                getter.cancel()  # Just in case getter is not done yet.
                try:
                    # Clean self._getters from canceled getters.
                    self._getters.remove(getter)
                except ValueError:
                    # The getter could be removed from self._getters by a
                    # previous put_nowait call.
                    pass
                if not self.empty() and not getter.cancelled():
                    # We were woken up by put_nowait(), but can't take
                    # the call.  Wake up the next in line.
                    self._wakeup_next(self._getters)
                raise
        return self.peek_nowait()

    def peek_nowait(self):
        if self.empty():
            raise asyncio.QueueEmpty
        item = self._peek()
        self._wakeup_next(self._putters)
        return item

    def _peek(self):
        return self._queue[0]


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

data1='/Users/LJ/gas_kinematicsdat.txt'
gas=[]
f=open(data1,'r')
f.seek(0)
for i in range(4194304):
 List=f.readline().strip().split()
 gas.append(List)

x_sun=8.3*np.cos(153./180.*np.pi)
y_sun=8.3*np.sin(153./180.*np.pi)
v_sun=210.
v_sun_x=-v_sun*np.sin(27./180.*np.pi)
v_sun_y=-v_sun*np.cos(27./180.*np.pi)
l=[]

for i in range(4194304):
 if np.sqrt((float(gas[i][0])**2+float(gas[i][1])**2))>=14.5:
  c=0
  l.append(c)
 if np.sqrt((float(gas[i][0])**2+float(gas[i][1])**2))<14.5:
  if float(gas[i][1])>(y_sun/x_sun)*float(gas[i][0]) and abs(float(gas[i][1])-(y_sun/x_sun)*float(gas[i][0]))>10**(-6):
   c=-1*math.acos((x_sun**2+y_sun**2-x_sun*float(gas[i][0])-y_sun*float(gas[i][1]))/(np.sqrt(x_sun**2+y_sun**2)*np.sqrt((float(gas[i][0])-x_sun)**2+(float(gas[i][1])-y_sun)**2)))*180/np.pi
   l.append(c)
  if float(gas[i][1])<(y_sun/x_sun)*float(gas[i][0]) and abs(float(gas[i][1])-(y_sun/x_sun)*float(gas[i][0]))>10**(-6):
   c=1*math.acos((x_sun**2+y_sun**2-x_sun*float(gas[i][0])-y_sun*float(gas[i][1]))/(np.sqrt(x_sun**2+y_sun**2)*np.sqrt((float(gas[i][0])-x_sun)**2+(float(gas[i][1])-y_sun)**2)))*180/np.pi
   l.append(c)
  if abs(float(gas[i][1])-(y_sun/x_sun)*float(gas[i][0]))<=10**(-6):
   c=0
   l.append(c)

v_los=[]
omega_b=33.
tmp_r=np.zeros(4194304)
e_los_x=np.zeros(4194304)
e_los_y=np.zeros(4194304)
velocity_x=np.zeros(4194304)
velocity_y=np.zeros(4194304)
v_los_tmp=np.zeros(4194304)
v_los_sun=np.zeros(4194304)

for k in range(4194304):
 if np.sqrt((float(gas[k][0])**2+float(gas[k][1])**2))<14.5:
  tmp_r[k]=np.sqrt((float(gas[k][0])-x_sun)**2+(float(gas[k][1])-y_sun)**2)
  e_los_x[k]=(float(gas[k][0])-x_sun)/tmp_r[k]
  e_los_y[k]=(float(gas[k][1])-y_sun)/tmp_r[k]
  v_los_tmp[k]=float(gas[k][3])*e_los_x[k]+float(gas[k][4])*e_los_y[k]
  v_los_sun[k]=v_sun_x*e_los_x[k]+v_sun_y*e_los_y[k]
  c=v_los_tmp[k]-v_los_sun[k]
  v_los.append(c)
 if np.sqrt((float(gas[k][0])**2+float(gas[k][1])**2))>=14.5:
  c=0
  v_los.append(c)

l=np.asarray(l)
v_los=np.asarray(v_los)
l1=[]
v_los1=[]
for j in range(900):
 index1=np.where((l>=-90.0+0.1*j) & (l<-90.0+0.1*(j+1)))
 index2=np.where(v_los==min(v_los[index1]))
 l1.append(l[index2])
 v_los1.append(v_los[index2])

l2=[]
v_los2=[]
v2=[]
for n in range(900):
 index3=np.where((l>=0.0+0.1*n) & (l<0.0+0.1*(n+1)))
 index4=np.where(v_los==max(v_los[index3]))
 l2.append(l[index4])
 v_los2.append(v_los[index4])

fig=plt.figure()
plt.plot(l1,v_los1,'.')
plt.plot(l2,v_los2,'.')
plt.xlabel("l(degree)")
plt.ylabel("v_los(km/s)")
plt.title("lv diagram")
plt.xlim(-90.0,90.0)
plt.show()


import socket, errno, sys
from pysnmp.carrier.asyncore.base import AbstractSocketTransport
from pysnmp.carrier import sockfix, sockmsg, error
from pysnmp import debug

# Ignore these socket errors
sockErrors = {errno.ESHUTDOWN: True,
              errno.ENOTCONN: True,
              errno.ECONNRESET: False,
              errno.ECONNREFUSED: False,
              errno.EAGAIN: False,
              errno.EWOULDBLOCK: False}

if hasattr(errno, 'EBADFD'):
    # bad FD may happen upon FD closure on n-1 select() event
    sockErrors[errno.EBADFD] = True

class DgramSocketTransport(AbstractSocketTransport):
    sockType = socket.SOCK_DGRAM
    retryCount = 3
    retryInterval = 1
    addressType = lambda x: x
    def __init__(self, sock=None, sockMap=None):
        self.__outQueue = []
        self._sendto = lambda s, b, a: s.sendto(b, a)
        def __recvfrom(s, sz):
            d, a = s.recvfrom(sz)
            return d, self.addressType(a)
        self._recvfrom = __recvfrom
        AbstractSocketTransport.__init__(self, sock, sockMap)

    def openClientMode(self, iface=None):
        if iface is not None:
            try:
                self.socket.bind(iface)
            except socket.error:
                raise error.CarrierError('bind() for %s failed: %s' % (iface is None and "<all local>" or iface, sys.exc_info()[1]))
        return self

    def openServerMode(self, iface=None):
        try:
            self.socket.bind(iface)
        except socket.error:
            raise error.CarrierError('bind() for %s failed: %s' % (iface, sys.exc_info()[1],))
        return self

    def enableBroadcast(self, flag=1):
        try:
            self.socket.setsockopt(
                socket.SOL_SOCKET, socket.SO_BROADCAST, flag
            )
        except socket.error:
            raise error.CarrierError('setsockopt() for SO_BROADCAST failed: %s' % (sys.exc_info()[1],))
        debug.logger & debug.flagIO and debug.logger('enableBroadcast: %s option SO_BROADCAST on socket %s' % (flag and "enabled" or "disabled", self.socket.fileno()))
        return self

    def enablePktInfo(self, flag=1):
        if not hasattr(self.socket, 'sendmsg') or \
           not hasattr(self.socket, 'recvmsg'):
            raise error.CarrierError('sendmsg()/recvmsg() interface is not supported by this OS and/or Python version')

        try:
            if self.socket.family in (socket.AF_INET, socket.AF_INET6):
                self.socket.setsockopt(socket.SOL_IP, socket.IP_PKTINFO, flag)
            if self.socket.family == socket.AF_INET6:
                self.socket.setsockopt(socket.SOL_IPV6, socket.IPV6_RECVPKTINFO, flag)
        except socket.error:
            raise error.CarrierError('setsockopt() for %s failed: %s' % (self.socket.family == socket.AF_INET6 and "IPV6_RECVPKTINFO" or "IP_PKTINFO", sys.exc_info()[1]))

        self._sendto = sockmsg.getSendTo(self.addressType)
        self._recvfrom = sockmsg.getRecvFrom(self.addressType)

        debug.logger & debug.flagIO and debug.logger('enablePktInfo: %s option %s on socket %s' % (self.socket.family == socket.AF_INET6 and "IPV6_RECVPKTINFO" or "IP_PKTINFO", flag and "enabled" or "disabled", self.socket.fileno()))
        return self

    def enableTransparent(self, flag=1):
        try:
            if self.socket.family == socket.AF_INET:
                self.socket.setsockopt(
                    socket.SOL_IP, socket.IP_TRANSPARENT, flag
                )
            if self.socket.family == socket.AF_INET6:
                self.socket.setsockopt(
                    socket.SOL_IPV6, socket.IP_TRANSPARENT, flag
                )
        except socket.error:
            raise error.CarrierError('setsockopt() for IP_TRANSPARENT failed: %s' % sys.exc_info()[1])
        except OSError:
            raise error.CarrierError('IP_TRANSPARENT socket option requires superusre previleges')

        debug.logger & debug.flagIO and debug.logger('enableTransparent: %s option IP_TRANSPARENT on socket %s' % (flag and "enabled" or "disabled", self.socket.fileno()))
        return self

    def sendMessage(self, outgoingMessage, transportAddress):
        self.__outQueue.append(
            (outgoingMessage, self.normalizeAddress(transportAddress))
            )
        debug.logger & debug.flagIO and debug.logger('sendMessage: outgoingMessage queued (%d octets) %s' % (len(outgoingMessage), debug.hexdump(outgoingMessage)))

    def normalizeAddress(self, transportAddress):
        if not isinstance(transportAddress, self.addressType):
            transportAddress = self.addressType(transportAddress)
        if not transportAddress.getLocalAddress():
            transportAddress.setLocalAddress(self.getLocalAddress())
        return transportAddress

    def getLocalAddress(self):
        # one evil OS does not seem to support getsockname() for DGRAM sockets
        try:
            return self.socket.getsockname()
        except:
            return ('0.0.0.0', 0)

    # asyncore API
    def handle_connect(self):
        pass

    def writable(self):
        return self.__outQueue

    def handle_write(self):
        outgoingMessage, transportAddress = self.__outQueue.pop(0)
        debug.logger & debug.flagIO and debug.logger('handle_write: transportAddress %r -> %r outgoingMessage (%d octets) %s' % (transportAddress.getLocalAddress(), transportAddress, len(outgoingMessage), debug.hexdump(outgoingMessage)))
        if not transportAddress:
            debug.logger & debug.flagIO and debug.logger('handle_write: missing dst address, loosing outgoing msg')
            return
        try:
            self._sendto(
                self.socket, outgoingMessage, transportAddress
            )
        except socket.error:
            if sys.exc_info()[1].args[0] in sockErrors:
                debug.logger & debug.flagIO and debug.logger('handle_write: ignoring socket error %s' % (sys.exc_info()[1],))
            else:
                raise error.CarrierError('sendto() failed for %s: %s' % (transportAddress, sys.exc_info()[1]))

    def readable(self):
        return 1

    def handle_read(self):
        try:
            incomingMessage, transportAddress = self._recvfrom(
                self.socket, 65535
            )
            transportAddress = self.normalizeAddress(transportAddress)
            debug.logger & debug.flagIO and debug.logger('handle_read: transportAddress %r -> %r incomingMessage (%d octets) %s' % (transportAddress, transportAddress.getLocalAddress(), len(incomingMessage), debug.hexdump(incomingMessage)))
            if not incomingMessage:
                self.handle_close()
                return
            else:
                self._cbFun(self, transportAddress, incomingMessage)
                return
        except socket.error:
            if sys.exc_info()[1].args[0] in sockErrors:
                debug.logger & debug.flagIO and debug.logger('handle_read: known socket error %s' % (sys.exc_info()[1],))
                sockErrors[sys.exc_info()[1].args[0]] and self.handle_close()
                return
            else:
                raise error.CarrierError('recvfrom() failed: %s' % (sys.exc_info()[1],))

    def handle_close(self):
        pass # no datagram connection


from models.user import User
from routes import *

import os
import flask

main = Blueprint('uploads', __name__)

Model = User

def file_name(filename):
    count = len(os.listdir('uploads')) + 1
    name = str(count) + '.' + filename.split('.')[-1]
    print(name)
    return name

@main.route('/add', methods=['POST'])
@login_required
def add():
    # 通过 request.files 访问上传的文件
    # uploaded 是上传时候的文件名
    f = request.files.get('uploaded')
    print(request)
    print('upload, ', request.files)
    if f:
        filename = f.filename
        ext = filename.split('.')[-1]
        valid_filetypes = ('png', 'jpg', 'jpeg', 'gif', 'apng')
        if ext in valid_filetypes:
            filename = file_name(filename)
            print('filename, ', filename)
            path = 'uploads/' + filename
            print(path)
            print(os.getcwd())
            f.save(path)
            u = current_user()
            u.img = '/' + path
            u.save()
            return redirect(url_for('user.profile'))
        else:
            return '
文件类型或大小不对
'
    else:
        return '
没有上传
'

@main.route('/<filename>')
def read(filename):
    # 用这个函数直接返回文件的响应
    return flask.send_from_directory('uploads/', filename)


import tkinter as tk

window = tk.Tk()
window.title("Address Entry Form")
window.resizable(False, False)
frame = tk.Frame(relief = tk.SUNKEN, borderwidth=1)

def Form(name, pos):
    label = tk.Label(master = frame, text = name, width=15, anchor='e')
    entry = tk.Entry(master = frame, width = 35)
    label.grid(column = 0, row = pos)
    entry.grid(column = 1, row = pos)

Form("First Name:", 0)
Form("Last Name:", 1)
Form("Address Line 1:", 2)
Form("Address Line 2:", 3)
Form("City:", 4)
Form("State/Province:", 5)
Form("Postal Code:", 6)
Form("Country:", 7)

frame.pack()
control = tk.Frame()
cncl = tk.Button(text="Cancel", master=control)
cncl.pack(pady=2, padx=2, side = tk.LEFT)
ok = tk.Button(text="Submit", master=control)
ok.pack(pady=2, padx=2)
control.pack(anchor='e')
window.mainloop()


import os
from dataclasses import FrozenInstanceError
from typing import Generator

import pytest

from pokeapi.search import config
from pokeapi.search.config import Singleton

def dynamic_connection_url() -> Generator[str, None, None]:
    if os.getenv("STAGE") == "development":
        yield "http://elasticsearch:9200"
    else:
        yield "http://localhost:9200"

class TestSingleton:
    class SingletonTestClass(metaclass=Singleton):
        pass

    def test_singleton(self) -> None:
        assert self.SingletonTestClass() is self.SingletonTestClass()

class TestConfig:
    @pytest.mark.usefixtures("_setup_get_config")
    @pytest.mark.parametrize("expected", dynamic_connection_url())
    def test_get_config(self, expected: str) -> None:
        actual = config.get_config()

        assert actual.ES_INDEX == "pokemon"
        assert actual.ES_CONNECTION_URL == expected

        actual_clone = config.get_config()
        assert actual is actual_clone

        with pytest.raises(FrozenInstanceError):
            actual.ES_INDEX = "hoge"  # type: ignore

        with pytest.raises(FrozenInstanceError):
            actual.ES_CONNECTION_URL = "hoge"  # type: ignore


from flask import Blueprint, Flask, request, jsonify
import api.book_routes as br
import api.author_routes as ar
import api.category_routes as cr
from datetime import datetime
import connection as conn
import query_data as db

app = Flask(__name__)

@app.route("/", methods=["GET"])
def welcome():
    return "Welcome to my App!"

@app.route("/hello/<name>", methods=["GET"])
def say_hello(name):
    return f"Hello {name}"

@app.route("/about")
def about():
    print(request.args)
    return "about me"

@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return f"Please Log in"
    elif request.method == "POST":
        print(request)
        print(request.json)
        if request.json["username"] == "Hello" and request.json["password"] == "World":
            return "Thank you for logging in"
        else:
            return "Incorrect Username or Password"

@app.route("/date/today")
def send_date():
    today = datetime.now()
    data = {
        "day": today.day,
        "month": today.month,
        "year": today.year
    }
    # return f"<h1>{today}</h1>"
    return jsonify(data)

app.register_blueprint(ar.publisher_routes, url_prefix='/api/publisher')
app.register_blueprint(cr.category_routes, url_prefix='/api/category')
app.register_blueprint(br.book_routes, url_prefix='/api/book')

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

phase 2 general practice/flask exercise/app.py


from pyspark.sql import SparkSession
from pyspark.sql.functions import when

spark = SparkSession.builder.appName("MobileAnalysis").getOrCreate()
df = spark.read.format("csv").option("header","True").option("inferSchema",True).option("delimiter",",").load('F:\SparkCourse\csv\mobileDataset.csv')

# Replace empty strings with null values
df = df.withColumn("Storage", when(df["Internal_memory"] != "", df["Internal_memory"]).otherwise(None))
df = df.withColumn("BatteryCapacity", when(df["Battery"] != "", df["Battery"]).otherwise(None))
df = df.withColumn("Processor", when(df["CPU"] != "", df["CPU"]).otherwise(None))
df = df.withColumn("Brand", when(df["Brand"] != "", df["Brand"]).otherwise(None))
df = df.withColumn("Network", when(df["Network"] != "", df["Network"]).otherwise(None))
df = df.withColumn("Model", when(df["Model"] != "", df["Model"]).otherwise(None))

# Convert relevant columns to numeric types
df = df.withColumn("Storage", df["Storage"].cast("int"))
df = df.withColumn("BatteryCapacity", df["BatteryCapacity"].cast("int"))

# Filter the dataset to exclude rows with null values
df = df.na.drop(subset=["Brand", "Model", "Storage", "BatteryCapacity", "Processor", "Network"])

from pyspark.sql.window import Window
from pyspark.sql.functions import row_number, desc

# Define a window specification
window_spec = Window.partitionBy("Operating_System").orderBy(desc("Storage"), desc("BatteryCapacity"), desc("Processor"))

# Add row numbers to the DataFrame based on the window specification
df = df.withColumn("rank", row_number().over(window_spec))

# Filter the top 5 phones for iOS and Android
ios_best_phones = df.filter((df["Operating_System"] == "iOS") & (df["rank"] <= 5))
android_best_phones = df.filter((df["Operating_System"] == "Android") & (df["rank"] <= 5))

#1.Market captured by mobile phone brands according to the number of phone models:
brand_market_share = df.groupBy("Brand").count().withColumnRenamed("count", "ModelCount")

#2.Phone models with 4G or LTE network, and phones with 5G network:
from pyspark.sql.functions import col

# Filter phone models with 4G/LTE and 5G networks
models_with_4g_lte = df.filter(col("Network").rlike(r'4G|LTE'))
models_with_5g = df.filter(col("Network").rlike(r'5G'))

#3.Brand with the most number of models with (LTE, 4G network) or 5G network:
from pyspark.sql.functions import when, count

# Create a column to flag whether a phone has (LTE, 4G network) or 5G network
df = df.withColumn("HasLTE4G", when(col("Network").rlike(r'4G|LTE'), "Yes").otherwise("No"))
df = df.withColumn("Has5G", when(col("Network").rlike(r'5G'), "Yes").otherwise("No"))

# Count the number of models for each brand with (LTE, 4G network) and 5G network
brand_with_most_models_lte = df.groupBy("Brand").agg(count("Model").alias("LTE4GCount")).orderBy(desc("LTE4GCount")).first()
brand_with_most_models_5g = df.groupBy("Brand").agg(count("Model").alias("5GCount")).orderBy(desc("5GCount")).first()

#4.List of discontinued phones released after the year 2015:
from pyspark.sql.functions import year, when

# Extract the year from the "Announced" column
df = df.withColumn("AnnouncedYear", year(df["Announced"]))

# Filter discontinued phones released after 2015
discontinued_phones_after_2015 = df.filter((df["Status"] == "Discontinued") & (df["AnnouncedYear"] > 2015))

export_path = "F:/project/"

brand_market_share.write.csv(export_path + "brand_market_share.csv", header=True, mode="overwrite")
models_with_4g_lte.write(export_path + "models_with_4g_lte.csv", header=True, mode="overwrite")
models_with_5g.write(export_path + "models_with_5g.csv", header=True, mode="overwrite")
brand_with_most_models_lte.write(export_path + "brand_with_most_models_lte.csv", header=True, mode="overwrite")
brand_with_most_models_5g.write(export_path + "brand_with_most_models_5g.csv", header=True, mode="overwrite")
discontinued_phones_after_2015.write(export_path + "discontinued_phones_after_2015.csv", header=True, mode="overwrite")


# _*_ coding:utf-8 _*_

from fastapi import APIRouter, status, HTTPException, Request
from fastapi.responses import JSONResponse

router = APIRouter()

"""响应状态"""

@router.get("/", status_code=200)
async def read_item():
    return {"item": "itemname"}

@router.post("/", status_code=status.HTTP_201_CREATED)
async def create_item(name: str):
    return {"name": name}

"""异常处理"""

# 2.1 抛出异常
@router.get("/exception/{item_id}/")
async def read_item1(item_id: str):
    items = {"foo": "The Foo Wrestlers"}
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item": items[item_id]}

# 2.2 异常中自定义头部信息
@router.get("/exception/my-header/{item_id}/")
async def read_item2(item_id: str):
    items = {"foo": "The Foo Wrestlers"}
    if item_id not in items:
        raise HTTPException(
            status_code=404,
            detail="My Define Response Header",
            headers={"X-Error": "There goes my error"}
    )
    return {"item": items[item_id]}

# 2.3 自定义异常类 (APIRouter中没有`exception_handler`方法,FastAPI中才有,这种使用方法在app中才能使用)
# class UnicornException(Exception):
#     def __init__(self, description: str):
#         self.description = description

# @router.exception_handler(UnicornException)  # 传入的是框架内部的异常类，则是重写异常处理
# async def unicorn_exception_handler(request: Request, exec: UnicornException):
#     return JSONResponse(
#         status_code=418,
#         content={"message": f"Oops! {exec.name} did something."}
#     )

# @router.get("/exception/unicorn/")
# async def read_unicorn(description: str):
#     if description != "yolo":
#         raise UnicornException(description=description)
#     return {"unicorn_description": description}