import os
import sys
import json
import time
import sqlite3
from util import callrpc, format8

class FindAddress():
    def __init__(self, address, dist_from_main):
        self.address = address

        self.txids_vout = set()
        self.dist_from_main = dist_from_main

class InputTxn():
    def __init__(self, tx, height, blockhash):
        self.tx = tx
        self.height = height
        self.blockhash = blockhash

class AddressInput():
    def __init__(self, address, amount):
        self.address = address
        self.amount = amount
        self.num_txns = 0
        self.min_height = -1
        self.max_height = -1

    def updateHeights(self, height):
        if self.min_height == -1 or height < self.min_height:
            self.min_height = height
        if height > self.max_height:
            self.max_height = height
        self.num_txns += 1

class Prevout():
    __slots__ = ('txid', 'n')

    def __init__(self, txid, n):
        self.txid = txid
        self.n = int(n)

    def __hash__(self):
        return hash((self.txid, self.n))

    def __eq__(self, other):
        if not isinstance(other, type(self)):
            return NotImplemented
        return self.txid == other.txid and self.n == other.n

addrs = {}
txns = {}
linked_prevouts = set()

def make_rpc_func(rpc_port, rpc_auth, wallet=None):
    rpc_port = rpc_port
    rpc_auth = rpc_auth
    wallet = wallet

    def rpc_func(cmd, args=[], wallet_override=None):
        nonlocal rpc_port, rpc_auth, wallet
        return callrpc(rpc_port, rpc_auth, cmd, args, wallet if wallet_override is None else wallet_override)
    return rpc_func

def main():
    particl_data_dir = os.path.expanduser(sys.argv[1])
    main_address = os.path.expanduser(sys.argv[2])

    max_dist_from_main = 3

    # db_filepath = '/tmp/find_inputs.sqlite'
    db_filepath = 'find_inputs.sqlite'

    chain = 'mainnet'

    authcookiepath = os.path.join(particl_data_dir, '' if chain == 'mainnet' else chain, '.cookie')
    for i in range(10):
        if not os.path.exists(authcookiepath):
            time.sleep(0.5)
    with open(authcookiepath) as fp:
        rpc_auth = fp.read()

    rpc_port = 51735 if chain == 'mainnet' else 51935

    callrpcw = make_rpc_func(rpc_port, rpc_auth)

    r = callrpcw('getnetworkinfo')
    print('Core version', r['version'])

    block_hash = callrpcw('getbestblockhash')

    '''
    height_from = 100000
    block_hash = callrpcw('getblockhash', [height_from,])
    '''
    print('Results from block', block_hash)
    print('max_dist_from_main', max_dist_from_main)

    dbc = sqlite3.connect(db_filepath)
    c = dbc.cursor()
    c.execute('''CREATE TABLE outputs
                 (txid TEXT, n INTEGER, type TEXT, anon_index INTEGER, value INTEGER, is_coinbase INTEGER, spent_txid TEXT, script TEXT, script_type TEXT, address TEXT)''')
    dbc.commit()

    addrs[main_address] = FindAddress(main_address, 0)

    # List of addreses in the (reverse) order they appear in the chain
    addrs_seen = []
    prevouts_skipped = 0

    while True:
        block_data = callrpcw('getblock', [block_hash, 2])

        block_height = block_data['height']
        for tx_i, tx in enumerate(block_data['tx']):
            txid = tx['txid']
            for tx_out in tx['vout']:

                min_dist_from_main = 1000
                found_addresses = []
                try:
                    if tx_out['type'] != 'standard':
                        continue
                    for k, addr_v in addrs.items():
                        if 'addresses' not in tx_out['scriptPubKey']:
                            # "asm": "OP_RETURN",
                            # prefork workaround for smsg/mp data output limits was to add an empty opreturn output
                            continue
                        if k in tx_out['scriptPubKey']['addresses']:
                            # Filter out prevouts that don't feed into the main address
                            if addr_v.dist_from_main > 0:
                                if Prevout(txid, tx_out['n']) not in linked_prevouts:
                                    prevouts_skipped += 1
                                    continue

                            if addr_v.dist_from_main < min_dist_from_main:
                                min_dist_from_main = addr_v.dist_from_main

                            found_addresses.append(k)

                except Exception as e:
                    print('error tx_out', e)
                    print('tx', json.dumps(tx, indent=4))

                if min_dist_from_main >= max_dist_from_main:
                    continue

                if len(found_addresses) == 0:
                    continue

                for k in found_addresses:
                    if k not in addrs_seen:
                        addrs_seen.append(k)
                    addr_v = addrs[k]
                    addr_v.txids_vout.add(txid)

                txns[txid] = InputTxn(tx, block_height, block_hash)

                for txi_n, tx_input in enumerate(tx['vin']):
                    if 'coinbase' in tx_input:
                        break
                    if 'type' in tx_input and tx_input['type'] == 'anon':
                        continue

                    prev_txid = tx_input['txid']
                    prev_tx = callrpcw('getrawtransaction', [prev_txid, True])
                    if prev_txid not in txns:
                        txns[prev_txid] = InputTxn(prev_tx, prev_tx['height'], prev_tx['blockhash'])
                    linked_prevouts.add(Prevout(prev_txid, tx_input['vout']))
                    prevout = prev_tx['vout'][tx_input['vout']]

                    for addr in prevout['scriptPubKey']['addresses']:
                        if addr not in addrs:
                            addrs[addr] = FindAddress(addr, min_dist_from_main + 1)

        if block_data['height'] % 10000 == 0:
            print('height', block_data['height'], flush=True)
            print('len(txns)', len(txns))

        try:
            block_hash = block_data['previousblockhash']
        except Exception as e:
            print('previousblockhash', e)
            break

    print('linked_prevouts', len(linked_prevouts))  # prevouts mapped to main_address
    print('prevouts_skipped', prevouts_skipped)  # prevouts of addresses linked to main_address not connected in the txout history
    print('len(txns)', len(txns))

    total_coinbase_amount = 0
    for addr in addrs_seen:
        print('\n\n------------------------------------------------------------')
        print('    ', addr)
        print('------------------------------------------------------------\n')

        plain_addrs_from = {}
        blind_addrs_from = {}

        anon_inputs = AddressInput('anon', 0)
        coinbase_inputs = AddressInput('coinbase', 0)
        anon_input_txids = []

        addr_info = addrs[addr]

        print('dist from main', addr_info.dist_from_main)

        c = dbc.cursor()

        for txid in addr_info.txids_vout:
            tx_obj = txns[txid]
            tx = tx_obj.tx
            tx_height = tx_obj.height
            num_anon_inputs = 0

            for txi_n, tx_input in enumerate(tx['vin']):
                if 'coinbase' in tx_input:
                    coinbase_inputs.updateHeights(tx_height)
                    for txo in tx['vout']:
                        try:
                            if addr in txo['scriptPubKey']['addresses']:
                                coinbase_inputs.amount += txo['valueSat']

                                c.execute('INSERT INTO outputs (txid, n, type, value, script, script_type, address, is_coinbase)  VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
                                          (txid, txo['n'], 'P', txo['valueSat'], txo['scriptPubKey']['hex'], txo['scriptPubKey']['type'], ' '.join(txo['scriptPubKey']['addresses']), 1))

                        except Exception as e:
                            print('error tx vout', e)
                            print('tx', json.dumps(tx, indent=4))

                    break
                if 'type' in tx_input and tx_input['type'] == 'anon':
                    num_anon_inputs += 1
                    anon_input_txids.append(Prevout(txid, txi_n))
                    anon_inputs.updateHeights(tx_height)
                    continue

                prev_tx_obj = txns[tx_input['txid']]
                prev_tx = prev_tx_obj.tx

                prevout = prev_tx['vout'][tx_input['vout']]

                try:
                    update_addrs_plain = set()
                    update_addrs_blind = set()
                    if prevout['type'] == 'blind':
                        for addr in prevout['scriptPubKey']['addresses']:
                            if addr not in blind_addrs_from:
                                blind_addrs_from[addr] = AddressInput(addr, 0)
                            update_addrs_blind.add(addr)
                    elif tx_out['type'] == 'anon':
                        raise ValueError('Shouldn\'t happen')
                    else:
                        for addr in prevout['scriptPubKey']['addresses']:
                            if addr not in plain_addrs_from:
                                plain_addrs_from[addr] = AddressInput(addr, prevout['valueSat'])
                            else:
                                plain_addrs_from[addr].amount += prevout['valueSat']
                            update_addrs_plain.add(addr)

                    for addr in update_addrs_plain:
                        if addr in plain_addrs_from:
                            plain_addrs_from[addr].updateHeights(tx_height)
                    for addr in update_addrs_blind:
                        if addr in blind_addrs_from:
                            blind_addrs_from[addr].updateHeights(tx_height)

                except Exception as e:
                    print('error format output', e)
                    print('txid source', txid)
                    print('txid input', tx_input['txid'])
                    print('vout input', tx_input['vout'])
                    print('prev_tx', json.dumps(prev_tx, indent=4))

        print('num_anon_inputs', num_anon_inputs)
        print('num_blind_inputs', len(blind_addrs_from))
        print('num_plain_inputs', len(plain_addrs_from))
        print('\nplain_addrs_from')

        output_fmt = '{:54}{:<12}{:<12}{:<12}{:>12}'
        print(output_fmt.format('Address', 'Num Txns', 'Min Height', 'Max Height', 'Amount'))
        for addr, obj in plain_addrs_from.items():
            print(output_fmt.format(addr, obj.num_txns, obj.min_height, obj.max_height, format8(obj.amount)))

        if len(blind_addrs_from) > 0:
            print('\nblind_addrs_from')
            print(output_fmt.format('Address', 'Num Txns', 'Min Height', 'Max Height', 'Amount'))
            for addr, obj in blind_addrs_from.items():
                print(output_fmt.format(addr, obj.num_txns, obj.min_height, obj.max_height, ''))

        if anon_inputs.num_txns > 0:
            print('\nanon inputs')
            print(output_fmt.format('anon', anon_inputs.num_txns, anon_inputs.min_height, anon_inputs.max_height, ''))

            for prevout in anon_input_txids:
                print(prevout.txid, prevout.n)

        if coinbase_inputs.num_txns > 0:
            print('\ncoinbase inputs')
            print(output_fmt.format('coinbase', coinbase_inputs.num_txns, coinbase_inputs.min_height, coinbase_inputs.max_height, format8(coinbase_inputs.amount)))
            total_coinbase_amount += coinbase_inputs.amount

        dbc.commit()

    print('total_coinbase_amount', format8(total_coinbase_amount))

    dbc.close()

if __name__ == '__main__':
    main()


#%%
def selamVer(isim):
    print("Selam", isim)

isim = ""
isim = input("İsminiz nedir? ")
if isim == "":
    print("Merhaba Dünyalı")
else:
    selamVer(isim)
#%%
def dikUcgenAlanHesapla(a, b):
    return (a * b) / 2

print(dikUcgenAlanHesapla(3, 4))
#%%
"""Bu fonksiyon üçgenin alanını hesaplar tek satırlık bir fonksiyondur"""
dikUcgenAlanHesapla2 = lambda a, b: (a * b) / 2
print(dikUcgenAlanHesapla2(3, 4))
print(type(dikUcgenAlanHesapla2))
x = dikUcgenAlanHesapla2
print(x(4, 5))


from django.shortcuts import render, redirect, HttpResponse, get_list_or_404, \
    get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import OnlineBooking
from .forms import OnlineBookingForm
from datetime import date
from django.contrib import messages
from django.views import View

class HomeView(View):
    def get(self, request):
        return render(request, 'home.html', {})

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

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

@login_required
def online_booking(request):

    if request.method == 'POST':
        form = OnlineBookingForm(request.POST)

        if form.is_valid():
            reservation = form.save(commit=False)
            reservation.user = request.user
            reservation.save()
            messages.success(
                request, 'Reservation request submitted succesfully.You can check you reservation at: My bookings'
                )
        else:
            messages.error(request, 'The table is already booked.')
            reservation = form.instance.date

    form = OnlineBookingForm()
    context = {
        'form': form,
    }
    return render(request, 'online_booking.html', context)

