# stolen two coil EDFA model from GNPy
import numpy as np
import math
def lin2db(x):
    return 10*np.log10(x)

def db2lin(x):
    return 10**(x/10)

def nf_model(gain_min, gain_max, nf_min, nf_max):

# NF estimation model based on nf_min and nf_max
    # delta_p:  max power dB difference between first and second stage coils
    # dB g1a:   first stage gain - internal VOA attenuation
    # nf1, nf2: first and second stage coils
    #           calculated by solving nf_{min,max} = nf1 + nf2 / g1a{min,max}
    delta_p = 5
    g1a_min = gain_min - (gain_max - gain_min) - delta_p
    g1a_max = gain_max - delta_p
    nf2 = lin2db((db2lin(nf_min) - db2lin(nf_max)) /
                 (1/db2lin(g1a_max) - 1/db2lin(g1a_min)))
    nf1 = lin2db(db2lin(nf_min) - db2lin(nf2)/db2lin(g1a_max))

    if nf1 < 4:
        print("First coil value too low")
        #raise EquipmentConfigError(f'First coil value too low {nf1} for amplifier {type_variety}')

    # Check 1 dB < delta_p < 6 dB to ensure nf_min and nf_max values make sense.
    # There shouldn't be high nf differences between the two coils:
    #    nf2 should be nf1 + 0.3 < nf2 < nf1 + 2
    # If not, recompute and check delta_p
    if not nf1 + 0.3 < nf2 < nf1 + 2:
        nf2 = np.clip(nf2, nf1 + 0.3, nf1 + 2)
        g1a_max = lin2db(db2lin(nf2) / (db2lin(nf_min) - db2lin(nf1)))
        delta_p = gain_max - g1a_max
        g1a_min = gain_min - (gain_max-gain_min) - delta_p
        if not 1 < delta_p < 11:
            #raise EquipmentConfigError(f'Computed \N{greek capital letter delta}P invalid \
            #    \n 1st coil vs 2nd coil calculated DeltaP {delta_p:.2f} for \
            #    \n amplifier {type_variety} is not valid: revise inputs \
            #    \n calculated 1st coil NF = {nf1:.2f}, 2nd coil NF = {nf2:.2f}')
            print("Computed \N{greek capital letter delta}P invalid")
    # Check calculated values for nf1 and nf2
    calc_nf_min = lin2db(db2lin(nf1) + db2lin(nf2)/db2lin(g1a_max))
    if not math.isclose(nf_min, calc_nf_min, abs_tol=0.01):
        #raise EquipmentConfigError(f'nf_min does not match calc_nf_min, {nf_min} vs {calc_nf_min} for amp {type_variety}')
        print("nf_min does not match calc_nf_min")
    calc_nf_max = lin2db(db2lin(nf1) + db2lin(nf2)/db2lin(g1a_min))
    if not math.isclose(nf_max, calc_nf_max, abs_tol=0.01):
        #raise EquipmentConfigError(f'nf_max does not match calc_nf_max, {nf_max} vs {calc_nf_max} for amp {type_variety}')
        print("nf_max does not match calc_nf_max")

    return nf1, nf2, delta_p, g1a_max, g1a_min


import datetime
import json

from django.conf import settings
from django.shortcuts import *
from django_redis import get_redis_connection

from utils.alipay import AliPay
from utils.encrypt import uid
from web.models import *

def index(request):
    return render(request, 'index.html')

def price(request):
    """套餐"""
    # 获取套餐
    policy_list = PricePolicy.objects.filter(category=2)
    return render(request, 'price.html', {'policy_list': policy_list})

def payment(request, policy_id):
    """支付页面"""
    # 1.价格策略（套餐）policy_id
    policy_object = PricePolicy.objects.filter(id=policy_id, category=2).first()
    if not policy_object:
        return redirect('price')
    # 2. 要购买的数量
    number = request.GET.get('number', '')
    if not number or not number.isdecimal():
        return redirect('price')
    number = int(number)
    if number < 1:
        return redirect('price')

    # 3. 计算原价
    origin_price = number * policy_object.price

    # 4.之前购买过套餐(之前掏钱买过）
    balance = 0
    _object = None
    if request.saas.price_policy.category == 2:
        # 找到之前订单：总支付费用 、 开始~结束时间、剩余天数 = 抵扣的钱
        # 之前的实际支付价格
        _object = Transaction.objects.filter(user=request.saas.user, status=2).order_by('-id').first()
        total_timedelta = _object.end_datetime - _object.start_datetime
        balance_timedelta = _object.end_datetime - datetime.datetime.now()
        print(total_timedelta.days)
        print(balance_timedelta.days)
        if total_timedelta.days == balance_timedelta.days:
            # 按照价值进行计算抵扣金额
            balance = _object.price / total_timedelta.days * (balance_timedelta.days - 1)
        else:
            balance = _object.price / total_timedelta.days * balance_timedelta.days

    if balance >= origin_price:
        return redirect('price')

    context = {
        'policy_id': policy_object.id,
        'number': number,
        'origin_price': origin_price,
        'balance': round(balance, 2),
        'total_price': origin_price - round(balance, 2)
    }
    # 订单信息存在redis中时间（30分钟）
    conn = get_redis_connection()
    key = 'payment_{}'.format(request.saas.user.phone)
    # conn.set(key, json.dumps(context), nx=60 * 30)
    conn.set(key, json.dumps(context), ex=60 * 30)  # nx参数写错了，应该是ex（表示超时时间） ps：nx=True,表示redis中已存在key，再次执行时候就不会再设置了。
    #
    context['policy_object'] = policy_object
    context['transaction'] = _object

    return render(request, 'payment.html', context)

"""
封装前
def pay(request):

    # 拿出数据校验
    conn = get_redis_connection()
    key = 'payment_{}'.format(request.saas.user.phone)
    context_string = conn.get(key)
    if not context_string:
        return redirect('price')
    context = json.loads(context_string.decode('utf-8'))

    #１．数据库生成交易记录（待支付）,
    order_id = uid(request.saas.user.phone) #根据手机号生成随机字符串
    total_price = context['total_price']
    Transaction.objects.create(
        status=1,
        order=order_id,
        user=request.saas.user,
        price_policy_id=context['policy_id'],
        count=context['number'],
        price=total_price
    )
    #2.跳转支付宝支付
    # -根据申请的支付信息　＋　支付宝文档　－＞跳转链接
    # -生成一个支付的链接 跳转
    #构造字典
    params = {
        'app_id': "2021000117617357",
        'method': 'alipay.trade.page.pay',
        'format': 'JSON',
        'return_url': "http://127.0.0.1:8001/pay/notify/",
        'notify_url': "http://127.0.0.1:8001/pay/notify/",
        'charset': 'utf-8',
        'sign_type': 'RSA2',
        'timestamp': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        'version': '1.0',
        'biz_content': json.dumps({
            'out_trade_no': order_id,
            'product_code': 'FAST_INSTANT_TRADE_PAY',
            'total_amount': total_price,
            'subject': "saas payment"
        }, separators=(',', ':'))
    }

    # 获取待签名的字符串
    unsigned_string = "&".join(["{0}={1}".format(k, params[k]) for k in sorted(params)])

    # 签名 SHA256WithRSA(对应sign_type为RSA2)
    from Crypto.PublicKey import RSA
    from Crypto.Signature import PKCS1_v1_5
    from Crypto.Hash import SHA256
    from base64 import decodebytes, encodebytes

    # SHA256WithRSA + 应用私钥 对待签名的字符串 进行签名
    private_key = RSA.importKey(open("files/sss.txt").read())
    print(private_key)
    signer = PKCS1_v1_5.new(private_key)
    signature = signer.sign(SHA256.new(unsigned_string.encode('utf-8')))

    # 对签名之后的执行进行base64 编码，转换为字符串
    sign_string = encodebytes(signature).decode("utf8").replace('\n', '')
    print(sign_string)

    # 把生成的签名赋值给sign参数，拼接到请求参数中。

    from urllib.parse import quote_plus
    result = "&".join(["{0}={1}".format(k, quote_plus(params[k])) for k in sorted(params)])
    result = result + "&sign=" + quote_plus(sign_string)

    gateway = "https://openapi.alipaydev.com/gateway.do"
    ali_pay_url = "{}?{}".format(gateway,result)

    return redirect(ali_pay_url)
"""

def pay(request):
    '''封装后'''
    # 拿出数据校验
    conn = get_redis_connection()
    key = 'payment_{}'.format(request.saas.user.phone)
    context_string = conn.get(key)
    if not context_string:
        return redirect('price')
    context = json.loads(context_string.decode('utf-8'))

    # １．数据库生成交易记录（待支付）,
    order_id = uid(request.saas.user.phone)  # 根据手机号生成随机字符串
    total_price = context['total_price']
    Transaction.objects.create(
        status=1,
        order=order_id,
        user=request.saas.user,
        price_policy_id=context['policy_id'],
        count=context['number'],
        price=total_price
    )
    # 生成支付宝链接
    ali_pay = AliPay(
        appid=settings.ALI_APPID,
        app_notify_url=settings.ALI_NOTIFY_URL,
        return_url=settings.ALI_RETURN_URL,
        app_private_key_path=settings.ALI_PRI_KEY_PATH,
        alipay_public_key_path=settings.ALI_PUB_KEY_PATH
    )
    query_params = ali_pay.direct_pay(
        subject="Saas 系统会员",  # 商品简单描述
        out_trade_no=order_id,  # 商户订单号
        total_amount=total_price
    )
    pay_url = "{}?{}".format(settings.ALI_GATEWAY, query_params)
    return redirect(pay_url)

def pay_notify(request):
    """ 支付成功之后触发的URL """
    ali_pay = AliPay(
        appid=settings.ALI_APPID,
        app_notify_url=settings.ALI_NOTIFY_URL,
        return_url=settings.ALI_RETURN_URL,
        app_private_key_path=settings.ALI_PRI_KEY_PATH,
        alipay_public_key_path=settings.ALI_PUB_KEY_PATH
    )
    if request.method == "GET":
        # 只做跳转，判断是否支付成功了，不做订单的状态更新。
        # 支付吧会讲订单号返回：获取订单ID，然后根据订单ID做状态更新 + 认证。
        # 支付宝公钥对支付给我返回的数据request.GET 进行检查，通过则表示这是支付宝返还的接口。
        params = request.GET.dict()
        sign = params.pop('sign', None)
        status = ali_pay.verify(params, sign)
        if status:
            current_datetime = datetime.datetime.now()
            out_trade_no = params['out_trade_no']
            _object = Transaction.objects.filter(order=out_trade_no).first()

            _object.status = 2
            _object.start_datetime = current_datetime
            _object.end_datetime = current_datetime + datetime.timedelta(days=365 * _object.count)
            _object.save()

            return HttpResponse('支付完成')
        return HttpResponse('支付失败')
    else:
        from urllib.parse import parse_qs
        body_str = request.body.decode('utf-8')
        post_data = parse_qs(body_str)
        post_dict = {}
        for k, v in post_data.items():
            post_dict[k] = v[0]

        sign = post_dict.pop('sign', None)
        status = ali_pay.verify(post_dict, sign)
        if status:
            current_datetime = datetime.datetime.now()
            out_trade_no = post_dict['out_trade_no']
            _object = Transaction.objects.filter(order=out_trade_no).first()

            _object.status = 2
            _object.start_datetime = current_datetime
            _object.end_datetime = current_datetime + datetime.timedelta(days=365 * _object.count)
            _object.save()
            return HttpResponse('success')

        return HttpResponse('error')


