from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework import serializers
from rest_framework import generics
from rest_framework import viewsets
from rest_framework.decorators import detail_route, list_route
from rest_framework.views import APIView
from core.models import *
from django.forms import widgets
from django.conf.urls import patterns, url
from services.cord.models import VOLTTenant, VBNGTenant, CordSubscriberRoot
from core.xoslib.objects.cordsubscriber import CordSubscriber
from plus import PlusSerializerMixin, XOSViewSet
from django.shortcuts import get_object_or_404
from xos.apibase import XOSListCreateAPIView, XOSRetrieveUpdateDestroyAPIView, XOSPermissionDenied
from xos.exceptions import *
import json
import subprocess

if hasattr(serializers, "ReadOnlyField"):
    # rest_framework 3.x
    ReadOnlyField = serializers.ReadOnlyField
else:
    # rest_framework 2.x
    ReadOnlyField = serializers.Field

class CordSubscriberIdSerializer(serializers.ModelSerializer, PlusSerializerMixin):
        id = ReadOnlyField()
        service_specific_id = ReadOnlyField()
        vlan_id = ReadOnlyField()      # XXX remove this
        c_tag = ReadOnlyField()
        s_tag = ReadOnlyField()
        vcpe_id = ReadOnlyField()
        instance = ReadOnlyField()
        image = ReadOnlyField()
        vbng_id = ReadOnlyField()
        firewall_enable = serializers.BooleanField()
        firewall_rules = serializers.CharField()
        url_filter_enable = serializers.BooleanField()
        url_filter_rules = serializers.CharField()
        url_filter_level = serializers.CharField(required=False)
        cdn_enable = serializers.BooleanField()
        instance_name = ReadOnlyField()
        image_name = ReadOnlyField()
        routeable_subnet = serializers.CharField(required=False)
        ssh_command = ReadOnlyField()
        bbs_account = ReadOnlyField()

        wan_container_ip = ReadOnlyField()
        uplink_speed = serializers.CharField(required=False)
        downlink_speed = serializers.CharField(required=False)
        status = serializers.CharField()
        enable_uverse = serializers.BooleanField()

        lan_ip = ReadOnlyField()
        wan_ip = ReadOnlyField()
        nat_ip = ReadOnlyField()
        private_ip = ReadOnlyField()

        wan_mac = ReadOnlyField()

        vcpe_synced = serializers.BooleanField()

        humanReadableName = serializers.SerializerMethodField("getHumanReadableName")

        class Meta:
            model = CordSubscriber
            fields = ('humanReadableName', 'id',
                      'service_specific_id', 'vlan_id', 's_tag', 'c_tag',
                      'vcpe_id', 'instance', 'instance_name', 'image', 'image_name',
                      'firewall_enable', 'firewall_rules',
                      'url_filter_enable', 'url_filter_rules', 'url_filter_level',
                      'bbs_account',
                      'ssh_command',
                      'vcpe_synced',
                      'cdn_enable', 'vbng_id', 'routeable_subnet', 'nat_ip', 'lan_ip', 'wan_ip', 'private_ip', 'wan_mac',
                      'wan_container_ip',
                      'uplink_speed', 'downlink_speed', 'status', 'enable_uverse')

        def getHumanReadableName(self, obj):
            return obj.__unicode__()

#------------------------------------------------------------------------------
# The "old" API
# This is used by the xoslib-based GUI
#------------------------------------------------------------------------------

class CordSubscriberList(XOSListCreateAPIView):
    queryset = CordSubscriber.get_tenant_objects().select_related().all()
    serializer_class = CordSubscriberIdSerializer

    method_kind = "list"
    method_name = "cordsubscriber"

class CordSubscriberDetail(XOSRetrieveUpdateDestroyAPIView):
    queryset = CordSubscriber.get_tenant_objects().select_related().all()
    serializer_class = CordSubscriberIdSerializer

    method_kind = "detail"
    method_name = "cordsubscriber"

# We fake a user object by pulling the user data struct out of the
# subscriber object...

def serialize_user(subscriber, user):
    return {"id": "%d-%d" % (subscriber.id, user["id"]),
            "name": user["name"],
            "level": user.get("level",""),
            "mac": user.get("mac", ""),
            "subscriber": subscriber.id }

class CordUserList(APIView):
    method_kind = "list"
    method_name = "corduser"

    def get(self, request, format=None):
        instances=[]
        for subscriber in CordSubscriber.get_tenant_objects().all():
            for user in subscriber.users:
                instances.append( serialize_user(subscriber, user) )

        return Response(instances)

    def post(self, request, format=None):
        data = request.DATA
        subscriber = CordSubscriber.get_tenant_objects().get(id=int(data["subscriber"]))
        user = subscriber.create_user(name=data["name"],
                                    level=data["level"],
                                    mac=data["mac"])
        subscriber.save()

        return Response(serialize_user(subscriber,user))

class CordUserDetail(APIView):
    method_kind = "detail"
    method_name = "corduser"

    def get(self, request, format=None, pk=0):
        parts = pk.split("-")
        subscriber = CordSubscriber.get_tenant_objects().filter(id=parts[0])
        for user in subscriber.users:
            return Response( [ serialize_user(subscriber, user) ] )
        raise XOSNotFound("Failed to find user %s" % pk)

    def delete(self, request, pk):
        parts = pk.split("-")
        subscriber = CordSubscriber.get_tenant_objects().get(id=int(parts[0]))
        subscriber.delete_user(parts[1])
        subscriber.save()
        return Response("okay")

    def put(self, request, pk):
        kwargs={}
        if "name" in request.DATA:
             kwargs["name"] = request.DATA["name"]
        if "level" in request.DATA:
             kwargs["level"] = request.DATA["level"]
        if "mac" in request.DATA:
             kwargs["mac"] = request.DATA["mac"]

        parts = pk.split("-")
        subscriber = CordSubscriber.get_tenant_objects().get(id=int(parts[0]))
        user = subscriber.update_user(parts[1], **kwargs)
        subscriber.save()
        return Response(serialize_user(subscriber,user))

#------------------------------------------------------------------------------
# The "new" API with many more REST endpoints.
# This is for integration with with the subscriber GUI
#------------------------------------------------------------------------------