@login_required
def mybookings(request):
    try:
        online_bookings = get_list_or_404(OnlineBooking, user=request.user)
    except Exception:
        online_bookings = None

    form = OnlineBookingForm()
    context = {
        'online_bookings': online_bookings,
    }
    return render(request, 'mybookings.html', context)

@login_required
def edit_booking(request, online_booking_id):

    online_booking = get_object_or_404(OnlineBooking, id=online_booking_id)
    if request.method == 'POST':
        form = OnlineBookingForm(request.POST, instance=online_booking)
        if form.is_valid():
            form.save()
            messages.success(request, 'Your booking has been edited.')
            return redirect('mybookings')
        else:
            messages.error(request, 'This reservation is already booked.')

    form = OnlineBookingForm(instance=online_booking)
    context = {
        'form': form,
    }
    return render(request, 'edit_booking.html', context)

@login_required
def delete_booking(request, online_booking_id):
    online_booking = get_object_or_404(OnlineBooking, online_booking_id)
    online_booking.delete()
    messages.success(request, 'Reservation is now deleted.')
    return redirect('mybookings')


# 爬取域名

DOMAIN = 'http://home.qutoutiao.net/pages/home.html'

# 数据储存

DATA_STORE = 'C:\\Users\\Franc\\Desktop\\Dir\\Python\\Evans\\Scrape\\qtt\\data'

# API

LIST_API = 'http://api.1sapp.com/content/outList?'

# OBS

LIST_LIMIT = 10

# CLASS

CATEGORY_INFO = [
    {"cid": 255, "name": "推荐"},
    {"cid": 1, "name": "热点"},
    {"cid": 6, "name": "娱乐"},
    {"cid": 5, "name": "养生"},
    {"cid": 2, "name": "搞笑"},
    {"cid": 7, "name": "科技"},
    {"cid": 8, "name": "生活"},
    {"cid": 10, "name": "财经"},
    {"cid": 9, "name": "汽车"}
]


import contextlib
import logging
import sys
import time
from datetime import datetime
from typing import Callable, Iterator, Optional, Tuple, Union, cast

import torch
from torch.optim.lr_scheduler import _LRScheduler as LRScheduler
from torch.optim.optimizer import Optimizer

import pystiche
from pystiche.pyramid.level import PyramidLevel

from .meter import AverageMeter, ETAMeter, LossMeter, ProgressMeter

__all__ = [
    "default_logger",
    "OptimLogger",
    "default_image_optim_log_fn",
    "default_pyramid_level_header",
    "default_transformer_optim_log_fn",
    "default_epoch_header_fn",
]

def default_logger(
    name: Optional[str] = None, log_file: Optional[str] = None
) -> logging.Logger:
    logger = logging.getLogger(name)
    logger.setLevel(logging.INFO)

    fmt = logging.Formatter(
        fmt="|%(asctime)s| %(message)s", datefmt="%d.%m.%Y %H:%M:%S"
    )

    sh = logging.StreamHandler(sys.stdout)
    sh.setLevel(logging.INFO)
    sh.addFilter(lambda record: record.levelno <= logging.INFO)
    sh.setFormatter(fmt)
    logger.addHandler(sh)

    sh = logging.StreamHandler(sys.stderr)
    sh.setLevel(logging.WARNING)
    sh.setFormatter(fmt)
    logger.addHandler(sh)

    if log_file is not None:
        fh = logging.FileHandler(log_file)
        fh.setLevel(logging.INFO)
        fh.setFormatter(fmt)
        logger.addHandler(fh)

    return logger

class OptimLogger:
    INDENT = 2
    SEP_LINE_LENGTH = 80
    SEP_CHARS = ("#", "*", "=", "-", "^", '"')

    def __init__(self, logger: Optional[logging.Logger] = None):
        if logger is None:
            name = f"pystiche_{datetime.now().strftime('%Y%m%d%H%M%S%f')}"
            logger = default_logger(name=name)
        self.logger = logger

        self._environ_indent_offset = 0
        self._environ_level_offset = 0

    def _calc_abs_indent(self, indent: int, rel: bool) -> int:
        abs_indent = indent
        if rel:
            abs_indent += self._environ_indent_offset
        return abs_indent

    def _calc_abs_level(self, level: int, rel: bool) -> int:
        abs_level = level
        if rel:
            abs_level += self._environ_level_offset
        return abs_level

    def message(self, msg: str, indent: int = 0, rel: bool = True) -> None:
        abs_indent = self._calc_abs_indent(indent, rel)
        for line in msg.splitlines():
            self.logger.info(" " * abs_indent + line)

    def sepline(self, level: int = 0, rel: bool = True) -> None:
        abs_level = self._calc_abs_level(level, rel)
        self.message(self.SEP_CHARS[abs_level] * self.SEP_LINE_LENGTH)

    def sep_message(
        self,
        msg: str,
        level: int = 0,
        rel: bool = True,
        top_sep: bool = True,
        bottom_sep: bool = True,
    ) -> None:
        if top_sep:
            self.sepline(level=level, rel=rel)
        self.message(msg, rel=rel)
        if bottom_sep:
            self.sepline(level=level, rel=rel)

    @contextlib.contextmanager
    def environment(self, header: str) -> Iterator:
        self.sep_message(header)
        self._environ_indent_offset += self.INDENT
        self._environ_level_offset += 1
        try:
            yield
        finally:
            self._environ_level_offset -= 1
            self._environ_indent_offset -= self.INDENT

def default_image_optim_log_fn(
    optim_logger: OptimLogger, log_freq: int = 50, max_depth: int = 1
) -> Callable[[int, Union[torch.Tensor, pystiche.LossDict]], None]:
    def log_fn(step: int, loss: Union[torch.Tensor, pystiche.LossDict]) -> None:
        if step % log_freq == 0:
            with optim_logger.environment(f"Step {step}"):
                if isinstance(loss, pystiche.LossDict):
                    loss = loss.aggregate(max_depth)

                if isinstance(loss, pystiche.LossDict):
                    msg = loss.format()
                elif isinstance(loss, torch.Tensor):
                    msg = f"loss: {loss.item():.3e}"
                else:
                    raise TypeError

                optim_logger.message(msg)

    return log_fn

def default_pyramid_level_header(
    num: int, level: PyramidLevel, input_image_size: Tuple[int, int]
) -> str:
    height, width = input_image_size
    return f"Pyramid level {num} with {level.num_steps} steps " f"({width} x {height})"

def default_transformer_optim_log_fn(
    optim_logger: OptimLogger,
    num_batches: int,
    log_freq: Optional[int] = None,
    show_loading_velocity: bool = True,
    show_processing_velocity: bool = True,
    show_running_means: bool = True,
) -> Callable[[int, Union[float, torch.Tensor, pystiche.LossDict], float, float], None]:
    if log_freq is None:
        log_freq = max(min(round(1e-3 * num_batches) * 10, 50), 1)

    window_size = min(10 * log_freq, 1000)

    meters = [
        ETAMeter(
            num_batches, window_size=window_size, show_local_eta=show_running_means
        ),
        LossMeter(window_size=window_size, show_local_avg=show_running_means),
    ]
    if show_loading_velocity:
        meters.append(
            AverageMeter(
                name="loading",
                window_size=window_size,
                show_local_avg=show_running_means,
                fmt="{:4.0f} img/s",
            )
        )
    if show_processing_velocity:
        meters.append(
            AverageMeter(
                name="processing",
                window_size=window_size,
                show_local_avg=show_running_means,
                fmt="{:4.0f} img/s",
            )
        )

    progress_meter = ProgressMeter(num_batches, *meters)

    def log_fn(
        batch: int,
        loss: Union[float, torch.Tensor, pystiche.LossDict],
        loading_velocity: float,
        processing_velocity: float,
    ) -> None:
        progress_meter.update(
            ETA=time.time(),
            loss=loss,
            loading=loading_velocity,
            processing=processing_velocity,
        )
        if batch % cast(int, log_freq) == 0:
            optim_logger.message(str(progress_meter))

    return log_fn

def default_epoch_header_fn(
    epoch: int, optimizer: Optimizer, lr_scheduler: Optional[LRScheduler]
) -> str:
    return f"Epoch {epoch}"


# write a python program to create a tuple with different data types.

num = int(input("How many values do you want to enter:"));

a = tuple()

for i in range (0,num):
    val = input("Enter values:");
    a.add(val);

print(a);


'''
Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.

Example 1:

Input: nums = [1,2,3,4,5]
Output: true
Explanation: Any triplet where i < j < k is valid.
Example 2:

Input: nums = [5,4,3,2,1]
Output: false
Explanation: No triplet exists.
Example 3:

Input: nums = [2,1,5,0,4,6]
Output: true
Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.

Constraints:

1 <= nums.length <= 5 * 105
-231 <= nums[i] <= 231 - 1
'''
from typing import *

import unittest

class Solution:
    def increasingTriplet(self, nums: List[int]) -> bool:
        bigger = [0 for _ in range(len(nums))]
        next_bigger = nums[-1]
        bigger[-1] = next_bigger
        for i in range(len(nums)-1)[::-1]:
            if nums[i] > next_bigger:
                next_bigger = nums[i]
            bigger[i] = next_bigger

        prev_smaller = nums[0]
        for i in range(1, len(nums)):
            if nums[i] < prev_smaller:
                prev_smaller = nums[i]
            if nums[i] > prev_smaller and bigger[i] > nums[i]:
                return True
        return False

class TestSolution(unittest.TestCase):
    def test_case(self):
        examples = (
            (([2,1,5,0,4,6],),True),
        )
        for first, second in examples:
            self.assert_function(first, second)

    def assert_function(self, first, second):
        self.assertEqual(Solution().increasingTriplet(*first), second,
                         msg="first: {}; second: {}".format(first, second))

unittest.main()

Leetcode/334. Increasing Triplet Subsequence.py


import random

# Function to check which questions user would like to answer
def question_checker(question):
    valid_responses = ["p", ""]
    while True:
        response = input(question).lower()
        if response in valid_responses:
            return response
        else:
            print("<error> Please enter 'p' to generate a Pythagorean triple or press <enter> for all types of "
                  "questions.")

# Number checker to ensure correct user input
def num_check(question, error, num_type, exit_code="xxx", low=None, high=None):
    while True:
        try:
            response = input(question)
            if response == exit_code:
                return response
            else:
                response = num_type(response)

            if low is not None and high is not None:
                if low < response < high:
                    return response
                else:
                    print(error)
                    print()
                    continue

            elif low is not None:
                if response > low:
                    return response
                else:
                    print(error)
                    print()
                    continue

            else:
                return response

        except ValueError:
            print(error)
            print()

# Function to check for yes or no responses
def yes_no(question):
    valid_responses = ["yes", "no", "y", "n"]
    while True:
        response = input(question).lower()
        if response in valid_responses:
            return response
        else:
            print("<error> Please say yes or no")
            print()

# Function to generate questions randomly
def generate_question(points_val):
    while True:
        n = random.randint(1, 10)
        a = 2 * n + 1
        b = n * (2 * n + 1) + n
        response = num_check("In a Pythagorean triple, if n = {}, what is the length of the hypotenuse "
                             "if the other two sides are {} and {}? ".format(n, a, b),
                             "<error> Please enter a number", float)

        if response == "xxx":
            print("You quit")
            return "quit"

            print("\033[1;32;40m \n")
            statement_generator("You got it right! +{} points".format(points_val), "*", "~")
            return "correct"
        else:
            print("\033[1;31;40m \n")
            statement_generator("You got it wrong. -10 points", "|", "-")
            return "incorrect"

# Function to print instructions
def instructions():
    print("\033[1;33;40m \n")
    statement_generator("Instructions", "|", "-")
    print("Welcome to the Pythagoras Quiz!")
    print("In this quiz, you will be shown the lengths of two sides of a right triangle.")
    print("Your task is to determine the length of the hypotenuse.")
    print("Each correct answer will earn you a certain number of points.")
    print("Each incorrect answer will deduct 10 points.")
    print("Let's get started!")

# Function to generate a formatted statement
def statement_generator(statement, deco_line, deco_char):
    print()
    print(deco_line * len(statement))
    print(statement)
    print(deco_char * len(statement))
    print()

