import requests
import json

import pytest

from library_registry.util.http import (
    HTTP,
    BadResponseException,
    RemoteIntegrationException,
    RequestNetworkException,
    RequestTimedOut,
)

class MockRequestsResponse:
    """
    A mock object that simulates an HTTP response from the `requests` library.
    """
    def __init__(self, status_code, headers={}, content=None, url=None):
        self.status_code = status_code
        self.headers = headers
        self.content = content
        self.url = url or "http://url/"

    def json(self):
        content = self.content
        # The queued content might be a JSON string or it might
        # just be the object you'd get from loading a JSON string.
        if isinstance(content, (bytes, str)):
            content = json.loads(self.content)
        return content

    @property
    def text(self):
        return self.content.decode("utf8")

class TestHTTP:

    def test_request_with_timeout_success(self):

        def fake_200_response(*args, **kwargs):
            return MockRequestsResponse(200, content="Success!")

        response = HTTP._request_with_timeout(
            "the url", fake_200_response, "a", "b"
        )
        assert response.status_code == 200
        assert response.content == "Success!"

    def test_request_with_timeout_failure(self):

        def immediately_timeout(*args, **kwargs):
            raise requests.exceptions.Timeout("I give up")

        with pytest.raises(RequestTimedOut) as exc:
            HTTP._request_with_timeout("http://url/", immediately_timeout, "a", "b")
        assert "Timeout accessing http://url/: I give up" in str(exc.value)

    def test_request_with_network_failure(self):

        def immediately_fail(*args, **kwargs):
            raise requests.exceptions.ConnectionError("a disaster")

        with pytest.raises(RequestNetworkException) as exc:
            HTTP._request_with_timeout("http://url/", immediately_fail, "a", "b")
        assert "Network error contacting http://url/: a disaster" in str(exc.value)

    def test_request_with_response_indicative_of_failure(self):

        def fake_500_response(*args, **kwargs):
            return MockRequestsResponse(500, content="Failure!")

        with pytest.raises(BadResponseException) as exc:
            HTTP._request_with_timeout("http://url/", fake_500_response, "a", "b")
        err_msg = r"Bad response from http://url/: Got status code 500 from external server, cannot continue."
        assert err_msg in str(exc.value)

    def test_allowed_response_codes(self):
        # Test our ability to raise BadResponseException when
        # an HTTP-based integration does not behave as we'd expect.

        def fake_401_response(*args, **kwargs):
            return MockRequestsResponse(401, content="Weird")

        def fake_200_response(*args, **kwargs):
            return MockRequestsResponse(200, content="Hurray")

        url = "http://url/"
        m = HTTP._request_with_timeout

        # By default, every code except for 5xx codes is allowed.
        response = m(url, fake_401_response)
        assert response.status_code == 401

        # You can say that certain codes are specifically allowed, and
        # all others are forbidden.
        with pytest.raises(BadResponseException) as exc:
            m(url, fake_401_response, allowed_response_codes=[201, 200])
        assert "Bad response" in str(exc.value)
        assert "Got status code 401 from external server, but can only continue on: 200, 201." in str(exc.value)

        response = m(url, fake_401_response, allowed_response_codes=[401])
        response = m(url, fake_401_response, allowed_response_codes=["4xx"])

        # In this way you can even raise an exception on a 200 response code.
        with pytest.raises(BadResponseException) as exc:
            m(url, fake_200_response, allowed_response_codes=[401])
        assert "Got status code 200 from external server, but can only continue on: 401." in str(exc.value)

        # You can say that certain codes are explicitly forbidden, and
        # all others are allowed.
        with pytest.raises(BadResponseException) as exc:
            m(url, fake_401_response, disallowed_response_codes=[401])
        assert "Got status code 401 from external server, cannot continue." in str(exc.value)

        with pytest.raises(BadResponseException) as exc:
            m(url, fake_200_response, disallowed_response_codes=["2xx", 301])
        assert "Got status code 200 from external server, cannot continue." in str(exc.value)

        response = m(url, fake_401_response,
                     disallowed_response_codes=["2xx"])
        assert response.status_code == 401

        # The exception can be turned into a useful problem detail document.
        exception = None
        try:
            m(url, fake_200_response,
              disallowed_response_codes=["2xx"])
        except Exception as e:
            exception = e
        assert exception is not None

        debug_doc = exception.as_problem_detail_document(debug=True)

        # 502 is the status code to be returned if this integration error
        # interrupts the processing of an incoming HTTP request, not the
        # status code that caused the problem.
        #
        assert debug_doc.status_code == 502
        assert debug_doc.title == "Bad response"
        assert debug_doc.detail == (
            'The server made a request to http://url/, and got an unexpected or invalid response.'
        )
        assert debug_doc.debug_message == (
            'Bad response from http://url/: Got status code 200 from external server, '
            'cannot continue.\n\nResponse content: Hurray'
        )

        no_debug_doc = exception.as_problem_detail_document(debug=False)
        assert no_debug_doc.title == "Bad response"
        assert no_debug_doc.detail == 'The server made a request to url, and got an unexpected or invalid response.'
        assert no_debug_doc.debug_message is None

    def test_unicode_converted_to_utf8(self):
        """Any Unicode that sneaks into the URL, headers or body is
        converted to UTF-8.
        """
        class ResponseGenerator:
            def __init__(self):
                self.requests = []

            def response(self, *args, **kwargs):
                self.requests.append((args, kwargs))
                return MockRequestsResponse(200, content="Success!")

        generator = ResponseGenerator()
        url = "http://foo"
        HTTP._request_with_timeout(
            url, generator.response, url, "POST",
            headers={"unicode header": "unicode value"},
            data="unicode data"
        )
        [(args, kwargs)] = generator.requests
        url, method = args
        headers = kwargs['headers']
        data = kwargs['data']

        # All the Unicode data was converted to bytes before being sent
        # "over the wire".
        for k, v in list(headers.items()):
            assert isinstance(k, bytes)
            assert isinstance(v, bytes)
        assert isinstance(data, bytes)

class TestRemoteIntegrationException:

    def test_with_service_name(self):
        """You don't have to provide a URL when creating a
        RemoteIntegrationException; you can just provide the service
        name.
        """
        exc = RemoteIntegrationException(
            "Unreliable Service",
            "I just can't handle your request right now."
        )

        # Since only the service name is provided, there are no details to
        # elide in the non-debug version of a problem detail document.
        debug_detail = exc.document_detail(debug=True)
        other_detail = exc.document_detail(debug=False)
        assert other_detail == debug_detail

        assert debug_detail == (
            'The server tried to access Unreliable Service but the third-party service experienced an error.'
        )

class TestBadResponseException:

    def test_helper_constructor(self):
        response = MockRequestsResponse(102, content="nonsense")
        exc = BadResponseException.from_response(
            "http://url/", "Terrible response, just terrible", response
        )

        # Turn the exception into a problem detail document, and it's full of useful information.
        doc, status_code, headers = exc.as_problem_detail_document(debug=True).response
        doc = json.loads(doc)

        assert doc['title'] == 'Bad response'
        assert doc['detail'] == 'The server made a request to http://url/, and got an unexpected or invalid response.'
        assert doc['debug_message'] == (
            'Bad response from http://url/: Terrible response, just terrible\n\nStatus code: 102\nContent: nonsense'
        )

        # Unless debug is turned off, in which case none of that information is present.
        doc, status_code, headers = exc.as_problem_detail_document(debug=False).response
        assert 'debug_message' not in json.loads(doc)

    def test_bad_status_code_helper(object):
        response = MockRequestsResponse(500, content="Internal Server Error!")
        exc = BadResponseException.bad_status_code("http://url/", response)
        doc, status_code, headers = exc.as_problem_detail_document(debug=True).response
        doc = json.loads(doc)

        assert "Got status code 500 from external server, cannot continue." in doc['debug_message']

    def test_as_problem_detail_document(self):
        exception = BadResponseException(
            "http://url/", "What even is this",
            debug_message="some debug info"
        )
        document = exception.as_problem_detail_document(debug=True)
        assert document.status_code == 502
        assert document.title == "Bad response"
        assert document.detail == "The server made a request to http://url/, and got an unexpected or invalid response."
        assert document.debug_message == "Bad response from http://url/: What even is this\n\nsome debug info"

class TestRequestTimedOut:

    def test_as_problem_detail_document(self):
        exception = RequestTimedOut("http://url/", "I give up")

        debug_detail = exception.as_problem_detail_document(debug=True)
        assert debug_detail.title == "Timeout"
        assert debug_detail.detail == 'The server made a request to http://url/, and that request timed out.'

        # If we're not in debug mode, we hide the URL we accessed and just
        # show the hostname.
        standard_detail = exception.as_problem_detail_document(debug=False)
        assert standard_detail.detail == "The server made a request to url, and that request timed out."

        # The status code corresponding to an upstream timeout is 502.
        document, status_code, headers = standard_detail.response
        assert status_code == 502

class TestRequestNetworkException:

    def test_as_problem_detail_document(self):
        exception = RequestNetworkException("http://url/", "Colossal failure")

        debug_detail = exception.as_problem_detail_document(debug=True)
        assert debug_detail.title == "Network failure contacting third-party service"
        assert debug_detail.detail == 'The server experienced a network error while contacting http://url/.'

        # If we're not in debug mode, we hide the URL we accessed and just
        # show the hostname.
        standard_detail = exception.as_problem_detail_document(debug=False)
        assert standard_detail.detail == "The server experienced a network error while contacting url."

        # The status code corresponding to an upstream timeout is 502.
        document, status_code, headers = standard_detail.response
        assert status_code == 502


# -*- coding: utf-8 -*-
import scrapy
import re
from bs4 import BeautifulSoup
from ..items import PoemsScraperItem

class PoemsSpider(scrapy.Spider):
    name = 'poems'
    # start_urls = ['https://www.poets.org/poetsorg/poems?field_poem_themes_tid=886']
    page_no = 1
    theme_id = 0
    custom_settings = {
        # specifies exported fields and order
        'FEED_EXPORT_FIELDS': ["theme","poem"],
    }
    def __init__(self, *args, **kwargs):
        super(PoemsSpider, self).__init__(*args, **kwargs)

        PoemsSpider.theme_id = kwargs.get('theme_id')
        self.start_urls = ["https://www.poets.org/poetsorg/poems?field_poem_themes_tid={}".format(kwargs.get('theme_id'))]

    def parse(self, response):
        max_pages = int(getattr(self,'max_pages'))
        theme = response.css(".title")[0].xpath("text()")[0].extract()
        bsObj = BeautifulSoup(response.text,"lxml")
        poems_tds = bsObj.find_all("td")
        for p_link in poems_tds:
            try:
                link = p_link.find("a")['href']
                if "poem" in link:
                    poem_link = "https://www.poets.org{}".format(link)
                    yield response.follow(poem_link, callback=self.parse_poem, meta = {'theme': theme})
            except:
                pass
        next_link = "https://www.poets.org/poetsorg/poems?field_poem_themes_tid={}&page={}".format(PoemsSpider.theme_id,PoemsSpider.page_no)
        if PoemsSpider.page_no < max_pages:
            PoemsSpider.page_no += 1
            yield response.follow(next_link, callback=self.parse)

    def parse_poem(self, response):
        items = PoemsScraperItem()
        items['theme'] = response.meta.get("theme")
        poem = response.css("pre::text").extract()
        if(poem == ''):
            poem = response.css("#poem-content .even").extract()
        poem = "".join(poem)
        poem = re.sub(" +"," ",poem)
        poem = poem.replace("\n"," ").replace("\t","").replace("\r","")
        items['poem'] = poem
        yield items