from src.common.config import notifications, telegram
from src.common.logger import logger

import requests
import json

def sendIM(body: str, forceSend: bool = False) -> bool:
    """Send an notification message to the service configured in .env; won't send
    anything if notifications are disabled, unless forceSend is True"""

    if not notifications["instantMessage"]["enable"] and not forceSend:
        return True

    notification_result = False
    try:
        if telegram["enable"]:
            notification_result = sendTelegramMessage(
                body=body, apiKey=telegram["apiKey"], chatId=telegram["chatId"]
            )

        # NOTE <add more IM services here>

    except:
        logger.warning("Notification Error!")
        return False

    return notification_result

def sendTelegramMessage(body: str, apiKey: str, chatId: str) -> bool:
    """Send a telegram message using rest api"""
    headers = {"Content-Type": "application/json"}

    data_dict = {
        "chat_id": chatId,
        "text": body,
        "parse_mode": "HTML",
        "disable_notification": True,
    }
    data = json.dumps(data_dict)

    url = f"https://api.telegram.org/bot{apiKey}/sendMessage"
    response = requests.post(url, data=data, headers=headers, timeout=1)
    return response.ok


from allauth.account.forms import SignupForm
from django import forms
from django.http import HttpRequest

class UserSignupForm(SignupForm):
    """
    Form that will be rendered on a user sign up section/screen.
    Default fields will be added automatically.
    """

    full_name = forms.CharField(
        label="Nom complet",
        widget=forms.TextInput(attrs={"placeholder": "Entrez votre nom complet"}),
    )
    short_name = forms.CharField(
        label="Nom court",
        widget=forms.TextInput(
            attrs={"placeholder": "Entrez votre petit nom ou un prénom"}
        ),
    )

    def save(self, request: HttpRequest):
        user = super().save(request)
        user.full_name = self.cleaned_data["full_name"]
        user.short_name = self.cleaned_data["short_name"]
        user.save()
        return user


from uuid import UUID
from fastapi import APIRouter, Depends, Query, Response, status
from pydantic import Json
from sqlalchemy.orm import Session
from routers.error import http_forbiden
from schemas.user import User
from services.auth_service import token_interceptor
from models.company_model import CompanyModel
from schemas.company import Company
from database import get_db_context
from services import company_service
from routers.error import http_exception, http_forbiden, http_badrequest
router = APIRouter(prefix='/api/v1/companies', tags=['Companies'])

@router.get('')
async def index(page: int = Query(ge=1, default=1),
                size: int = Query(ge=1, le=50, default=10),
                keyword: str = Query(default=None),
                db: Session = Depends(get_db_context)):
    items = company_service.get_companies(page, size, keyword, db)
    total = company_service.count_companies(keyword, db)
    return {
        "items": items,
        "pageInfo": {
            "total": total,
            "size": size,
            "page": page
        }
    }

@router.get('/{company_id}')
async def get_by_id(company_id: UUID, db: Session = Depends(get_db_context)):
    item = company_service.get_company_by_id(company_id, db)
    if item is not None:
        return item
    raise http_exception()

@router.post('', status_code=status.HTTP_201_CREATED)
async def add_company(request: CompanyModel,
                     user: User = Depends(token_interceptor),
                     db: Session = Depends(get_db_context)):
    if not user.is_admin:
        raise http_forbiden()

    company = company_service.add_company(request, db)

    return company

@router.put('/{company_id}')
async def update_company(company_id: UUID,
                     request: CompanyModel,
                     user: User = Depends(token_interceptor),
                     db: Session = Depends(get_db_context)):
    if not user.is_admin:
        raise http_forbiden()

    result = company_service.edit_company(company_id, request, db)

    if result == False:
        raise http_badrequest()

    return Response(status_code=status.HTTP_204_NO_CONTENT)

@router.delete('/{company_id}')
async def delete_company(company_id: UUID,
                     user: User = Depends(token_interceptor),
                     db: Session = Depends(get_db_context)):
    if not user.is_admin:
        raise http_forbiden()

    result = company_service.delete_company(company_id, db)

    if result == False:
        raise http_badrequest()

    return Response(status_code=status.HTTP_204_NO_CONTENT)


import pandas as pd
import csv

def load_primarydata():
    # use pandas to load the data structure
    data = pd.read_csv("bank-full.csv", sep=";").drop(["contact", "day", "month", "duration",
                                                      "campaign", "pdays", "previous", "poutcome"], axis=1)
    return data
    pass

def data2file(data):
    # create a csv file to store the useful data from the intergate data
    file = open("fullpre.csv", "w", encoding="gbk", newline="")
    writer = csv.writer(file)
    writer.writerow(['age', 'job', 'marital', 'education', 'default', 'balance', 'housing', 'loan', 'subscribe'])
    for i in range(len(data)):
        row = list(data.iloc[i])   # ix and iloc have the same ability

        # divide age into 4 class
        if row[0] < 30:
            row[0] = 'young'
        elif row[0] < 45:
            row[0] = 'middle'
        elif row[0] < 60:
            row[0] = 'preold'
        else:
            row[0] = 'old'

        # divide balance into 4 class
        if row[5] < 0:
            row[5] = 'bad'
        elif row[5] < 5000:
            row[5] = 'soso'
        elif row[5] < 20000:
            row[5] = 'ok'
        else:
            row[5] = 'good'

        writer.writerow([row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]])
    file.close()

def convert2onehot(data, name):
    # covert data to onehot
    onehot = pd.get_dummies(data, prefix=data.columns)
    onehot.to_csv(name, index=False, )

    # return pd.get_dummies(data, prefix=data.columns)


import sys
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline

def dfs(vertex, parent):
    global count
    order[vertex] = count
    count += 1

    compare = order[vertex]

    for next in graph[vertex]:
        if next == parent:
            continue

        if order[next] == 0:
            minValue = dfs(next, vertex)

            if minValue > order[vertex]:
                if next > vertex:
                    result.append([vertex, next])
                else:
                    result.append([next, vertex])

            compare = min(compare, minValue)
        else:
            compare = min(compare, order[next])

    return compare

V, E = map(int, input().split())

graph = [[] for _ in range(V + 1)]

for _ in range(E):
    a, b = map(int, input().split())

    graph[a].append(b)
    graph[b].append(a)

count = 1

order = [0] * (V + 1)
result = []

for i in range(1, V + 1):
    if order[i] == 0:
        dfs(i, 0)

result.sort()

print(len(result))
for i in range(len(result)):
    print(result[i][0], result[i][1])


# -*- coding: utf-8 -*-
import os

from core.toad.generictask import GenericTask
from lib.images import Images
from lib import util

__author__ = "Christophe Bedetti"
__copyright__ = "Copyright (C) 2014, TOAD"
__credits__ = ["Christophe Bedetti","Mathieu Desrosiers"]