# Main code
instructions()

points = 0
another_question = "yes"

while another_question == "yes":
    question_type = question_checker("Enter 'p' to generate a Pythagorean triple or press <enter> for all types of "
                                     "questions: ")
    if question_type == "p" or question_type == "":
        result = generate_question(10)
        print("\033[1;32;40m \n")
        if result == "correct":
            points += 10
        else:
            points -= 10

    another_question = yes_no("Do you want another question? (yes/no): ")

print("Your final score is:", points)
print("\033[1;35;40m \n")
print("Thank you for doing the Pythagoras Quiz!")


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('logistics_api', '0009_auto_20160409_1915'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='driver',
            name='attendance',
        ),
        migrations.RemoveField(
            model_name='driver',
            name='trip_id',
        ),
        migrations.RemoveField(
            model_name='trip',
            name='waypoint',
        ),
        migrations.AddField(
            model_name='orders',
            name='add_contact_num',
            field=models.BigIntegerField(default=0),
        ),
        migrations.AddField(
            model_name='orders',
            name='additional_info',
            field=models.CharField(default=b' ', max_length=360),
        ),
        migrations.AddField(
            model_name='orders',
            name='name',
            field=models.CharField(default=b' ', max_length=90),
        ),
        migrations.AddField(
            model_name='truck',
            name='driver_id',
            field=models.ForeignKey(default=0, to='logistics_api.Driver'),
        ),
        migrations.AddField(
            model_name='truck',
            name='truck_number',
            field=models.CharField(default=b' ', max_length=20),
        ),
        migrations.AlterField(
            model_name='logistics_user',
            name='contact_num',
            field=models.BigIntegerField(default=0, serialize=False, primary_key=True),
        ),
        migrations.AlterField(
            model_name='logistics_user',
            name='name',
            field=models.CharField(max_length=90),
        ),
        migrations.AlterField(
            model_name='trip',
            name='trip_capacity',
            field=models.IntegerField(default=0),
        ),
        migrations.AlterField(
            model_name='trip',
            name='trip_id',
            field=models.IntegerField(default=0, serialize=False, primary_key=True),
        ),
        migrations.AlterField(
            model_name='truck',
            name='truck_id',
            field=models.IntegerField(default=0, serialize=False, primary_key=True),
        ),
    ]


COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
import random
from turtle import Turtle

class CarManager():
    def __init__(self):
       self.all_cars=[]

    def create_car(self):
        newcar=Turtle()
        newcar.penup()
        newcar.shape('square')
        newcar.shapesize(0.5,1.5)
        newcar.color(random.choice(COLORS))
        newcar.goto(300,random.choice(range(-300,300,30)))
       # newcar.setheading(270)
        self.all_cars.append(newcar)

    def move(self):
        for i in self.all_cars:
            i.backward(STARTING_MOVE_DISTANCE)

   # pass


"""WAVES models export module for Services """
from __future__ import unicode_literals

from django.db import transaction
from rest_framework import serializers

from waves.wcore.models import Runner, AdaptorInitParam
from waves.wcore.import_export import RelatedSerializerMixin

class RunnerParamSerializer(serializers.ModelSerializer):
    class Meta:
        model = AdaptorInitParam
        fields = ('name', 'value', 'prevent_override')

    def to_representation(self, instance):
        repre = super(RunnerParamSerializer, self).to_representation(instance)
        if instance.name == 'password' or instance.crypt:
            repre['value'] = "xxxxxx"
        return repre

class RunnerSerializer(serializers.ModelSerializer, RelatedSerializerMixin):
    class Meta:
        model = Runner
        fields = ('name', 'clazz', 'runner_params')

    runner_params = RunnerParamSerializer(many=True, source='adaptor_params')

    @transaction.atomic
    def create(self, validated_data):
        runner_params = validated_data.pop('runner_params')
        runner = Runner.objects.create(**validated_data)
        runner.runner_run_params.all().delete()
        runner.runner_run_params = self.create_related(foreign={'runner': runner},
                                                       serializer=RunnerParamSerializer,
                                                       datas=runner_params)
        return runner


from django.db import models
from django.contrib.auth.models import User
from cloudinary.models import CloudinaryField

SwordfighterSTATUS = ((0, 'Pending Approval'), (1, 'Published'), (2, 'Published with edit'), (3, 'Disapproved'))
CommentSTATUS = ((0, 'Unmanaged'), (1, 'Approved'))

class Swordfighter(models.Model):
    name = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    appears_on = models.CharField(max_length=100)
    description = models.CharField(max_length=255)
    profile_img = CloudinaryField('image', default='placeholder')
    upvotes = models.ManyToManyField(User, related_name="swordfighter_upvotes", blank=True)
    status = models.IntegerField(choices=SwordfighterSTATUS, default=0)
    suggested_by = models.CharField(max_length=100, default='admin')

    class meta:
        ordering = ['upvotes']

    def __str__(self):
        return self.name

    def number_of_upvotes(self):
        return self.upvotes.count()

class Comment(models.Model):
    swordfighter = models.ForeignKey(Swordfighter, on_delete=models.CASCADE, related_name="comments")
    submitted_by = models.CharField(max_length=100)
    submitted_on_date = models.DateTimeField(auto_now_add=True)
    content = models.TextField()
    flags = models.ManyToManyField(User, related_name='comment_flag', blank=True)
    num_flags = models.IntegerField(default=0)
    status = models.IntegerField(choices=CommentSTATUS, default=0)

    class Meta:
        ordering = ["-submitted_on_date"]

    def __str__(self):
        return f"{self.submitted_by} on {self.submitted_on_date} - {self.content}"

    def flag(self, user):
        if self.flags.filter(id=user.id).exists():
            self.flags.remove(user)
        else:
            self.flags.add(user)
        self.num_flags = self.flags.count()
        self.save()


import sys
import tensorflow as tf
import logging
from typing import *
from tensorflow import Tensor
from tensorflow_addons.layers.embedding_bag import EmbeddingBag
from keras import Sequential, Model, layers, losses

logger = logging.getLogger("general_logger")

class DLRM(Model):
    """
    Customized DLRM model, using embedding bags to replace latent_factor.
    """

    def __init__(
            self,
            embed_dim,
            num_embed,
            embed_vocab_size,
            ln_bot,
            ln_top,
            # arch_interaction_op='dot',
            # arch_interaction_itself=False,
            sigmoid_bot=False,
            sigmoid_top=True,
            loss_func='bce',
            loss_threshold=0.0):
        '''
        embed_dim: the dimensionality of sparse feature embeddings
        num_embed: the size of sparse feature embeddings (num_instances)
        embed_vocab_size: the input vocab size of embedding bags
        ln_bot: the size of the bottom MLP
        ln_top: the size of the top MLP
        '''

        super(DLRM, self).__init__()

        self._num_embed = num_embed
        self._embed_dim = embed_dim
        self._embed_vocab_size = embed_vocab_size
        self._ln_bot = ln_bot
        self._ln_top = ln_top

        self._loss_threshold = loss_threshold
        self._loss_func = loss_func
        self._embedding_bag: List[EmbeddingBag] = [EmbeddingBag(input_dim=num,
                                            output_dim=self._embed_dim) for num in embed_vocab_size]

        # for eb in self._embedding_bag:
        #     print(eb.get_config())

        # self._mlp_bot = MLP(units_list=ln_bot,
        #                     out_activation='sigmoid' if sigmoid_bot else 'relu')
        # self._mlp_top = MLP(units_list=ln_top,
        #                     out_activation='sigmoid' if sigmoid_top else 'relu')

        self._mlp_bot: Sequential = Sequential(name="bottom_mlp")
        self._mlp_bot.add(layers.Dense(ln_bot, activation=None))

        self._mlp_top: Sequential = Sequential(name="top_mlp")
        self._mlp_top.add(layers.Dense(ln_top, activation=None))

        self._dot_interaction = None
        # if arch_interaction_op == 'dot':
        #     self._dot_interaction = SecondOrderFeatureInteraction(
        #         self_interaction=arch_interaction_itself
        #     )

        # elif arch_interaction_op != 'cat':
        #     sys.exit(
        #         "ERROR: arch_interaction_op="
        #         + arch_interaction_op
        #         + " is not supported"
        #     )

        if loss_func == 'mse':
            self._loss = tf.keras.losses.MeanSquaredError(reduction=tf.keras.losses.Reduction.NONE)
        elif loss_func == 'bce':
            self._loss = tf.keras.losses.BinaryCrossentropy(reduction=tf.keras.losses.Reduction.NONE)
        else:
            sys.exit(
                "ERROR: loss_func="
                + loss_func
                + " is not supported"
            )

    def get_weights(self):
        weights = {}
        weights["ln_bot"] = self._mlp_bot.weights
        weights["ln_top"] = self._mlp_top.weights
        weights["embedding_bags"] = {}
        for i, eb in enumerate(self._embedding_bag):
            weights["embedding_bags"][i] = eb.weights
        return weights

    def get_params(self):
        params = {}
        params["num_embed"] = self._num_embed
        params["embed_dim"] = self._embed_dim
        params["ln_bot"] = self._ln_bot
        params["ln_top"] = self._ln_top
        params["embed_vocab_size"] = self._embed_vocab_size
        return params

    def get_myloss(self, dense_features, sparse_features, label):
        '''
        dense_features shape: [batch_size, num of dense features]
        sparse_features shape: [batch_size, num_of_sparse_features]
        label shape: [batch_size]
        '''

        prediction = self.inference(dense_features, sparse_features)

        prediction = tf.reshape(prediction, [-1, 1])
        label = tf.reshape(label, [-1, 1])

        loss = self._loss(y_true=label,
                          y_pred=prediction)

        return loss

    def get_myloss_dist(self, dense_features: Tensor, sparse_features: Tensor, label: Tensor, global_batch_size: int):
        prediction = self.inference(dense_features, sparse_features)
        # print(tf.shape(prediction), tf.shape(label))
        prediction = tf.reshape(prediction, [-1, 1])
        label = tf.reshape(label, [-1, 1])

        per_example_loss = self._loss(label, prediction)
        # logger.info("per example loss:{l}".format(l=per_example_loss))
        # return per_example_loss

        loss = tf.nn.compute_average_loss(per_example_loss, global_batch_size=global_batch_size)
        # print(tf.shape(loss))
        return loss

    def call(self, inputs, training=None, mask=None):
        dense_features, sparse_features = inputs
        return self.inference(dense_features, sparse_features)

    def predict(self, inputs: tf.data.Dataset):
        inf_result: List[Tensor] = []
        for data in inputs:
            inf_result.append(self.inference(**data))
        return tf.stack(inf_result)

    def sparse_func(self, pair):
        return pair[1](pair[0])

    def inference(self, dense_features, sparse_features):
        '''
        dense_features shape: [batch_size, num of dense features]
        sparse_features shape: [batch_size, num_of_sparse_features]
        '''
        # print(dense_features, '\n', sparse_features)

        self._set_inputs([dense_features, sparse_features])
        # for i in zip(tf.unstack(sparse_features, axis=1), self._embedding_bag):
        #     print(i)
        sparse_emb_vecs = list(map(self.sparse_func,
                                   zip(tf.unstack(sparse_features, axis=1),
                                       self._embedding_bag)))

        dense_emb_vec = self._mlp_bot(dense_features)

        if self._dot_interaction is not None:
            prediction = self._mlp_top(tf.concat([dense_emb_vec,
                                                  self._dot_interaction(sparse_emb_vecs + [dense_emb_vec])],
                                                 axis=1))
        else:
            prediction = self._mlp_top(tf.concat(sparse_emb_vecs + [dense_emb_vec],
                                                 axis=1))

        out = tf.sigmoid(tf.reduce_mean(prediction, axis=1))

        # if 0.0 < self._loss_threshold and self._loss_threshold < 1.0:
        #     prediction = tf.clip_by_value(
        #         prediction, self._loss_threshold, 1.0 - self._loss_threshold)
        # print(out)

        return tf.reshape(out, [-1])


from squeze.squeze_common_functions import load_json, deserialize
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter

fig, ax = plt.subplots()