class CordSubscriberViewSet(XOSViewSet):
    base_name = "subscriber"
    method_name = "rs/subscriber"
    method_kind = "viewset"
    queryset = CordSubscriber.get_tenant_objects().select_related().all()
    serializer_class = CordSubscriberIdSerializer

    def get_vcpe(self):
        subscriber = self.get_object()
        if not subscriber.vcpe:
            raise XOSMissingField("vCPE object is not present for subscriber")
        return subscriber.vcpe

    @classmethod
    def get_urlpatterns(self):
        patterns = super(CordSubscriberViewSet, self).get_urlpatterns()
        patterns.append( self.detail_url("vcpe_synced/$", {"get": "get_vcpe_synced"}, "vcpe_synced") )
        patterns.append( self.detail_url("url_filter/$", {"get": "get_url_filter"}, "url_filter") )
        patterns.append( self.detail_url("url_filter/(?P<level>[a-zA-Z0-9\-_]+)/$", {"put": "set_url_filter"}, "url_filter") )
        patterns.append( self.detail_url("services/$", {"get": "get_services"}, "services") )
        patterns.append( self.detail_url("services/(?P<service>[a-zA-Z0-9\-_]+)/$", {"get": "get_service"}, "get_service") )
        patterns.append( self.detail_url("services/(?P<service>[a-zA-Z0-9\-_]+)/true/$", {"put": "enable_service"}, "enable_service") )
        patterns.append( self.detail_url("services/(?P<service>[a-zA-Z0-9\-_]+)/false/$", {"put": "disable_service"}, "disable_service") )

        patterns.append( self.detail_url("users/$", {"get": "get_users", "post": "create_user"}, "users") )
        patterns.append( self.detail_url("users/clearusers/$", {"get": "clear_users", "put": "clear_users", "post": "clear_users"}, "clearusers") )
        patterns.append( self.detail_url("users/newuser/$", {"put": "create_user", "post": "create_user"}, "newuser") )
        patterns.append( self.detail_url("users/(?P<uid>[0-9\-]+)/$", {"delete": "delete_user"}, "user") )
        patterns.append( self.detail_url("users/(?P<uid>[0-9\-]+)/url_filter/$", {"get": "get_user_level"}, "user_level") )
        patterns.append( self.detail_url("users/(?P<uid>[0-9\-]+)/url_filter/(?P<level>[a-zA-Z0-9\-_]+)/$", {"put": "set_user_level"}, "set_user_level") )

        patterns.append( self.detail_url("bbsdump/$", {"get": "get_bbsdump"}, "bbsdump") )

        patterns.append( url("^rs/initdemo/$", self.as_view({"put": "initdemo", "get": "initdemo"}), name="initdemo") )

        patterns.append( url("^rs/subidlookup/(?P<ssid>[0-9\-]+)/$", self.as_view({"get": "ssiddetail"}), name="ssiddetail") )
        patterns.append( url("^rs/subidlookup/$", self.as_view({"get": "ssidlist"}), name="ssidlist") )

        patterns.append( url("^rs/vbng_mapping/$", self.as_view({"get": "get_vbng_mapping"}), name="vbng_mapping") )

        return patterns

    def list(self, request):
        object_list = self.filter_queryset(self.get_queryset())

        serializer = self.get_serializer(object_list, many=True)

        return Response({"subscribers": serializer.data})

    def get_vcpe_synced(self, request, pk=None):
        subscriber = self.get_object()
        return Response({"vcpe_synced": subscriber.vcpe_synced})

    def get_url_filter(self, request, pk=None):
        subscriber = self.get_object()
        return Response({"level": subscriber.url_filter_level})

    def set_url_filter(self, request, pk=None, level=None):
        subscriber = self.get_object()
        subscriber.url_filter_level = level
        subscriber.save()
        return Response({"level": subscriber.url_filter_level})

    def get_users(self, request, pk=None):
        subscriber = self.get_object()
        return Response(subscriber.users)

    def get_user_level(self, request, pk=None, uid=None):
        subscriber = self.get_object()
        user = subscriber.find_user(uid)
        if user and user.get("level", None):
            level = user["level"]
        else:
            level = self.get_object().url_filter_level

        return Response( {"id": uid, "level": level} )

    def set_user_level(self, request, pk=None, uid=None, level=None):
        subscriber = self.get_object()
        subscriber.update_user(uid, level=level)
        subscriber.save()
        return self.get_user_level(request, pk, uid)

    def create_user(self, request, pk=None):
        data = request.DATA
        name = data.get("name",None)
        mac = data.get("mac",None)
        if (not name):
             raise XOSMissingField("name must be specified when creating user")
        if (not mac):
             raise XOSMissingField("mac must be specified when creating user")

        subscriber = self.get_object()
        newuser = subscriber.create_user(name=name, mac=mac)
        subscriber.save()

        return Response(newuser)

    def delete_user(self, request, pk=None, uid=None):
        subscriber = self.get_object()
        subscriber.delete_user(uid)
        subscriber.save()

        return Response( {"id": uid, "deleted": True} )

    def clear_users(self, request, pk=None):
        subscriber = self.get_object()
        subscriber.users = []
        subscriber.save()

        return Response( "Okay" )

    def get_services(self, request, pk=None):
        subscriber = self.get_object()
        return Response(subscriber.services)

    def get_service(self, request, pk=None, service=None):
        service_attr = service+"_enable"
        subscriber = self.get_object()
        return Response({service: getattr(subscriber, service_attr)})

    def enable_service(self, request, pk=None, service=None):
        service_attr = service+"_enable"
        subscriber = self.get_object()
        setattr(subscriber, service_attr, True)
        subscriber.save()
        return Response({service: getattr(subscriber, service_attr)})

    def disable_service(self, request, pk=None, service=None):
        service_attr = service+"_enable"
        subscriber = self.get_object()
        setattr(subscriber, service_attr, False)
        subscriber.save()
        return Response({service: getattr(subscriber, service_attr)})

    def get_bbsdump(self, request, pk=None):
        subscriber = self.get_object()
        if not subsciber.volt or not subscriber.volt.vcpe:
            raise XOSMissingField("subscriber has no vCPE")
        if not subscriber.volt.vcpe.bbs_account:
            raise XOSMissingField("subscriber has no bbs_account")

        result=subprocess.check_output(["python", "/opt/xos/observers/vcpe/broadbandshield.py", "dump", subscriber.volt.vcpe.bbs_account, "123"])
        if request.GET.get("theformat",None)=="text":
            from django.http import HttpResponse
            return HttpResponse(result, content_type="text/plain")
        else:
            return Response( {"bbs_dump": result } )

    def setup_demo_subscriber(self, subscriber):
        # nuke the users and start over
        subscriber.users = []
        subscriber.create_user(name="Mom's PC",      mac="010203040506", level="PG_13")
        subscriber.create_user(name="Dad's PC",      mac="90E2Ba82F975", level="PG_13")
        subscriber.create_user(name="Jack's Laptop", mac="685B359D91D5", level="PG_13")
        subscriber.create_user(name="Jill's Laptop", mac="34363BC9B6A6", level="PG_13")
        subscriber.save()

    def initdemo(self, request):
        object_list = CordSubscriber.get_tenant_objects().all()

        # reset the parental controls in any existing demo vCPEs
        for o in object_list:
            if str(o.service_specific_id) in ["0", "1"]:
                self.setup_demo_subscriber(o)

        demo_subscribers = [o for o in object_list if o.is_demo_user]

        if demo_subscribers:
            return Response({"id": demo_subscribers[0].id})

        subscriber = CordSubscriberRoot(service_specific_id=1234,
                                        name="demo-subscriber",)
        subscriber.is_demo_user = True
        subscriber.save()

        self.setup_demo_subscriber(subscriber)

        return Response({"id": subscriber.id})

    def ssidlist(self, request):
        object_list = CordSubscriber.get_tenant_objects().all()

        ssidmap = [ {"service_specific_id": x.service_specific_id, "subscriber_id": x.id} for x in object_list ]

        return Response({"ssidmap": ssidmap})

    def ssiddetail(self, pk=None, ssid=None):
        object_list = CordSubscriber.get_tenant_objects().all()

        ssidmap = [ {"service_specific_id": x.service_specific_id, "subscriber_id": x.id} for x in object_list if str(x.service_specific_id)==str(ssid) ]

        if len(ssidmap)==0:
            raise XOSNotFound("didn't find ssid %s" % str(ssid))

        return Response( ssidmap[0] )

    def get_vbng_mapping(self, request):
        object_list = VBNGTenant.get_tenant_objects().all()

        mappings = []
        for vbng in object_list:
            if vbng.mapped_ip and vbng.routeable_subnet:
                mappings.append( {"private_ip": vbng.mapped_ip, "routeable_subnet": vbng.routeable_subnet, "mac": vbng.mapped_mac, "hostname": vbng.mapped_hostname} )

        return Response( {"vbng_mapping": mappings} )