# value.py
from multiprocessing import Value,Process
import time
import random
# 创建共享内存
money = Value('i',5000)

# 创建共享内存
def man():
    for i in range(30):
        time.sleep(0.2)
        money.value += random.randint(1,1000)

def girl():
    for i in range(30):
        time.sleep(0.15)
        money.value -= random.randint(100,900)

m = Process(target = man)
g = Process(target = girl)
m.start()
g.start()
m.join()
g.join()

print("一月余额:",money.value)


''' forum.py
Collection of routes and functions dealing with the forum grouping of threads,
forums hold their own subforums and threads, this includes routes and functions
to handle the creation of subforums and threads based on the forum that will
control them.  Creates and stores an endpoint for the root forum on creation.
'''
import httplib
import datetime
from . import app
from .decorators import datatype, require_permissions, paginate
from .database import Forum, Thread, errors
from flask import request, session

forum_base = '/forum/<forum_id>'
forum_route = forum_base + '/forum'
thread_route = forum_base + '/thread'

@app.get(forum_base)
@datatype
def get_forum(forum_id, page=0, per_page=25):
    ''' get_forum -> GET /forum/<forum_id>

    Retrieves the base listing for the specified forum (specified by the route
    arg of <forum_id>).  This will return the basic information for the forum,
    including the URLs to retrieve the list of subforums and the list of
    threads.  Returns a NOT_FOUND if the <forum_id> fails to find a
    corresponding forum.
    '''
    try:
        forum = Forum.get(forum_id)
    except errors.NoEntryError as err:
        return str(err), httplib.NOT_FOUND
    return forum if isinstance(forum, dict) else httplib.NOT_FOUND

@app.get(thread_route)
@paginate
@datatype
def get_threads(forum_id, page=0, per_page=25):
    ''' get_threads -> GET /forum/<forum_id>/thread

    Retrieves a paged list of threads for the specified forum (specified by
    the route arg of <forum_id>).  The result will be paged based on the format
    dictated by the paginate decorator.  The threads in the list will be a
    summary packet for each, with the majority of information coming from the
    URL provided by each packet.  Returns a NOT_FOUND if the <forum_id> fails
    to find results.
    '''
    try:
        threads = Thread.get(
            forum=forum_id, limit=per_page, start=(page * per_page))
    except errors.NoEntryFound as err:
        return str(err), httplib.NOT_FOUND
    return threads if isinstance(threads, list) else httplib.NOT_FOUND

@app.post(thread_route)
@datatype
@require_permissions
def create_thread(forum_id):
    ''' create_thread -> POST /forum/<forum_id>/thread
        POST: title=[string]&content=[string]

    Tries to create a thread for the forum specified by the <forum_id> route
    arg.  Expects for both 'title' and 'content' to be provided in the POST
    header.  Uses these to try and create the thread using the current session
    as the creating user.  Will return a BAD_REQUEST if the request is lacking
    required information and a NOT_FOUND if the <forum_id> does not correspond
    to an existing forum in the database, otherwise returns CREATED and the
    new thread structure.
    '''
    if 'title' not in request.form and 'content' not in request.form:
        return httplib.BAD_REQUEST

    title = request.form['title']
    content = request.form['content']
    try:
        thread = Thread.create({
            "title": title,
            "content": content,
            "user": session['id'],
            "created": datetime.datetime.utcnow(),
            "forum": forum_id
        })
    except errors.MissingInfoError as err:
        return str(err), httplib.BAD_REQUEST
    except errors.NoEntryFound as err:
        return str(err), httplib.NOT_FOUND
    return thread, httplib.CREATED

@app.get(forum_route)
@datatype
def get_forums(forum_id):
    ''' get_forums -> GET /forum/<forum_id>/forum

    Retrieves a list of forums that are children of the specified forum
    (specified by the <forum_id> route arg).  These are not currently
    paginated.  If the forum_id fails to find a corresponding forum, a
    NOT_FOUND will be returned otherwise will be the list of subforums.
    '''
    try:
        forums = Forum.children(parent=forum_id)
    except errors.NoEntryFound as err:
        return str(err), httplib.NOT_FOUND
    return forums if isinstance(forums, list) else httplib.NOT_FOUND

@app.post(forum_route)
@datatype
@require_permissions(forum=True)
def create_forum(forum_id):
    ''' create_forum -> POST /forum/<forum_id>
        POST: name=[string]

    Tries to create a forum using the provided information.  Requires the
    current user to have permissions on the forum specified by <forum_id>.  The
    new forum will be a sub forum of this forum.  If the creation succeeds, a
    CREATED will be returned with the new forum's information.  If there is
    information missing, a BAD_REQUEST will be returned, if the <forum_id>
    does not correspond to a forum in the system.
    '''
    if not request.json and "name" not in request.form:
        return httplib.BAD_REQUEST

    packet = request.json if request.json else {"name": request.form['name']}
    packet['parent'] = forum_id

    try:
        forum = Forum.create(packet)
    except errors.NoEntryFound as err:
        return str(err), httplib.NOT_FOUND
    except errors.MissingInfoError as err:
        return str(err), httplib.BAD_REQUEST

    return (forum, httplib.CREATED) if forum else httplib.NOT_FOUND

# Creates the initial root forum if it doesn't exist
app.endpoint('root', '/forum/' + str(Forum.get_root()))


class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        from collections import deque

        adjList = {i:[] for i in range(numCourses)}
        inDegrees = [0]*numCourses

#       Create Adjacency List and inDegrees array
        for p in prerequisites:
            adjList[p[1]].append(p[0])
            inDegrees[p[0]] += 1

        q = deque()

#       Add all courses with no prereqs (in-degrees == 0) to the q
        for i in range(numCourses):
            if inDegrees[i] == 0: q.append(i)

#       count keeps track of nodes/courses that we can detach/take
        count = 0
        while q:
            count += 1
            course = q.pop()

            for nextCourse in adjList[course]:
                inDegrees[nextCourse] -= 1
                if inDegrees[nextCourse] == 0:
                    q.append(nextCourse)

        return True if count == numCourses else False


from setuptools import setup

APP = ['words.py']
DATA_FILES = ['words.txt', 'dockicon.png']
OPTIONS = {
    'argv_emulation': True,
    'iconfile':'icon.icns',
    'plist': {
        'LSUIElement': True,
    },
    'packages': ['rumps'],
}

setup(
    app=APP,
    data_files=DATA_FILES,
    options={'py2app': OPTIONS},
    setup_requires=['py2app'],
)


from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponseRedirect
from django.http import HttpResponse, JsonResponse
from django.contrib import messages
from .forms import AdminRegistrationForm, UserLoginForm, AppointmentForm, AppointmentRequestForm, AppointmentResponseForm, MessageForm
from django.contrib.auth.decorators import login_required
from .models import *
from . import forms, models
from django.db.models import Sum
from django.contrib.auth.models import Group
from django.contrib.auth.decorators import login_required, user_passes_test
from datetime import datetime, timedelta, date

# Create your views here.

def homePage(request):
    categories = ConsultancyCategories.objects.all()
    context = {'categories' : categories}
    return render(request, 'baseapp/homePage.html', context)

def consultantsList(request):
    consultants = Consultant.objects.all()
    context = {'consultants' : consultants}
    return render(request, 'baseapp/consultants_list.html', context)