for n in [1, 2, 4, 8]:
    samples = ["../sample_quasars/processed_validation_64plates_sample{}.json".format(i) for i in range(n)]
    n_bins = 20
    c = 3e5

    sample_dfs = [deserialize(load_json(sample)) for sample in samples]

    df = pd.concat(sample_dfs, sort=False).copy()

    df = df[df["is_correct"] == True]

    df = df.sort_values(by="prob")
    df["Delta_v"] = df["Delta_z"] / (1 + df["z_try"]) * c

    bins = np.linspace(0.32, 1, n_bins)
    group = df.groupby(pd.cut(df.prob, bins))

    plot_centers = (bins[:-1] + bins[1:])/2
    plot_values = group.Delta_v.std()

    ax.plot(plot_centers, plot_values, label=n, alpha=n*0.125)

plt.xlabel("Confidence ($p$)")
plt.ylabel("$\Delta v$ std")
plt.title("$\Delta v$ std by {} bins of $p$".format(n_bins))
plt.xticks(rotation=45)
ax.xaxis.set_major_formatter(FormatStrFormatter('%0.2f'))
ax.xaxis.set_major_locator(plt.FixedLocator(bins))
ax.set_ylim(ymin=0)
ax.set_xlim(xmin=bins[0], xmax=bins[-1])
plt.grid(True)
plt.tight_layout()
plt.legend()
plt.show()


import os
import csv

SOP_FILEPATH = 'src/sop_template.tex'
REFERENCES_FILEPATH = 'references.bib'
OUTPUT_PATH = 'src/build/'
sop, references = None, None
universities = []

# Default LaTeX variables.
variables = {
    '\\hw': 'Heriot-Watt University',
    '\\supervisor': '\\textbf{Professor Neamat El Gayar}',
    '\\project': 'Multi-Element Association Rule Derivation from Minimum Spanning Trees'
}

def read_universities():
    global universities
    with open('universities.csv', 'r') as file:
        reader = csv.DictReader(file)

        for i, row in enumerate(reader):
            if i == 0:
                pass
            universities.append(row)

def init():
    global sop, references, universities
    # Read in document
    with open(SOP_FILEPATH, 'r') as f:
        sop = f.read()
        # sop = sop.replace('\\ ', ' ')

    # Read in docuemnts
    with open(REFERENCES_FILEPATH, 'r') as f:
        references = f.read()

    # Write out references
    with open(f'{OUTPUT_PATH}/references.bib', 'w+') as f:
        f.write(references)

    # Read in universities
    read_universities()

    # Move into src directory
    os.chdir(OUTPUT_PATH)

def make_pdf(university_details):

    # Merge two dictionaries in the local scope
    commands = variables.copy()
    commands.update(university_details)

    # Extract university name
    university = commands['\\uni']
    # Add 'the' prefix if first word is University
    if university.lower().split(' ')[0] == 'university':
        commands['\\uni'] = f'the {university}'

    # LaTeX commands string to prefix
    latex_commands = ''
    for key, value in commands.items():
        latex_commands += '\\newcommand{'+key+'}{'+value+'}\n'

    university = university.replace(' ', '_')
    # Write out .tex file
    output_file = f'{university}.tex'
    with open(output_file, 'w+') as f:
        f.write(latex_commands + sop)

    # PdfLatex + Biber + PdfLatex (x2)
    pdflatex = f'pdflatex -synctex=1 -interaction=nonstopmode -shell-escape {output_file}'
    biber = f'biber {university}'
    compilation = [pdflatex, biber, pdflatex, pdflatex]
    print(f'Currently in {os.getcwd()}')

    for cmd in compilation:
        print(f'Running `{cmd}`')
        os.system(cmd)

    # Move pdf to compile folder
    os.system(f'mv {university}.pdf compiled/')
    # Clear build folder
    build_file_extensions = ['aux', 'bbl', 'bcf', 'blg', 'log', 'run.xml', 'synctex.gz']
    for extension in build_file_extensions:
        os.system(f'rm *.{extension}')

if __name__ == '__main__':
    init()
    for uni in universities:
        make_pdf(uni)


import katagames_sdk as katasdk
katasdk.bootstrap(1)

# kataen = kengi = katasdk.import_kengi()
import katagames_engine as kengi
kengi.bootstrap_e()

import glvars
# from katagames_sdk.capsule.networking.httpserver import HttpServer
from defs import GameStates
import loctexts
from app.puzzle.state import PuzzleState
from app.title_screen.state import TitleScreenState

pygame = katasdk.import_pygame()

old_v_kengi = katasdk.import_kengi()
HttpServer = old_v_kengi.network.HttpServer  # katasdk.network.HttpServer in future versions

def run_game():
    kengi.init()
    glvars.init_fonts_n_colors()
    loctexts.init_repo(glvars.CHOSEN_LANG)

    kengi.declare_states(
        GameStates,
        {
            GameStates.TitleScreen: TitleScreenState,
            GameStates.Puzzle: PuzzleState
        },
        glvars
    )

    # - juste un test réseau, ce reset game ne sert a rien pour BLOKU-MAN,
    # il est utile pour mConquest...
    serv = HttpServer.instance()
    url = 'https://sc.gaudia-tech.com/tom/'
    params = {}
    full_script = url+'resetgame.php'
    print(full_script)
    res = serv.proxied_get(full_script, params)

    # - fin test réseau

    if not glvars.DEV_MODE:
        serv.set_debug_info(False)

    # cgm_engine.init(glvars.SCREEN_SIZE)
    # pygame.display.set_caption(tsl(Labels.WindowCaption))

    game_ctrl = kengi.get_game_ctrl()
    game_ctrl.turn_on()

    # launch the game, exit properly
    game_ctrl.loop()
    pygame.mixer.quit()

    if not kataen.runs_in_web():
        kataen.cleanup()

if __name__ == "__main__":
    run_game()


from rest_framework.urls import path

from .views import Signup, UserList

from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
    TokenVerifyView
)