class CordDebugIdSerializer(serializers.ModelSerializer, PlusSerializerMixin):
    # Swagger is failing because CordDebugViewSet has neither a model nor
    # a serializer_class. Stuck this in here as a placeholder for now.
    id = ReadOnlyField()
    class Meta:
        model = CordSubscriber

class CordDebugViewSet(XOSViewSet):
    base_name = "cord_debug"
    method_name = "rs/cord_debug"
    method_kind = "viewset"
    serializer_class = CordDebugIdSerializer

    @classmethod
    def get_urlpatterns(self):
        patterns = []
        patterns.append( url("^rs/cord_debug/vbng_dump/$", self.as_view({"get": "get_vbng_dump"}), name="vbng_dump"))
        return patterns

    # contact vBNG service and dump current list of mappings
    def get_vbng_dump(self, request, pk=None):
        result=subprocess.check_output(["curl", "http://10.0.3.136:8181/onos/virtualbng/privateip/map"])
        if request.GET.get("theformat",None)=="text":
            from django.http import HttpResponse
            result = json.loads(result)["map"]

            lines = []
            for row in result:
                for k in row.keys():
                     lines.append( "%s %s" % (k, row[k]) )

            return HttpResponse("\n".join(lines), content_type="text/plain")
        else:
            return Response( {"vbng_dump": json.loads(result)["map"] } )


import sys
from PyQt6.QtWidgets import QApplication, QWidget, QLabel
from PyQt6.QtGui import QPixmap, QFont

class MainWindow(QWidget):
    def __init__(self):
        """constructor for Empty windows """
        super().__init__()
        self.initializeUI()

    def initializeUI(self):
        """Set up the application"""
        # setGeometry()两个参数用于指定窗口显示的位置, 后两个参数用于指定窗口大小
        self.setGeometry(500, 500, 250, 400)
        self.setWindowTitle("User profile")

        self.setupMainWindow()
        self.show()
    def creatImageLabels(self):
        """Create Qlabel to be displayed in the main windows"""
        skyblue_path = '../Beginning-PyQt-resource/Chapter02/images/skyblue.png'
        try:
            with open(skyblue_path):
                skyblue = QLabel(self)
                pixmap = QPixmap(skyblue_path)
                skyblue.setPixmap(pixmap)
        except FileNotFoundError as error:
            print(f"Image not found. \nError: {error}")
        profile_path = '../Beginning-PyQt-resource/Chapter02/images/profile_image.png'
        try:
            with open(profile_path):
                profile = QLabel(self)
                pixmap = QPixmap(profile_path)
                profile.setPixmap(pixmap)
                profile.move(80, 20)
        except FileNotFoundError as error:
            print(f"Image not found. \nError: {error}")

    def setupMainWindow(self):
        self.creatImageLabels()

        user_label = QLabel(self)
        user_label.setText("John Doe")
        user_label.setFont(QFont("Arial", 20))
        user_label.move(85, 140)

        bio_label = QLabel(self)
        bio_label.setText("Biography")
        bio_label.setFont(QFont("Arial", 17))
        bio_label.move(15, 170)

        about_label = QLabel(self)
        about_label.setText("I'm a software Engineer with 10 years\
                            exprience creating awesome code!")
        about_label.setWordWrap(True)   # set auto line
        about_label.move(15, 190)
# Run the program
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec())


# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from odoo import api, models, _
_logger = logging.getLogger(__name__)

class AccountInvoice(models.Model):
    _inherit = 'account.invoice'

    @api.multi
    def action_auto_open(self):
        return_item = super(AccountInvoice, self).action_auto_open()
        # action_send_account_invoice_create_message_slack
        for item in self:
            item.action_send_account_invoice_create_message_slack()
        # return
        return return_item

    @api.multi
    def action_send_account_invoice_create_message_slack(self):
        self.ensure_one()
        web_base_url = self.env['ir.config_parameter'].sudo().get_param('web.base.url')
        url_item = '%s/web?#id=%s&view_type=form&model=account.invoice' % (
            web_base_url,
            self.id
        )
        attachments = [
            {
                "title": _('Invoice has been created automatically'),
                "text": self.number,
                "color": "#36a64f",
                "fallback": "View invoice %s %s" % (
                    self.number,
                    url_item
                ),
                "actions": [
                    {
                        "type": "button",
                        "text": _("View invoice %s") % self.number,
                        "url": url_item
                    }
                ],
                "fields": [
                    {
                        "title": _("Customer"),
                        "value": self.partner_id.name,
                        'short': True,
                    },
                    {
                        "title": _("Origin"),
                        "value": self.origin,
                        'short': True,
                    }
                ],
            }
        ]
        vals = {
            'attachments': attachments,
            'model': 'account.invoice',
            'res_id': self.id,
            'channel': self.env['ir.config_parameter'].sudo().get_param(
                'slack_log_contabilidad_channel'
            ),
        }
        self.env['slack.message'].sudo().create(vals)


import uvicorn
import datetime
from loguru import logger
from fastapi import FastAPI
from sqlalchemy import select
from fastapi.middleware.cors import CORSMiddleware

from SAGIRIBOT.ORM.AsyncORM import orm
from SAGIRIBOT.Core.AppCore import AppCore
from SAGIRIBOT.command_parse.Commands import *
from SAGIRIBOT.ORM.AsyncORM import Setting, FunctionCalledRecord

app = FastAPI(docs_url=None, redoc_url=None)