#---------------------------------BASE PRELOGIN VIEWS--------------------------#
def home_view(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect('afterlogin')
    return render(request,'baseapp/homePage.html')

#for showing signup/login button for admin(by sumit)
def adminclick_view(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect('afterlogin')
    return render(request,'baseapp/adminclick.html')

#for showing signup/login button for doctor(by sumit)
def consultantclick_view(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect('afterlogin')
    return render(request,'baseapp/consultantclick.html')

#for showing signup/login button for patient(by sumit)
def clientclick_view(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect('afterlogin')
    return render(request,'baseapp/clientclick.html')

#-------------Registration Views--------#
def admin_signup_view(request):
    form=forms.AdminRegistrationForm()
    context = {'form': form}
    if request.method=='POST':
        form=forms.AdminRegistrationForm(request.POST)
        if form.is_valid():
            user=form.save()
            user.set_password(user.password)
            user.save()
            my_admin_group = Group.objects.get_or_create(name='ADMIN')
            my_admin_group[0].user_set.add(user)
            return HttpResponseRedirect('adminlogin')
    return render(request,'baseapp/adminsignup.html', context)

def consultant_signup_view(request):
    userForm=forms.ConsultantUserForm()
    context = {'userForm':userForm}
    if request.method=='POST':
        userForm=forms.ConsultantUserForm(request.POST)
        if userForm.is_valid():
            user=userForm.save()
            user.set_password(user.password)
            user.save()
            my_consultant_group = Group.objects.get_or_create(name='CONSULTANT')
            my_consultant_group[0].user_set.add(user)
        return HttpResponseRedirect('consultantlogin')
    return render(request,'baseapp/consultantsignup.html', context)

def client_signup_view(request):
    userForm=forms.ClientUserForm()
    context = {'userForm' : userForm}
    if request.method=='POST':
        userForm = forms.ClientUserForm(request.POST)
        if userForm.is_valid():
            user=userForm.save()
            user.set_password(user.password)
            user.save()
            my_client_group = Group.objects.get_or_create(name='CLIENT')
            my_client_group[0].user_set.add(user)
        return HttpResponseRedirect('clientlogin')
    return render(request,'baseapp/clientsignup.html', context)

#-----------for checking user is CONSULTANT , CLIENT or admin(by sumit)
def is_admin(user):
    return user.groups.filter(name='ADMIN').exists()
def is_consultant(user):
    return user.groups.filter(name='CONSULTANT').exists()
def is_client(user):
    return user.groups.filter(name='CLIENT').exists()

#---------AFTER ENTERING CREDENTIALS WE CHECK WHETHER USERNAME AND PASSWORD IS OF ADMIN,CONSULTANT OR CLIENT
def afterlogin_view(request):
    if is_admin(request.user):
        return redirect('admin-dashboard')
    elif is_consultant(request.user):
        accountapproval=models.Consultant.objects.all().filter(user_id=request.user.id,availability_status=True)
        if accountapproval:
            return redirect('consultant-dashboard')
        else:
            return render(request,'baseapp/consultant_wait_for_approval.html')
    elif is_client(request.user):
        accountapproval=models.Client.objects.all().filter(user_id=request.user.id,status=True)
        if accountapproval:
            return redirect('client-dashboard')
        else:
            return render(request,'baseapp/client_wait_for_approval.html')

#---------------------------------------------------------------------------------
#------------------------ ADMIN RELATED VIEWS START ------------------------------
#---------------------------------------------------------------------------------

def admin_dashboard_view(request):
    # for both table in admin dashboard
    consultants=models.Consultant.objects.all().order_by('-id')
    clients=models.Client.objects.all().order_by('-id')
    #for three cards
    consultantcount=models.Consultant.objects.all().filter(status=True).count()
    pendingconsultantcount=models.Consultant.objects.all().filter(status=False).count()

    clientcount=models.Client.objects.all().filter(status=True).count()
    pendingclientcount=models.Client.objects.all().filter(status=False).count()

    appointmentcount=models.Appointment.objects.all().filter(status=True).count()
    pendingappointmentcount=models.Appointment.objects.all().filter(status=False).count()
    context = {
    'consultants':consultants,
    'clients':clients,
    'consultantcount':consultantcount,
    'pendingconsultantcount':pendingconsultantcount,
    'clientcount':clientcount,
    'pendingclientcount':pendingclientcount,
    'appointmentcount':appointmentcount,
    'pendingappointmentcount':pendingappointmentcount,
    }
    return render(request,'baseapp/admin_dashboard.html', context)

# this view for sidebar click on admin page

def admin_consultant_view(request):
    return render(request,'baseapp/admin_consultant.html')

def admin_view_consultant_view(request):
    consultants = models.Consultant.objects.all().filter(status=True)
    context = {'consultants':consultants}
    return render(request,'baseapp/admin_view_consultant.html', context)

def delete_consultant_from_hospital_view(request,pk):
    consultant=models.Consultant.objects.get(id=pk)
    user=models.User.objects.get(id=consultant.user_id)
    user.delete()
    consultant.delete()
    return redirect('admin-view-consultant')

def update_consultant_view(request,pk):
    consultant=models.Consultant.objects.get(id=pk)
    user=models.User.objects.get(id=consultant.user_id)

    userForm=forms.ConsultantUserForm(instance=user)
    context = {'userForm':userForm}
    if request.method=='POST':
        userForm=forms.ConsultantUserForm(request.POST,instance=user)
        if userForm.is_valid():
            user=userForm.save()
            user.set_password(user.password)
            user.save()
            return redirect('admin-view-consultant')
    return render(request,'baseapp/admin_update_consultant.html',context)

def admin_add_consultant_view(request):
    userForm=forms.ConsultantUserForm()
    context = {'userForm':userForm}
    if request.method=='POST':
        userForm=forms.ConsultantUserForm(request.POST)
        if userForm.is_valid():
            user=userForm.save()
            user.set_password(user.password)
            user.save()
            my_consultant_group = Group.objects.get_or_create(name='CONSULTANT')
            my_consultant_group[0].user_set.add(user)
        return HttpResponseRedirect('admin-view-consultant')
    return render(request,'baseapp/admin_add_consultant.html',context)

def admin_approve_consultant_view(request):
    #those whose approval are needed
    consultant = models.Consultant.objects.all().filter(status=False)
    context = {'consultant':consultant}
    return render(request,'baseapp/admin_approve_consultant.html', context)

def approve_consultant_view(request,pk):
    consultant = models.Consultant.objects.get(id=pk)
    consultant.status=True
    consultant.save()
    return redirect(reverse('admin-approve-consultant'))

def reject_consultant_view(request,pk):
    consultant = models.Consultant.objects.get(id=pk)
    user=models.User.objects.get(id=consultant.user_id)
    user.delete()
    consultant.delete()
    return redirect('admin-approve-consultant')

def admin_view_consultant_specialisation_view(request):
    consultant = models.Consultant.objects.all().filter(status=True)
    context = {'consultant':consultant}
    return render(request,'baseapp/admin_view_consultant_specialisation.html', context)

def admin_client_view(request):
    return render(request,'baseapp/admin_client.html')

def admin_view_client_view(request):
    clients = models.Client.objects.all().filter(status=True)
    context = {'clients':clients}
    return render(request,'baseapp/admin_view_patient.html', context)

def delete_client_from_hospital_view(request,pk):
    client=models.Client.objects.get(id=pk)
    user=models.User.objects.get(id=client.user_id)
    user.delete()
    client.delete()
    return redirect('admin-view-client')

def update_client_view(request,pk):
    client=models.Client.objects.get(id=pk)
    user=models.User.objects.get(id=client.user_id)

    userForm=forms.ClientUserForm(instance=user)

    context = {'userForm':userForm}
    if request.method=='POST':
        userForm=forms.ClientUserForm(request.POST,instance=user)
        if userForm.is_valid():
            user=userForm.save()
            user.set_password(user.password)
            user.save()
            return redirect('admin-view-client')
    return render(request,'baseapp/admin_update_client.html', context)

def admin_add_client_view(request):
    userForm=forms.ClientUserForm()
    context = {'userForm':userForm}
    if request.method=='POST':
        userForm=forms.ClientUserForm(request.POST)
        if userForm.is_valid():
            user=userForm.save()
            user.set_password(user.password)
            user.save()
            my_client_group = Group.objects.get_or_create(name='CLIENT')
            my_client_group[0].user_set.add(user)
        return HttpResponseRedirect('admin-view-client')
    return render(request,'baseapp/admin_add_client.html',context)

def admin_inbox(request):
    adminRecivedmessages = Message.objects.filter(reciever=request.user)
    context = {'messages' : adminRecivedmessages}
    return render(request, 'baseapp/admin_inbox.html', context)

def admin_notifications(request):
    adminNotifcations =Notification.objects.filter(user=request.user).order_by('-timestamp')
    context = {'notifications' : adminNotifcations}
    return render(request, 'baseapp/admin_notifications.html', context)

#------------------FOR APPROVING CLIENTS BY ADMIN----------------------

def admin_approve_client_view(request):
    #those whose approval are needed
    clients = models.Client.objects.all().filter(status=False)
    context = {'clients':clients}
    return render(request,'baseapp/admin_approve_client.html', context)

def approve_client_view(request,pk):
    client=models.Client.objects.get(id=pk)
    client.status=True
    client.save()
    return redirect(reverse('admin-approve-client'))

def reject_client_view(request,pk):
    client=models.Client.objects.get(id=pk)
    user=models.User.objects.get(id=client.user_id)
    user.delete()
    client.delete()
    return redirect('admin-approve-client')

#-----------------APPOINTMENT START----------------------------------------------------------------#####

def admin_appointment_view(request):
    return render(request,'baseapp/admin_appointment.html')

def admin_view_appointment_view(request):
    appointments=models.Appointment.objects.all().filter(status=True)
    context = {'appointments':appointments}
    return render(request,'baseapp/admin_view_appointment.html', context)

def admin_add_appointment_view(request):
    appointmentForm=forms.AppointmentForm()
    context = {'appointmentForm':appointmentForm,}
    if request.method=='POST':
        appointmentForm=forms.AppointmentForm(request.POST)
        if appointmentForm.is_valid():
            appointment=appointmentForm.save(commit=False)
            appointment.consultantID=request.POST.get('consultantID')
            appointment.clientID=request.POST.get('clientID')
            appointment.appointmentRequestCategory=request.POST.get('category')
            appointment.description=request.POST.get('description')
            appointment.notes=request.POST.get('notes')
            appointment.consultantName=models.User.objects.get(id=request.POST.get('consultantID')).first_name
            appointment.clientName=models.User.objects.get(id=request.POST.get('clientID')).first_name
            appointment.status=True
            appointment.save()
        return HttpResponseRedirect('admin-view-appointment')
    return render(request,'hospital/admin_add_appointment.html',context)

def admin_approve_appointment_view(request):
    #those whose approval are needed
    appointments=models.Appointment.objects.all().filter(status=False)
    context = {'appointments':appointments}
    return render(request,'baseapp/admin_approve_appointment.html', context)

def approve_appointment_view(request,pk):
    appointment=models.Appointment.objects.get(id=pk)
    appointment.status=True
    appointment.save()
    return redirect(reverse('admin-approve-appointment'))

def reject_appointment_view(request,pk):
    appointment=models.Appointment.objects.get(id=pk)
    appointment.delete()
    return redirect('admin-approve-appointment')
#---------------------------------------------------------------------------------
#------------------------ ADMIN RELATED VIEWS END ------------------------------
#---------------------------------------------------------------------------------

#---------------------------------------------------------------------------------
#------------------------ CONSULTANT RELATED VIEWS START ------------------------------
#---------------------------------------------------------------------------------

def consultant_dashboard_view(request):
    # for three cards
    clientcount=models.Client.objects.all().filter(status=True,assignedConsultantID=request.user.id).count()
    appointmentcount=models.Appointment.objects.all().filter(status=True,consultantID=request.user.id).count()
    clientdischarged=models.ClientDischargeDetails.objects.all().distinct().filter(assignedConsultantName=request.user.first_name).count()

    #for  table in doctor dashboard
    appointments=models.Appointment.objects.all().filter(status=True,consultantID=request.user.id).order_by('-id')
    clientID=[]
    for appointment in appointments:
        clientID.append(appointment.clientID)
    clients=models.Client.objects.all().filter(status=True,user_id__in=clientID).order_by('-id')
    appointments=zip(appointments,clients)
    context = {
    'clientcount':clientcount,
    'appointmentcount':appointmentcount,
    'clientdischarged':clientdischarged,
    'appointments':appointments,
    'consultant':models.Consultant.objects.get(user_id=request.user.id), #for profile picture of doctor in sidebar
    }
    return render(request,'baseapp/consultant_dashboard.html', context)

def consultant_client_view(request):
    consultant = models.Consultant.objects.get(user_id=request.user.id)
    context =   {'consultant': consultant}
   #for profile picture of CONSULTANT in sidebar}
    return render(request,'baseapp/consultant_client.html',context)

def consultant_view_client_view(request):
    clients = models.Client.objects.all().filter(status=True,assignedConsultantID=request.user.id)
    consultant = models.Consultant.objects.get(user_id=request.user.id) #for profile picture of CONSULTANT in sidebar
    context = {'clients':clients,'consultant':consultant}
    return render(request,'baseapp/consultant_view_client.html', context)

def consultant_view_discharge_client_view(request):
    dischargedclients = models.ClientDischargeDetails.objects.all().distinct().filter(assignedConsultantName=request.user.first_name)
    consultant = models.Consultant.objects.get(user_id=request.user.id) #for profile picture of cosultant in sidebar
    context = {'dischargedclients':dischargedclients,'consultant':consultant}
    return render(request,'baseapp/consultant_view_discharge_client.html', context)

def consultant_appointment_view(request):
    consultant = models.Consultant.objects.get(user_id=request.user.id) #for profile picture of COSULTANT in sidebar
    context = {'consultant':consultant}
    return render(request,'baseapp/consultant_appointment.html', context)

def consultant_view_appointment_view(request):
    consultant = models.Consultant.objects.get(user_id=request.user.id) #for profile picture of CONSULTANT in sidebar
    appointments=models.Appointment.objects.all().filter(status=True,consultantID=request.user.id)
    clientID=[]
    for appiontment in appointments:
        clientID.append(appiontment.clientID)
    clients=models.Client.objects.all().filter(status=True,user_id__in=clientID)
    appointments=zip(appointments, clients)
    context = {'appointments':appointments,'consultant':consultant}
    return render(request,'baseapp/consultant_view_appointment.html', context)

def consultant_delete_appointment_view(request):
    consultant = models.Consultant.objects.get(user_id=request.user.id) #for profile picture of CONSULTANT in sidebar
    appointments=models.Appointment.objects.all().filter(status=True,doctorId=request.user.id)
    clientID=[]
    for appointment in appointments:
        clientID.append(appointment.clientID)
    clients = models.Client.objects.all().filter(status=True,user_id__in=clientID)
    appointments=zip(appointments, clients)
    context = {'appointments':appointments,'consultant':consultant}
    return render(request,'baseapp/consultant_delete_appointment.html', context)

def delete_appointment_view(request,pk):
    appointment=models.Appointment.objects.get(id=pk)
    appointment.delete()
    consultant = models.Consultant.objects.get(user_id=request.user.id) #for profile picture of CONSULTANT in sidebar
    appointments=models.Appointment.objects.all().filter(status=True,consultantID=request.user.id)
    clientID=[]
    for appointment in appointments:
        clientID.append(appointment.clientID)
    clients = models.Client.objects.all().filter(status=True,user_id__in=clientID)
    appointments=zip(appointments, clients)
    context = {'appointments':appointments,'consultant':consultant}
    return render(request,'baseapp/consultant_delete_appointment.html', context)

def consultant_inbox(request):
    consultant = models.Consultant.objects.get(user_id=request.user.id)
    consultantRecivedmessages = Message.objects.filter(reciever=request.user)
    context = {'messages' : consultantRecivedmessages, 'consultant' : consultant}
    return render(request, 'baseapp/consultant_inbox.html', context)

def consultant_notifications(request):
    consultant = models.Consultant.objects.get(user_id=request.user.id)
    consultantNotifcations =Notification.objects.filter(user=request.user).order_by('-timestamp')
    context = {'notifications' : consultantNotifcations}
    return render(request, 'baseapp/consultant_notifications.html', context)

def consultantServicesView(request, username):
    services = ConsultancyService.objects.filter(consultant__username=username)
    context = {'services': services}
    return render(request, 'baseapp/consultantServices.html', context)

def consultancyServiceDetail(request, serviceID):
    service = get_object_or_404(ConsultancyService, id=serviceID)
    if request.method == 'POST':
        ConsultationRequest.objects.create(
            client=request.user,
            consultant=service.consultant,
            service=service
        )
        return redirect('profile', username=request.user.username)
    context = {'service' : service}
    return render(request, 'baseapp/serviceDetail.html', context)

def manageAppointments(request):
    appointments = Appointment.objects.filter(client=request.user.client)
    context = {'appiontments' : appointments}
    return render(request, 'baseapp/manage_appiontments.html', context)

def acceptDeclineRequest(request, requestID, action):
    consultationRequest = get_object_or_404(ConsultationRequest, id=requestID)
    if action == 'accept':
        consultationRequest.requestStatus = 'accepted'
        consultationRequest.save()
    elif action == 'decline':
        consultationRequest.requestStatus = 'declined'
        consultationRequest.save()
    return redirect('consultation_request')

def respond_appointment_request(request, appointment_id):
    appointment = Appointment.objects.get(id=appointment_id)
    client = appointment.client

    if request.method == 'POST':
        form = AppointmentResponseForm(request.POST)
        if form.is_valid():
            response = form.cleaned_data['response']

            # Update the appointment status
            appointment.status = response
            appointment.save()

            # Create a notification for the client
            message = f"Your appointment request has been {response}."
            notification = Notification(user=client, message=message)
            notification.save()

            return redirect('appointment_response_confirmation')  # Redirect to a confirmation page
    else:
        form = AppointmentResponseForm()

    return render(request, 'consultancy/respond_appointment_request.html', {'form': form, 'appointment': appointment})

def respond_to_client(request, client_id):
    client = User.objects.get(id=client_id)

    if request.method == 'POST':
        response_message = request.POST['response_message']  # Adjust this based on your form
        # Your response logic here...

        # Create a notification for the client
        message = f"A response has been received from the consultant: {response_message}"
        notification = Notification(user=client, message=message)
        notification.save()

        return redirect('response_confirmation')  # Redirect to a confirmation page

    return render(request, 'consultancy/respond_to_client.html', {'client': client})

#---------------------------------------------------------------------------------
#------------------------ CONSULTANT RELATED VIEWS END ------------------------------
#---------------------------------------------------------------------------------

#---------------------------------------------------------------------------------
#------------------------ CLIENT RELATED VIEWS START ------------------------------
#---------------------------------------------------------------------------------

def client_dashboard_view(request):
    client = models.Client.objects.get(user_id=request.user.id)
    consultant = models.Consultant.objects.get(user_id=client.assignedConsultantID)
    context = {'client': client,'consultantName': consultant.get_name, 'consultantEmail' : consultant.email, 'consultantAvailability' : consultant.availability_status}
    return render(request,'baseapp/client_dashboard.html',context)

def client_appointment_view(request):
    client = models.Client.objects.get(user_id=request.user.id) #for profile picture of Client in sidebar
    context = {'client':client}
    return render(request,'baseapp/client_appointment.html', context)

def client_book_appointment_view(request):
    appointmentForm=forms.AppointmentForm()
    client = models.Client.objects.get(user_id=request.user.id) #for profile picture of Client in sidebar
    context = {'appointmentForm':appointmentForm,'client': client}
    if request.method=='POST':
        appointmentForm=forms.AppointmentForm(request.POST)
        if appointmentForm.is_valid():
            appointment=appointmentForm.save(commit=False)
            appointment.consultantID=request.POST.get('consultantID')
            appointment.cientID=request.user.id #----user can choose any client but only their info will be stored
            appointment.appointmentRequestCategory=request.POST.get('category')
            appointment.description=request.POST.get('description')
            appointment.notes=request.POST.get('notes')
            appointment.consultantName=models.User.objects.get(id=request.POST.get('consultantID')).first_name
            appointment.clientName=request.user.first_name #----user can choose any CLIENT but only their info will be stored
            appointment.status=False
            appointment.save()
        return HttpResponseRedirect('client-view-appointment')
    return render(request,'baseapp/client_book_appointment.html',context)

def client_view_appointment_view(request):
    client = models.Client.objects.get(user_id=request.user.id) #for profile picture of Client in sidebar
    appointments=models.Appointment.objects.all().filter(clientID=request.user.id)
    context = {'appointments':appointments,'client':client}
    return render(request,'baseapp/client_view_appointment.html', context)

def consultant_detail(request, consultant_id):
    consultant = get_object_or_404(Consultant, id=consultant_id)
    context = {'consultant' : consultant}
    return render(request, 'baseapp/consultant_detail.html', context)

def client_inbox(request):
    client = models.Client.objects.get(user_id=request.user.id)
    clientRecivedmessages = Message.objects.filter(reciever=request.user)
    context = {'messages' : clientRecivedmessages}
    return render(request, 'baseapp/client_inbox.html', context)

def client_notifications(request):
    client = models.Client.objects.get(user_id=request.user.id)
    clientnNotifcations =Notification.objects.filter(user=request.user).order_by('-timestamp')
    context = {'notifications' : clientnNotifcations}
    return render(request, 'baseapp/client_notifications.html', context)

def scheduleAppointment(request, consultant_id):
    consultant = get_object_or_404(Consultant, id=consultant_id)

    if request.method == 'POST':
        form = AppointmentForm(request.POST)
        if form.is_valid():
            appointment = form.save(commit=False)
            appointment.client = request.user
            appointment.consultant = consultant
            appointment.save()

            return redirect('appointment_confirmation')
    else:
        form = AppointmentForm()
    context = {'form' : form, 'consultant' : consultant}
    return render(request, 'baseapp/schedule_appointment.html', context)

def cancelAppointment(request, appointment_id):
    appiontment = get_object_or_404(Appointment, id=appointment_id)

    if request.user.client == appiontment.client:
        appiontment.delete()

    return redirect('manage_appointments')

def sendMessage(request, reciever_id):
    if request.method == 'POST':
        content = request.POST.get('content')
        reciever = User.objects.get(id=reciever_id)
        message = Message.objects.create(sender=request.user, reciever=reciever, content=content)
        message.save()

        notification = Notification.objects.create(user=reciever, message=f'You have a New Message from {request.user}')
        notification.save()

        return redirect('inbox')

#------------------------ CLIENT RELATED VIEWS END ------------------------------
#---------------------------------------------------------------------------------

#---------------------------------------------------------------------------------
#------------------------ ABOUT US AND CONTACT US VIEWS START ------------------------------
#---------------------------------------------------------------------------------
def aboutus_view(request):
    return render(request,'baseapp/aboutus.html')

def contactus_view(request):
    subscribeForm = forms.ContactusForm()
    if request.method == 'POST':
        subscribeForm = forms.ContactusForm(request.POST)
        if subscribeForm.is_valid():
            email = subscribeForm.cleaned_data['Email']
            name=subscribeForm.cleaned_data['Name']
            message = subscribeForm.cleaned_data['Message']
            send_mail(str(name)+' || '+str(email),message, EMAIL_HOST_USER, EMAIL_RECEIVING_USER, fail_silently = False)
            return render(request, 'baseapp/contactussuccess.html')
        context = {'form':subscribeForm}
    return render(request, 'baseapp/contactus.html', context)

#\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\#####

def consultationRequest(request):
    consultationRequests = ConsultationRequest.objects.filter(consultant=request.user)
    context = {'consultationRequests' : consultationRequests}
    return render(request, 'baseapp/consultationRequests.html', context)

def request_appointment(request, consultant_id):
    consultant = User.objects.get(id=consultant_id)

    if request.method == 'POST':
        form = AppointmentRequestForm(request.POST)
        if form.is_valid():
            # Your appointment request logic here...

            # Create a notification for the consultant
            message = f"A client has requested an appointment with you."
            notification = Notification(user=consultant, message=message)
            notification.save()

            return redirect('appointment_request_confirmation')  # Redirect to a confirmation page
    else:
        form = AppointmentRequestForm()

    return render(request, 'consultancy/request_appointment.html', {'form': form, 'consultant': consultant})

def send_message(request, recipient_id):
    recipient = User.objects.get(id=recipient_id)

    if request.method == 'POST':
        form = MessageForm(request.POST)
        if form.is_valid():
            message = form.cleaned_data['message']

            # Create a notification for the recipient
            notification = Notification(user=recipient, message=message)
            notification.save()

            return redirect('message_sent_confirmation')  # Redirect to a confirmation page
    else:
        form = MessageForm()

    return render(request, 'consultancy/send_message.html', {'form': form, 'recipient': recipient})

def appointmentConfirmation(request):
    return render(request, 'baseapp/appointment_confirmation.html')


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os

cwd = os.getcwd()
np.set_printoptions(threshold=np.nan)

# Importing the dataset
import sys

try:
    dataset = pd.read_csv('..\\ReinforcementLearning_ThompsonSampling\\Ads_CTR_Optimisation.csv')
    #there is no apriori implementation in python?
    #using the file given in our examples apyori.py
    #sys.path.insert(0, '..\\AssociationRulesLearning_Apriori\\')
except:
    #there is no apriori implementation in python?
    #using the file given in our examples apyori.py
    dataset = pd.read_csv('UdemyMLAZ\\ReinforcementLearning_ThompsonSampling\\Ads_CTR_Optimisation.csv')
    #sys.path.insert(0, 'UdemyMLAZ\\AssociationRulesLearning_Apriori\\')

dataset

#implement thompson sampling step by step
import random
"""
step 1: declare 2 variables,
for each round n:
Ni1(n): the count of times the ad i was rewarded 1
Ni0(n): the count of times the ad i was rewarded 0
we do 10,000 rounds to the size of dataset
"""
N = len(dataset)
d = len(dataset.columns)
ads_selected = []
total_reward = 0

count_of_rewards_1 = [0] * d
count_of_rewards_0 = [0] * d
for n in range(0,N):
    """
    step2: for each ad i, take a random draw from the distrbution below:
    theta(n) = beta(Ni1(n)+1, Ni0(n)+1)
    """
    max_random = 0
    ad = 0
    for i in range(0,d):
        random_beta = random.betavariate(count_of_rewards_1[i] + 1, count_of_rewards_0[i] + 1)

        #calculate max random among all ads
        #keep track of the index of the ad
        #choose the maximum random variable
        if random_beta > max_random:
            max_random = random_beta
            ad = i
    """
    we update the selected ads, calculate reward, update it for every selected ad
    """
    ads_selected.append(ad)
    reward = dataset.values[n,ad]
    if reward == 1:
        count_of_rewards_1[ad] += 1
    else:
        count_of_rewards_0[ad] += 1
    total_reward += reward

"""
step3: we select the ad i that has the higest theta(n)
"""
best_ad = count_of_rewards_1.index(max(count_of_rewards_1))
print("the best ad is Ad %d with value %d" % (best_ad, count_of_rewards_1[best_ad]))

#plot ads and access frequency
plt.hist(ads_selected)
plt.title("Ads access frequency")
plt.xlabel("Ads")
plt.ylabel("Access frequency")
plt.show()


from flask import jsonify, Blueprint, abort
from flask_restful import (Resource, Api, reqparse, fields,
                           marshal, marshal_with, url_for)
from flask_login import login_required, current_user
import models

# defining the fields we want on the responses
trip_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'park': fields.String,
    'userId': fields.String
    # 'date': fields.String
}

class TripsList(Resource):
    def __init__(self):
        # setting up reqparse
        self.reqparse = reqparse.RequestParser()
        # requiring each to be true so that the user must input these
        self.reqparse.add_argument(
            'name',
            required=True,
            help='No name inputted',
            location=['form', 'json']
        )

        self.reqparse.add_argument(
            'park',
            required=True,
            help='No park selected',
            location=['form', 'json']
        )
        self.reqparse.add_argument(
            'userId',
            required=False,
            help='No date inputted',
            location=['form', 'json']
        )

        # self.reqparse.add_argument(
        #     'date',
        #     required=False,
        #     help='No date inputted',
        #     location=['form', 'json']
        # )
        # Inheriting from Resource and calling its init method
        # allows us to use self :)
        super(TripsList, self).__init__()

    # to select all the trips -> models.Trip.select() -> look up peewee queries
    # for generating response object -> look up marshal in flask
    # get route
    def get(self):
        new_trips = [marshal(trip, trip_fields)
                     for trip in models.Trip.select()]
        return new_trips
    # marshal is converting the model into a json object
    @marshal_with(trip_fields)
    def post(self):
        # reading the args aka "req.body"
        args = self.reqparse.parse_args()
        print(args, '<--- args (req.body)')
        # **args turns the inputs from the form into string variables that can be passed to the create function
        trip = models.Trip.create(**args)
        print(trip, '<---', type(trip))
        return (trip, 201)

class Trip(Resource):
    def __init__(self):
        # setting up reqparse
        self.reqparse = reqparse.RequestParser()
        # requiring each to be true so that the user must input these
        self.reqparse.add_argument(
            'name',
            required=True,
            help='No name inputted',
            location=['form', 'json']
        )

        self.reqparse.add_argument(
            'park',
            required=True,
            help='No park selected',
            location=['form', 'json']
        )

        self.reqparse.add_argument(
            'date',
            required=False,
            help='No date inputted',
            location=['form', 'json']
        )
        # Inheriting from Resource and calling its init method
        # allows us to use self :)
        super().__init__()

     # show route
    @marshal_with(trip_fields)
    def get(self, id):
        try:
            trip = models.Trip.get(models.Trip.id == id)
        except models.Trip.DoesNotExist:
            abort(404)
        else:
            return(trip, 200)

    # update route
    @marshal_with(trip_fields)
    def put(self, id):
        # parsing args (get req.body)
        args = self.reqparse.parse_args()
        # searching for the Trip that has the same model as we put in
        query = models.Trip.update(**args).where(models.Trip.id == id)
        # executing query
        query.execute()
        print(query, '<--- this is the query')
        # the query doesn't respond with the updated object
        return (models.Trip.get(models.Trip.id == id), 200)

    # delete route
    # you have to execute the update and delete queries
    def delete(self, id):
        query = models.Trip.delete().where(models.Trip.id == id)
        query.execute()
        return {"message": "trip deleted"}

# setting up module of view functions that can be attached to the flask app
trips_api = Blueprint('resources.trips', __name__)
# instantiating the api from the blueprint
api = Api(trips_api)

api.add_resource(
    TripsList,
    '/trips'
)
api.add_resource(
    # Identifying the Trip class above
    Trip,
    # this variable will be passed into the functions above
    '/trips/<int:id>'
)


"""
N개의 정수로 이루어진 수열이 있을 때,
크기가 양수인 부분수열 중에서
그 수열의 원소를 다 더한 값이 S가 되는 경우의 수를 구하는 프로그램을 작성하시오.

8시30분까지

5 0
-7 -3 -2 5 8
"""
import sys
from collections import deque

input = sys.stdin.readline

N, S = map(int, input().strip().split())
num = list(map(int, input().strip().split()))

stack = deque([])
ans = 0

def dfs(start):
    global ans

    if sum(stack) == S and len(stack) > 0:
        ans += 1
        # return
        # return
        # return 을 쓰면 안되는 이유: 재귀 호출을 끝내면, 이 이후 수열을 더하지 않고 return 해버림

    for k in range(start, len(num)):
        stack.append(num[k])
        dfs(k + 1)
        print(stack)
        stack.pop()

dfs(0)
print(ans)


"""This script is used to convert xml format to txt format for HRSC Dataset for evaluation."""

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

class Convert(object):
    def __init__(self, xml_path, txt_path, image_path):
        self.xml_path = xml_path
        self.txt_path = txt_path
        self.image_path = image_path
        self.xml_lists = os.listdir(xml_path)
        self._makedir()

    def _makedir(self):
        if not os.path.exists(self.txt_path):
            os.makedirs(self.txt_path)

    def _readXml(self, single_xml):
        with open(os.path.join(self.xml_path, single_xml), 'r', encoding='utf-8-sig') as f:
            content = f.read()
            objects = content.split('<HRSC_Object>')
            info = objects.pop(0)

            results = []
            for obj in objects:
                cls_name = 'ship'
                cx = round(eval(obj[obj.find('<mbox_cx>') + 9: obj.find('</mbox_cx>')]))
                cy = round(eval(obj[obj.find('<mbox_cy>') + 9: obj.find('</mbox_cy>')]))
                w = round(eval(obj[obj.find('<mbox_w>') + 8: obj.find('</mbox_w>')]))
                h = round(eval(obj[obj.find('<mbox_h>') + 8: obj.find('</mbox_h>')]))
                angle = eval(obj[obj.find('<mbox_ang>') + 10: obj.find('</mbox_ang>')]) / math.pi * 180
                rbox = np.array([cx, cy, w, h, angle])
                quad_box = rbox_2_quad(rbox, 'xywha').squeeze()
                line = cls_name + ' ' + str(quad_box[0]) + ' ' + str(quad_box[1]) + ' ' + str(quad_box[2]) + ' ' +\
                    str(quad_box[3]) + ' ' + str(quad_box[4]) + ' ' + str(quad_box[5]) + ' ' + str(quad_box[6]) +\
                    ' ' + str(quad_box[7]) + '\n'
                results.append(line)
        return results

    def writeTxt(self):
        for single_xml in self.xml_lists:
            lines = self._readXml(single_xml)
            txt_file = single_xml.replace('xml', 'txt')
            with open(os.path.join(self.txt_path, txt_file), 'w') as f:
                for single_line in lines:
                    f.write(single_line)

    def plotgt(self):
        for single_xml in self.xml_lists:
            single_image = single_xml.replace('xml', 'jpg')
            image = cv2.cvtColor(cv2.imread(os.path.join(self.image_path, single_image), cv2.IMREAD_COLOR),
                                 cv2.COLOR_BGR2RGB)
            lines = self._readXml(single_xml)
            for single_line in lines:
                single_line = single_line.strip().split(' ')
                box = np.array(list(map(float, single_line[1:])))
                cv2.polylines(image, [box.reshape(-1, 2).astype(np.int32)], True, (255, 0, 0), 3)
            plt.imshow(image)
            plt.show()

if __name__ == '__main__':
    convert = Convert(xml_path='/data/fzh/HRSC/train/Annotations/',
                      txt_path='/data/fzh/HRSC/train/train-ground-truth/',
                      image_path='/data/fzh/HRSC/train/images/')

    convert.writeTxt()


#!/usr/bin/env python

from subprocess import check_output
import re
import json
import os.path
from licenses_vivaldi_texts import onlineLicenses

basepath = "../../vivapp"
maindeps = check_output(["python", basepath+"/bin/list_jsdeps.py", basepath, "src/app.js"])

modules = {}

for m in re.findall(r"(.*node_modules/([^/]+))", maindeps):
  moduledir = m[0]
  modulename = m[1]
  if (moduledir in modules
     or (modulename == "chrome") # ours
     or (modulename == "wo-stringencoding") # ours
     or modulename == "vivaldi-color" # ours
     or (modulename == "url") # ignore for now, LICENSE file is on master, https://github.com/defunctzombie/node-url
     or (modulename == "ripemd160") # ignore for now, LICENSE file is on master, https://github.com/cryptocoinjs/ripemd160
     or (modulename == "indexof") # trivial
     or (modulename == "binary-search") # CC0-1.0, no need to put in credits file
    ):
      continue
  entry = {"name": modulename}

  # get license file (in order of preference)
  for l in ["LICENSE-MIT", "LICENSE-MIT.TXT", "LICENSE.MIT", "LICENSE.BSD",
      "LICENSE.APACHE2", "LICENSE", "LICENSE.txt", "LICENSE.md", "License",
      "license.txt", "License.md", "LICENSE.mkd"]:
    if os.path.exists(basepath+"/"+moduledir+"/"+l):
      f = open(basepath+"/"+moduledir+"/"+l)
      entry["license"] = f.read()
      f.close()
      break

  # get one word license type from package.json
  f = open(basepath+"/"+moduledir+"/package.json")
  pjson = json.loads(f.read())
  f.close()
  if "license" in pjson:
    entry["licensetype"] = pjson["license"]
  elif "licence" in pjson: # typo in react-list
    entry["licensetype"] = pjson["licence"]
  elif "licenses" in pjson:
    if type(pjson["licenses"]) is str:
      entry["licensetype"] = pjson["licenses"]
    elif type(pjson["licenses"]) is list:
      entry["licensetype"] = pjson["licenses"][0]["type"]
      entry["licenseurl"] = pjson["licenses"][0]["url"]
    elif type(pjson["licenses"]) is dict:
      entry["licensetype"] = pjson["licenses"]["type"]
      entry["licenseurl"] = pjson["licenses"]["url"]
  if "licensetype" in entry and entry["licensetype"] not in ["MIT", "BSD",
      "Apache 2.0", "Apache-2.0", "Apache License, Version 2.0", "Creative Commons Attribution 2.5 License", "MPL",
      "BSD-3-Clause", "ISC", "MPL-2.0 OR Apache-2.0"]:
    print("ERROR: " + moduledir + " uses a license that hasn't been reviewed for Vivaldi: " + entry["licensetype"])
    exit(1)

  if not "license" in entry and "licenseurl" in entry:
    if entry["licenseurl"] in onlineLicenses:
      entry["license"] = onlineLicenses[entry["licenseurl"]]
    else:
      print("ERROR: " + modulename + " provides URL " + entry["licenseurl"] + " as a license but it hasn't been copied to licenses_vivaldi_texts.py")
      exit(1)
  if not "license" in entry and "licensetype" in entry:
    entry["license"] = entry["licensetype"]

  if not "license" in entry:
    print("ERROR: License statement missing for module " + moduledir + ". Add it to the list of exceptions in licenses_vivaldi.py if it's not a third party module.")
    exit(1)

  if "homepage" in pjson:
    entry["url"] = pjson["homepage"]
  else:
    entry["url"] = ("https://www.npmjs.org/package/"+entry["name"])

  if "licensetype" in entry and entry["licensetype"] == "MPL":
    entry["license_unescaped"] = "Source code is available for download at <a href='http://registry.npmjs.org/"+modulename+"/-/"+modulename+"-"+pjson["version"]+".tgz'>http://registry.npmjs.org/"+modulename+"/-/"+modulename+"-"+pjson["version"]+".tgz<a/>. No source code files were modified for use in Vivaldi."
  else:
    entry["license_unescaped"] = ""

  for e in entry:
    try:
      entry[e] = entry[e].encode("ASCII")
    except:
      pass
  modules[moduledir] = entry


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('advisor_dash', '0005_remove_advisor_dly_advisor_dashboard_key'),
    ]

    operations = [
        migrations.AddField(
            model_name='advisor',
            name='dly_advisor_dashboard_key',
            field=models.IntegerField(default=-1),
            preserve_default=False,
        ),
    ]


# -*- coding: utf-8 -*-
"""
Created on Tue May  9 12:08:04 2023

@author: tarun
"""

from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation

# Load the 20 newsgroups dataset
newsgroups = fetch_20newsgroups(subset='all', shuffle=True, random_state=42)

# Vectorize the text data using a bag-of-words representation
vectorizer = CountVectorizer(max_df=0.95, min_df=2, stop_words='english')
X = vectorizer.fit_transform(newsgroups.data)

# Fit an LDA model to the data
lda = LatentDirichletAllocation(n_components=20, random_state=42)
lda.fit(X)

# Print the top 10 words for each topic
feature_names = vectorizer.get_feature_names_out()
for topic_idx, topic in enumerate(lda.components_):
    print("Topic %d:" % (topic_idx))
    print(" ".join([feature_names[i] for i in topic.argsort()[:-10 - 1:-1]]))
    print()

#which toipic for which document

# Get the topic distribution for each document
doc_topic_dist = lda.transform(X)

# Print the top topic for the first 10 documents
df= pd.DataFrame({"text":newsgroups.data, "label":newsgroups.target})

df["lda"]=999

for i in range(len(df)):
    df["lda"].iloc[i] = doc_topic_dist[i].argmax()
    print("Document %d: Top Topic = %d" % (i, top_topic_idx))

df.lda.value_counts()
df.label.value_counts()

#pca
import numpy as np
from sklearn.decomposition import PCA

# Generate some sample data
X = np.random.randn(100, 5)  # 100 samples with 5 features each

# Create a PCA object with 2 components
pca = PCA(n_components=4)

# Fit the PCA model to the data
pca.fit(X)

# Transform the data to the lower-dimensional space
X_pca = pca.transform(X)

# Print the explained variance ratio of each component
print(pca.explained_variance_ratio_)
sum(pca.explained_variance_ratio_)

# Access the components (i.e. eigenvectors) of the PCA model
components = pca.components_

# Print the components
print(components)


from django.urls import path
from . import views

app_name = 'demand_manager'
urlpatterns = [
    # ex: /demand_manager/
    # path('', views.DemandTopView.as_view(), name='top'),
    path('', views.DemandTopFilterView.as_view(), name='top'),

    # ex: /demand_manager/login/
    #path('login/', views.DemandLoginView.as_view(), name='login'),
    # ex: /demand_manager/logout/
    #path('logout/', views.DemandLogoutView.as_view(), name='logout'),

    # ex: /demand_manager/create/
    path('create/', views.DemandCreateView.as_view(), name='create'),
    # ex: /demand_manager//2/
    path('<int:pk>/', views.DemandDetailView.as_view(), name='detail'),
    # ex: /demand_manager/2/update/
    path('<int:pk>/update/', views.DemandUpdateView.as_view(), name='update'),
    # ex: /demand_manager/2/delete/
    path('<int:pk>/delete/', views.DemandDeleteView.as_view(), name='delete'),
    # ex: /demand_manager/analysis/
    path('analysis/', views.DemandAnalysisView.as_view(), name='analysis'),
    # ex: /demand_manager/import/
    path('import/', views.ImportReleasedLicenseView.as_view(), name='import'),
]


#!/usr/bin/env python
# coding=utf-8
import sys
sys.path.append("/home/jiangyy/workspace/enroll-score-ocr-parser/score/")
sys.path.append("/home/jiangyy/workspace/enroll-score-ocr-parser/enroll/")
sys.path.append("/home/jiangyy/workspace/enroll-score-ocr-parser/extractor/")
sys.path.append("/home/jiangyy/workspace/enroll-score-ocr-parser/common/")
sys.path.append("/home/jiangyy/workspace/enroll-score-ocr-parser/conf/")
import re, os
import csv
import Levenshtein
from conf.setting import ROOT_DIR, STD_WMZY_SCH_NAME_FILE

class SchNameMatcher(object):
    """
    学校名称标准化匹配
    """
    def __init__(self):

        self.file_path = os.path.join(ROOT_DIR, STD_WMZY_SCH_NAME_FILE)
        self.std_sch_names = set()
        self.__read_std_sch_names()

    def __read_std_sch_names(self):
        with(open(self.file_path, newline='')) as sch_file:
            rows = csv.reader(sch_file, delimiter=',', )
            next(rows)
            for row in rows:
                std_name = row[0]
                alias_name = row[1]
                clean_name = re.sub("[^\u4e00-\u9fa5]+", "", std_name)
                if clean_name:
                    self.std_sch_names.add(clean_name)
                clean_name = re.sub("[^\u4e00-\u9fa5]+", "", alias_name)
                if clean_name:
                    self.std_sch_names.add(clean_name)

    def match_std_sch(self, sch_raw):
        """
        按照编辑比例计算一个sen是不是学校
        """
        # 删除所有非中文
        sen = re.sub("[^\u4e00-\u9fa5]+", "", sch_raw)
        if sen in self.std_sch_names:
            return sen

        for item in self.std_sch_names:
            if sen.startswith(item) or item.startswith(sen):
                return sen
        lis = [(sch, Levenshtein.distance(sen, sch)) for sch in self.std_sch_names]

        if lis:
            candi = min(lis, key=lambda x: x[1])
            ratio = 1 - candi[1] * 1.0 / max(len(sen), len(candi[0]))  # 不用改的
        else:
            ratio = 0.0

        if ratio > 0.75:
            return candi[0]
        else:
            return None

    def is_sch_name(self, sch_name_raw):
        # 取第一个全中文子字符串
        sch_name = re.sub("[^\u4e00-\u9fa5]", " ", sch_name_raw.strip()).strip().split(" ")[0]
        #  大学或者学院
        sch_name_suffix = ["大学", "学院", "分校", "校区", "学校", "书院"]
        for item in sch_name_suffix:
            if item in sch_name:
                if item in ["大学"] and sch_name.endswith(item) and len(sch_name) > len(item) * 3:
                    return True

                std_sch = self.match_std_sch(sch_name)
                if std_sch:
                    return True

        # 对院校名称太长被分割成两行的情况进行补充, 并过滤掉一大批短名称专业
        if len(sch_name) > 5:
            std_sch = self.match_std_sch(sch_name)
            if std_sch:
                return True
        return False


"""
Demo of a basic pie chart plus a few additional features.

In addition to the basic pie chart, this demo shows a few optional features:

    * slice labels
    * auto-labeling the percentage
    * offsetting a slice with "explode"
    * drop-shadow
    * custom start angle

Note about the custom start angle:

The default ``startangle`` is 0, which would start the "Frogs" slice on the
positive x-axis. This example sets ``startangle = 90`` such that everything is
rotated counter-clockwise by 90 degrees, and the frog slice starts on the
positive y-axis.
"""
import matplotlib.pyplot as plt

# The slices will be ordered and plotted counter-clockwise.
labels = 'Calculation Time', 'Non-Calculation (Data Transfer) Time'
all_sizes = {
    'cpu-001': (19.17495022, 11.15104978),
    'alpha': (27.79285035, 8.755149649),
    'nsls-ii': (22.90918903, 23.21681097),
}
colors = ['yellowgreen', 'gold']

for k in sorted(all_sizes.keys()):
    plt.pie(all_sizes[k], labels=labels, colors=colors,
            autopct='%1.1f%%', shadow=True, startangle=90)
    # Set aspect ratio to be equal so that pie is drawn as a circle.
    plt.axis('equal')
    plt.title('cpu-001 server, NSLS-II FMX beamline, sampling factor = 0.7')
    plt.show()


# Source: https://github.com/areum-lee/SENet_Segmentation/blob/master/2d_densenetse_model.py

import torch
import torch.functional as F
import torch.nn as nn

def center_crop(layer, max_height, max_width):
    batch_size, n_channels, layer_height, layer_width = layer.size()
    xy1 = (layer_width - max_width) // 2
    xy2 = (layer_height - max_height) // 2
    return layer[:, :, xy2:(xy2 + max_height), xy1:(xy1 + max_width)]

class DenseLayer(nn.Sequential):
    def __init__(self, in_channels, growth_rate):
        super(DenseLayer, self).__init__()
        self.add_module('norm', nn.BatchNorm2d(num_features=in_channels))
        self.add_module('relu', nn.ReLU(inplace=True))

        self.add_module('conv', nn.Conv2d(in_channels=in_channels,
                                          out_channels=growth_rate, kernel_size=3, stride=1,
                                          padding=1, bias=True))

        self.add_module('drop', nn.Dropout2d(0.2))

    def forward(self, x):
        out = super(DenseLayer, self).forward(x)
        return out

class DenseBlock(nn.Module):
    def __init__(self, in_channels, growth_rate, n_layers, upsample=False):
        super(DenseBlock, self).__init__()
        self.upsample = upsample
        self.layers = nn.ModuleList([DenseLayer(
            in_channels + i * growth_rate, growth_rate)
            for i in range(n_layers)])

        self.SE_upsample1 = nn.Conv2d(growth_rate * n_layers, growth_rate * n_layers // 16, kernel_size=1)
        self.SE_upsample2 = nn.Conv2d(growth_rate * n_layers // 16, growth_rate * n_layers, kernel_size=1)
        self.SE1 = nn.Conv2d((in_channels + growth_rate * n_layers), (in_channels + growth_rate * n_layers) // 16, kernel_size=1)
        self.SE2 = nn.Conv2d((in_channels + growth_rate * n_layers) // 16, (in_channels + growth_rate * n_layers), kernel_size=1)

    def forward(self, x):
        if self.upsample:
            new_features = []
            for layer in self.layers:
                out = layer(x)
                x = torch.cat([x, out], 1)
                new_features.append(out)
            out = torch.cat(new_features, 1)
            fm_size = out.size()[2]
            scale_weight = F.avg_pool2d(out, fm_size)
            scale_weight = F.relu(self.SE_upsample1(scale_weight))
            scale_weight = F.sigmoid(self.SE_upsample2(scale_weight))
            out = out * scale_weight.expand_as(out)
            return out
        else:
            for layer in self.layers:
                out = layer(x)
                x = torch.cat([x, out], 1)  # 1 = channel axis
            fm_size = x.size()[2]
            scale_weight = F.avg_pool2d(x, fm_size)
            scale_weight = F.relu(self.SE1(scale_weight))
            scale_weight = F.sigmoid(self.SE2(scale_weight))
            x = x * scale_weight.expand_as(x)
            return x

class TransitionDown(nn.Sequential):
    def __init__(self, in_channels):
        super(TransitionDown, self).__init__()
        self.add_module('norm', nn.BatchNorm2d(num_features=in_channels))
        self.add_module('relu', nn.ReLU(inplace=True))
        self.add_module('conv', nn.Conv2d(in_channels=in_channels,
                                          out_channels=in_channels, kernel_size=1, stride=1,
                                          padding=0, bias=True))
        self.add_module('drop', nn.Dropout2d(0.2))
        self.add_module('maxpool', nn.MaxPool2d(2))

    def forward(self, x):
        out = super(TransitionDown, self).forward(x)

        return out

class TransitionUp(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(TransitionUp, self).__init__()
        self.convTrans = nn.ConvTranspose2d(in_channels=in_channels,
                                            out_channels=out_channels, kernel_size=3, stride=2,
                                            padding=0,
                                            bias=True)  # crop = 'valid' means padding=0. Padding has reverse effect for transpose conv (reduces output size)

    def forward(self, x, skip):
        out = self.convTrans(x)
        out = center_crop(out, skip.size(2), skip.size(3))
        out = torch.cat([out, skip], 1)

        return out

class Bottleneck(nn.Sequential):
    def __init__(self, in_channels, growth_rate, n_layers):
        super(Bottleneck, self).__init__()
        self.add_module('bottleneck', DenseBlock(in_channels, growth_rate, n_layers, upsample=True))

    def forward(self, x):
        out = super(Bottleneck, self).forward(x)
        return out

class FCDenseNet(nn.Module):
    def __init__(self, in_channels=3, down_blocks=(5, 5, 5, 5, 5),
                 up_blocks=(5, 5, 5, 5, 5), bottleneck_layers=5,
                 growth_rate=16, out_chans_first_conv=48, n_classes=12):
        super(FCDenseNet, self).__init__()
        self.down_blocks = down_blocks
        self.up_blocks = up_blocks

        cur_channels_count = 0
        skip_connection_channel_counts = []

        #####################
        # First Convolution #
        #####################

        self.add_module('firstconv', nn.Conv2d(in_channels=in_channels,
                                               out_channels=out_chans_first_conv, kernel_size=3,
                                               stride=1, padding=1, bias=True))
        cur_channels_count = out_chans_first_conv

        #####################
        # Downsampling path #
        #####################

        self.denseBlocksDown = nn.ModuleList([])
        self.transDownBlocks = nn.ModuleList([])
        for i in range(len(down_blocks)):
            self.denseBlocksDown.append(
                DenseBlock(cur_channels_count, growth_rate, down_blocks[i]))
            cur_channels_count += (growth_rate * down_blocks[i])
            skip_connection_channel_counts.insert(0, cur_channels_count)
            self.transDownBlocks.append(TransitionDown(cur_channels_count))

        #####################
        #     Bottleneck    #
        #####################

        self.add_module('bottleneck', Bottleneck(cur_channels_count,
                                                 growth_rate, bottleneck_layers))
        prev_block_channels = growth_rate * bottleneck_layers
        cur_channels_count += prev_block_channels

        #######################
        #   Upsampling path   #
        #######################

        self.transUpBlocks = nn.ModuleList([])
        self.denseBlocksUp = nn.ModuleList([])
        for i in range(len(up_blocks) - 1):
            self.transUpBlocks.append(TransitionUp(prev_block_channels, prev_block_channels))
            cur_channels_count = prev_block_channels + skip_connection_channel_counts[i]

            self.denseBlocksUp.append(DenseBlock(
                cur_channels_count, growth_rate, up_blocks[i],
                upsample=True))
            prev_block_channels = growth_rate * up_blocks[i]
            cur_channels_count += prev_block_channels

        # One final dense block
        self.transUpBlocks.append(TransitionUp(
            prev_block_channels, prev_block_channels))
        cur_channels_count = prev_block_channels + skip_connection_channel_counts[-1]

        self.denseBlocksUp.append(DenseBlock(
            cur_channels_count, growth_rate, up_blocks[-1],
            upsample=False))
        cur_channels_count += growth_rate * up_blocks[-1]

        #####################
        #      Softmax      #
        #####################

        self.finalConv = nn.Conv2d(in_channels=cur_channels_count,
                                   out_channels=n_classes, kernel_size=1, stride=1,
                                   padding=0, bias=True)
        self.softmax = nn.LogSoftmax()

    def forward(self, x):
        out = self.firstconv(x)

        skip_connections = []
        for i in range(len(self.down_blocks)):
            out = self.denseBlocksDown[i](out)
            skip_connections.append(out)
            out = self.transDownBlocks[i](out)

        out = self.bottleneck(out)
        for i in range(len(self.up_blocks)):
            skip = skip_connections.pop()
            out = self.transUpBlocks[i](out, skip)
            out = self.denseBlocksUp[i](out)

        out = self.finalConv(out)
        out = self.softmax(out)
        return out

def FCDenseNet57(n_classes):
    return FCDenseNet(in_channels=2, down_blocks=(4, 4, 4, 4, 4),
                      up_blocks=(4, 4, 4, 4, 4), bottleneck_layers=4,
                      growth_rate=4, out_chans_first_conv=48, n_classes=n_classes)

def FCDenseNet67(n_classes):
    return FCDenseNet(in_channels=2, down_blocks=(5, 5, 5, 5, 5),
                      up_blocks=(5, 5, 5, 5, 5), bottleneck_layers=5,
                      growth_rate=16, out_chans_first_conv=48, n_classes=n_classes)

def FCDenseNet103(n_classes):
    return FCDenseNet(in_channels=2, down_blocks=(4, 5, 7, 10, 12),
                      up_blocks=(12, 10, 7, 5, 4), bottleneck_layers=15,
                      growth_rate=16, out_chans_first_conv=48, n_classes=n_classes)


import setuptools

with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()

INSTALL_REQUIRES = []

setuptools.setup(
    name="rate_limiter",
    version="0.0.1",
    author="Shenglong Zhang",
    author_email="songnon@gmail.com",
    description="HTTP request rate limiting",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/",
    packages=setuptools.find_packages(),
    install_requires=INSTALL_REQUIRES,
    package_data={'rate_limiter': ['*.json', '*.ini']},
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.8',
)


from nltk.corpus import wordnet

def syns_test(word):
    syns = wordnet.synsets(word)
    # print(syns[0].name())
    syns_list=[]
    for i in range (0,len(syns)):
        for j in range (0,len(syns[i].lemmas())):
            syns_list.append(syns[i].lemmas()[j].name())
    syns_list.sort()
    print(syns_list[0])

if __name__=='__main__':
    syns = wordnet.synsets("./")
    syns_list=[]
    for i in range (0,len(syns)):
        for j in range (0,len(syns[i].lemmas())):
            syns_list.append(syns[i].lemmas()[j].name())
    for word in syns_list:
        syns_test(word)


import sqlite3
from utility.constants import FILE

def db_loader(sql_file_path):
    try:
        connection = sqlite3.connect(FILE.DB_FILE)
        cursor = connection.cursor()
        sql_file = open(sql_file_path)
        sql_as_string = sql_file.read()
        cursor.executescript(sql_as_string)
        return True
    except (OSError, ConnectionError):
        print('Error while loading sql file')


from setuptools import find_packages
from setuptools import setup

try:
    README = open("README.md").read() + "\n\n" + open("CHANGELOG.md").read()
except IOError:
    README = None

setup(
    name="guillotina_batch",
    version="6.0.1.dev0",
    description="batch endpoint for guillotina",
    long_description=README,
    long_description_content_type="text/markdown",
    install_requires=["guillotina>=6.0.0b5", "backoff"],
    author="Nathan Van Gheem",
    author_email="vangheem@gmail.com",
    url="https://github.com/guillotinaweb/guillotina_batch",
    packages=find_packages(exclude=["demo"]),
    package_data={"": ["*.txt", "*.rst"], "guillotina_batch": ["py.typed"]},
    include_package_data=True,
    license="BSD",
    extras_require={
        "test": [
            "pytest>=4.1.1",
            "aiohttp>=3.6.0,<4.0.0",
            "docker",
            "backoff",
            "jsonschema==2.6.0",
            "psycopg2-binary",
            "pytest-asyncio==0.10.0",
            "pytest-cov",
            "coverage==4.4.0",
            "pytest-docker-fixtures",
            "asyncpg==0.15.0",
            "async_asgi_testclient==1.4.4",
        ]
    },
    classifiers=[
        "License :: OSI Approved :: BSD License",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Topic :: Software Development :: Libraries :: Python Modules",
        "Topic :: Internet :: WWW/HTTP",
        "Intended Audience :: Developers",
    ],
    entry_points={},
)


from bs4 import BeautifulSoup
import urllib.request
import time
import random

site= 'https://etherscan.io/txs?a=0xd0a6e6c54dbc68db5db3a091b171a77407ff7ccf&p='
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
       'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
       'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
       'Accept-Encoding': 'none',
       'Accept-Language': 'en-US,en;q=0.8',
       'Connection': 'keep-alive'}

f = open('workfile', 'a')

for i in range(1167, 1947):
    req = urllib.request.Request(site + str(i), headers=hdr)
    page = urllib.request.urlopen(req)
    content = page.read()
    soup = BeautifulSoup(content, "html.parser")
    f.write(soup.find('tbody').text)
    print (i)
    #time.sleep(random.random())


# -*- coding: utf-8 -*-
import os
import sys
__root_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if __root_path not in sys.path:
    sys.path.append(__root_path)
import requests
import datetime
from tornado.httpclient import AsyncHTTPClient
import asyncio
import urllib.parse
import threading
import time

url = "http://127.0.0.1:7011/query"
data = {"sn": "34444444"}

async def asy(n):
    client = AsyncHTTPClient()
    count = 0
    begin = datetime.datetime.now()
    for i in range(n):
        resp = await client.fetch(url, method='POST', body=urllib.parse.urlencode(data))
        if resp.code == 200:
            count += 1
            # print(resp.body)
    end = datetime.datetime.now()
    delta = (end - begin).total_seconds()
    print("异步查询{}个查询耗时{}秒,成功率: {}%".format(n, delta, (count / n) * 100))

def batch_req(n):
    with requests.Session() as ses:
        count = 0
        begin = datetime.datetime.now()
        for i in range(n):
            resp = ses.post(url, data=data)
            if resp.status_code == 200:
                count += 1
        end = datetime.datetime.now()
        delta = (end - begin).total_seconds()
        print("顺序查询{}个查询耗时{}秒,成功率: {}%".format(n, delta, (count / n) * 100))

def req(m, count):
    with requests.Session() as ses:
        m = int(m)
        for i in range(m):
            resp = ses.post(url, data=data)
            if resp.status_code == 200:
                count['val'] = count['val'] + 1
    count['status'] = True

def th(n):
    begin = datetime.datetime.now()
    count1 = {"val": 0, "status": False}
    count2 = {"val": 0, "status": False}
    count3 = {"val": 0, "status": False}
    count4 = {"val": 0, "status": False}
    t1 = threading.Thread(target=req, args=(n/4, count1,), daemon=True)
    t2 = threading.Thread(target=req, args=(n/4, count2,), daemon=True)
    t3 = threading.Thread(target=req, args=(n/4, count3,), daemon=True)
    t4 = threading.Thread(target=req, args=(n/4, count4,), daemon=False)
    t1.start()
    t2.start()
    t3.start()
    t4.start()
    while not (count1['status'] and count2['status'] and count3['status'] and count4['status']):
        time.sleep(0.0000001)
    end = datetime.datetime.now()
    delta = (end - begin).total_seconds()
    count = count1['val'] + count2['val'] + count3['val'] + count4['val']
    print("4线程查询{}个查询耗时{}秒,成功率: {}%".format(n, delta, (count / n) * 100))

if __name__ == "__main__":
    # batch_req(2000)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asy(2000))
    th(2000)
    pass


import _init_paths
import NaviSense as ns
import open3d as o3d
import numpy as np
import cv2
import sys

def process1(im_rgbd, cameraMatrix):
    global model

    # detect floor plane
    point2d = ns.getPlane(im_rgbd, cameraMatrix)

    # image segmentation
    raw_image = cv2.cvtColor(np.asarray(im_rgbd.color), cv2.COLOR_BGR2RGB)
    segmented = ns.seg.segmentationfun(model, raw_image)

    # transfrom to top view
    wrapped, masked = ns.getTransform(point2d, segmented)

    # cleanup some artifacts
    cleaned = ns.cleanup(wrapped)
    return cleaned

# path for recorded bag file
recorded_file = "../Video/extra/20230329_170533.bag"
#recorded_file = "../Video/extra/20230504_171902.bag"

# initialize bag reader and config
bag_reader = o3d.t.io.RSBagReader()
bag_reader.open(recorded_file)
im_rgbd = bag_reader.next_frame()
width = 1280; height = 720; fx = 649.302; fy = fx; cx = 649.934; cy = 335.776
cameraMatrix = np.array([[fx, 0, cx], [0, fx, cy], [0, 0, 1]])
intrinsic_t = o3d.core.Tensor(cameraMatrix)

# initialize segmentation model
model = ns.seg.init_model()

# start at this time
bag_reader.seek_timestamp(53024000)
#bag_reader.seek_timestamp(33870000)
l1 = 300
l2 = 500

while not bag_reader.is_eof():

    #segmented and cleaned
    cleaned = process1(im_rgbd, cameraMatrix)

    #cv2.imshow("Mask", masked)
    #cv2.imshow("wrappped", wrapped)
    cv2.imshow("Cleanuped", cleaned)

    cleaned_copy = np.copy(cleaned)
    map = ns.create_occupacny_map(cleaned)
    angle, value = ns.max_value_angle(map, l1)
    angle2, value2 = ns.max_value_angle(map, l2)
    #print(angle)

    C_value, O_value  = ns.obstacle_value(angle, cleaned, l1)
    C_value2, O_value2 = ns.obstacle_value(angle2, cleaned, l2)

    ns.drawLine(cleaned, angle2, l2)
    ns.drawLine(cleaned, angle, l1, [0,255,0])
    cv2.putText(img=cleaned, text=f'Certaity value: {str(C_value)}', org=(0, 300), fontFace=cv2.FONT_HERSHEY_PLAIN, fontScale=1, color=(0, 255, 0),thickness=1)
    cv2.putText(img=cleaned, text=f'Obstacle value: {str(O_value)}', org=(0, 310), fontFace=cv2.FONT_HERSHEY_PLAIN, fontScale=1, color=(255, 0, 0),thickness=1)
    cv2.putText(img=cleaned, text=f'Certaity value: {str(C_value2)}', org=(0, 320), fontFace=cv2.FONT_HERSHEY_PLAIN, fontScale=1, color=(0, 255, 0),thickness=1)
    cv2.putText(img=cleaned, text=f'Obstacle value: {str(O_value2)}', org=(0, 330), fontFace=cv2.FONT_HERSHEY_PLAIN, fontScale=1, color=(255, 0, 0),thickness=1)
    cv2.putText(img=cleaned, text=f'value1: {str(value)}', org=(0, 350), fontFace=cv2.FONT_HERSHEY_PLAIN, fontScale=1, color=(0, 255, 0),thickness=1)
    cv2.putText(img=cleaned, text=f'value2: {str(value2)}', org=(0, 370), fontFace=cv2.FONT_HERSHEY_PLAIN, fontScale=1, color=(0, 255, 0),thickness=1)
    cv2.imshow("line", cleaned)

    #test new algorithm
    result = ns.hybrid_maximum_angle(map, cleaned_copy)
    line_result = ns.hybrid_drawLine(cleaned_copy, result)
    cv2.imshow("Hybrid", line_result)

    key = cv2.waitKey(1)
        # if pressed escape exit program
    if key == 27:
        cv2.destroyAllWindows()
        break
    im_rgbd = bag_reader.next_frame()

bag_reader.close()


#!/usr/bin/python
# map the trainIds to 1,2,3,4,5,6,7......
from __future__ import print_function
import os, glob, sys
import PIL.Image as Image
import numpy as np

# The main method
def main():
    # Where to look for Cityscapes
#    cityscapesPath = os.path.join(os.path.dirname(os.path.realpath(__file__)),'datasets/cityscapes')
    cityscapesPath = os.path.dirname(os.path.realpath(__file__))
    print("cityscapesPath:",cityscapesPath)
    # how to search for all ground truth
    searchTrain   = os.path.join( cityscapesPath , "gtFine/train"  , "*" , "*_gt*_instanceTrainIds.png" )
    searchVal = os.path.join( cityscapesPath , "gtFine/val" , "*" , "*_gt*_instanceTrainIds.png" )
    searchTest = os.path.join( cityscapesPath , "gtFine/test" , "*" , "*_gt*_instanceTrainIds.png" )

    # search files
    filesTrain = glob.glob( searchTrain )
    filesTrain.sort()
    filesVal = glob.glob( searchVal )
    filesVal.sort()
    filesTest = glob.glob( searchTest )
    filesTest.sort()

    # concatenate fine and coarse
    files = filesTrain + filesVal + filesTest# use this line if fine is enough for now.

    # a bit verbose
    print("Processing {} annotation files".format(len(files)))

    # iterate through files
    progress = 0
    print("Progress: {:>3} %".format( progress * 100 / len(files) ), end=' ')
    for f in files:

        # create the output filename
        dst = f.replace( "_instanceTrainIds.png" , "_instanceLabelmeIds_align.png" )
        if not os.path.exists(dst):
            # do the conversion
            labelImg = Image.open(f)
            labelNP = np.asarray(labelImg)
            labelUnique = np.unique(labelNP)
            numLabel = len(labelUnique)

            objectLabel = []
            for n in range(numLabel):

    #            if labelUnique[n] == 11 or labelUnique[n] == 12 or labelUnique[n] == 13 or labelUnique[n] == 14 or labelUnique[n] == 15 or labelUnique[n] == 17 or labelUnique[n] == 18:
                if (labelUnique[n] >= 11000 and labelUnique[n] < 16000) or (labelUnique[n] >= 17000 and labelUnique[n] < 19000):
                    objectLabel.append(labelUnique[n])

            changeLabel = range(1, len(objectLabel)+1)

            print("objectLabel:", objectLabel)
            print("changeLabel:", changeLabel)

            width, height = labelImg.size

            changeLabelNp = np.zeros([height, width], dtype=np.uint8)
    #        size = (width, height)
    #        changeLabelImg = Image.new("L", size, 0)
    #        changeLabelImg.load()
    #    Label(  'person'               , 24 ,       11 , 'human'           , 6       , True         , False        , (220, 20, 60) ),
    #    Label(  'rider'                , 25 ,       12 , 'human'           , 6       , True         , False        , (255,  0,  0) ),
    #    Label(  'car'                  , 26 ,       13 , 'vehicle'         , 7       , True         , False        , (  0,  0,142) ),
    #    Label(  'truck'                , 27 ,       14 , 'vehicle'         , 7       , True         , False        , (  0,  0, 70) ),
    #    Label(  'bus'                  , 28 ,       15 , 'vehicle'         , 7       , True         , False        , (  0, 60,100) ),
    #    Label(  'motorcycle'           , 32 ,       17 , 'vehicle'         , 7       , True         , False        , (  0,  0,230) ),
    #    Label(  'bicycle'              , 33 ,       18 , 'vehicle'         , 7       , True         , False        , (119, 11, 32) ),

            for i in range(width):
                for j in range(height):

                    at_pixel = labelImg.getpixel((i, j))

                    for k in range(len(objectLabel)):
                        if at_pixel == objectLabel[k]:
                            changeLabelNp[j, i]  = changeLabel[k]

    #                if at_pixel ==  11:
    #                    changeLabelImg[i, j] = 1
    #                elif at_pixel ==  12:
    #                    changeLabelImg[i, j] = 2
    #                elif at_pixel ==  13:
    #                    changeLabelImg[i, j] = 3
    #                elif at_pixel ==  14:
    #                    changeLabelImg[i, j] = 4
    #                elif at_pixel ==  15:
    #                    changeLabelImg[i, j] = 5
    #                elif at_pixel ==  17:
    #                    changeLabelImg[i, j] = 6
    #                elif at_pixel ==  18:
    #                    changeLabelImg[i, j] = 7

    #                if at_pixel ==  11:
    #                    changeLabelNp[j, i] = 1
    #                elif at_pixel ==  12:
    #                    changeLabelNp[j, i] = 2
    #                elif at_pixel ==  13:
    #                    changeLabelNp[j, i] = 3
    #                elif at_pixel ==  14:
    #                    changeLabelNp[j, i] = 4
    #                elif at_pixel ==  15:
    #                    changeLabelNp[j, i] = 5
    #                elif at_pixel ==  17:
    #                    changeLabelNp[j, i] = 6
    #                elif at_pixel ==  18:
    #                    changeLabelNp[j, i] = 7
            # create the output filename
            dst = f.replace( "_instanceTrainIds.png" , "_instanceLabelmeIds_align.png" )
    #        print("dst:",dst)
            changeLabelImg = Image.fromarray(changeLabelNp)
            changeLabelImg.save(dst)

            # status
            progress += 1
            print("\rProgress: {:>3} %".format( progress * 100 / len(files) ), end=' ')
            sys.stdout.flush()

# call the main
if __name__ == "__main__":
    main()