urlpatterns = [
    path('login', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('signup', Signup.as_view()),
    path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('token/verify/', TokenVerifyView.as_view(), name='token_verify'),
    path('users/<int:pk>', UserList.as_view())
]


from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, MetaData, Table,Column
from flask import Flask, jsonify, render_template
import pandas as pd
import numpy as np
#################################################
# Flask Setup
#################################################
app = Flask(__name__)
#################################################
# Database Setup
#################################################
engine = create_engine("sqlite:///DataSets/belly_button_biodiversity.sqlite")
print("Connected to DB")

metadata = MetaData()
metadata.reflect(engine)
Base = automap_base()
Base.prepare(engine, reflect=True)

# mapped classes are ready
Otu =  Base.classes.otu
Samples = Base.classes.samples
Samples_Metadata = Base.classes.samples_metadata

# Create our session (link) from Python to the DB
session = Session(engine)

@app.route("/")
def home():
    """Render Home Page."""
    #return render_template("index.html")
    return render_template("index.html")

@app.route('/names')
def names():
    samples = metadata.tables['samples'].columns.keys()
    names = samples[1: len(samples)]
    return jsonify(names)

@app.route('/otu')
def sampleDesc():
    desc= session.query(Otu.lowest_taxonomic_unit_found).all()
    sample_desc = [ "%s" % x for x in desc ]
    return jsonify(sample_desc)

@app.route('/otu/<otuId>')
def sampleOtuDesc(otuId):
    print("otuId "+ otuId)
    desc= session.query(Otu.lowest_taxonomic_unit_found).filter(Otu.otu_id == otuId).first()
    print("desc "+ str(desc))
    sample_desc = [ "%s" % x for x in desc ]
    print("sample_desc "+ str(sample_desc))
    return jsonify(sample_desc)

@app.route('/metadata/<sample>')
def sampleMetadata(sample):
    sampleId = sample.split("_")[1]
    result= session.query(Samples_Metadata).filter(Samples_Metadata.SAMPLEID == sampleId).first()
    sample_metadata = vars(result)
    sample_metadata.pop('_sa_instance_state', None)
    return jsonify(sample_metadata)

@app.route('/wfreq/<sample>')
def washFrequency(sample):
    sampleId = sample.split("_")[1]
    freq= session.query(Samples_Metadata.WFREQ).filter(Samples_Metadata.SAMPLEID == sampleId).first()
    return jsonify(freq[0])

@app.route('/samples/<sample>')
def otuSampleValues(sample):
    sampleId = sample
    samples_df = pd.read_csv("DataSets/belly_button_biodiversity_samples.csv")
    #samples_df.head()
    otu_samples_df = samples_df[['otu_id', sampleId]]
    otu_samples_df = otu_samples_df.loc[otu_samples_df[sampleId] > 0]
    sorted_otu_samples_df = otu_samples_df.sort_values(by=sampleId, ascending=False)

    final_otuIds = list(sorted_otu_samples_df['otu_id'])
    list_otuIds = []
    for x in final_otuIds:
        list_otuIds.append( np.asscalar(x))
    final_sample_values = list(sorted_otu_samples_df[sampleId])
    list_sample_values = []
    for x in final_sample_values:
        list_sample_values.append( np.asscalar(x))
    otu_samples_dict = {'otu_ids': list_otuIds , 'sample_values': list_sample_values}
    print("otu_samples_dict " + str(otu_samples_dict))
    return jsonify(otu_samples_dict)

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


# Author：Pathfinder
# 文件名: goods_list_page
# IDE ：PyCharm
import logging

import allure
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions

from litemall_page_objects.base_page import BasePage

"""
商品列表页面
提供页面的方法
"""

class GoodsListPage(BasePage):
    goods_name_edit = 'Mikoto'
    _TEXT_FIRST_ROW_GOODS_NAME = (By.XPATH, "//tbody//tr[1]//td[3]/div")
    _INPUT_GOODS_ID = (By.XPATH, "//input[@type='text'][@placeholder='请输入商品ID']")
    _INPUT_GOODS_NUMBER = (By.XPATH, "//input[@type='text'][@placeholder='请输入商品编号']")
    _INPUT_GOODS_NAME = (By.XPATH, "//input[@type='text'][@placeholder='请输入商品名称']")
    _GOODS_ID = (By.XPATH, f"//*[contains(text(),'{goods_name_edit}')]/../../td[2]/div")
    _GOODS_NAME = (By.XPATH, "//tr[@class='el-table__row current-row']//td[3]/div[@class='cell']")
    _BUTTON_GOODS_EDIT = (By.XPATH, "//tr[@class='el-table__row']//td[12]//span[contains(text(),'编辑')]")
    _BUTTON_GOODS_DELETE = (By.XPATH, "//tbody//tr[1]//td[12]//span[contains(text(),'删除')]")
    _BUTTON_SEARCH = (By.XPATH, "//i[@class='el-icon-search']")
    _TOAST_EDIT_SUCCESS = (By.XPATH, "//div[@class='el-notification__content']/p[contains(text(),'编辑成功')]")
    _TOAST_DELETE_SUCCESS = (By.XPATH, "//div[@class='el-notification__content']/p")

    # 获取商品名称
    def get_goods_name(self):
        # name = self.driver.find_element(*self._TEXT_GOODS_NAME).text
        # print(name)
        logging.info("4.获取上架商品名称")
        with allure.step("步骤4：获取上架商品名称"):
            wait = WebDriverWait(self.driver, 5)
            goods_name = wait.until(
                expected_conditions.visibility_of_element_located(self._TEXT_FIRST_ROW_GOODS_NAME)).text
            return goods_name

    # 获取删除成功toast
    def get_delete_success_toast(self):
        logging.info("4.获取删除成功TOAS")
        with allure.step("步骤4：获取删除成功TOAST"):
            result_toast = self.driver.find_element(*self._TOAST_DELETE_SUCCESS).get_attribute('innerText')
            return result_toast

    # 获取编辑成功toast
    def get_edit_success_toast(self):
        logging.info("5.获取编辑成功TOAST")
        with allure.step("步骤5：获取编辑成功TOAST"):
            result_toast = self.driver.find_element(*self._TOAST_EDIT_SUCCESS).get_attribute('innerText')
            return result_toast

    # 删除商品按钮
    def goods_delete(self):
        """
        商品删除按钮
        :return:
        """
        logging.info("3.用商品编码搜索商品，删除商品")
        with allure.step("步骤3：用商品编码搜索商品，删除商品"):
            # 用商品编码搜索出对应的商品
            logging.info("-用商品编码搜索商品")
            self.driver.find_element(*self._INPUT_GOODS_NUMBER).send_keys(f"{self.goods_number}")
            # 点击查找
            logging.info("-点击查找")
            self.button_click(*self._BUTTON_SEARCH)
            # 删除商品
            logging.info("-点击删除商品")
            self.button_click(*self._BUTTON_GOODS_DELETE)
            # 返回页面本身，继续调用页面的方法
            return self

    # 商品编辑按钮
    def goods_edit(self):
        """
        商品编辑按钮
        :return:
        """
        logging.info("3.用商品编码搜索出商品，点击编辑")
        with allure.step("步骤3：用商品编码搜索出商品，点击编辑"):
            # 用商品编码搜索出对应商品
            logging.info("-先用商品编码搜索出对应商品")
            self.driver.find_element(*self._INPUT_GOODS_NUMBER).send_keys(f"{self.goods_number}")
            # 点击查找按钮
            logging.info("-点击查找按钮")
            self.button_click(*self._BUTTON_SEARCH)
            # 点击编辑
            logging.info("-点击编辑")
            self.button_click(*self._BUTTON_GOODS_EDIT)
            from litemall_page_objects.goods_edit_page import GoodsEditPage
            # 跳转到商品编辑页面
            return GoodsEditPage(self.driver)

    # 用商品id搜索出对应商品
    def search_by_goods_id(self):
        """
        使用商品id搜索出对应商品
        :return:
        """
        logging.info("3.用商品id搜索对应商品")
        with allure.step("步骤3：用商品id搜索对应商品"):
            # 以商品名字定位对应的商品id
            logging.info("-获取商品名称的对应商品id")
            goods_id = self.driver.find_element(*self._GOODS_ID).get_attribute('innerText')
            # 搜索栏输入商品id
            logging.info("-搜索栏输入商品id")
            self.form_send_keys(*self._INPUT_GOODS_ID, goods_id)
            # 点击查找
            logging.info("-点击查找")
            self.button_click(*self._BUTTON_SEARCH)
            # 搜索出的商品
            logging.info("-获取搜索出的商品名称")
            wait = WebDriverWait(self.driver, 5)
            goods_id_search_result = wait.until(
                expected_conditions.visibility_of_element_located(self._TEXT_FIRST_ROW_GOODS_NAME)).text

            return goods_id_search_result

    # 用商品编码搜索出对应的商品
    def search_by_goods_number(self):
        """
        使用商品编码搜索出对应的商品
        :return:
        """
        logging.info("3.用商品编码搜索出对应的商品")
        with allure.step("步骤3：用商品编码搜索出对应的商品"):
            # 在搜索栏输入商品编码
            logging.info("-在搜索栏输入商品编码")
            self.form_send_keys(*self._INPUT_GOODS_NUMBER, self.goods_number)
            # 点击查找
            logging.info("-点击查找")
            self.button_click(*self._BUTTON_SEARCH)
            # 搜索出的商品
            logging.info("-获取搜索出的商品名称")
            wait = WebDriverWait(self.driver, 5)
            goods_number_search_result = wait.until(
                expected_conditions.visibility_of_element_located(self._TEXT_FIRST_ROW_GOODS_NAME)).text

            return goods_number_search_result

    # 用商品名搜索出对应的商品
    def search_by_goods_name(self):
        """
        使用商品名称搜索出对应的商品
        :return:
        """
        logging.info("3.用商品名搜索出对应的商品")
        with allure.step("步骤3：用商品名搜索出对应的商品"):
            # 在搜索栏输入商品名
            logging.info("-在搜索栏输入商品名")
            self.form_send_keys(*self._INPUT_GOODS_NAME, "Mikoto")
            # 点击查找
            logging.info("-点击查找")
            self.button_click(*self._BUTTON_SEARCH)
            # 搜索出的商品
            logging.info("-获取搜索出的商品名称")
            wait = WebDriverWait(self.driver, 5)
            goods_name_search_result = wait.until(
                expected_conditions.visibility_of_element_located(self._TEXT_FIRST_ROW_GOODS_NAME)).text

            return goods_name_search_result


class TextValidation(object):

    def __init__(self, blacklist=None):
        self.root = dict()
        self.END = '/'
        self.blacklist = blacklist
        self.initialize_trie()

    def initialize_trie(self):
        for phrase in blacklist:
            node = self.root
            words = phrase.split()
            for word in words:
                node.setdefault(word, dict())
                node = node[word]
            node[self.END] = None

    def is_safe(self, text):
        words = text.split()
        for start, word in enumerate(words):
            if word in self.root:
                node = self.root[word]
                if self.END in node:
                    return False
                for w in words[start + 1:]:
                    if w in node:
                        node = node[w]
                        if self.END in node:
                            return False
                    else:
                        break
        return True

blacklist = ["machine guns", "world war i", "hate"]
textValid = TextValidation(blacklist)
s1 = "i love world war i"
s2 = "i love world war ii"
s3 = "world i love world war i"
s4 = "hate"
s = [s1, s2, s3, s4]

for ss in s:
    print(textValid.is_safe(ss))


import numpy as np
import torch
import os
import sys
import random
import torch.nn as nn
import torch.utils.data as tdata
import h5py
import glob
import scipy.io as sio
import math

sys.path.append(".")
from preprocess_face import preprocess_face, non_linearity

class VideoLoader:
	def __init__(self, root):
		self.vid_dir = root
		self.prev_frame = np.zeros((640,240), dtype=np.float32)

	def __call__(self, vid_fname):
		#pf = preprocess_face()
		print("reading video")
		self.frames = []
		self.par_vid_path = f'{self.vid_dir}/{vid_fname}'
		self.vid_path = glob.glob(self.par_vid_path)
		if(len(self.vid_path)) == 0:
			print("Video file ", self.par_vid_path, "not found")
			return -1

		video_mat = h5py.File(self.vid_path[0],'r')['data']
		print(video_mat)
		if(video_mat.shape[0] == 0):
			print("no frames read...")
		else:
			for idx in range(video_mat.shape[0]-300):
				#print(idx)
				try:
					image  = video_mat[idx,:,:]
				except:
					print("Failed to read frame")
					return self.prev_frame
				image = np.flipud(image)
				image = np.fliplr(image)
				image = np.uint8(image*255)
				self.frames.append(image)
			self.frames = np.array(self.frames)

		return self.frames

class LabelLoader:
	def __init__(self, root):
		self.label_dir = root

	def __call__(self,index):
		print("loading ecg signal")
		self.ecg_signal = np.load(self.label_dir[index])

		return self.ecg_signal

class VidEcg_sync:
	def __init__(self, root):
		self.sync_sig_dir = root
		print(self.sync_sig_dir)
		self.ts_file = sio.loadmat(self.sync_sig_dir)['timingCell']

	def __call__(self, sub, ses, task):
		'''each session is a 195 seconds window
		+ve ST(Start Time) means IR video recording started earlier then ECG recodring
		--clip the IR video to t_th second & ECG from zero reading
		-ve ST means IR video recodring started later then ECG recording
		--clip the ECG signal by t seconds & IR video from zero reading
		IR video frame rate : 15hz & ECG signal rate : 1920hz
		1 IR video frame = 128 ECG readings'''
		#sub = 135; ses = 3; task = 'cf'
		#print(sub, ses, task)
		'''type-casting to supress the python FutureWarning'''
		sub_loc  = np.where(self.ts_file[:,0:1] == int(sub))
		ses_loc  = np.where(self.ts_file[sub_loc[0],1:2]== int(ses))
		task_loc = np.where(self.ts_file[sub_loc[0],:][ses_loc[0],2:3] == str(task))
		start_ts = self.ts_file[sub_loc[0],:][ses_loc[0],:][task_loc[0],:][0][3][0][0]
		feetin_ts= self.ts_file[sub_loc[0],:][ses_loc[0],:][task_loc[0],:][0][3][0][2]
		print("start time", start_ts, "Immerse feet: ", feetin_ts)

		return start_ts, feetin_ts

#------------------------------------------------------------------------------------------------------------------------------------#

class thermaldataset(tdata.Dataset):

	def __init__(self, label, ir_video, sync_sig, phase):
		'''ecg label data path'''# sj160_se03_cv_LJ.mea.mat
		self.label = label
		self.label_files = os.listdir(self.label)
		self.all_dir=[os.path.join(self.label,a) for a in self.label_files]
		#Init load label class
		self.labelloader = LabelLoader(self.all_dir)
		'''ir_video data path'''
		self.ir_video = ir_video
		self.videoloader = VideoLoader(self.ir_video)
		'''sync signal for ecg/ir_video'''
		self.sync_sig = sync_sig
		self.sync_sig_file = os.path.join(self.sync_sig, os.listdir(self.sync_sig)[0])
		self.videcg_sync = VidEcg_sync(self.sync_sig_file)
		'''train/validate/test phase'''
		self.phase = phase

	def __getitem__(self, index):
		#label data
		label_data = self.labelloader(index)
		#vid filename
		label_fname = self.all_dir[index].split('/')[-1].split('_')
		sub = label_fname[0].split('sj')[-1]
		ses = label_fname[1].split('se')[-1].split('0')[-1]
		vid_fname = f'BOSS_-BOSS_{sub}_1_{ses}_{label_fname[2]}-*'
		#IR video data
		ir_video_data = self.videoloader(vid_fname)
		#In case the video read fails
		try:
			if(ir_video_data.all() == -1 ):
				print("Error..")
				return -1
		except:
			if(ir_video_data == -1 ):
				print("File not found")
				return -1

		print("shape of video data", ir_video_data.shape, vid_fname)
		#update corresponding label if person moves out of frame
		#ir video & ecg signal sync
		start_ts, feetin_ts = self.videcg_sync(sub, ses, label_fname[2])
		'''IR vid frame rate : 15hz & ECG rate : 1920hz, 128 label per video frame'''
		if(start_ts > 0):
			start_frame  = math.ceil(start_ts*15)
			if(start_frame > ir_video_data.shape[0]*.75):
				print("getitem, start_frame > ir_vid")
				return -1
			ir_video_data = ir_video_data[start_frame:,:,:]
			label_data = label_data[:(ir_video_data.shape[0]*128)]
			feetin_frame = math.ceil(feetin_ts*15) - start_frame
		else:
			start_ecg = math.ceil(abs(start_ts)*1920)
			if(start_ecg > label_data.shape[0]*0.75):
				print("getitem, start_ecg> label shape")
				return -1
			label_data = label_data[start_ecg:(start_ecg + (ir_video_data.shape[0]*128))]
			feetin_frame = math.ceil(feetin_ts*15)

		#making length of label_data = len(vid)*128
		rem = label_data.shape[0]%128
		label_pad_len = 0
		if(rem != 0):
			div = label_data.shape[0]/128
			label_pad_len = ((int(div)+1)*128) - label_data.shape[0]

		label_data = np.pad(label_data, (0, int(label_pad_len)), 'symmetric').reshape((-1, 128))
		#update corresponding label if person moves out of frame
		print(ir_video_data.shape, label_data.shape)
		#added if the person moves out of the frame then make label 0
		if(ir_video_data.shape[0] != label_data.shape[0]):
			print("Label and video length mismatch")
			return -1
		data_sample = {'data'     : ir_video_data,
					   'label'    : label_data,
					   'feetin_frame' : feetin_frame,
					   'feetin_ts': feetin_ts,
					   'filename' : vid_fname}
		return data_sample

	def __len__(self):
		return len(self.all_dir)

#------------------------------------------------------------------------------------------------------------------------------------#
#file usage : python dataloader.py ../data/test_label ../data/mat_files ../data/sync_data

if __name__=='__main__':
	label_name    = sys.argv[1]
	ir_vid_name   = sys.argv[2]
	sync_sig_name = sys.argv[3]

	print(label_name, ir_vid_name)
	label    = "{}/".format(label_name)
	ir_video = "{}/".format(ir_vid_name)
	print(label, ir_video)

	train_dataset = thermaldataset(
		label    = "{}/".format(label_name),
		ir_video = "{}/".format(ir_vid_name),
		sync_sig = "{}/".format(sync_sig_name),
        phase='train'
	)

	#for i in range(len(train_dataset)):
	#	sample = train_dataset[i]
	#	print(i, sample['video_frames'].shape, sample['label'].shape)

	trainloader = torch.utils.data.DataLoader(train_dataset,batch_size=1,shuffle=True,num_workers=2)
	for i in trainloader:
		pass
		#import pdb;pdb.set_trace()


import os
import numpy as np
import scipy.io

from crop_extraction_common import *

dataset_path = '../data/CUB-200-2011'
cmr_cachedir_path = '../data/cmr-cachedir'
preprocessed_path = '../preprocessed-data/CUB-200-2011'

split = 'train'

crop_size = 192
crops_per_file = 256
augmentation_factor = 10

def get_matrices_from_sfm(sfm_annotation, crop_centre_x, crop_centre_y, crop_size, crop_rotation_matrix):

    # In the original data...
    # x is the horizontal / across-the-wings / mirror-symmetric axis
    # y is the front-to-back / beak-to-tail axis
    # z is the dorsal-frontal axis
    # In our conventions...
    # x is length = beak-to-tail
    # y is vertical = dorsal-frontal
    # z = mirror-symmetric = across-the-wings
    canonicalisation_matrix = np.float32([
        [0., 0., 1.],
        [1., 0., 0.],
        [0., 1., 0.],
    ]).T

    rotation_matrix = sfm_annotation.rot
    scale = sfm_annotation.scale
    translation = sfm_annotation.trans

    rotation_matrix = rotation_matrix.T
    scale_matrix = np.diag([1., 1., -1.]) * scale

    view_matrix = np.concatenate([
        np.concatenate([
            np.matmul(np.matmul(canonicalisation_matrix, rotation_matrix), scale_matrix),
            np.zeros([3, 1])
        ], axis=1),
        [[translation[0], translation[1], -2.732 * scale, 1.]]
    ], axis=0)

    near = 10.
    far = 1200.

    projection_matrix = np.float32([
        [2. / crop_size, 0., 0., -(crop_centre_x * 2 - 2) / crop_size],  # the -2 offset accounts for 1-indexing in matlab
        [0., -2. / crop_size, 0., (crop_centre_y * 2 - 2) / crop_size],
        [0., 0., -2. / (far - near), -(far + near) / (far - near)],
        [0., 0., 0., 1.],
    ]).T
    crop_rotation_matrix_4x4 = np.eye(4)
    crop_rotation_matrix_4x4[:2, :2] = crop_rotation_matrix
    projection_matrix = np.matmul(projection_matrix, crop_rotation_matrix_4x4)

    return view_matrix, projection_matrix

def main():

    output_path = '{}/{}x{}_{}-per-file_{}x-jr-augm/{}'.format(preprocessed_path, crop_size, crop_size, crops_per_file, augmentation_factor, split)
    if not os.path.exists(output_path):
        os.makedirs(output_path)

    image_infos = scipy.io.loadmat(cmr_cachedir_path + '/cub/data/{}_cub_cleaned.mat'.format(split), squeeze_me=True, struct_as_record=False)['images']
    sfm_annotations = scipy.io.loadmat(cmr_cachedir_path + '/cub/sfm/anno_{}.mat'.format(split), squeeze_me=True, struct_as_record=False)['sfm_anno']

    image_base_path = '{}/CUB_200_2011/images'.format(dataset_path)

    with ShardedRecordWriter(output_path + '/{:04d}.tfrecords', crops_per_file) as writer:

        for image_index, (image_info, sfm_annotation) in enumerate(zip(image_infos, sfm_annotations)):

            print('{} / {}: {}'.format(image_index + 1, len(image_infos), image_info.rel_path))

            image_filename = os.path.join(image_base_path, image_info.rel_path)

            image = cv2.imread(image_filename)
            assert image.shape[-1] == 3

            for _ in range(augmentation_factor):

                crop_jitter = np.random.uniform(-0.05, 0.05, size=[4])
                bbox = np.float32([image_info.bbox.x1, image_info.bbox.y1, image_info.bbox.x2, image_info.bbox.y2])
                raw_crop_width = bbox[2] - bbox[0]
                raw_crop_height = bbox[3] - bbox[1]
                bbox += crop_jitter * [raw_crop_width, raw_crop_height, raw_crop_width, raw_crop_height]
                bbox = (bbox + 0.5).astype(np.int32)
                crop_centre_x = (bbox[0] + bbox[2]) / 2
                crop_centre_y = (bbox[1] + bbox[3]) / 2

                crop_rotation = np.random.uniform(-15., 15.)  # degrees
                rotation_matrix = cv2.getRotationMatrix2D((crop_centre_x, crop_centre_y), crop_rotation, 1.0)
                rotated_image = cv2.warpAffine(image, rotation_matrix, image.shape[1::-1], borderMode=cv2.BORDER_REFLECT)
                rotated_mask = cv2.warpAffine(image_info.mask, rotation_matrix, image.shape[1::-1], borderMode=cv2.BORDER_REFLECT)

                cropped_image, crop_original_size = extract_crop(rotated_image, image.shape[1], image.shape[0], crop_size, 0.05, *bbox)
                cropped_mask, _ = extract_crop(rotated_mask, image.shape[1], image.shape[0], crop_size, 0.05, *bbox)

                view_matrix, projection_matrix = get_matrices_from_sfm(
                    sfm_annotation,
                    crop_centre_x, crop_centre_y,
                    crop_original_size,
                    rotation_matrix[:, :2]
                )

                background = cv2.inpaint(cropped_image, cv2.dilate(cropped_mask, np.ones([3, 3]), iterations=2), 5, cv2.INPAINT_TELEA)

                example = tf.train.Example(
                    features=tf.train.Features(
                        feature={
                            'pixels': jpeg_feature(cropped_image),
                            'background': jpeg_feature(background),
                            'mask': png_feature(cropped_mask.astype(np.float32)),
                            'rotation': float32_feature(0.),
                            'projection_matrix': float32_feature(projection_matrix),
                            'view_rotation_matrix': float32_feature(view_matrix),  # note that it is in fact a complete view matrix in our case!
                            'dataset_name': string_feature('CUB-200-2011')
                        }))
                writer.write(example.SerializeToString())

if __name__ == '__main__':
    main()


from tkinter import *

root=Tk()
root.title('Calculator')
root.geometry('354x460')

mylabel=Label(root,text="CALCULATOR",font=("Courier New",30,'bold')).pack(side=TOP)

textin=StringVar()
operator=""

def clickbut(numbers):
	global operator
	operator = operator + str(numbers)
	textin.set(operator)

def clrbut():
	textin.set('')

def equbut():
	global operator
	try:
		add=str(eval(operator))
	except:
		add = str(eval(textin.get()))
	textin.set(add)
	operator=''

# Buttons
metext = Entry(root,font=("Courier New",12,'bold'),textvar=textin,width=25,bd=5,bg='powder blue').pack()

b1 = Button(root,padx=18,pady=18,bd=4,bg='light blue',command=lambda:clickbut(1),text="1",font=("Courier New",10,'bold'))
b1.place(x=10,y=100)

b2 = Button(root,padx=18,pady=18,bd=4,bg='light blue',command=lambda:clickbut(2),text="2",font=("Courier New",10,'bold'))
b2.place(x=10,y=170)

b3 = Button(root,padx=18,pady=18,bd=4,bg='light blue',command=lambda:clickbut(3),text="3",font=("Courier New",10,'bold'))
b3.place(x=10,y=240)

b4 = Button(root,padx=18,pady=18,bd=4,bg='light blue',command=lambda:clickbut(4),text="4",font=("Courier New",10,'bold'))
b4.place(x=75,y=100)

b5 = Button(root,padx=18,pady=18,bd=4,bg='light blue',command=lambda:clickbut(5),text="5",font=("Courier New",10,'bold'))
b5.place(x=75,y=170)

b6 = Button(root,padx=18,pady=18,bd=4,bg='light blue',command=lambda:clickbut(6),text="6",font=("Courier New",10,'bold'))
b6.place(x=75,y=240)

b7 = Button(root,padx=18,pady=18,bd=4,bg='light blue',command=lambda:clickbut(7),text="7",font=("Courier New",10,'bold'))
b7.place(x=140,y=100)

b8 = Button(root,padx=18,pady=18,bd=4,bg='light blue',command=lambda:clickbut(8),text="8",font=("Courier New",10,'bold'))
b8.place(x=140,y=170)

b9 = Button(root,padx=18,pady=18,bd=4,bg='light blue',command=lambda:clickbut(9),text="9",font=("Courier New",10,'bold'))
b9.place(x=140,y=240)

b0 = Button(root,padx=18,pady=18,bd=4,bg='light blue',command=lambda:clickbut(0),text="0",font=("Courier New",10,'bold'))
b0.place(x=10,y=310)

plus = Button(root,padx=18,pady=18,bd=4,bg='light blue',command=lambda:clickbut('+'),text="+",font=("Courier New",10,'bold'))
plus.place(x=205,y=100)

minus = Button(root,padx=18,pady=18,bd=4,bg='light blue',command=lambda:clickbut('-'),text="-",font=("Courier New",10,'bold'))
minus.place(x=205,y=170)

mult = Button(root,padx=18,pady=18,bd=4,bg='light blue',command=lambda:clickbut('*'),text="*",font=("Courier New",10,'bold'))
mult.place(x=205,y=240)

divi = Button(root,padx=18,pady=18,bd=4,bg='light blue',command=lambda:clickbut('/'),text="/",font=("Courier New",10,'bold'))
divi.place(x=205,y=310)

dot = Button(root,padx=50,pady=18,bd=4,bg='light blue',command=lambda:clickbut('.'),text=".",font=("Courier New",10,'bold'))
dot.place(x=75,y=310)

clear = Button(root,padx=14,pady=123,bd=4,bg='light blue',command=clrbut,text="CE",font=("Courier New",10,'bold'))
clear.place(x=270,y=100)

equal = Button(root,padx=151,pady=14,bd=4,bg='light blue',command=equbut,text="=",font=("Courier New",10,'bold'))
equal.place(x=10,y=380)

root.mainloop()


################## Helper Code Below -- don't delete! ##################

# Helper Code 1
bach_data = []
with open("Bachelors.txt", "r") as f:
    for num in f:
        num = float(num.strip())
        bach_data.append(num)
f.close()

# Helper Code 2
pop_data = []
with open("Population.txt", "r") as file:
    for value in file:
        value = float(value.strip())
        pop_data.append(value)
file.close()

# Helper Code 3
avg_income = []
with open("Income.txt", "r") as file:
    for value in file:
        value = float(value.strip())
        avg_income.append(value)
file.close()

# Helper Code 4
high_school_data = []
with open("HighSchool.txt", "r") as file:
    for value in file:
        value = float(value.strip())
        high_school_data.append(value)
file.close()

# Helper Code 5
poverty_data = []
with open("Poverty.txt", "r") as file:
    for value in file:
        value = float(value.strip())
        poverty_data.append(value)
file.close()

# TASK 1

# QUESTION 1.1
def percent_bachelors(bach_data, pop_data):
    '''
    This function takes the bachelor's and population data
    for each county and returns the percentage of people
    with a bachelors or higher across all counties
    '''
    bs_sum = 0
    population = 0
    for i in range(len(bach_data)):
        bs_sum += ((bach_data[i]/100)*pop_data[i])
        population += pop_data[i]
    return (bs_sum / population) * 100

# QUESTION 1.2

def income_above_50k(avg_income):
    '''
    This function takes the average income of all counties
    and returns the percentage of counties with an income
    above $50,000
    '''
    total_county = 0
    for income in avg_income:
        if income > 50000:
            total_county += 1
    return (total_county/len(avg_income)) * 100

# ---------------------------------------------------------------------------------------------------- #

# TASK 2
def high_school_below_threshold(high_school_data, threshold):
    '''
    This function takes the percentage of high graduate in each county and
    returns the number counties with a percentage lower than a threshold number
    '''
    i = 0
    for x in high_school_data:
        if x < threshold:
            i += 1
    return i

# ---------------------------------------------------------------------------------------------------- #

# TASK 3
def bachelors_above_threshold(bach_data, threshold):
    '''
    This function takes the percentage of bachelor degree holders
    in all counties and returns the number of counties with a
    percentage higher than a threshold number
    '''
    i = 0
    for x in bach_data:
        if x > threshold:
            i += 1
    return i

# ---------------------------------------------------------------------------------------------------- #

# TASK 4

def below_poverty_total(poverty_data, pop_data):
    '''This function takes the percentage of people below poverty level in a county
    and the total population in a county and returns the total number of
    people below poverty level across all counties
    '''
    count = 0
    for i in range(len(poverty_data)):
        count += ((poverty_data[i]/100)*pop_data[i])
    return count

# ---------------------------------------------------------------------------------------------------- #

# TASK 5
def percent_below_poverty(poverty_data, pop_data):
    '''This function takes the total number of people
    below poverty level from the function above and
    returns the percentage of people living in poverty'''
    population = 0
    for x in pop_data:
        population += x
    return (below_poverty_total(poverty_data, pop_data) / population) * 100

# ---------------------------------------------------------------------------------------------------- #

# TASK 6
def education_vs_poverty(bach_data, poverty_data):
    '''This function takes the percentage of bachelor degrees and poverty
    level in each county and returns the average poverty level for
    counties with respect to a certain percentage of bachelors degree'''
    L1 = 0
    L2 = 0
    L3 = 0
    L4 = 0
    count1 = 0
    count2 = 0
    count3 = 0
    count4 = 0
    for i in range(len(bach_data)):
        if bach_data[i] < 10:
            L1 += poverty_data[i]
            count1 += 1
        elif 10 <= bach_data[i] < 20:
            L2 += poverty_data[i]
            count2 += 1
        elif 20 <= bach_data[i] < 30:
            L3 += poverty_data[i]
            count3 += 1
        elif 30 <= bach_data[i]:
            L4 += poverty_data[i]
            count4 += 1
    return f'Average Poverty Level:\nBachelors <10%: {(L1/count1)}%\nBachelors >=10% and <20%: {L2/count2}%\nBachelors >=20% and <30%: {L3/count3}%\nBachelors >=30: {L4/count4}%'

BS_Percentage = percent_bachelors(bach_data,pop_data)
print(f'National Percentage of People with a Bachelors: {BS_Percentage}%\n')

County_Percentage = income_above_50k(avg_income)
print(f"Percentage of Counties with an Average Income Higher than $50,000: {County_Percentage}%\n")

threshold = float(input('Enter a Threshold Percentage for High School Graduates: '))
total_number_of_counties = high_school_below_threshold(high_school_data, threshold)
print(f"Total Number of Counties with a Percentage of High School Graduate Below {threshold}%: {total_number_of_counties} Counties\n")

threshold = float(input('Enter a Threshold Percentage for BS Degree Holders: '))
total_BS_Counties = bachelors_above_threshold(bach_data, threshold)
print(f'Total Number of Counties with a Percentage of BS Degree Holders above {threshold}%: {total_BS_Counties} Counties \n')

total_number_below_poverty = below_poverty_total(poverty_data, pop_data)
print(f"Total Number of People Below Poverty Level: {total_number_below_poverty}\n")

percentage_poverty = percent_below_poverty(poverty_data, pop_data)
print(f'Percentage of People below Poverty Level: {percentage_poverty}\n')

national_averages = education_vs_poverty(bach_data,poverty_data)
print(national_averages)


#!/usr/bin/env python
'''
    AnimateTools
    Library which has a simple and extendable way to animate
    agent-based simulation of active-matter (swarms, colloids, flocks....).
    The animation can be saved as movies, gifs, images of can just be displayed.
    v0.1, 24.8.2020

    (C) 2020 Pascal Klamser

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''
from time import sleep
from scipy import spatial
import numpy as np
import matplotlib
if __name__ == '__main__':
    matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib import animation
from functools import partial
import os

def setDefault(x, val):
    if x is None:
        x = val
    return x

def voronoi_Lines(vor):
    """
    Plot the given Voronoi diagram in 2-D

    Parameters
    ----------
    vor : scipy.spatial.Voronoi instance
        Diagram to plot

    Returns
    -------
    finite_segments
    infinite_segments
    """
    if vor.points.shape[1] != 2:
        raise ValueError("Voronoi diagram is not 2-D")

    center = vor.points.mean(axis=0)
    ptp_bound = vor.points.ptp(axis=0)

    finite_segments = []
    infinite_segments = []
    for pointidx, simplex in zip(vor.ridge_points, vor.ridge_vertices):
        simplex = np.asarray(simplex)
        if np.all(simplex >= 0):
            finite_segments.append(vor.vertices[simplex])
        else:
            i = simplex[simplex >= 0][0]  # finite end Voronoi vertex

            t = vor.points[pointidx[1]] - vor.points[pointidx[0]]  # tangent
            t /= np.linalg.norm(t)
            n = np.array([-t[1], t[0]])  # normal

            midpoint = vor.points[pointidx].mean(axis=0)
            direction = np.sign(np.dot(midpoint - center, n)) * n
            far_point = vor.vertices[i] + direction * ptp_bound.max()

            infinite_segments.append([vor.vertices[i], far_point])
    return finite_segments, infinite_segments

class voro_lines:
    def __init__(self, preys, axs, preds=None, t0pred=None):
        '''
        INPUT:
            preys datCollector object
                position and velocity data of prey
            axs
            preys datCollector object
                position and velocity data of predators
            t0p int
                time-step at which predator appears
        '''
        self.t0pred = t0pred
        self.pos = preys.pos
        self.posExtra = None
        if preds is not None:
            self.posExtra = preds.pos
        posNow = self.pos[0]
        if preds is not None and t0pred == 0:
            posNow = np.vstack((posNow, self.posExtra[0]))
        vor = spatial.Voronoi(posNow)
        lines_normal, lines_inf = voronoi_Lines(vor)
        self.voro_lines = axs.add_collection(LineCollection(lines_normal,
                                                            colors='b',
                                                            alpha=0.3, lw=0.9))

    def update(self, s):
        posNow = self.pos[s]
        if self.posExtra is not None and s >= self.t0pred:
            posNow = np.vstack((posNow, self.posExtra[s-self.t0pred]))
        posNow = posNow[~np.isnan(posNow)].reshape(-1, 2)
        vor = spatial.Voronoi(posNow)
        lines_normal, lines_inf = voronoi_Lines(vor)
        self.voro_lines.set_segments(lines_normal)
        return self.voro_lines

class velocityArrows:
    def __init__(self, dat, ax, color=None, delay=None):
        '''
        INPUT:
            pos.shape (N, 2)
            vel.shape (N, 2)
        '''
        if color is None:
            color = 'r'
        if delay is None:
            delay = 0
        self.pos = dat.pos
        self.vel = dat.vel
        self.delay = delay
        self.createFunc = partial(ax.quiver, color=color,
                            angles='xy', scale_units='xy', scale=1)
    def create(self):
        self.Q = self.createFunc(self.pos[0].T[0], self.pos[0].T[1],
                                 self.vel[0].T[0], self.vel[0].T[1])

    def update(self, s):
        s -= self.delay
        if s == 0:
            self.create()
        elif s > 0:
            if not hasattr(self, 'Q'):
                self.create()
            self.Q.set_offsets(self.pos[s])
            self.Q.set_UVC(self.vel[s].T[0], self.vel[s].T[1])
        if s >= 0:
            return self.Q

def h5ReadDset(h5file, dname):
    data = h5file.get(dname)
    np_data = np.array(data)
    print(np_data)
    if gname in list(h5file.keys()):
        data2 = h5file.get(gname + '/datadouble')
        np_data2 = np.array(data2)
        print(np_data2)

class datCollector:
    def __init__(self, dat):
        if dat is None:
            self.pos = None
            self.vel = None
        else:
            dat = dat.T
            self.pos = dat[:2].T
            self.vel = dat[2:4].T
            if len(dat) > 4:
                self.fitness = dat[4].T
                self.force = dat[5:].T
            dead = np.where( np.sum(self.pos, axis=-1) == 0 )
            self.pos[dead] = np.nan
            self.vel[dead] = np.nan

class headAndTail:
    def __init__(self, data, size, colors, ax, tail_length,
                 cmap=None, scatter=None, marker=None, delay=None):
        '''
        INPUT:
            data.shape(Time, N, N_coord)
                data containing for "Time" time points the position for "N"
                agents.
            size float
                radius of marker size
            colors.shape(N) or (Time, N)
                array or list containing for each particle a colorcode (float)
            ax matplotlib.axes.AxesSubplot object
                Subplot where the data is plotted
            cmap matplotlib.Colormap
                e.g.: cmap = plt.get_cmap('Reds')
            scatter boolean
                if true scatter is used instead of plot
        OUTPUT:
            heads
            tails
        '''
        if delay is None:
            delay = 0
        if type(colors[0]) == np.ndarray:
            if cmap is None:
                cmap = plt.get_cmap('coolwarm')
            self.colors = colors
            self.cmap = cmap
            colors = cmap(colors[0])
        self.pos = data.pos
        self.tail_length = tail_length
        self.scatter = scatter
        self.delay = delay
        self.ax = ax
        self.sizeRaw = size
        if marker is None:
            marker = 'o'
        if self.scatter is None:
            self.scatter = True
        if self.scatter:
            self.createFunc = partial(ax.scatter, marker=marker, c=colors)# , cmap=cmap)
        else:
            print('ATTENTION: scatter=False does not support change of colors')
            self.createFunc = partial(ax.plot, marker=marker, c=colors, linestyle='none')

    def sizeAdjust(self):
        trans = self.ax.transData
        pixels = trans.transform([(0, 1), (1, 0)]) - trans.transform((0, 0))
        xpix = pixels[1].max()
        self.size = self.sizeRaw * xpix / 77. * 100
        if self.scatter:
            self.size = self.size ** 2

    def create(self):
        posInit = self.pos[0]   # use Time=1 for initialization
        if self.scatter:
            self.heads = self.createFunc(posInit.T[0], posInit.T[1], s=self.size)
            self.tails = self.createFunc(posInit.T[0], posInit.T[1],
                                         s=self.size/4, alpha=0.5)
        else:
            self.heads = self.createFunc(posInit.T[0], posInit.T[1], ms=self.size)[0]
            self.tails = self.createFunc(posInit.T[0], posInit.T[1],
                                         ms=self.size/2, alpha=0.5)[0]

    def update(self, s):
        self.sizeAdjust()
        s = s - self.delay
        if s == 0:
            self.create()
        elif s > 0:
            if not hasattr(self, 'heads'):
                self.create()
            endtail = s - self.tail_length
            if endtail < 0:
                endtail = 0
            if self.scatter:
                tail = self.pos[endtail:s].reshape(-1, 2)
                self.heads.set_offsets(self.pos[s])
                self.tails.set_offsets(tail)
                self.heads.set_sizes(len(self.pos[s]) * [self.size])
                self.tails.set_sizes(len(tail) * [self.size / 4])
                if hasattr(self, 'colors'):
                    self.heads.set_color(self.cmap(self.colors[s]))
                    self.tails.set_color(self.cmap(self.colors[s]))
            else:
                self.heads.set_data(self.pos[s].T[0], self.pos[s].T[1])
                self.tails.set_data(self.pos[endtail:s].T[0],
                                    self.pos[endtail:s].T[1])
                self.heads.set_markersize(self.size)
                self.tails.set_markersize(self.size / 2)
        if s >= 0:
            return self.heads, self.tails

class Limits4Pos:
    '''
    adjust the limits of the axis to the positions of the agents
    -> always see all agents and not more
    '''
    def __init__(self, positions, ax, delay=None):
        '''
        Assumes that the start-positions can be different
        but all end synchrounously
        INPUT:
            positions [posA, posB, ....]
                list of arrays containing positions, i.e.
                    posA.shape = [Time, Nagents, 2] OR [Time, 2]
        '''
        if delay is None:
            delay = 0
        self.delay = delay
        self.ax = ax
        times = [len(pos) for pos in positions]
        limits = np.zeros((max(times), 4)) * np.nan
        for i, limitFunc in enumerate([np.nanmin, np.nanmax]):
            for j in range(2): # x or y
                for k, pos in enumerate(positions):
                    if len(pos.shape) < 3:
                        pos = np.expand_dims(pos, axis=1)
                    limitGlob = limits[:times[k], i*2+j]
                    limitHere = limitFunc(pos[::-1, :, j], axis=1)
                    compareLimits = np.vstack((limitHere, limitGlob))
                    limitGlob[:] = limitFunc(compareLimits, axis=0)
        limits = limits[::-1]
        extra = 1
        self.xMin = limits[:, 0] - extra
        self.yMin = limits[:, 1] - extra
        self.xMax = limits[:, 2] + extra
        self.yMax = limits[:, 3] + extra

    def update(self, s):
        s = s - self.delay
        if s >= 0:
            self.ax.set_xlim(self.xMin[s], self.xMax[s])
            self.ax.set_ylim(self.yMin[s], self.yMax[s])
        return self.ax

class LimitsByCOM:
    def __init__(self, pos, ax, centerSize):
        '''
        INPUT:
            pos.shape [T, N, 2]
        '''
        self.ax = ax
        self.cs = centerSize
        if len(pos.shape) < 3:
            pos = np.expand_dims(pos, axis=1)
        self.com = np.nanmean(pos, axis=1)

    def update(self, s):
        self.ax.set_xlim(self.com[s, 0] - 0.5 * self.cs,
                         self.com[s, 0] + 0.5 * self.cs)
        self.ax.set_ylim(self.com[s, 1] - 0.5 * self.cs,
                         self.com[s, 1] + 0.5 * self.cs)
        return self.ax

class ForceLines:
    def __init__(self, pos, force, ax, magnify=None):
        '''
        INPUT:
            pos.shape [T, N, 2]
            force.shape [T, N, 2]
        '''
        if magnify is None:
            magnify = 0.25
        assert len(pos.shape) == 3, 'wrong shape for ForceLines'
        self.N = pos.shape[1]
        self.magni = magnify
        self.pos = pos
        self.force = force
        line = self.posAndForce2Line(0)
        self.forceLines = ax.plot(line[0], line[1])[0]

    def posAndForce2Line(self, s):
        line = []
        for i in range(2):
            line += [np.array(list(zip(self.pos[s, :, i],
                                       self.pos[s, :, i] + self.magni * self.force[s, :, i],
                                       self.N * [None]))).flatten()]
        return line

    def update(self, s):
        line = self.posAndForce2Line(s)
        self.forceLines.set_data(line[0], line[1])
        return self.forceLines

class lineCOM:
    def __init__(self, pos, color, ax):
        self.com = np.nanmean(pos, axis=1)
        self.lineCOM = ax.plot(self.com[0 ,0], self.com[0, 1], c=color)[0]

    def update(self, s):
        self.lineCOM.set_data(self.com[:s ,0], self.com[:s, 1])
        return self.lineCOM

class lineFadingCOM:
    def __init__(self, pos, ax, lineLength, alpha=None):
        if alpha is None:
            alpha = 0.7
        self.N = lineLength
        self.com = np.nanmean(pos, axis=1)
        points = np.array(self.N*[self.com[0]]).reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        norm = plt.Normalize(0, self.N-1)
        lc = LineCollection(segments, cmap='Reds', norm=norm, alpha=alpha)
        lc.set_array(np.arange(self.N))
        self.lc = ax.add_collection(lc)

    def update(self, s):
        if s >= self.N:
            points = self.com[s-self.N+1:s+1].reshape(-1, 1, 2)
        else:
            points = np.vstack(( (self.N-s) * [self.com[0]],
                                 self.com[:s+1])).reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        self.lc.set_segments(segments)
        return self.lc

class circleCOM:
    def __init__(self, pos, radius, color, ax):
        self.com = np.nanmean(pos, axis=1)
        circle = plt.Circle((self.com[0 ,0], self.com[0, 1]), radius,
                            color=color, fill=False)
        self.circCom = ax.add_artist(circle)

    def update(self, s):
        self.circCom.center = self.com[s ,0], self.com[s, 1]
        # self.circCom.set_center((self.com[s ,0], self.com[s, 1]))
        return self.circCom

class circlesCOM:
    def __init__(self, pos, radius, color, ax, Ncircs):
        self.com = np.nanmean(pos, axis=1)
        self.circCom = []
        radiis = np.linspace(radius, radius/2, Ncircs)
        for rad in radiis:
            circle = plt.Circle((self.com[0 ,0], self.com[0, 1]), rad,
                                color=color, fill=False)
            self.circCom.append(ax.add_artist(circle))

    def update(self, s):
        for i, circ in enumerate(self.circCom):
            z = s-i
            if z > 0:
                circ.center = self.com[z ,0], self.com[z, 1]
                # circ.set_center((self.com[z ,0], self.com[z, 1]))
        return tuple(self.circCom)

class taskCollector:
    '''
    collects tasks (=objects with update(s) method returning artist objects)
    '''
    def __init__(self):
        self.taskList = []

    def append(self, task):
        self.taskList.append(task)

    def update(self, s):
        '''
        returns all output summarized
        '''
        artistObjs = ()
        for task in self.taskList:
            artist = task.update(s)
            if type(artist) != tuple:
                artist = tuple([artist])
            # print(type(artistObjs), type(artist), task.__class__)
            artistObjs += artist
        return artistObjs

def UpdateViaDraw(fig, tasks, tmin, tmax, fps=None, dpi=None,
                  mode=None, name=None, repeat=None):
    '''
    TODO: repeat is only dummy (ensure same parameters as UpdateViaAnimation)
    '''
    fps = setDefault(fps, 15)
    dpi = setDefault(dpi, 300)
    mode = setDefault(mode, 'normal')
    name = setDefault(name, 'Animation')
    plt.show(block=False) # necessary for normal
    maxFps = 20 # this is system specific
    interval = 1/fps - 1/maxFps
    for s in range(tmin, tmax):
        _ = tasks.update(s)
        if(mode != 'movie'):
            fig.canvas.draw()
            if interval > 0:
                sleep(interval)
        if(mode != 'normal'):
            fig.savefig('f%06d.jpg' % s, dpi=dpi)
    if (mode == 'movie'):
        com0 = 'mencoder mf://f*.jpg -mf fps={}:type=jpg'.format(fps)
        com1 = ' -vf scale=-10:-1 -ovc x264 -x264encopts'
        com2 = ' bitrate=2400 -o {}.avi'.format(moviename)
        os.system(com0+com1+com2)
        os.system("rm f*.jpg")
    elif(mode == 'gif'):
        print('gif-representation not implemented')

def UpdateViaAnimation(fig, tasks, tmin, tmax, fps=None, dpi=None,
                       mode=None, name=None, repeat=None):
    fps = setDefault(fps, 15)
    dpi = setDefault(dpi, 300)
    mode = setDefault(mode, 'normal')
    name = setDefault(name, 'Animation')
    repeat = setDefault(repeat, True)
    interval = 1000*(1/fps)
    anim = animation.FuncAnimation(fig, tasks.update, interval=interval,
                                   frames=range(tmin-1, tmax), repeat=repeat)
    if mode == 'movie':
        anim.save(name + '.mp4', writer='ffmpeg', dpi=dpi)
    elif mode == 'gif':
        anim.save(name + '.gif', writer='imagemagick', dpi=dpi)
    else:
        plt.show()


#!/usr/bin/env python3

import os
import sys

PROJECT_NAME = 'superBonobros2'

def clear():
    return os.system('rm -rf ./build' if os.name == 'posix' else 'rd /s /q .\\build\\')

def cmake():
    return os.system('cmake -B ./build' if os.name == 'posix' else 'cmake -B .\\build')

def make():
    if os.system('make -C ./build' if os.name == 'posix' else 'msbuild .\\build\\' + PROJECT_NAME + '.sln /p:Configuration=Release') != 0:
        return 1
    if os.name == 'nt':
        if os.system('copy .\\libs\\SFML-2.5.1\\bin\\*.dll .\\build\\Release\\') != 0:
            return 1
    return os.system('cp ./assets ./build/assets -r' if os.name == 'posix' else 'xcopy /Y .\\assets .\\build\\Release\\assets\\')

def run():
    return os.system('./build/' + PROJECT_NAME if os.name == 'posix' else '.\\build\\Release\\' + PROJECT_NAME + '.exe')

def full():
    if cmake() != 0:
        return 1
    return make()

def re():
    if clear() != 0:
        return 1
    return full()

process = {
    're': re,
    'all': full,
    'full': full,
    'clear': clear,
    'cmake': cmake,
    'make': make,
    'run': run
}

def build(options):
    if not len(options):
        if full() != 0:
            print('ERROR: process failed !')
    for option in options:
        if process[option]() != 0:
            print('ERROR: process \'' + option + '\' failed !')
            return

def usage(binary_name):
    print("Usage:")
    print("\t" + binary_name + " <option>")
    print("Options:")
    print("\tcmake:\t\tbuild the project with cmake")
    print("\tmake:\t\tcompile using the UNIX makefiles. In Windows, it will open the Explorer in the build directory, where the Visual Studio project is located (.sln)")
    print("\tall:\t\tinstall the dependencies, build an compile the project in only one command")
    print("\tclear:\t\tclear the build/compilation/binary files")
    print("\tre:\t\tErase the build directory and then build & compile from scratch")
    print("\trun:\t\tLaunch the binary")

if __name__ == "__main__":
    if len(sys.argv) == 2 and sys.argv[1] in ['-h','--help']:
        usage(sys.argv[0])
    elif os.name == 'posix' or os.name == 'nt':
        build(sys.argv[1:])
    else:
        print('ERROR: Invalid operating system !')


import os, sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

from sklearn.cluster import DBSCAN, KMeans
import numpy as np
import lidar3d.utils as utils

def segmentation(x, mode='rule'):
    if mode == 'rule':
        y_pred = (x[:,2] > 1)
    if mode == 'dbscan':
        y_pred = DBSCAN().fit_predict(x)
    if mode == 'kmeans':
        y_pred = KMeans().fit_predict(x)
    print(np.unique(y_pred))
    pnts = []
    for l in np.unique(y_pred):
        pnts.append(x[y_pred == l])
        print(l, pnts[-1].shape[0])
    return pnts

def make_pnts_actor(pnts):
    actors = []
    for p in pnts:
        a = utils.makeActor(utils.makePointCloud(p, radius=0.2), color=[np.random.random(1),
                                                                        np.random.random(1),
                                                                        np.random.random(1)])
        actors.append(a)
    return actors

def points2Image(pnts):
    import cv2
    # transpose is to make
    # [[xyz];[xyz];[xyz]]
    # into [xxx; yyy; zzz]
    allPnts = np.vstack(pnts).T
    xmin = np.min(allPnts[0])
    xmax = np.max(allPnts[0])
    ymin = np.min(allPnts[1])
    ymax = np.max(allPnts[0])

    origin = np.array([xmin, ymin], dtype=np.int64)
    bounds = [int(xmax-xmin) + 1, int(ymax-ymin) + 1]
    data = np.zeros(shape=(*bounds, 3), dtype=np.uint8)

    for p in pnts:
        color = np.random.randint(0, 255, size=3)

        p = p[:, :2].astype(np.int64) - origin
        #data[p[:0], p[:1]] = color
        for a in p:
            data[a[0], a[1]] = color

    obj_map = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY)
    obj_map[obj_map > 0] = 255

    cv2.imshow('imgs', data)
    cv2.waitKey(0)
    cv2.imshow('obj_map', obj_map)
    cv2.waitKey(0)
    cv2.imwrite('obj_map.bmp', obj_map)

if __name__ == '__main__':

    x = np.load('test_pnt.npy')
    x_seg = segmentation(x, 'rule')
    # x_seg = segmentation(x, 'kmeans')
    # x_seg = segmentation(x, 'dbscan')
    actors = make_pnts_actor(x_seg)
    points2Image(x_seg)
    #utils.show_in_vtk(actors)