origins = ["*"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get('/getGroups')
async def getGroups():
    groups = await orm.fetchall(select(Setting.group_id, Setting.group_name).where(Setting.active == True))
    return [{"value": group[0], "label": group[1]} for group in groups]

@app.get('/getGroupSetting')
async def getGroupSetting(groupId: int):
    options_bool = ["repeat", "frequency_limit", "setu", "real", "real_high_quality", "bizhi", "r18", "img_search",
                    "bangumi_search", "debug", "compile", "anti_revoke", "online_notice", "switch"]
    options_str = ["long_text_type", "r18_process", "speak_mode", "music"]
    valid_str_option_value = {
        "long_text_type": LongTextType.valid_values,
        "r18_process": R18Process.valid_values,
        "speak_mode": SpeakMode.valid_values,
        "music": Music.valid_values
    }
    bool_result = await orm.fetchone(select(
        Setting.repeat,
        Setting.frequency_limit,
        Setting.setu, Setting.real, Setting.real_high_quality, Setting.bizhi, Setting.r18,
        Setting.img_search,
        Setting.bangumi_search,
        Setting.debug,
        Setting.compile,
        Setting.anti_revoke,
        Setting.online_notice,
        Setting.switch
    ).where(
        Setting.group_id == groupId
    ))
    str_result = await orm.fetchone(select(
        Setting.long_text_type,
        Setting.r18_process,
        Setting.speak_mode,
        Setting.music
    ).where(
        Setting.group_id == groupId
    ))
    return [
        [{"label": options_bool[i], "value": bool_result[i]} for i in range(len(bool_result))],
        [{"label": options_str[i], "value": str_result[i], "validValue": valid_str_option_value[options_str[i]]} for i in range(len(str_result))]
    ]

@app.get('/modifyGroupSetting')
async def modifyGroupSetting(groupId: int, settingName: str, newValue):
    if newValue in ["true", "false"]:
        newValue = True if newValue == "true" else False
    try:
        await orm.update(
            Setting,
            [Setting.group_id == groupId],
            {"group_id": groupId, settingName: newValue}
        )
    except Exception as e:
        logger.error(f"api error: {e}")
        return False
    return True

@app.get("/getStatus")
async def getStatus():
    return {
        "functionCalled": len(await orm.fetchall(
            select(FunctionCalledRecord).where(FunctionCalledRecord.time >= datetime.date.today())
        )),
        "handlerCount": len(AppCore.get_core_instance().get_group_chains()),
        "sayaCount": len(AppCore.get_core_instance().get_saya_channels())
    }

def run_api():
    uvicorn.run(app, host="127.0.0.1", port=8000, log_level="error")


from flask import Flask, request, abort

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import *

# My Code
from util import *

app = Flask(__name__)

# Channel Access Token
line_bot_api = LineBotApi('++7wQ1tXdLomUPrrUbvcKEE12HAh+eeIh1s46ynQESIAH2zkobGXkk19oxFSHS/5fgOju9fHnX3wu02ALT70wQSYcrFuE5ZoKd5vYwkr+VRIdTiMfFSVFerWzr5j1Syf5YlS5NGCFoXbPBiF730F3AdB04t89/1O/w1cDnyilFU=')
# Channel Secret
handler = WebhookHandler('095348740b93fb668776aa36c9571a44')

# 監聽所有來自 /callback 的 Post Request
@app.route("/callback", methods=['POST'])
def callback():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']
    # get request body as text
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)
    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)
    return 'OK'

# 處理訊息
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    msg = event.message.text
    if '聯絡方式' in msg:
        message = imagemap_message()
        line_bot_api.reply_message(event.reply_token, message)
    elif '你是誰' in msg:
        message = TextSendMessage(text= "嗨我是吳岳，很高興認識你！")
        line_bot_api.reply_message(event.reply_token, message)
    elif '你會什麼' in msg:
        message = Carousel_Template()
        line_bot_api.reply_message(event.reply_token, message)
    elif '你喜歡什麼' in msg:
        message = image_gallery()
        line_bot_api.reply_message(event.reply_token, message)
    elif "你想去哪裡工作" in msg:
        line_bot_api.reply_message(event.reply_token,LocationSendMessage(title='LINE Taiwan', address='No. 333號, Ruiguang Rd, Neihu District, Taipei City, 114', latitude=25.07726625171245, longitude=121.57513202616131))
    else:
        message = TextSendMessage(text='echo: ' + msg)
        line_bot_api.reply_message(event.reply_token, message)

import os
if __name__ == "__main__":
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)


"""initial

Revision ID: 977a56225963
Revises: None
Create Date: 2016-09-24 22:05:55.701455

"""

# revision identifiers, used by Alembic.
revision = '977a56225963'
down_revision = None

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('series',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('title', sa.String(length=120), nullable=True),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('title')
    )
    op.create_table('chapter',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('title', sa.String(length=120), nullable=True),
    sa.Column('body', sa.String(length=1000000), nullable=True),
    sa.Column('series_id', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['series_id'], ['series.id'], ),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('title')
    )
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('chapter')
    op.drop_table('series')
    ### end Alembic commands ###


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import copy
import datetime
import locale
import os
from tqdm import tqdm
from collections import *
from typing import Optional,List,Tuple

from trident.backend.common import *
from trident.backend.pytorch_ops import *
from trident.backend.pytorch_backend import to_tensor, get_device, load,fix_layer,set_device
from trident.data.utils import download_model_from_google_drive,download_file_from_google_drive
from trident.layers.pytorch_layers import *
from trident import context
from trident.context import make_dir_if_need,split_path,sanitize_path

ctx=context._context()

__all__ = ['Word2Vec','ChineseWord2Vec']

_trident_dir = get_trident_dir()
dirname = os.path.join(_trident_dir, 'models')
if not os.path.exists(dirname):
    try:
        os.makedirs(dirname)
    except OSError:
        # Except permission denied and potential race conditions
        # in multi-threaded environments.
        pass

download_path= os.path.join(_trident_dir, 'download','vocabs_tw.txt')
make_dir_if_need(download_path)