class QA(GenericTask):

    def __init__(self, subject):
        GenericTask.__init__(self, subject, 'backup')
        self.setCleanupBeforeImplement(False)
        self.subjectName = subject.getName()

    def implement(self):

        if not os.path.exists(self.qaImagesDir):
            os.makedirs(self.qaImagesDir)

        #Copy logo
        logoName = self.config.get('qa', 'logo')
        logoLink = os.path.join(
                self.toadDir, 'templates', 'files', logoName)
        util.copy(logoLink, self.qaImagesDir, logoName)

        #Copy menu, css & js
        styleFiles = ('menu', 'css', 'jquery', 'js')
        for tag in styleFiles:
            fileName = self.config.get('qa', tag)
            fileLink = os.path.join(
                    self.toadDir, 'templates', 'files', fileName)
            util.copy(fileLink, self.workingDir, fileName)

        #Create index.html
        self.createTaskHtml(
                {'parseHtmlTables':'
Methodology when pipeline is finished
'}, 'index.html')

    def meetRequirement(self, result=True):
        """
        """
        return result

    def isDirty(self):
        """Validate if this tasks need to be submit for implementation

        """
        return Images(
                (os.path.join(self.workingDir, 'index.html'), 'QA index.html'),
                (os.path.join(self.workingDir, self.config.get('qa', 'jquery')), 'Jquery library'))


import subprocess
from django.http import JsonResponse
import json

# Create your views here.
def index(request):
    query = request.GET['query']
    cmd = ['java', 'TW3Main', query]
    print(cmd)
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    output, stderr = p.communicate()
    print(output)
    output = json.loads(output.decode('utf-8'))
    return JsonResponse(output, status=200, safe=False)


from odoo import models
import requests
import json

class PostWorkPackages(models.TransientModel):
    _name = 'post.work_packages'
    _description = 'Create Work_Packages'
    headers = {
        'content-type': 'application/json'
    }

    @staticmethod
    def get_main_url(project_id):
        base_path = "http://localhost:3000"
        endpoint_url = "/api/v3/projects/%s/work_packages" % project_id
        main_url = "%s%s" % (base_path, endpoint_url)
        return main_url

    @staticmethod
    def get_payload(project_id, id):
        payload = {
            "subject": "package%s" % id,
            "description": {
                "format": "markdown",
                "raw": None,
                "html": ""
            },
            "scheduleManually": False,
            "startDate": None,
            "dueDate": None,
            "estimatedTime": None,
            "percentageDone": 0,
            "remainingTime": None,
            "_links": {
                "category": {
                    "href": None
                },
                "type": {
                    "href": "/api/v3/types/1",
                    "title": "Task"
                },
                "priority": {
                    "href": "/api/v3/priorities/8",
                    "title": "Normal"
                },
                "project": {
                    "href": "/api/v3/projects/%s" % project_id,
                },
                "status": {
                    "href": "/api/v3/statuses/1",
                    "title": "New"
                },
                "responsible": {
                    "href": None
                },
                "assignee": {
                    "href": None
                },
                "version": {
                    "href": None
                },
                "parent": {
                    "href": None,
                    "title": None
                }
            }
        }
        return payload

    def get_api_key(self):
        api_key = self.env['ir.config_parameter'].sudo(
        ).get_param('openproject.api_key') or False
        return api_key

    def post_response(self, url, payload):
        api_key = self.get_api_key()

        resp = requests.post(
            url,
            auth=('apikey', api_key),
            data=json.dumps(payload),
            headers=self.headers
        )
        return json.loads(resp.text)

    def cron_create_work_packages(self):
        try:
            for p in range(1843, 1862):
                main_url = self.get_main_url(p)
                print(p)
                print("main_url: ", main_url)
                for id in range(1, 5):
                    response = self.post_response(main_url, self.get_payload(p, id))
                    print(response)
            # Range: first and last id of projects
        except Exception as e:
            print("Exception has occurred: ", e)
            print("Exception type: ", type(e))


import random

class Game:
    def __init__(self, decks_count, reset_on_dealer_blackjack):
        self.deck = Deck(decks_count)
        self.reset_on_dealer_blackjack = reset_on_dealer_blackjack

    def start_round(self):
        self.deck.reset()
        game_round = Round(self.deck)
        return game_round

    def run_managed_game(self, round_callback):
        game_round = self.start_round()

        if self.reset_on_dealer_blackjack:
            while game_round.dealer_has_blackjack():
                game_round = self.start_round()

        while game_round.is_player_alive():
            action = round_callback(game_round.player_sum, game_round.dealer_sum)
            if action == 'HIT':
                game_round.draw_for_player()
            elif action == 'STAND':
                return game_round.resolve_round()
            else:
                raise ValueError(f"Invalid player action: {action}")
        return 'LOSE'

class Deck:
    def __init__(self, decks_count=1):
        self.deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] * 4 * decks_count  # 4 suits. All 10-valued cards are identical in behavior
        self.drawn_cards_indices = set()
        self.reset()

    def reset(self):
        self.drawn_cards_indices = set()

    # Draw a card by picking a random one until we pick one we've not chosen before.
    # Since we pick such a low fraction of the deck each game, this is much faster than shuffling or removing from the deck
    # There's a time and place for functional programming; this isn't it.
    def draw(self):
        if len(self.drawn_cards_indices) >= len(self.deck):
            raise RuntimeError("Tried to pick a card from an empty deck")

        while True:
            drawn_card_index = random.randrange(len(self.deck))
            if drawn_card_index not in self.drawn_cards_indices:
                self.drawn_cards_indices.add(drawn_card_index)
                return self.deck[drawn_card_index]

class Round:
    def __init__(self, deck):
        self.deck = deck
        self.dealer_cards_visible = [self.deck.draw()]
        self.dealer_cards_hidden = [self.deck.draw()]
        self.player_cards = [self.deck.draw(), self.deck.draw()]

    def sum_cards(self, cards):
        current_sum = sum([c for c in cards if c != 1])
        aces = [11 for c in cards if c == 1]

        # Treat aces as 11. If the score busts 21, downgrade aces from 11 to 1 one at a time
        while current_sum + sum(aces) > 21 and 11 in aces:
            aces[aces.index(11)] = 1
        return current_sum + sum(aces)

    @property
    def dealer_sum(self):
        return self.sum_cards(self.dealer_cards_visible)

    @property
    def player_sum(self):
        return self.sum_cards(self.player_cards)

    def dealer_has_blackjack(self):
        # Dealer blackjack requires a visible 10 and hidden Ace, or vice-versa
        if len(self.dealer_cards_hidden) == 1 and len(self.dealer_cards_visible) == 1 and (
                    (self.dealer_cards_visible[0] == 1 and self.dealer_cards_hidden[0] == 10) or
                    (self.dealer_cards_visible[0] == 10 and self.dealer_cards_hidden[0] == 1)):
            return True
        else:
            return False

    def is_player_alive(self):
        return self.player_sum <= 21 and self.dealer_has_blackjack() is False

    def draw_for_player(self):
        self.player_cards.append(self.deck.draw())

    def start_round(self):
        self.dealer_cards_visible.append(self.deck.draw())
        self.dealer_cards_hidden.append(self.deck.draw())
        self.player_cards.extend([self.deck.draw(), self.deck.draw()])

    def resolve_round(self):
        self.dealer_cards_visible.extend(self.dealer_cards_hidden)
        self.dealer_cards_hidden = []

        # Dealer had first turn blackjack. Instant loss.
        if self.dealer_sum == 21:
            return 'LOSE'

        if self.player_sum > 21:
            return 'LOSE'

        while self.dealer_sum < 17:
            self.dealer_cards_visible.append(self.deck.draw())

        if self.dealer_sum > 21:
            return 'WIN'
        if self.dealer_sum == self.player_sum:
            return 'DRAW'
        elif self.player_sum > self.dealer_sum:
            return 'WIN'
        else:
            return 'LOSE'


""" test fancy indexing & misc """

from datetime import datetime
import re
import weakref

import numpy as np
import pytest

from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype

import pandas as pd
from pandas import DataFrame, Index, NaT, Series
import pandas._testing as tm
from pandas.core.indexing import maybe_numeric_slice, non_reducing_slice
from pandas.tests.indexing.common import _mklbl

from .test_floats import gen_obj

def getitem(x):
    return x

def setitem(x):
    return x

def loc(x):
    return x.loc

def iloc(x):
    return x.iloc

# ------------------------------------------------------------------------
# Indexing test cases

class TestFancy:
    """ pure get/set item & fancy indexing """

    def test_setitem_ndarray_1d(self):
        # GH5508

        # len of indexer vs length of the 1d ndarray
        df = DataFrame(index=Index(np.arange(1, 11)))
        df["foo"] = np.zeros(10, dtype=np.float64)
        df["bar"] = np.zeros(10, dtype=complex)

        # invalid
        msg = "Must have equal len keys and value when setting with an iterable"
        with pytest.raises(ValueError, match=msg):
            df.loc[df.index[2:5], "bar"] = np.array([2.33j, 1.23 + 0.1j, 2.2, 1.0])

        # valid
        df.loc[df.index[2:6], "bar"] = np.array([2.33j, 1.23 + 0.1j, 2.2, 1.0])

        result = df.loc[df.index[2:6], "bar"]
        expected = Series(
            [2.33j, 1.23 + 0.1j, 2.2, 1.0], index=[3, 4, 5, 6], name="bar"
        )
        tm.assert_series_equal(result, expected)

        # dtype getting changed?
        df = DataFrame(index=Index(np.arange(1, 11)))
        df["foo"] = np.zeros(10, dtype=np.float64)
        df["bar"] = np.zeros(10, dtype=complex)

        msg = "Must have equal len keys and value when setting with an iterable"
        with pytest.raises(ValueError, match=msg):
            df[2:5] = np.arange(1, 4) * 1j

    @pytest.mark.parametrize("idxr", [getitem, loc, iloc])
    def test_getitem_ndarray_3d(self, index, frame_or_series, idxr):
        # GH 25567
        obj = gen_obj(frame_or_series, index)
        idxr = idxr(obj)
        nd3 = np.random.randint(5, size=(2, 2, 2))

        msg = "|".join(
            [
                r"Buffer has wrong number of dimensions \(expected 1, got 3\)",
                "Cannot index with multidimensional key",
                r"Wrong number of dimensions. values.ndim != ndim \[3 != 1\]",
                "Index data must be 1-dimensional",
                "positional indexers are out-of-bounds",
                "Indexing a MultiIndex with a multidimensional key is not implemented",
            ]
        )

        potential_errors = (IndexError, ValueError, NotImplementedError)
        with pytest.raises(potential_errors, match=msg):
            with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False):
                idxr[nd3]

    @pytest.mark.parametrize("indexer", [setitem, loc, iloc])
    def test_setitem_ndarray_3d(self, index, frame_or_series, indexer):
        # GH 25567
        obj = gen_obj(frame_or_series, index)
        idxr = indexer(obj)
        nd3 = np.random.randint(5, size=(2, 2, 2))

        if indexer.__name__ == "iloc":
            err = ValueError
            msg = f"Cannot set values with ndim > {obj.ndim}"
        elif (
            isinstance(index, pd.IntervalIndex)
            and indexer.__name__ == "setitem"
            and obj.ndim == 1
        ):
            err = AttributeError
            msg = (
                "'pandas._libs.interval.IntervalTree' object has no attribute 'get_loc'"
            )
        else:
            err = ValueError
            msg = r"Buffer has wrong number of dimensions \(expected 1, got 3\)|"

        with pytest.raises(err, match=msg):
            idxr[nd3] = 0

    def test_inf_upcast(self):
        # GH 16957
        # We should be able to use np.inf as a key
        # np.inf should cause an index to convert to float

        # Test with np.inf in rows
        df = DataFrame(columns=[0])
        df.loc[1] = 1
        df.loc[2] = 2
        df.loc[np.inf] = 3

        # make sure we can look up the value
        assert df.loc[np.inf, 0] == 3

        result = df.index
        expected = pd.Float64Index([1, 2, np.inf])
        tm.assert_index_equal(result, expected)

        # Test with np.inf in columns
        df = DataFrame()
        df.loc[0, 0] = 1
        df.loc[1, 1] = 2
        df.loc[0, np.inf] = 3

        result = df.columns
        expected = pd.Float64Index([0, 1, np.inf])
        tm.assert_index_equal(result, expected)

    def test_setitem_dtype_upcast(self):

        # GH3216
        df = DataFrame([{"a": 1}, {"a": 3, "b": 2}])
        df["c"] = np.nan
        assert df["c"].dtype == np.float64

        df.loc[0, "c"] = "foo"
        expected = DataFrame(
            [{"a": 1, "b": np.nan, "c": "foo"}, {"a": 3, "b": 2, "c": np.nan}]
        )
        tm.assert_frame_equal(df, expected)

        # GH10280
        df = DataFrame(
            np.arange(6, dtype="int64").reshape(2, 3),
            index=list("ab"),
            columns=["foo", "bar", "baz"],
        )

        for val in [3.14, "wxyz"]:
            left = df.copy()
            left.loc["a", "bar"] = val
            right = DataFrame(
                [[0, val, 2], [3, 4, 5]],
                index=list("ab"),
                columns=["foo", "bar", "baz"],
            )

            tm.assert_frame_equal(left, right)
            assert is_integer_dtype(left["foo"])
            assert is_integer_dtype(left["baz"])

        left = DataFrame(
            np.arange(6, dtype="int64").reshape(2, 3) / 10.0,
            index=list("ab"),
            columns=["foo", "bar", "baz"],
        )
        left.loc["a", "bar"] = "wxyz"

        right = DataFrame(
            [[0, "wxyz", 0.2], [0.3, 0.4, 0.5]],
            index=list("ab"),
            columns=["foo", "bar", "baz"],
        )

        tm.assert_frame_equal(left, right)
        assert is_float_dtype(left["foo"])
        assert is_float_dtype(left["baz"])

    def test_dups_fancy_indexing(self):

        # GH 3455

        df = tm.makeCustomDataframe(10, 3)
        df.columns = ["a", "a", "b"]
        result = df[["b", "a"]].columns
        expected = Index(["b", "a", "a"])
        tm.assert_index_equal(result, expected)

        # across dtypes
        df = DataFrame([[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]], columns=list("aaaaaaa"))
        df.head()
        str(df)
        result = DataFrame([[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]])
        result.columns = list("aaaaaaa")

        # TODO(wesm): unused?
        df_v = df.iloc[:, 4]  # noqa
        res_v = result.iloc[:, 4]  # noqa

        tm.assert_frame_equal(df, result)

        # GH 3561, dups not in selected order
        df = DataFrame(
            {"test": [5, 7, 9, 11], "test1": [4.0, 5, 6, 7], "other": list("abcd")},
            index=["A", "A", "B", "C"],
        )
        rows = ["C", "B"]
        expected = DataFrame(
            {"test": [11, 9], "test1": [7.0, 6], "other": ["d", "c"]}, index=rows
        )
        result = df.loc[rows]
        tm.assert_frame_equal(result, expected)

        result = df.loc[Index(rows)]
        tm.assert_frame_equal(result, expected)

        rows = ["C", "B", "E"]
        with pytest.raises(KeyError, match="with any missing labels"):
            df.loc[rows]

        # see GH5553, make sure we use the right indexer
        rows = ["F", "G", "H", "C", "B", "E"]
        with pytest.raises(KeyError, match="with any missing labels"):
            df.loc[rows]

        # List containing only missing label
        dfnu = DataFrame(np.random.randn(5, 3), index=list("AABCD"))
        with pytest.raises(
            KeyError,
            match=re.escape(
                "\"None of [Index(['E'], dtype='object')] are in the [index]\""
            ),
        ):
            dfnu.loc[["E"]]

        # ToDo: check_index_type can be True after GH 11497

        # GH 4619; duplicate indexer with missing label
        df = DataFrame({"A": [0, 1, 2]})
        with pytest.raises(KeyError, match="with any missing labels"):
            df.loc[[0, 8, 0]]

        df = DataFrame({"A": list("abc")})
        with pytest.raises(KeyError, match="with any missing labels"):
            df.loc[[0, 8, 0]]

        # non unique with non unique selector
        df = DataFrame({"test": [5, 7, 9, 11]}, index=["A", "A", "B", "C"])
        with pytest.raises(KeyError, match="with any missing labels"):
            df.loc[["A", "A", "E"]]

    def test_dups_fancy_indexing2(self):
        # GH 5835
        # dups on index and missing values
        df = DataFrame(np.random.randn(5, 5), columns=["A", "B", "B", "B", "A"])

        with pytest.raises(KeyError, match="with any missing labels"):
            df.loc[:, ["A", "B", "C"]]

        # GH 6504, multi-axis indexing
        df = DataFrame(
            np.random.randn(9, 2), index=[1, 1, 1, 2, 2, 2, 3, 3, 3], columns=["a", "b"]
        )

        expected = df.iloc[0:6]
        result = df.loc[[1, 2]]
        tm.assert_frame_equal(result, expected)

        expected = df
        result = df.loc[:, ["a", "b"]]
        tm.assert_frame_equal(result, expected)

        expected = df.iloc[0:6, :]
        result = df.loc[[1, 2], ["a", "b"]]
        tm.assert_frame_equal(result, expected)

    @pytest.mark.parametrize("case", [getitem, loc])
    def test_duplicate_int_indexing(self, case):
        # GH 17347
        s = Series(range(3), index=[1, 1, 3])
        expected = s[1]
        result = case(s)[[1]]
        tm.assert_series_equal(result, expected)

    def test_indexing_mixed_frame_bug(self):

        # GH3492
        df = DataFrame(
            {"a": {1: "aaa", 2: "bbb", 3: "ccc"}, "b": {1: 111, 2: 222, 3: 333}}
        )

        # this works, new column is created correctly
        df["test"] = df["a"].apply(lambda x: "_" if x == "aaa" else x)

        # this does not work, ie column test is not changed
        idx = df["test"] == "_"
        temp = df.loc[idx, "a"].apply(lambda x: "-----" if x == "aaa" else x)
        df.loc[idx, "test"] = temp
        assert df.iloc[0, 2] == "-----"

    def test_multitype_list_index_access(self):
        # GH 10610
        df = DataFrame(np.random.random((10, 5)), columns=["a"] + [20, 21, 22, 23])

        with pytest.raises(KeyError, match=re.escape("'[-8, 26] not in index'")):
            df[[22, 26, -8]]
        assert df[21].shape[0] == df.shape[0]

    def test_set_index_nan(self):

        # GH 3586
        df = DataFrame(
            {
                "PRuid": {
                    17: "nonQC",
                    18: "nonQC",
                    19: "nonQC",
                    20: "10",
                    21: "11",
                    22: "12",
                    23: "13",
                    24: "24",
                    25: "35",
                    26: "46",
                    27: "47",
                    28: "48",
                    29: "59",
                    30: "10",
                },
                "QC": {
                    17: 0.0,
                    18: 0.0,
                    19: 0.0,
                    20: np.nan,
                    21: np.nan,
                    22: np.nan,
                    23: np.nan,
                    24: 1.0,
                    25: np.nan,
                    26: np.nan,
                    27: np.nan,
                    28: np.nan,
                    29: np.nan,
                    30: np.nan,
                },
                "data": {
                    17: 7.9544899999999998,
                    18: 8.0142609999999994,
                    19: 7.8591520000000008,
                    20: 0.86140349999999999,
                    21: 0.87853110000000001,
                    22: 0.8427041999999999,
                    23: 0.78587700000000005,
                    24: 0.73062459999999996,
                    25: 0.81668560000000001,
                    26: 0.81927080000000008,
                    27: 0.80705009999999999,
                    28: 0.81440240000000008,
                    29: 0.80140849999999997,
                    30: 0.81307740000000006,
                },
                "year": {
                    17: 2006,
                    18: 2007,
                    19: 2008,
                    20: 1985,
                    21: 1985,
                    22: 1985,
                    23: 1985,
                    24: 1985,
                    25: 1985,
                    26: 1985,
                    27: 1985,
                    28: 1985,
                    29: 1985,
                    30: 1986,
                },
            }
        ).reset_index()

        result = (
            df.set_index(["year", "PRuid", "QC"])
            .reset_index()
            .reindex(columns=df.columns)
        )
        tm.assert_frame_equal(result, df)

    def test_multi_assign(self):

        # GH 3626, an assignment of a sub-df to a df
        df = DataFrame(
            {
                "FC": ["a", "b", "a", "b", "a", "b"],
                "PF": [0, 0, 0, 0, 1, 1],
                "col1": list(range(6)),
                "col2": list(range(6, 12)),
            }
        )
        df.iloc[1, 0] = np.nan
        df2 = df.copy()

        mask = ~df2.FC.isna()
        cols = ["col1", "col2"]

        dft = df2 * 2
        dft.iloc[3, 3] = np.nan

        expected = DataFrame(
            {
                "FC": ["a", np.nan, "a", "b", "a", "b"],
                "PF": [0, 0, 0, 0, 1, 1],
                "col1": Series([0, 1, 4, 6, 8, 10]),
                "col2": [12, 7, 16, np.nan, 20, 22],
            }
        )

        # frame on rhs
        df2.loc[mask, cols] = dft.loc[mask, cols]
        tm.assert_frame_equal(df2, expected)

        df2.loc[mask, cols] = dft.loc[mask, cols]
        tm.assert_frame_equal(df2, expected)

        # with an ndarray on rhs
        # coerces to float64 because values has float64 dtype
        # GH 14001
        expected = DataFrame(
            {
                "FC": ["a", np.nan, "a", "b", "a", "b"],
                "PF": [0, 0, 0, 0, 1, 1],
                "col1": [0.0, 1.0, 4.0, 6.0, 8.0, 10.0],
                "col2": [12, 7, 16, np.nan, 20, 22],
            }
        )
        df2 = df.copy()
        df2.loc[mask, cols] = dft.loc[mask, cols].values
        tm.assert_frame_equal(df2, expected)
        df2.loc[mask, cols] = dft.loc[mask, cols].values
        tm.assert_frame_equal(df2, expected)

        # broadcasting on the rhs is required
        df = DataFrame(
            {
                "A": [1, 2, 0, 0, 0],
                "B": [0, 0, 0, 10, 11],
                "C": [0, 0, 0, 10, 11],
                "D": [3, 4, 5, 6, 7],
            }
        )

        expected = df.copy()
        mask = expected["A"] == 0
        for col in ["A", "B"]:
            expected.loc[mask, col] = df["D"]

        df.loc[df["A"] == 0, ["A", "B"]] = df["D"]
        tm.assert_frame_equal(df, expected)

    def test_setitem_list(self):

        # GH 6043
        # iloc with a list
        df = DataFrame(index=[0, 1], columns=[0])
        df.iloc[1, 0] = [1, 2, 3]
        df.iloc[1, 0] = [1, 2]

        result = DataFrame(index=[0, 1], columns=[0])
        result.iloc[1, 0] = [1, 2]

        tm.assert_frame_equal(result, df)

        # iloc with an object
        class TO:
            def __init__(self, value):
                self.value = value

            def __str__(self) -> str:
                return f"[{self.value}]"

            __repr__ = __str__

            def __eq__(self, other) -> bool:
                return self.value == other.value

            def view(self):
                return self

        df = DataFrame(index=[0, 1], columns=[0])
        df.iloc[1, 0] = TO(1)
        df.iloc[1, 0] = TO(2)

        result = DataFrame(index=[0, 1], columns=[0])
        result.iloc[1, 0] = TO(2)

        tm.assert_frame_equal(result, df)

        # remains object dtype even after setting it back
        df = DataFrame(index=[0, 1], columns=[0])
        df.iloc[1, 0] = TO(1)
        df.iloc[1, 0] = np.nan
        result = DataFrame(index=[0, 1], columns=[0])

        tm.assert_frame_equal(result, df)

    def test_string_slice(self):
        # GH 14424
        # string indexing against datetimelike with object
        # dtype should properly raises KeyError
        df = DataFrame([1], Index([pd.Timestamp("2011-01-01")], dtype=object))
        assert df.index._is_all_dates
        with pytest.raises(KeyError, match="'2011'"):
            df["2011"]

        with pytest.raises(KeyError, match="'2011'"):
            df.loc["2011", 0]

        df = DataFrame()
        assert not df.index._is_all_dates
        with pytest.raises(KeyError, match="'2011'"):
            df["2011"]

        with pytest.raises(KeyError, match="'2011'"):
            df.loc["2011", 0]

    def test_astype_assignment(self):

        # GH4312 (iloc)
        df_orig = DataFrame(
            [["1", "2", "3", ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG")
        )

        df = df_orig.copy()
        df.iloc[:, 0:2] = df.iloc[:, 0:2].astype(np.int64)
        expected = DataFrame(
            [[1, 2, "3", ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG")
        )
        tm.assert_frame_equal(df, expected)

        df = df_orig.copy()
        df.iloc[:, 0:2] = df.iloc[:, 0:2]._convert(datetime=True, numeric=True)
        expected = DataFrame(
            [[1, 2, "3", ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG")
        )
        tm.assert_frame_equal(df, expected)

        # GH5702 (loc)
        df = df_orig.copy()
        df.loc[:, "A"] = df.loc[:, "A"].astype(np.int64)
        expected = DataFrame(
            [[1, "2", "3", ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG")
        )
        tm.assert_frame_equal(df, expected)

        df = df_orig.copy()
        df.loc[:, ["B", "C"]] = df.loc[:, ["B", "C"]].astype(np.int64)
        expected = DataFrame(
            [["1", 2, 3, ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG")
        )
        tm.assert_frame_equal(df, expected)

        # full replacements / no nans
        df = DataFrame({"A": [1.0, 2.0, 3.0, 4.0]})
        df.iloc[:, 0] = df["A"].astype(np.int64)
        expected = DataFrame({"A": [1, 2, 3, 4]})
        tm.assert_frame_equal(df, expected)

        df = DataFrame({"A": [1.0, 2.0, 3.0, 4.0]})
        df.loc[:, "A"] = df["A"].astype(np.int64)
        expected = DataFrame({"A": [1, 2, 3, 4]})
        tm.assert_frame_equal(df, expected)

    @pytest.mark.parametrize("indexer", [getitem, loc])
    def test_index_type_coercion(self, indexer):

        # GH 11836
        # if we have an index type and set it with something that looks
        # to numpy like the same, but is actually, not
        # (e.g. setting with a float or string '0')
        # then we need to coerce to object

        # integer indexes
        for s in [Series(range(5)), Series(range(5), index=range(1, 6))]:

            assert s.index.is_integer()

            s2 = s.copy()
            indexer(s2)[0.1] = 0
            assert s2.index.is_floating()
            assert indexer(s2)[0.1] == 0

            s2 = s.copy()
            indexer(s2)[0.0] = 0
            exp = s.index
            if 0 not in s:
                exp = Index(s.index.tolist() + [0])
            tm.assert_index_equal(s2.index, exp)

            s2 = s.copy()
            indexer(s2)["0"] = 0
            assert s2.index.is_object()

        for s in [Series(range(5), index=np.arange(5.0))]:

            assert s.index.is_floating()

            s2 = s.copy()
            indexer(s2)[0.1] = 0
            assert s2.index.is_floating()
            assert indexer(s2)[0.1] == 0

            s2 = s.copy()
            indexer(s2)[0.0] = 0
            tm.assert_index_equal(s2.index, s.index)

            s2 = s.copy()
            indexer(s2)["0"] = 0
            assert s2.index.is_object()

class TestMisc:
    def test_float_index_to_mixed(self):
        df = DataFrame({0.0: np.random.rand(10), 1.0: np.random.rand(10)})
        df["a"] = 10
        tm.assert_frame_equal(
            DataFrame({0.0: df[0.0], 1.0: df[1.0], "a": [10] * 10}), df
        )

    def test_float_index_non_scalar_assignment(self):
        df = DataFrame({"a": [1, 2, 3], "b": [3, 4, 5]}, index=[1.0, 2.0, 3.0])
        df.loc[df.index[:2]] = 1
        expected = DataFrame({"a": [1, 1, 3], "b": [1, 1, 5]}, index=df.index)
        tm.assert_frame_equal(expected, df)

        df = DataFrame({"a": [1, 2, 3], "b": [3, 4, 5]}, index=[1.0, 2.0, 3.0])
        df2 = df.copy()
        df.loc[df.index] = df.loc[df.index]
        tm.assert_frame_equal(df, df2)

    def test_float_index_at_iat(self):
        s = Series([1, 2, 3], index=[0.1, 0.2, 0.3])
        for el, item in s.items():
            assert s.at[el] == item
        for i in range(len(s)):
            assert s.iat[i] == i + 1

    def test_rhs_alignment(self):
        # GH8258, tests that both rows & columns are aligned to what is
        # assigned to. covers both uniform data-type & multi-type cases
        def run_tests(df, rhs, right_loc, right_iloc):
            # label, index, slice
            lbl_one, idx_one, slice_one = list("bcd"), [1, 2, 3], slice(1, 4)
            lbl_two, idx_two, slice_two = ["joe", "jolie"], [1, 2], slice(1, 3)

            left = df.copy()
            left.loc[lbl_one, lbl_two] = rhs
            tm.assert_frame_equal(left, right_loc)

            left = df.copy()
            left.iloc[idx_one, idx_two] = rhs
            tm.assert_frame_equal(left, right_iloc)

            left = df.copy()
            left.iloc[slice_one, slice_two] = rhs
            tm.assert_frame_equal(left, right_iloc)

        xs = np.arange(20).reshape(5, 4)
        cols = ["jim", "joe", "jolie", "joline"]
        df = DataFrame(xs, columns=cols, index=list("abcde"), dtype="int64")

        # right hand side; permute the indices and multiplpy by -2
        rhs = -2 * df.iloc[3:0:-1, 2:0:-1]

        # expected `right` result; just multiply by -2
        right_iloc = df.copy()
        right_iloc["joe"] = [1, 14, 10, 6, 17]
        right_iloc["jolie"] = [2, 13, 9, 5, 18]
        right_iloc.iloc[1:4, 1:3] *= -2
        right_loc = df.copy()
        right_loc.iloc[1:4, 1:3] *= -2

        # run tests with uniform dtypes
        run_tests(df, rhs, right_loc, right_iloc)

        # make frames multi-type & re-run tests
        for frame in [df, rhs, right_loc, right_iloc]:
            frame["joe"] = frame["joe"].astype("float64")
            frame["jolie"] = frame["jolie"].map("@{}".format)
        right_iloc["joe"] = [1.0, "@-28", "@-20", "@-12", 17.0]
        right_iloc["jolie"] = ["@2", -26.0, -18.0, -10.0, "@18"]
        run_tests(df, rhs, right_loc, right_iloc)

    def test_str_label_slicing_with_negative_step(self):
        SLC = pd.IndexSlice

        def assert_slices_equivalent(l_slc, i_slc):
            tm.assert_series_equal(s.loc[l_slc], s.iloc[i_slc])

            if not idx.is_integer:
                # For integer indices, .loc and plain getitem are position-based.
                tm.assert_series_equal(s[l_slc], s.iloc[i_slc])
                tm.assert_series_equal(s.loc[l_slc], s.iloc[i_slc])

        for idx in [_mklbl("A", 20), np.arange(20) + 100, np.linspace(100, 150, 20)]:
            idx = Index(idx)
            s = Series(np.arange(20), index=idx)
            assert_slices_equivalent(SLC[idx[9] :: -1], SLC[9::-1])
            assert_slices_equivalent(SLC[: idx[9] : -1], SLC[:8:-1])
            assert_slices_equivalent(SLC[idx[13] : idx[9] : -1], SLC[13:8:-1])
            assert_slices_equivalent(SLC[idx[9] : idx[13] : -1], SLC[:0])

    def test_slice_with_zero_step_raises(self):
        s = Series(np.arange(20), index=_mklbl("A", 20))
        with pytest.raises(ValueError, match="slice step cannot be zero"):
            s[::0]
        with pytest.raises(ValueError, match="slice step cannot be zero"):
            s.loc[::0]

    def test_indexing_assignment_dict_already_exists(self):
        df = DataFrame({"x": [1, 2, 6], "y": [2, 2, 8], "z": [-5, 0, 5]}).set_index("z")
        expected = df.copy()
        rhs = {"x": 9, "y": 99}
        df.loc[5] = rhs
        expected.loc[5] = [9, 99]
        tm.assert_frame_equal(df, expected)

    def test_indexing_dtypes_on_empty(self):
        # Check that .iloc returns correct dtypes GH9983
        df = DataFrame({"a": [1, 2, 3], "b": ["b", "b2", "b3"]})
        df2 = df.iloc[[], :]

        assert df2.loc[:, "a"].dtype == np.int64
        tm.assert_series_equal(df2.loc[:, "a"], df2.iloc[:, 0])

    @pytest.mark.parametrize("size", [5, 999999, 1000000])
    def test_range_in_series_indexing(self, size):
        # range can cause an indexing error
        # GH 11652
        s = Series(index=range(size), dtype=np.float64)
        s.loc[range(1)] = 42
        tm.assert_series_equal(s.loc[range(1)], Series(42.0, index=[0]))

        s.loc[range(2)] = 43
        tm.assert_series_equal(s.loc[range(2)], Series(43.0, index=[0, 1]))

    @pytest.mark.parametrize(
        "slc",
        [
            pd.IndexSlice[:, :],
            pd.IndexSlice[:, 1],
            pd.IndexSlice[1, :],
            pd.IndexSlice[[1], [1]],
            pd.IndexSlice[1, [1]],
            pd.IndexSlice[[1], 1],
            pd.IndexSlice[1],
            pd.IndexSlice[1, 1],
            slice(None, None, None),
            [0, 1],
            np.array([0, 1]),
            Series([0, 1]),
        ],
    )
    def test_non_reducing_slice(self, slc):
        df = DataFrame([[0, 1], [2, 3]])

        tslice_ = non_reducing_slice(slc)
        assert isinstance(df.loc[tslice_], DataFrame)

    def test_list_slice(self):
        # like dataframe getitem
        slices = [["A"], Series(["A"]), np.array(["A"])]
        df = DataFrame({"A": [1, 2], "B": [3, 4]}, index=["A", "B"])
        expected = pd.IndexSlice[:, ["A"]]
        for subset in slices:
            result = non_reducing_slice(subset)
            tm.assert_frame_equal(df.loc[result], df.loc[expected])

    def test_maybe_numeric_slice(self):
        df = DataFrame({"A": [1, 2], "B": ["c", "d"], "C": [True, False]})
        result = maybe_numeric_slice(df, slice_=None)
        expected = pd.IndexSlice[:, ["A"]]
        assert result == expected

        result = maybe_numeric_slice(df, None, include_bool=True)
        expected = pd.IndexSlice[:, ["A", "C"]]
        assert all(result[1] == expected[1])
        result = maybe_numeric_slice(df, [1])
        expected = [1]
        assert result == expected

    def test_partial_boolean_frame_indexing(self):
        # GH 17170
        df = DataFrame(
            np.arange(9.0).reshape(3, 3), index=list("abc"), columns=list("ABC")
        )
        index_df = DataFrame(1, index=list("ab"), columns=list("AB"))
        result = df[index_df.notnull()]
        expected = DataFrame(
            np.array([[0.0, 1.0, np.nan], [3.0, 4.0, np.nan], [np.nan] * 3]),
            index=list("abc"),
            columns=list("ABC"),
        )
        tm.assert_frame_equal(result, expected)

    def test_no_reference_cycle(self):
        df = DataFrame({"a": [0, 1], "b": [2, 3]})
        for name in ("loc", "iloc", "at", "iat"):
            getattr(df, name)
        wr = weakref.ref(df)
        del df
        assert wr() is None

    def test_label_indexing_on_nan(self):
        # GH 32431
        df = Series([1, "{1,2}", 1, None])
        vc = df.value_counts(dropna=False)
        result1 = vc.loc[np.nan]
        result2 = vc[np.nan]

        expected = 1
        assert result1 == expected
        assert result2 == expected

class TestSeriesNoneCoercion:
    EXPECTED_RESULTS = [
        # For numeric series, we should coerce to NaN.
        ([1, 2, 3], [np.nan, 2, 3]),
        ([1.0, 2.0, 3.0], [np.nan, 2.0, 3.0]),
        # For datetime series, we should coerce to NaT.
        (
            [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],
            [NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)],
        ),
        # For objects, we should preserve the None value.
        (["foo", "bar", "baz"], [None, "bar", "baz"]),
    ]

    @pytest.mark.parametrize("start_data,expected_result", EXPECTED_RESULTS)
    def test_coercion_with_setitem(self, start_data, expected_result):
        start_series = Series(start_data)
        start_series[0] = None

        expected_series = Series(expected_result)
        tm.assert_series_equal(start_series, expected_series)

    @pytest.mark.parametrize("start_data,expected_result", EXPECTED_RESULTS)
    def test_coercion_with_loc_setitem(self, start_data, expected_result):
        start_series = Series(start_data)
        start_series.loc[0] = None

        expected_series = Series(expected_result)
        tm.assert_series_equal(start_series, expected_series)

    @pytest.mark.parametrize("start_data,expected_result", EXPECTED_RESULTS)
    def test_coercion_with_setitem_and_series(self, start_data, expected_result):
        start_series = Series(start_data)
        start_series[start_series == start_series[0]] = None

        expected_series = Series(expected_result)
        tm.assert_series_equal(start_series, expected_series)

    @pytest.mark.parametrize("start_data,expected_result", EXPECTED_RESULTS)
    def test_coercion_with_loc_and_series(self, start_data, expected_result):
        start_series = Series(start_data)
        start_series.loc[start_series == start_series[0]] = None

        expected_series = Series(expected_result)
        tm.assert_series_equal(start_series, expected_series)

class TestDataframeNoneCoercion:
    EXPECTED_SINGLE_ROW_RESULTS = [
        # For numeric series, we should coerce to NaN.
        ([1, 2, 3], [np.nan, 2, 3]),
        ([1.0, 2.0, 3.0], [np.nan, 2.0, 3.0]),
        # For datetime series, we should coerce to NaT.
        (
            [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],
            [NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)],
        ),
        # For objects, we should preserve the None value.
        (["foo", "bar", "baz"], [None, "bar", "baz"]),
    ]

    @pytest.mark.parametrize("expected", EXPECTED_SINGLE_ROW_RESULTS)
    def test_coercion_with_loc(self, expected):
        start_data, expected_result = expected

        start_dataframe = DataFrame({"foo": start_data})
        start_dataframe.loc[0, ["foo"]] = None

        expected_dataframe = DataFrame({"foo": expected_result})
        tm.assert_frame_equal(start_dataframe, expected_dataframe)

    @pytest.mark.parametrize("expected", EXPECTED_SINGLE_ROW_RESULTS)
    def test_coercion_with_setitem_and_dataframe(self, expected):
        start_data, expected_result = expected

        start_dataframe = DataFrame({"foo": start_data})
        start_dataframe[start_dataframe["foo"] == start_dataframe["foo"][0]] = None

        expected_dataframe = DataFrame({"foo": expected_result})
        tm.assert_frame_equal(start_dataframe, expected_dataframe)

    @pytest.mark.parametrize("expected", EXPECTED_SINGLE_ROW_RESULTS)
    def test_none_coercion_loc_and_dataframe(self, expected):
        start_data, expected_result = expected

        start_dataframe = DataFrame({"foo": start_data})
        start_dataframe.loc[start_dataframe["foo"] == start_dataframe["foo"][0]] = None

        expected_dataframe = DataFrame({"foo": expected_result})
        tm.assert_frame_equal(start_dataframe, expected_dataframe)

    def test_none_coercion_mixed_dtypes(self):
        start_dataframe = DataFrame(
            {
                "a": [1, 2, 3],
                "b": [1.0, 2.0, 3.0],
                "c": [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],
                "d": ["a", "b", "c"],
            }
        )
        start_dataframe.iloc[0] = None

        exp = DataFrame(
            {
                "a": [np.nan, 2, 3],
                "b": [np.nan, 2.0, 3.0],
                "c": [NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)],
                "d": [None, "b", "c"],
            }
        )
        tm.assert_frame_equal(start_dataframe, exp)

def test_extension_array_cross_section():
    # A cross-section of a homogeneous EA should be an EA
    df = DataFrame(
        {
            "A": pd.core.arrays.integer_array([1, 2]),
            "B": pd.core.arrays.integer_array([3, 4]),
        },
        index=["a", "b"],
    )
    expected = Series(pd.core.arrays.integer_array([1, 3]), index=["A", "B"], name="a")
    result = df.loc["a"]
    tm.assert_series_equal(result, expected)

    result = df.iloc[0]
    tm.assert_series_equal(result, expected)

def test_extension_array_cross_section_converts():
    # all numeric columns -> numeric series
    df = DataFrame(
        {"A": pd.array([1, 2], dtype="Int64"), "B": np.array([1, 2])}, index=["a", "b"]
    )
    result = df.loc["a"]
    expected = Series([1, 1], dtype="Int64", index=["A", "B"], name="a")
    tm.assert_series_equal(result, expected)

    result = df.iloc[0]
    tm.assert_series_equal(result, expected)

    # mixed columns -> object series
    df = DataFrame(
        {"A": pd.array([1, 2], dtype="Int64"), "B": np.array(["a", "b"])},
        index=["a", "b"],
    )
    result = df.loc["a"]
    expected = Series([1, "a"], dtype=object, index=["A", "B"], name="a")
    tm.assert_series_equal(result, expected)

    result = df.iloc[0]
    tm.assert_series_equal(result, expected)

def test_setitem_with_bool_mask_and_values_matching_n_trues_in_length():
    # GH 30567
    ser = Series([None] * 10)
    mask = [False] * 3 + [True] * 5 + [False] * 2
    ser[mask] = range(5)
    result = ser
    expected = Series([None] * 3 + list(range(5)) + [None] * 2).astype("object")
    tm.assert_series_equal(result, expected)

def test_missing_labels_inside_loc_matched_in_error_message():
    # GH34272
    s = Series({"a": 1, "b": 2, "c": 3})
    error_message_regex = "missing_0.*missing_1.*missing_2"
    with pytest.raises(KeyError, match=error_message_regex):
        s.loc[["a", "b", "missing_0", "c", "missing_1", "missing_2"]]

def test_many_missing_labels_inside_loc_error_message_limited():
    # GH34272
    n = 10000
    missing_labels = [f"missing_{label}" for label in range(n)]
    s = Series({"a": 1, "b": 2, "c": 3})
    # regex checks labels between 4 and 9995 are replaced with ellipses
    error_message_regex = "missing_4.*\\.\\.\\..*missing_9995"
    with pytest.raises(KeyError, match=error_message_regex):
        s.loc[["a", "c"] + missing_labels]

def test_long_text_missing_labels_inside_loc_error_message_limited():
    # GH34272
    s = Series({"a": 1, "b": 2, "c": 3})
    missing_labels = [f"long_missing_label_text_{i}" * 5 for i in range(3)]
    # regex checks for very long labels there are new lines between each
    error_message_regex = "long_missing_label_text_0.*\\\\n.*long_missing_label_text_1"
    with pytest.raises(KeyError, match=error_message_regex):
        s.loc[["a", "c"] + missing_labels]

def test_setitem_categorical():
    # https://github.com/pandas-dev/pandas/issues/35369
    df = DataFrame({"h": Series(list("mn")).astype("category")})
    df.h = df.h.cat.reorder_categories(["n", "m"])
    expected = DataFrame(
        {"h": pd.Categorical(["m", "n"]).reorder_categories(["n", "m"])}
    )
    tm.assert_frame_equal(df, expected)


# Faça um algoritmo que leia o preço de um produto e mostre seu
# novo preço, com 5% de desconto.

produto = float(input('Insira o valor do produto: '))

desconto = produto * 0.05
precoFinal = produto - desconto

print('O preço do produto normal é: {} Reais'.format(produto))
print('O preço com desconto de 5% é: {} Reais'.format(precoFinal))


from unittest.mock import MagicMock
import sys

sys.modules["materializationengine.chunkedgraph_gateway"] = MagicMock()
from materializationengine.workflows.update_root_ids import (
    get_expired_root_ids_from_pcg,
    get_new_root_ids,
    get_supervoxel_id_queries,
)
import logging

mocked_expired_root_id_data = [
    [20000000, 20000001],
    [20000002, 20000003],
    [20000004, 20000005],
    [20000006, 20000007],
    [20000008, 20000009],
]

mocked_supervoxel_chunks = [
    {
        "post_pt_supervoxel_id": 10000000,
        "pre_pt_supervoxel_id": 10000000,
        "id": 1,
        "post_pt_root_id": 20000000,
        "pre_pt_root_id": 20000000,
    },
    {
        "post_pt_supervoxel_id": 10000000,
        "pre_pt_supervoxel_id": 10000000,
        "id": 2,
        "post_pt_root_id": 20000000,
        "pre_pt_root_id": 20000000,
    },
    {
        "post_pt_supervoxel_id": 10000000,
        "pre_pt_supervoxel_id": 10000000,
        "id": 3,
        "post_pt_root_id": 20000000,
        "pre_pt_root_id": 20000000,
    },
]

class TestUpdateRootIds:
    def test_get_expired_root_ids(self, monkeypatch, mat_metadata):
        def mock_lookup_expire_root_ids(*args, **kwargs):
            return list(range(20000000, 20000010))

        monkeypatch.setattr(
            "materializationengine.workflows.update_root_ids.lookup_expired_root_ids",
            mock_lookup_expire_root_ids,
        )
        expired_root_ids = get_expired_root_ids_from_pcg(mat_metadata, 2)
        index = 0
        for root_id in expired_root_ids:
            logging.info(root_id)
            assert root_id == mocked_expired_root_id_data[index]
            index += 1

    def test_get_supervoxel_ids(self, annotation_data, mat_metadata):
        expired_roots = annotation_data["expired_root_ids"]

        supervoxel_ids = get_supervoxel_id_queries(expired_roots, mat_metadata)
        logging.info(supervoxel_ids)
        assert supervoxel_ids == [
            {
                "pre_pt_root_id": "SELECT test_synapse_table__test_pcg.id, test_synapse_table__test_pcg.pre_pt_root_id, test_synapse_table__test_pcg.pre_pt_supervoxel_id \n"
                "FROM test_synapse_table__test_pcg \n"
                "WHERE test_synapse_table__test_pcg.pre_pt_root_id IN (10000000000000000, 40000000000000000, 50000000000000000) OR test_synapse_table__test_pcg.pre_pt_root_id IS NULL"
            },
            {
                "post_pt_root_id": "SELECT test_synapse_table__test_pcg.id, test_synapse_table__test_pcg.post_pt_root_id, test_synapse_table__test_pcg.post_pt_supervoxel_id \n"
                "FROM test_synapse_table__test_pcg \n"
                "WHERE test_synapse_table__test_pcg.post_pt_root_id IN (10000000000000000, 40000000000000000, 50000000000000000) OR test_synapse_table__test_pcg.post_pt_root_id IS NULL"
            },
        ]

    def test_get_new_roots(self, monkeypatch, mat_metadata, annotation_data):
        def mock_lookup_new_root_ids(*args, **kwargs):
            return annotation_data["new_root_ids"]

        monkeypatch.setattr(
            "materializationengine.workflows.update_root_ids.lookup_new_root_ids",
            mock_lookup_new_root_ids,
        )

        supervoxel_chunk = annotation_data["segmentation_data"]
        new_roots = get_new_root_ids.s(supervoxel_chunk, mat_metadata).apply()
        assert new_roots.get() == "Number of rows updated: 3"


# -*- coding: utf-8 -*-
"""
This PyQt5 Audio Conveter Tools (brianlu0703)
Vesion 02
Example: WAV file to MP3 file

Created on Mon Aug 26 10:52:58 2019

@author: Brian Lu
"""
"""Fixed QT import error only (pyinstaller)"""
#import fix_qt_import_error

import sys, os, time
from PyQt5.QtWidgets import QApplication, QFileDialog, QComboBox
from PyQt5.QtWidgets import QLabel, QTextEdit, QPushButton, QMainWindow, QAction, QProgressBar, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QBasicTimer
from pydub import AudioSegment

files    = []
wavfiles = []
mp3files = []
curdir = ""
combo_act = "WAV to MP3"
audio_dic = { "WAV to MP3": ["wav","mp3"], "MP3 to WAV": ["mp3","wav"]}
src_audio = "wav"
des_audio = "mp3"
helpmsgtitle = "About audio conveter tool"

class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'This PyQt5 Audio Conveter Tools v02'
        self.left = 100
        self.top = 100
        self.width = 640
        self.height = 480
        self.initUI()

    def initUI(self):
        global os_platform

        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('File')
        helpMenu = mainMenu.addMenu('Help')

        newAct = QAction('New', self)
        newAct.setShortcut('Ctrl+N')
        newAct.setStatusTip('New Files')
        newAct.triggered.connect(self.toggle_menu)

        exitButton = QAction(QIcon('exit.png'), 'Exit', self)
        exitButton.setShortcut('Ctrl+Q')
        exitButton.setStatusTip('Exit application')
        exitButton.triggered.connect(self.close)

        fileMenu.addAction(newAct)
        fileMenu.addAction(exitButton)

        readAct = QAction('About', self)
        readAct.setStatusTip('About ths application')
        readAct.triggered.connect(self.toggle_help_menu)
        helpMenu.addAction(readAct)

        # Create textbox
        self.textbox = QTextEdit(self)
        self.textbox.move(10, 70)
        self.textbox.resize(300,360)

        self.textbox_view = QTextEdit(self)
        self.textbox_view.move(320, 70)
        self.textbox_view.resize(300,360)

        self.label = QLabel('The Audio Source Files', self)
        self.label.resize(250,32)
        self.label.move(10,40)

        self.label2 = QLabel('The Audio Destination Files', self)
        self.label2.resize(250,32)
        self.label2.move(320,40)

        self.label3 = QLabel('Convert Files:', self)
        self.label3.resize(125,30)
        self.label3.move(10,440)

        self.combo = QComboBox(self)
        combo_list = ["WAV to MP3", "MP3 to WAV"]

        for cl in combo_list:
            self.combo.addItem(cl)

        self.combo.resize(150,30)
        self.combo.move(130, 440)
        self.combo.activated[str].connect(self.onChanged) #Signal

        # Create Convert Button
        self.button = QPushButton("RUN", self)
        self.button.resize(100,30)
        self.button.move(320,440)
        self.button.clicked.connect(self.on_click)

        #self.button = QPushButton("Stop", self)
        #self.button.resize(80,32)
        #self.button.move(330,440)
        #self.button.clicked.connect(self.on_click)

        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(430, 440, 200, 30)

        self.step = 0
        self.timer = QBasicTimer()

        self.show_select_files()
        self.show()

    def timerEvent(self, e):
        if self.step >= 100:
            self.timer.stop()
            self.step = 0
            return

        self.step = self.step + 1
        self.pbar.setValue(self.step)

    def onChanged(self, text):
        global combo_act
        global src_audio
        global des_audio

        self.textbox_view.setText("")
        self.timer.stop()
        self.step = 0
        self.pbar.setValue(0)

        #self.textbox_view.setText(text)
        combo_act = text
        #self.textbox_view.setText(combo_act)

        if combo_act in audio_dic:
            src_audio = audio_dic[combo_act][0]
            des_audio = audio_dic[combo_act][1]
            #for k in audio_dic[combo_act]:
            #    self.textbox_view.append(k+"\n")
            #self.textbox_view.setText(src_audio + des_audio)

    def toggle_help_menu(self):
        QMessageBox.about(self, helpmsgtitle, "This tool is convert any audio files")

    def toggle_menu(self):
        global files
        global wavfiles
        global curdir
        files    = []
        wavfiles = []
        curdir = ""

        self.openFileNamesDialog()
        self.show_select_files()

        self.textbox_view.setText("")
        self.timer.stop()
        self.step = 0
        self.pbar.setValue(0)

    def openFileNamesDialog(self):
        global files
        global curdir
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        files, _ = QFileDialog.getOpenFileNames(self,"Select all audio files", "","All Files (*);;Python Files (*.py)", options=options)

        #Check current open dir
        for f in files:
            if sys.platform == "win32":
                tmp = f.split("/")
            else:
                tmp = f.split("/")

            n = len(tmp)
            fs = len(tmp[n-1])
            curdir = f[:-fs]
            #self.textbox_view.append(curdir+"\n")
            print("Current dir is " + curdir)
            break

    def show_select_files(self):
        global files
        global wavfiles

        #textboxValue = self.textbox.text()
        msgs = ""
        self.textbox.setText(msgs)

        for msg in files:
            if sys.platform == "win32":
                tmp = msg.split("/")
            else:
                tmp = msg.split("/")

            n = len(tmp)
            msgs += tmp[n-1] + "\n"
            wavfiles.append(tmp[n-1])

        self.textbox.setText(msgs)

    def on_click(self):
        print("button clicked, clear the view textbox")
        self.textbox_view.setText("")
        self.convert_audio()

    def convert_audio(self):
        global files
        global wavfiles
        global curdir
        global combo_act
        global src_audio
        global des_audio

        try:

            #if not self.timer.isActive():
            #self.timer.start(100, self)
            #self.pbar.setMinimum(0)
            #self.pbar.setMaximum(0)

            if sys.platform == "win32":
                filedir = os.getcwd() + "\convert_" + des_audio
            else:
                filedir = os.getcwd() + "/convert_" + des_audio

            if not os.path.exists(filedir):
                os.makedirs(filedir)

            total = len(wavfiles)

            for i, fn in enumerate(wavfiles):

                #if fn.endswith('.wav') or fn.endswith('.WAV'):
                if fn.endswith('.'+src_audio) or fn.endswith('.'+src_audio.upper()):
                    # check system platform add appropriate file path
                    if sys.platform == "win32":
                        newpath = "\\"
                    else:
                        newpath = "/"

                    src = curdir  + fn[:-4] + "." + src_audio
                    dst = filedir + newpath + fn[:-4] + "." + des_audio

                    print("convert from {0} to {1}".format(src,dst))

                    if os.path.isfile(dst):
                        #print("Found {} audio file and deleted it".format(dst))
                        os.remove(dst)

                    # convert wav to mp3
                    if  src_audio == "wav":
                        sound = AudioSegment.from_wav(src)
                    elif src_audio == "mp3":
                        sound = AudioSegment.from_mp3(src)

                    sound.export(dst, format=des_audio)
                    self.textbox_view.append(dst[len(filedir)+1:])

                    #Update progress bar after converted
                    #Due to QT Basictimer event can't increas step value while converting file
                    self.pbar.setValue(i/total*100)
                    time.sleep(0.2)

            self.pbar.setValue(100)
        except:
            print("convert audio {} to {} file error".format(src_audio,des_audio))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())


conversion_dict = {"MPH": 1.60934, "KPH": 0.621371, "KM": 0.621371,
"MI": 1.60934, "Wh_km": 0.1, "Wh_mi": 0.0621371, "CM": 0.393701, "INCH": 2.54}

def executer(value, original, desired):
    resulting_value_and_unit = main_converter(value, original, desired)
    return resulting_value_and_unit

def main_converter(value, original, desired):
    if original == "WH":
        resultkm = float(value) * conversion_dict["Wh_km"]
        resultmi = float(value) * conversion_dict["Wh_mi"]
        printthis = "{0:.2f} watt hours should get you: ".format(float(value)) + "{0:.2f}KM or ".format(resultkm) + "{0:.2f}MI".format(resultmi)
    else:
        result = float(value) * conversion_dict[original]
        printthis = "{0:.2f}".format(result) + desired
    return printthis


# -*- coding: utf-8 -*-
from django.conf.urls import url

from .views import VerificarSi, VerificarNo, AgregarFacebookCandidato, ScrapeElectionView

urlpatterns = [
    url(r'^verificar_si/(?P<pk>\d+)/$',
        VerificarSi.as_view(),
        name='verificar_si'),
    url(r'^verificar_no/(?P<pk>\d+)/$',
        VerificarNo.as_view(),
        name='verificar_no'),
    url(r'^agregar_facebook_a_candidato/(?P<pk>[-\w]+)/$',
        AgregarFacebookCandidato.as_view(),
        name='agregar_facebook_a_candidato'),
    url(r'^scrape_election/(?P<slug>[-\w]+)/$',
        ScrapeElectionView.as_view(),
        name='scrape_election'),
]


def solution(s):
    change = ""
    for i in range(len(s)):

        if i == len(s)-1:
            change += s[i]
        elif (s[i+1].isdigit() == True or s[i+1].isalpha() == True) and s[i] == " ":
            change += "*"
        else:
            change += s[i]
    print(change)
    array = list(change.split("*"))
    print(array)
    answer = []
    for x in array:
        x = x.lower()
        star_count = x.count("*")
        x = x.replace("*", " ")
        if x[star_count].isdigit() == True:
            pass
        else:
            x = x[:star_count] + x[star_count].upper() + x[star_count+1:]

        answer.append(x)

    print(' '.join(answer))
    return ' '.join(answer)

프로그래머스/lv2/12951. JadenCase 문자열 만들기/JadenCase 문자열 만들기.py


import yfinance as yf
import pandas as pd

tickers = ["SPY"]

for stock in tickers:
  df = yf.Ticker(stock).history(period="max", interval = '1d')

  # Simple Moving average
  MA200 = df['Close'].rolling(200).mean()
  MA50 = df['Close'].rolling(50).mean()

  # Exponential Moving Average
  MA200_expo = df['Close'].ewm(span=200, adjust=False).mean()
  MA50_expo = df['Close'].ewm(span=50, adjust=False).mean()

  # Average True Range
  tr1 = df["High"] - df["Low"]
  tr2 = df["High"] - df["Close"].shift()
  tr3 = df["Low"] - df["Close"].shift()
  tr = pd.concat([tr1, tr2, tr3], axis = 1, join = 'inner').max(axis = 1)
  atr = tr.rolling(14).mean()

  # Relative Strength Index
  delta = df['Close'].diff()
  up = delta.clip(lower=0)
  down = -1*delta.clip(upper=0)
  ema_up = up.ewm(com=13, adjust=False).mean()
  ema_down = down.ewm(com=13, adjust=False).mean()
  rs = ema_up/ema_down
  RSI1 = 100 - (100/(1 + rs))

  # Moving Average Convergence / Divergence
  k = df.ewm(span=20, adjust=False, min_periods=20).mean()
  d = df.ewm(span=70, adjust=False, min_periods=70).mean()
  macd1 = k - d
  trigger_price = macd1.ewm(span=15, adjust=False, min_periods=15).mean()

  # Keltner Channels (Uses ATR)
  kc_middle = df['Close'].ewm(span=19).mean()
  kc_upper = kc_middle + 1.5 * atr
  kc_lower = kc_middle - 1.5 * atr

  # Volume Weighted Average Price
  v = df['Volume']
  tp = (df['Low'] + df['Close'] + df['High'])/3
  vwap = df.assign(vwap=((tp * v).cumsum()) / v.cumsum())

  # Anchored Volume Weighted Average Price
  anch_v = df['Volume']
  anch_tp = (df['Low'] + df['Close'] + df['High'])/3
  anch_vwap = df.assign(vwap=((anch_tp * anch_v).rolling(90).sum()) / anch_v.rolling(90).sum())["vwap"]

  # Bollinger Bands
  movingAvg = df['Close'].rolling(20).mean()
  stdv = df['Close'].rolling(20).std()
  upper_band = movingAvg + 2 * stdv
  lower_band = movingAvg - 2 * stdv

# Display the data you want outside of the for loop


# To load mp3 files we need an additional third party library such as pydup (with ffmpeg).

from pydub import AudioSegment

audio = AudioSegment.from_wav("poznan.wav")

# increase the volume by 6dB.
audio = audio + 6

audio = audio * 2

audio = audio.fade_in(2000) # 2000 miliseconds equals 2 seconds.

audio.export("mashup.mp3", format="mp3")

audio2 = AudioSegment.from_mp3("mashup.mp3")
print("done")


import unittest
from lxml import etree

from jinja2 import Template

from rwmgmtapi import confd
# from rwmgmtapi.test.xmlcompare import xml_compare

QUERY = Template("""
<start-query xmlns="http://tail-f.com/ns/tailf-rest-query">
    <foreach>{{foreach}}</foreach>
    {% for select in selects %}
    <select>
        <expression>{{select.expression}}</expression>
        <result-type>{{select.result_type}}</result-type>
        <label>{{select.label}}</label>
    </select>
    {% endfor %}
</start-query>
""")
class TestQueryBuilder(unittest.TestCase):

    def testQueryBuilder(self):
        actual = confd.QueryBuilder()
        actual.query('x')
        actual.select('e', 'r', 'l')
        expected_data = {
            'foreach' : 'x',
            'selects' : [{
                'expression' : 'e',
                'result_type' : 'r',
                'label' : 'l'
            }]
        }
        expected = etree.XML(QUERY.render(expected_data))
        def reporter(z):
            self.fail(z)
        print(expected)
        #  Not in OS
        # xml_compare(actual.xml, expected, reporter)

########################################
# BEGIN BOILERPLATE JENKIN INTEGRATION
import logging
import xmlrunner
import argparse
import sys
import os
def main(argv=sys.argv[1:]):
    logging.basicConfig(format='TEST %(message)s')

    parser = argparse.ArgumentParser()
    parser.add_argument('-v', '--verbose', action='store_true')

    args = parser.parse_args(argv)

    # Set the global logging level
    logging.getLogger().setLevel(logging.DEBUG if args.verbose else logging.ERROR)

    # The unittest framework requires a program name, so use the name of this
    # file instead (we do not want to have to pass a fake program name to main
    # when this is called from the interpreter).
    unittest.main(argv=[__file__] + argv,
            testRunner=xmlrunner.XMLTestRunner(
                output=os.environ["RIFT_MODULE_TEST"]))

if __name__ == '__main__':
    main()


import matplotlib.pyplot as plt
import torch
from torch.utils.data import DataLoader

from model import MLP, PlantsDataset, test

def load_model():
    model = MLP()
    model.load_state_dict(torch.load('./model_out'))
    return model

def load_dev_dataset(batch_size=64):
    plant_dev = PlantsDataset('Plant_1_Generation_Data.csv.dev')
    return DataLoader(plant_dev, batch_size=batch_size)

def make_plot(values):
    build_nums = list(range(1, len(values) + 1))
    plt.xlabel('Build number')
    plt.ylabel('MSE Loss')
    plt.plot(build_nums, values, label='Model MSE Loss over builds')
    plt.legend()
    plt.savefig('trend.png')

def main():
    model = load_model()
    dataloader = load_dev_dataset()

    loss_fn = torch.nn.MSELoss()

    loss = test(dataloader, model, loss_fn)
    with open('evaluation_results.txt', 'a+') as f:
        f.write(f'{str(loss)}\n')
    with open('evaluation_results.txt', 'r') as f:
        values = [float(line) for line in f.readlines() if line]
        make_plot(values)

if __name__ == "__main__":
    main()


import multiprocessing
import socket
import time
import re
import requests
from bs4 import BeautifulSoup

client= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostbyname("openbarrage.douyutv.com")
port = 8601
client.connect((host,port))
danmu_path =re.compile(b'txt@=(.+?)/cid@')
uid_path = re.compile(b'uid@=(.+?)/nn@')
nickname_path = re.compile(b'nn@(.+?)/txt@')
level_path = re.compile(b'level@=([1-9][0-9])/sahf')

def sendmsg(msgstr):
    msg = msgstr.encode('utf-8')
    data_length = len(msg) + 8
    code = 689
    msgHead = int.to_bytes(data_length, 4, 'little')  + int.to_bytes(data_length, 4, 'little') +int.to_bytes(code, 4, 'little')
    client.send(msgHead)
    sent=0
    print(msg)
    while sent < len(msg):
        tn=client.send(msg[sent:])
        sent=sent+tn

def start(roomid):
    msg='type@=loginreq/username@=rieuse/password@=douyu/roomid@={}/\0'.format(roomid)
    sendmsg(msg)
    msg_more='type@+joingroup/rid@={}/gid@=-9999/\0'.format(roomid)
    sendmsg(msg_more)
    print('~~~~~~~~~进入{}直播间~~~~~~~~'.format(get_name(roomid)))
    while True :
        print("start")
        data=client.recv(1024)
        print("22222222222")
        print(data)
        uid_more=uid_path.findall(data)
        nickname_more= nickname_path.findall(data)
        level_more=level_path.findall(data)
        danmu_more=danmu_path.findall(data)
        print(danmu_more)
        if not level_more:
            level_more=b'0'
        if not data:
            break
        else:
            for i in range(0,len(danmu_more)):
                    product={
                        'uid':uid_more[i].decode(encoding='utf-8'),
                        'nickname':nickname_more[i].decode(encoding='utf-8'),
                        'level':level_more[i].decode(encoding='utf-8'),
                        'danmu':danmu_more[i].decode(encoding='utf-8')
                        }
                    print(product)

def keeplive():
    print("keeplive")
    while True :
        print("alive")
        msg='type@=keeplive/tick@='+str(int(time.time()))+'/\0'
        sendmsg(msg)
        time.sleep(15)

def get_name(roomid):
    r=requests.get("http://www.douyu.com/"+roomid)
    soup= BeautifulSoup(r.text,'lxml')
    return soup.find('a',{'class','zb-name'}).string

if __name__=='__main__':
    #room_id=input('请输入房间号：')
    room_id="530716"
    p1=multiprocessing.process(target=start(room_id))
    p2=multiprocessing.process(target=keeplive)
    p1.start()
    p2.start()


from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views

app_name = 'members'

urlpatterns = [

    path('', views.all_members, name='all_members' ),
    path('add', views.Add_mumber, name='Add_mumber' ),

    path('<int:id>', views.detalis_members, name='detalis_members'),
    path('<int:id>edit', views.Editr_Mumber, name='Editr_Mumber'),
    path('<int:id>edit_sub', views.Editr_Mumber_usb, name='Editr_Mumber_usb'),

   # path('<str:slug>', views.job_detail, name='job_detail'),
]

urlpatterns +=  static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


import torch
import torch.nn as nn

from torch.utils.checkpoint import checkpoint

from torch_dimcheck import dimchecked
from harmonic.cmplx import magnitude

class CReLU(nn.Module):
    def __init__(self, repr, dim=2, eps=1e-3):
        super(CReLU, self).__init__()

        self.repr = repr
        self.eps = eps
        self.dim = 2

        bias = torch.zeros(1, 1, sum(repr), *(self.dim * [1]))
        bias.exponential_(1.17) # exponential so that bias is always positive
        self.bias = nn.Parameter(bias, requires_grad=True)

    @dimchecked
    def forward(self, x: [2, 'b', 'f', 'h', 'w', ...]) -> [2, 'b', 'f', 'h', 'w', ...]:
        return checkpoint(self._forward, x)

    @dimchecked
    def _forward(self, x: [2, 'b', 'f', 'h', 'w', ...]) -> [2, 'b', 'f', 'h', 'w', ...]:
        magn = magnitude(x).unsqueeze(0)
        normalized = x / (magn + self.eps)
        magn_biased = magn - self.bias

        zero = x.new_zeros((1, ))
        return torch.where(magn_biased > 0, normalized * magn_biased, zero)

    def __repr__(self):
        return f'CReLU{self.dim}d(repr={self.repr})'

if __name__ == '__main__':
    import unittest

    class CReLUTests(unittest.TestCase):
        def test_forward(self):
            nonl = CReLU((3, 6, 0, 1))
            n, h, w = 3, 40, 40
            inputs = torch.randn(2, n, 3 + 6 + 1, h, w)
            output = nonl(inputs)

            print(nonl.bias[0, 0, 0])
            print(magnitude(inputs[:, 0, 0]))
            print(output[0, 0, 0])

    unittest.main()

#    n = 10000
#    samples = torch.randn(2, n)
#    mags = magnitude(samples)
#
#    thresholds = torch.zeros(n)
#    lambda_ = torch.sqrt(-2. * torch.log(torch.tensor(0.5)))
#    thresholds.exponential_(lambda_)
#    passed = mags > thresholds
#
#    print(lambda_)
#    print(passed.sum().float() / n)


import pickle

f = open('../pklFile/test_ini.pkl', 'rb')
df = pickle.load(f)
f.close()

list4624_4625=df[0]
print(list4624_4625.values[0][1])
# for data in list4624_4625.index:
#     print(data.loc[list4624_4625].values, data.loc[list4624_4625].values[0], data.loc[list4624_4625].values[1])

# def findEnumerationCrackRDP(list4624_4625):
'''
    爆破检测函数
'''
lastTime='2002-04-11 05:21:00'
count_Attact=0
for data in list4624_4625.values:
    # print(data[1]) #2022-04-18 20:11:53
    # if data[2]=='4624':
    #     ipaddress=data[]
    # if data[2]=='4625'
    #     ipaddress=data[29]
    # print(data[2])
    # print(type(data))
    print(data)
    # print(data[2])

    # if lastTime==a[1]:
    #     print(1)
    # lastTime = a[1]

'''
#显示所有列
pd.set_option('display.max_columns', None)
#显示所有行
pd.set_option('display.max_rows',None)

下面三行查看dataframe的数据结构信息（列名）
c = list4624_4625.dtypes
for i in c.index: # 依次选取Series的各个key
    print(i,'   ',c[i]) # 这里的c[i]的使用，在Series中可以使用Series[key]的形式取出对应的value
'''