class Word2Vec(Embedding):
    """中文詞向量
        繼承Embedding Layer

    """

    def __init__(self, pretrained=False, embedding_dim: Optional[int] = None, num_embeddings: Optional[int] = None, vocabs: Optional[List[str]] = None,
                 padding_idx: Optional[int] = None,
                 max_norm: Optional[float] = None, norm_type: float = 2., scale_grad_by_freq: bool = False,
                 sparse: bool = False, _weight: Optional[Tensor] = None, filter_index=-1, keep_output: bool = False, name: Optional[str] = None) -> None:

        """
        Py Word2vec结构
        """
        super().__init__(num_embeddings=num_embeddings, embedding_dim=embedding_dim, max_norm=max_norm, norm_type=norm_type, scale_grad_by_freq=scale_grad_by_freq, sparse=sparse,
                         _weight=_weight,padding_idx=padding_idx, keep_output=keep_output, name=name)
        self.pretrained=pretrained
        self.filter_index=filter_index
        self.locale =ctx.locale
        print('locale:', self.locale)

        self._vocabs = OrderedDict()
        if vocabs is not None:
            for k in range(len(vocabs)):
                self._vocabs[vocabs[k]] = k
        download_file_from_google_drive(file_id='16yDlJJ4-O9pHF-ZbXy7XPZZk6vo3aw4e', dirname=os.path.join(_trident_dir, 'download'), filename='vocabs_tw.txt')

    @property
    def vocabs(self):
        # 詞彙表
        return self._vocabs

    def word2idx(self, word: str):
        # 文字轉索引(根據locale處理繁簡轉換)
        if self.locale != 'zh_cn' and word in self.tw2cn:
            word = self.tw2cn[word]
        if word in self._vocabs:
            return self._vocabs[word]
        else:
            return None

    def idx2word(self, index: int):
        # 索引轉文字(根據locale處理繁簡轉換)
        if index < len(self._vocabs):
            word = self._vocabs.key_list[index]
            if self.locale != 'zh_cn' and word in self.cn2tw:
                word = self.cn2tw[word]
            return word
        else:
            return None

    @classmethod
    def load(cls):
        # 從google drive載入模型
        st = datetime.datetime.now()
        set_device('cpu')
        dirname = os.path.join(get_trident_dir(), 'models')

        download_model_from_google_drive('13XZPWh8QhEsC8EdIp1niLtZz0ipatSGC', dirname, 'word2vec_chinese.pth')
        recovery_model = load(os.path.join(dirname, 'word2vec_chinese.pth'))
        recovery_weight=recovery_model.state_dict()['weight']
        shp=int_shape(recovery_weight)

        v = cls(pretrained=True,num_embeddings=shp[0], embedding_dim=shp[-1],_weight=recovery_weight,name='word2vec_chinese')
        v._vocabs=copy.deepcopy(recovery_model._vocabs)
        v.tw2cn =copy.deepcopy(recovery_model.tw2cn)
        v.cn2tw = copy.deepcopy(recovery_model.cn2tw)
        del recovery_model
        v.locale =ctx.locale
        v.to(get_device())
        et = datetime.datetime.now()
        print('total loading time:{0}'.format(et - st))
        return v

    def find_similar(self, reprt: (str, Tensor), n: int = 10, ignore_indexes=None):
        # 根據文字或是向量查詢空間中最近文字
        reprt_idx = None
        if ignore_indexes is None:
            ignore_indexes = []
        if isinstance(reprt, str):
            reprt_idx = self.word2idx(reprt)
            ignore_indexes.append(reprt_idx)
            reprt = self.weight[reprt_idx].expand_dims(0) if reprt in self._vocabs else None
        if is_tensor(reprt):
            correlate = element_cosine_distance(reprt, self.weight)[0]
            sorted_idxes = argsort(correlate, descending=True)

            sorted_idxes = sorted_idxes[:n + len(ignore_indexes)]
            sorted_idxes = to_tensor([idx for idx in sorted_idxes if idx.item() not in ignore_indexes]).long()
            probs = to_list(correlate[sorted_idxes])[:n]
            words = [self.idx2word(idx.item()) for idx in sorted_idxes][:n]
            return OrderedDict(zip(words, probs))
        else:
            raise ValueError('Valid reprt should be a word or a tensor .')

    def analogy(self, reprt1: (str, Tensor, list), reprt2: (str, Tensor, list), reprt3: (str, Tensor, list), n: int = 10):
        # 類比關係 (男人之於女人等於國王之於皇后)
        reprt1_idx = None
        reprt2_idx = None
        reprt3_idx = None
        reprt1_arr = None
        reprt2_arr = None
        reprt3_arr = None
        exclude_list = []
        if isinstance(reprt1, str):
            reprt1_idx = self.word2idx(reprt1)
            exclude_list.append(reprt1_idx)
            reprt1_arr = self.weight[reprt1_idx].expand_dims(0) if reprt1_idx is not None else None
        elif isinstance(reprt1, Tensor):
            reprt1_arr = reprt1
        elif isinstance(reprt1, list):
            if isinstance(reprt1[0], str):
                reprt1_arr = self.get_words_centroid(*reprt1)
                for item in reprt1:
                    exclude_list.append(self.word2idx(item))

        if isinstance(reprt2, str):
            reprt2_idx = self.word2idx(reprt2)
            exclude_list.append(reprt2_idx)
            reprt2_arr = self.weight[reprt2_idx].expand_dims(0) if reprt2_idx is not None else None
        elif isinstance(reprt2, Tensor):
            reprt2_arr = reprt2
        elif isinstance(reprt2, list):
            if isinstance(reprt2[0], str):
                reprt2_arr = self.get_words_centroid(*reprt2)
                for item in reprt2:
                    exclude_list.append(self.word2idx(item))

        if isinstance(reprt3, str):
            reprt3_idx = self.word2idx(reprt3)
            exclude_list.append(reprt3_idx)
            reprt3_arr = self.weight[reprt3_idx].expand_dims(0) if reprt3_idx is not None else None
        elif isinstance(reprt3, Tensor):
            reprt3_arr = reprt3
        elif isinstance(reprt3, list):
            if isinstance(reprt3[0], str):
                reprt3_arr = self.get_words_centroid(*reprt3)
                for item in reprt3:
                    exclude_list.append(self.word2idx(item))

        if reprt1_arr is not None and reprt2_arr is not None and reprt3_arr is not None:
            reprt4 = reprt2_arr - reprt1_arr + reprt3_arr
            return self.find_similar(reprt4, n=n, ignore_indexes=exclude_list)
        else:
            not_find = []
            if reprt1_arr is None:
                not_find.append(reprt1)
            if reprt2_arr is None:
                not_find.append(reprt2)
            if reprt3_arr is None:
                not_find.append(reprt3)
            raise ValueError(' ,'.join(not_find) + ' was not in vocabs.')

    def get_words_centroid(self, *args):
        # 取得數個文字的向量均值
        centroid = 0
        for arg in args:
            reprt_idx = self.word2idx(arg)
            if reprt_idx is not None:
                centroid += self.weight[reprt_idx].expand_dims(0) if reprt_idx is not None else None
        return centroid / len(args)

    def get_words_vector(self, word):
        # 取得單一文字的向量
        reprt_idx = self.word2idx(word)
        if reprt_idx is not None:
            return self.weight[reprt_idx].expand_dims(0) if reprt_idx is not None else None
        return None

    def get_enumerators(self, *args, negative_case=None, n=10, exclude_samples=True):
        # 取得整體距離輸入案例最接近，但是離負案例最遠(negative_case)的文字列表
        positive_correlate = 0
        negative_correlate = 0
        exclude_list = []
        for arg in args:
            positive_correlate += element_cosine_distance(self.get_words_vector(arg), self.weight)[0]

        correlate = positive_correlate
        if negative_case is None:
            pass
        else:
            if isinstance(negative_case, str):
                negative_case = [negative_case]
            if isinstance(negative_case, (list, tuple)):
                for arg in negative_case:
                    negative_correlate += element_cosine_distance(self.get_words_vector(arg), self.weight)[0]
                correlate = positive_correlate - negative_correlate
        sorted_idxes = argsort(correlate, descending=True)
        sorted_idxes = sorted_idxes[:n + len(exclude_list)]
        sorted_idxes = to_tensor([idx for idx in sorted_idxes if idx.item() not in exclude_list]).long()
        probs = to_list(correlate[sorted_idxes])[:n]
        words = [self.idx2word(idx.item()) for idx in sorted_idxes][:n]
        return OrderedDict(zip(words, probs))

def ChineseWord2Vec(pretrained=True, freeze_features=True, **kwargs):
    if pretrained==True:
        model=Word2Vec.load()
        if freeze_features:
            model.trainable=False
        return model
    else:
        return Word2Vec()


from django.db import models

from book_archive.models import Genre
from config.models import User

class BookRequest(models.Model):
    title = models.CharField('Наименование', max_length=128)
    author = models.CharField('Автор', max_length=128, null=True, blank=True)
    genre = models.ForeignKey(Genre, on_delete=models.CASCADE, verbose_name='Жанры', null=True, blank=True)
    year = models.PositiveIntegerField('Год', default=0)
    created_at = models.DateTimeField('Дата запроса', auto_now_add=True)
    user = models.ForeignKey(
        User, null=True, blank=True,
        on_delete=models.CASCADE, verbose_name='Кто добавил',
    )
    is_approved = models.BooleanField('Одобрено ли', null=True, blank=True)

    class Meta:
        db_table = 'book_request'
        verbose_name = 'Запрос книги'
        verbose_name_plural = 'Запросы книг'

    def __str__(self):
        return f'{self.title}'


from torch import nn
import torch
import utils
import cv2
import numpy as np
import supervisely_lib as sly

def inference(model: nn.Module, input_height, input_width, image_path, device=None):
    with torch.no_grad():
        model.eval()
    image = sly.image.read(image_path)  # RGB
    input = utils.prepare_image_input(image, input_width, input_height)
    input = torch.unsqueeze(input, 0)
    input = utils.cuda(input, device)
    output = model(input)

    image_height, image_width = image.shape[:2]
    predicted_classes_indices = output.data.cpu().numpy().argmax(axis=1)[0]
    result = cv2.resize(predicted_classes_indices, (image_width, image_height), interpolation=cv2.INTER_NEAREST)
    return result

def convert_prediction_to_sly_format(predicted_class_indices, classes_json, model_classes: sly.ProjectMeta):
    height, width = predicted_class_indices.shape[:2]
    labels = []
    for idx, class_info in enumerate(classes_json):  # curr_col2cls.items():
        class_mask = predicted_class_indices == idx  # exact match (3-channel img & rgb color)
        if not np.any(class_mask):
            # 0 pixels for class
            continue
        bitmap = sly.Bitmap(data=class_mask)
        obj_class = model_classes.get_obj_class(class_info["title"])
        labels.append(sly.Label(bitmap, obj_class))
    ann = sly.Annotation(img_size=(height, width), labels=labels)
    return ann

def load_model(weights_path, num_classes, model_name, device):
    from train import model_list
    model_class = model_list[model_name]["class"]
    model = model_class(num_classes=num_classes)
    state = torch.load(weights_path)
    model.load_state_dict(state)
    model.to(device)
    model.eval()
    return model


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

img=cv2.imread('/home/hasantha/Desktop/repos/old-yolov4-deepsort-master/data/download2.png' ,0)
#img=img[423:998,806:1408]

ret, bw_img = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY) #165
kernel = np.ones((1,1),np.uint8)
#erosion = cv2.erode(img,kernel,iterations = 1)
opening = cv2.morphologyEx(bw_img, cv2.MORPH_OPEN, kernel)
#closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel)

#Append lane line coordinates to a matrix
lane_line_co=[]
x_cord_lane = np.where(opening == 255)[1]#+806     #+805
y_cord_lane = np.where(opening == 255)[0]#+423     #+389

for q in range(0, len(x_cord_lane)):
    lane_line_co.append((x_cord_lane[q],y_cord_lane[q]))

def get_lane_line_co():
    return x_cord_lane,y_cord_lane,lane_line_co

#print(lane_line_co)

#print(get_lane_line_co()[2])


"""See `TestSet` for an example."""
from typing import Type, MutableSet

from tests.collection_testing import unordered_equal

class MutableSetTests:
    mutable_set: Type = None

    @classmethod
    def create_mutable_set(cls) -> MutableSet:
        return cls.mutable_set()

    @staticmethod
    def get_element(i):
        return i

    def test_add_coverage(self):
        instance = self.create_mutable_set()
        element1 = self.get_element(1)

        instance.add(element1)
        # And add a second time for good measure
        instance.add(element1)

    def test_discard_missing_element_passes(self):
        instance = self.create_mutable_set()
        element1 = self.get_element(1)

        instance.discard(element1)

    def test_discard_passes(self):
        instance = self.create_mutable_set()
        element1 = self.get_element(1)

        instance.add(element1)
        instance.discard(element1)

    def test_contains_len(self):
        instance = self.create_mutable_set()
        element1 = self.get_element(1)

        assert len(instance) == 0
        assert element1 not in instance
        instance.add(element1)
        assert element1 in instance
        assert len(instance) == 1

        element2 = self.get_element(2)
        assert element2 not in instance
        instance.add(element2)
        assert element2 in instance
        assert len(instance) == 2

        assert element1 in instance
        instance.discard(element1)
        assert element1 not in instance
        assert len(instance) == 1

        assert element2 in instance
        instance.discard(element2)
        assert element1 not in instance
        assert element2 not in instance
        assert len(instance) == 0

    def test_iter(self):
        instance = self.create_mutable_set()
        element1 = self.get_element(1)
        element2 = self.get_element(2)

        assert list(iter(instance)) == []
        instance.add(element1)
        assert unordered_equal(iter(instance), [element1])

        instance.add(element2)
        assert unordered_equal(iter(instance), [element1, element2])

class TestMutableSet(MutableSetTests):
    mutable_set = set


import cv2 as cv
import numpy as np

def nothing(x):
    pass
cap= cv.VideoCapture('pranay1.avi')
fourcc= cv.VideoWriter_fourcc('X', 'V', 'I', 'D')
out= cv.VideoWriter('final1.avi', fourcc, 20.0, (640,480) )
#cv.namedWindow('Tracking')
#cv.createTrackbar('l_h', 'Tracking', 0, 255, nothing)
#cv.createTrackbar('l_s', 'Tracking', 0, 255, nothing)
#cv.createTrackbar('l_v', 'Tracking', 0, 255, nothing)
#cv.createTrackbar('u_h', 'Tracking', 255, 255, nothing)
#cv.createTrackbar('u_s', 'Tracking', 255, 255, nothing)
#cv.createTrackbar('u_v', 'Tracking', 255, 255, nothing)
while(True):
    ret, frame= cap.read()
    frame= cv.resize(frame, (640,480))
    hsv= cv.cvtColor(frame, cv.COLOR_BGR2HSV)
    #lh = cv.getTrackbarPos('l_h', 'Tracking')
    #ls = cv.getTrackbarPos('l_s', 'Tracking')
    #lv = cv.getTrackbarPos('l_v', 'Tracking')
    #uh = cv.getTrackbarPos('u_h', 'Tracking')
    #us = cv.getTrackbarPos('u_s', 'Tracking')
    #uv = cv.getTrackbarPos('u_v', 'Tracking')
    lh= 82
    ls= 51
    lv= 51
    uh= 133
    us= 255
    uv= 255
    lhb= 0
    lsb= 0
    lvb= 0
    uhb= 255
    usb= 255
    uvb= 0
    lbb= np.array([lhb, lsb, lvb])
    ubb= np.array([uhb, usb, uvb])
    lb= np.array([lh,ls,lv])
    ub= np.array([uh,us,uv])
    backg= cv.imread('pranay42.JPG')
    backg= cv.resize(backg, (640,480))
    mask= cv.inRange(hsv, lb, ub)
    masknot= cv.bitwise_not(mask)
    res= cv.bitwise_and(frame, frame, mask = masknot)
    a= cv.bitwise_and(backg, backg, mask=mask)
    fres= cv.addWeighted(res,1,a,1,1)
    cv.imshow('frame', frame)
    cv.imshow('fres', fres)
    key= cv.waitKey(1)
    if ret==True:
        out.write(fres)
    if key == 27:
        break
cap.release()
cv.destroyAllWindows()


import random
from datetime import datetime

ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
conteudo = 'There are many variations of passages of Lorem Ipsum available, but the ' \
           'majority have suffered alteration in some form, by injected humour, or randomised ' \
           'words which look even slightly believable. '
excerto = 'Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots' \
          ' in a piece of classical Latin'
now = datetime.now()
year = str(now.year).zfill(4)
month = str(now.month).zfill(2)
hour = str(now.hour).zfill(2)
minute = str(now.minute).zfill(2)
second = str(now.second).zfill(2)

for categoria_post_id in range(1, 5):  # Pressupõe 4 categorias
    for i in range(5):  # 5 posts para cada categoria
        titulo_post = ' '.join([''.join(random.choices(ALPHABET, k=random.randint(3, 8))) for i in range(3)])
        data_post = f'{year}-{month}-{str((now.day - i) % 29).zfill(2)} {hour}:{minute}:{second}'
        conteudo_post = (conteudo * random.randint(3, 25) + '.</br>') * 5
        excerto_post = excerto * random.randint(3, 5) + '. '
        imagem_post = f'post_img/2022/02/26/13estacio-sistemas.jpg'  # Mude para uma imagem que você tenha feito upload
        publicado_post = random.randint(0, 1)
        autor_post_id = 1  # id do seu super usuário

        sql_post = (f"INSERT INTO blog_django.posts_post"
                    f"(titulo_post,data_post,conteudo_post,excerto_post,imagem_post,"
                    f"publicado_post,autor_post_id,categoria_post_id)"
                    f"VALUES ('{titulo_post}','{data_post}','{conteudo_post}',"
                    f"'{excerto_post}','{imagem_post}',{publicado_post},"
                    f"{autor_post_id},{categoria_post_id});")

        print(sql_post)


#!/usr/bin/env python
#
# This example creates a polygonal model of a cone, and then renders it to
# the screen. It will rotate the cone 360 degrees and then exit. The basic
# setup of source -> mapper -> actor -> renderer -> renderwindow is
# typical of most VTK programs.
#

#
# First we include the VTK Python packages that will make available
# all of the VTK commands to Python.
#
import vtk
import time

#
# Next we create an instance of vtkConeSource and set some of its
# properties. The instance of vtkConeSource "cone" is part of a visualization
# pipeline (it is a source process object); it produces data (output type is
# vtkPolyData) which other filters may process.
#
cone = vtk.vtkConeSource()
cone.SetHeight( 3.0 )
cone.SetRadius( 1.0 )
cone.SetResolution( 10 )

#
# In this example we terminate the pipeline with a mapper process object.
# (Intermediate filters such as vtkShrinkPolyData could be inserted in
# between the source and the mapper.)  We create an instance of
# vtkPolyDataMapper to map the polygonal data into graphics primitives. We
# connect the output of the cone souece to the input of this mapper.
#
coneMapper = vtk.vtkPolyDataMapper()
coneMapper.SetInputConnection( cone.GetOutputPort() )

#
# Create an actor to represent the cone. The actor orchestrates rendering of
# the mapper's graphics primitives. An actor also refers to properties via a
# vtkProperty instance, and includes an internal transformation matrix. We
# set this actor's mapper to be coneMapper which we created above.
#
coneActor = vtk.vtkActor()
coneActor.SetMapper( coneMapper )

#
# Create the Renderer and assign actors to it. A renderer is like a
# viewport. It is part or all of a window on the screen and it is
# responsible for drawing the actors it has.  We also set the background
# color here
#
ren1= vtk.vtkRenderer()
ren1.AddActor( coneActor )
ren1.SetBackground( 0.1, 0.2, 0.4 )

#
# Finally we create the render window which will show up on the screen
# We put our renderer into the render window using AddRenderer. We also
# set the size to be 300 pixels by 300
#
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer( ren1 )
renWin.SetSize( 300, 300 )

#
# now we loop over 360 degreeees and render the cone each time
#
# for i in range(0,360):
#     time.sleep(0.03)

#     renWin.Render()
#     ren1.GetActiveCamera().Azimuth( 1 )


import csv
import numpy as np
import os
import pydicom
from segmentation_models.backbones import get_preprocessing
import tensorflow as tf

from pneumothorax_segmentation.constants import image_size, folder_path
from pneumothorax_segmentation.data_augment import apply_random_data_augment
from pneumothorax_segmentation.params import tf_image_size

# Documentation for reading dicom files at https://pydicom.github.io/pydicom/stable/viewing_images.html#using-pydicom-with-matplotlib

preprocess_input = get_preprocessing("resnet34")

def get_all_images_list(folder):
    "Load all images filenames in folder. Returns a list of (filepath, filename)"
    all_images_in_folder = []

    for dirName, _, fileList in os.walk(folder_path + "/data/dicom-images-%s" % folder):
        for filename in fileList:
            if ".dcm" in filename.lower():
                all_images_in_folder.append((os.path.join(dirName,filename), filename.replace(".dcm", "")))

    return all_images_in_folder

def get_dicom_data(file_path):
    "Return the dicom raw data of a given file"
    return pydicom.dcmread(file_path)

cached_csv = []
def get_raw_masks(name):
    """
        Returns a list of the masks as they appear in train-rle.csv. Masks '-1' are filtered out\n
        Note side-effect: loads the csv on the first run and caches it
    """
    global cached_csv

    # The csv data is stored in a cache. This way, the csv is read only once
    if (len(cached_csv) == 0):
        with open(folder_path + '/data/train-rle.csv') as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')
            for row in csv_reader:
                cached_csv.append(row)

    # Retrieve masks as they are in the csv
    raw_masks = []
    for row in cached_csv:
        if row[0] == name:
            raw_masks.append(row[1])

    # Remove the -1 from images with no mask
    if (raw_masks[0] == " -1"):
        raw_masks = []

    return raw_masks

def get_image_label(name):
    "Returns 1 if there is a pneumothorax, 0 otherwise. Based on data in train-rle.csv"
    raw_masks = get_raw_masks(name)
    if len(raw_masks) == 0:
        return 0
    return 1

def get_true_mask(name):
    "Takes the name of the image as input and returns the mask mapping as a numpy matrix of shape (image_size, image_size) and values 0-1"

    raw_masks = get_raw_masks(name)

    # Format the masks to an exploitable format
    masks = []
    for raw_mask in raw_masks:
        mask = raw_mask.split(" ")
        mask = mask[1:] # raw_mask starts with a space
        mask = [int(m) for m in mask]
        masks.append(mask)

    # Use the masks to create the actual mapping of image_size * image_size
    mask_mapping = np.zeros(image_size ** 2, dtype=np.int)
    for mask in masks:
        is_it_a_mask = False
        current_pixel = 0
        for pixel_long_movement in mask:
            if is_it_a_mask:
                for i in range(pixel_long_movement):
                    mask_mapping[current_pixel + i] = 1
            current_pixel += pixel_long_movement
            is_it_a_mask = not is_it_a_mask
    mask_mapping = np.reshape(mask_mapping, (image_size, image_size))
    mask_mapping = np.transpose(mask_mapping, (1, 0))

    return mask_mapping

def format_pixel_array_for_tf(pixel_array, apply_data_augment_technique=None):
    """
        Inputs pixel_array as they are stroed in the dicom file. Outputs a tensor ready to go through the models\n
        apply_data_augment_technique can be used to apply data augmentation. See apply_random_data_augment for values
    """
    image = tf.convert_to_tensor(pixel_array, dtype=tf.float32)
    image = tf.reshape(image, (1, image_size, image_size, 1))
    if (apply_data_augment_technique != None):
        image = apply_random_data_augment(image, apply_data_augment_technique)
    # tf.image.resize behaves weirdly with the default method when reducing size. AREA method makes more sense in our case, thought the default bilinear method makes more sense when making an image bigger
    image = tf.image.resize(image, (tf_image_size, tf_image_size), align_corners=True, method=tf.image.ResizeMethod.AREA)
    image = tf.image.grayscale_to_rgb(image)
    image = preprocess_input(image)
    return image


from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.home, name='index'),
    # url(r'^games/(?P<steamid>[0-9]+)$', views.games, name='games'),
    url(r'^home/$', views.home, name='home'),
    url(r'^games/', views.games, name='games'),
    url(r'^friends/', views.friends, name='friends'),
    url(r'^calculator/', views.calculator, name='calculator')

]


import gym
from collections import deque
import numpy as np
import time

import torch
torch.manual_seed(0) # set random seed
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical
from policy import Policy
from gym.wrappers.monitoring.video_recorder import VideoRecorder

env = gym.make('Acrobot-v1')
env.seed(0)
print('observation space:', env.observation_space)
print('action space:', env.action_space)

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

policy = Policy().to(device)
optimizer = optim.Adam(policy.parameters(), lr=0.001)

def reinforce(n_episodes=5000, max_t=1000, gamma=1.0, print_every=100):
    scores_deque = deque(maxlen=100)
    scores = []
    for i_episode in range(1, n_episodes+1):
        saved_log_probs = []
        rewards = []
        state = env.reset()
        for t in range(max_t):
            action, log_prob = policy.act(state)
            saved_log_probs.append(log_prob)
            state, reward, done, _ = env.step(action)
            rewards.append(reward)
            if done:
                break
        scores_deque.append(sum(rewards))
        scores.append(sum(rewards))

        discounts = [gamma**i for i in range(len(rewards)+1)]
        R = sum([a*b for a,b in zip(discounts, rewards)])

        policy_loss = []
        for log_prob in saved_log_probs:
            policy_loss.append(-log_prob * R)
        policy_loss = torch.cat(policy_loss).sum()

        optimizer.zero_grad()
        policy_loss.backward()
        optimizer.step()

        if i_episode % print_every == 0:
            torch.save(policy.state_dict(), 'checkpoint.pth')
            print('Episode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_deque)))
    return scores

scores = reinforce()


import argparse
import yaml
from pyspark.sql.functions import udf, when, year

class CreateSqlInput:
    def __init__(self):
        self.name = 'CalculateStats'

    @staticmethod
    @udf
    def extract_production(dict_string):
        try:
            production_array = yaml.load(dict_string, Loader=yaml.FullLoader)
            parsed_production = []
            for production in production_array:
                parsed_production.append(production['name'])
        except ValueError:
            parsed_production = []
        return parsed_production

    @staticmethod
    def main(spark, config):
        joined_parquet_path = config.get('PATHS', 'joined_parquet_path')
        sql_input_path = config.get('PATHS', 'sql_input_path')
        joined_df = spark.read.parquet(joined_parquet_path)

        joined_df = joined_df.withColumn('production_companies',
                                         CreateSqlInput.extract_production('production_companies'))

        joined_df = joined_df.withColumn('ratio',
                                         when(joined_df['revenue'] != 0, joined_df['budget']/joined_df['revenue'])
                                         .otherwise(0.0))

        joined_df = joined_df.withColumn('year', year('release_date'))

        joined_df = joined_df.orderBy('ratio', ascending=False)
        joined_df.select('title', 'production_companies', 'budget', 'revenue', 'ratio', 'year').show(5, False)

        joined_df.select(['title',
                          'budget',
                          'year',
                          'revenue',
                          'vote_average',
                          'ratio',
                          'production_companies',
                          'url',
                          'abstract']).write.mode('overwrite').parquet(sql_input_path)

if __name__ == '__main__':
    import sys
    from os import path
    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
    from tfi_etl.sparkscript import SparkScriptRunner

    parser = argparse.ArgumentParser()
    parser.add_argument('-config')

    args = parser.parse_args()
    config_path = str(args.config)

    calculate_stats = CreateSqlInput()
    script_runner = SparkScriptRunner(config_path, calculate_stats)
    script_runner.run()


from __future__ import annotations

from datetime import datetime
from datetime import timedelta
from unittest.mock import MagicMock

import pytest
from common.reddit_client import RedditClient
from prawcore.exceptions import Forbidden
from requests import Response

@pytest.fixture
def reddit_client():
    return RedditClient(
        reddit_client_id="YOUR_CLIENT_ID",
        reddit_client_secret="YOUR_CLIENT_SECRET",
        reddit_user_agent="YOUR_USER_AGENT",
    )

@pytest.fixture
def subreddit_mock(reddit_client):
    reddit_client.reddit_client.subreddit = MagicMock()
    return reddit_client.reddit_client.subreddit.return_value

@pytest.fixture
def post_data():
    date = datetime(2023, 7, 28)

    post1 = MagicMock()
    post1.id = "post1"
    post1.title = "Test Post 1"
    post1.selftext = "This is test post 1."
    post1.subreddit.display_name = "test_subreddit"
    post1.upvote_ratio = 0.75
    post1.ups = 10
    post1.downs = 2
    post1.total_awards_received = 1
    post1.num_comments = 5
    post1.created_utc = date.timestamp()

    post2 = MagicMock()
    post2.id = "post2"
    post2.title = "Test Post 2"
    post2.selftext = "This is test post 2."
    post2.subreddit.display_name = "test_subreddit"
    post2.upvote_ratio = 0.80
    post2.ups = 15
    post2.downs = 3
    post2.total_awards_received = 2
    post2.num_comments = 8
    post2.created_utc = (date + timedelta(days=1)).timestamp()
    return [post1, post2]

@pytest.fixture
def subreddit_new_mock(subreddit_mock, post_data):
    subreddit_mock.new = MagicMock(return_value=post_data)
    return subreddit_mock.new

def test_remove_submissions_not_on_date(reddit_client):
    date = datetime(2021, 10, 4).date()
    submissions = [
        {"created_utc": 1633393174},
        {"created_utc": 1633306774},
        {"created_utc": 1633220374},
    ]
    expected_submissions = [{"created_utc": 1633306774}]
    result = reddit_client._remove_submissions_not_on_date(submissions, date)
    assert result == expected_submissions

def test_fetch_submissions_made_on_date_forbidden_error(reddit_client, subreddit_new_mock):
    forbidden_response = Response()
    forbidden_response.status_code = 403
    subreddit_new_mock.side_effect = Forbidden(forbidden_response)
    result = reddit_client.fetch_submissions_made_on_date("test_subreddit", datetime(2023, 7, 28))
    assert result == []

def test_fetch_submissions_made_on_date_no_posts(reddit_client, subreddit_new_mock):
    subreddit_new_mock.return_value = []
    result = reddit_client.fetch_submissions_made_on_date("test_subreddit", datetime(2023, 7, 28))
    assert result == []


from celery import Celery
from celery.schedules import crontab

app = Celery(
    "vivaldi",
    broker_url="redis://localhost:6379/0",
    result_backend="redis://localhost:6379/0",
    imports=["tasks"],
    task_serializer="json",
    result_serializer="json",
    accept_content=["json"],
    timezone="Europe/Lisbon",
)
beat_schedule = {
    "set_default": {
        "task": "tasks.default_browser",
        "schedule": crontab(minute=0, hour=1),
        "args": (),
    },
}

if __name__ == "__main__":
    app.start()