"""
35. 搜索插入位置
给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5
输出: 2

示例 2:
输入: [1,3,5,6], 2
输出: 1

示例 3:
输入: [1,3,5,6], 7
输出: 4

示例 4:
输入: [1,3,5,6], 0
输出: 0
"""
from typing import List
class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        ans = 0
        for i in range(len(nums)):
            if target <= nums[i]:
                return i
        return len(nums)

    def searchInsert_2(self, nums: List[int], target: int) -> int:
        # 上面的遍历方法提交之后，时间空间都不好，因为这是有序的，那么我们可以用二分查找啊
        nums_len = len(nums)
        left = 0
        right = nums_len - 1

        if target > nums[-1]:
            return nums_len
        while left < right:
            mid = (left + right) // 2
            if target == nums[mid]:
                return mid
            elif target > nums[mid]:
                left = mid+1
            elif target < nums[mid]:
                right = mid
        return left

solu = Solution()
nums = [1,3,5,6]
target = 0
ans = solu.searchInsert_2(nums, target)
print(ans)


"""
Em uma competição de salto em distância cada atleta tem direito a cinco saltos. No final da série de saltos de cada atleta,
o melhor e o pior resultados são eliminados. O seu resultado fica sendo a média dos três valores restantes. Você deve fazer
um programa que receba o nome e as cinco distâncias alcançadas pelo atleta em seus saltos e depois informe a média dos saltos
conforme a descrição acima informada (retirar o melhor e o pior salto e depois calcular a média). O programa deve ser encerrado
quando não for informado o nome do atleta. A saída do programa deve ser conforme o exemplo abaixo:
Atleta: Rodrigo Curvêllo

Primeiro Salto: 6.5 m
Segundo Salto: 6.1 m
Terceiro Salto: 6.2 m
Quarto Salto: 5.4 m
Quinto Salto: 5.3 m
#29.5/5

Melhor salto:  6.5 m
Pior salto: 5.3 m
Média dos demais saltos: 5.9 m

Resultado final:
Rodrigo Curvêllo: 5.9 m
"""

nome, NomeMelhor = str(''), str()
distancia, media, melhorMedia = float(), float(), float()
melhorSalto, PiorSalto = float(), float()
j = int()

while True:
    j += 1
    media = 0

    nome = str(input('Atleta[Não informar encerra]: '))
    if nome == '' or nome == ' ':
        break
    for i in range(0,5):
        if i == 0:
            melhorSalto = PiorSalto = distancia
            distancia = float(input('Primeiro salto: '))
        if i == 1: distancia = float(input('Segundo salto: '))
        if i == 2: distancia = float(input('Terceiro salto: '))
        if i == 3: distancia = float(input('Quarto salto: '))
        if i == 4: distancia = float(input('Quinto salto: '))

        if distancia > melhorSalto: melhorSalto = distancia
        if PiorSalto > distancia : PiorSalto = distancia

        media += distancia

    if j == 1:
        melhorMedia = media
        NomeMelhor = nome
    if melhorMedia < media:
        melhorMedia = media
        NomeMelhor = nome

    media = media/5
    print(f'Melho salto: {melhorSalto}\nPior salto{PiorSalto}\nMedia dos demais saltos: {media:.2f}')
print(f'Resultado final:\n{NomeMelhor}: {melhorMedia:.2f}')


import http

import flask

from advertisements.controller import category_controller

blueprint = flask.Blueprint("category", __name__)

@blueprint.route("/category", methods=("GET",))
def get():
    return {
        "data": [
            {
                "id": category.id,
                "name": category.name,
            }
            for category in category_controller.fetch_all()
        ]
    }, 200


from flask import Flask, request, jsonify
import sqlite3
from flask_cors import CORS
import numpy as np

app = Flask(__name__)
CORS(app)

def save_var_list(list_name,input_label):
    conn = sqlite3.connect('database.db')
    cursor = conn.cursor()
    # store values of label values
    cursor.execute('''CREATE TABLE IF NOT EXISTS label_values (
                      id INTEGER PRIMARY KEY,
                      list_name TEXT,
                      strings TEXT)''')
    strings_str = ';'.join(input_label)  # Convert the list of strings to a semicolon-separated string
    cursor.execute('''INSERT INTO label_values (list_name, strings)
                      VALUES (?, ?)''', (list_name, strings_str))
    conn.commit()

def generate_zpl():
    start = "^XA"
    end = "^XZ"
    label_pos = "^FT"
    label_text_tag = "^FD"

    change_font = "^CFA,30"
    start_of_field ="^FO"
    end_of_field = "^FS"

    data = request.get_json()
    print("****************************************",data)
    is_barcode = data['is_barcode']
    is_qrcode = data['is_qrcode']

    input_text = data['label_text']
    input_label = data['label_values']

    company_name = data['company_name']
    address = data['company_address']

    line_co_ordinates = data['line_co_ordinates']

    selected_element_co_text = data['selected_element_co_text']
    selected_element_co_label = data['selected_element_co_label']

    rect_co_ordinates = data['rect_co_ordinates']

    save_var_list("label1",input_label)

    x_start_label = 80
    y_start_label = 130

    x_start_value = 350
    y_start_value = 130

    y_diff_label = 40
    y_diff_value = 40

    head = start_of_field+str(330) +","+str(20)+label_text_tag+company_name+end_of_field

    code = []
    code.append(start)
    code.append("^CF0,60")
    code.append(head)
    code.append("^CF0,40")
    address = start_of_field+str(360) +","+str(80)+label_text_tag+address+end_of_field

    code.append(address)
    code.append("^CFA,30")

    input_text_x = []
    input_text_y = []
    input_label_x  = []
    input_label_y = []

    for item in selected_element_co_text:
        if(item is not None):
            #print("***************************************************",item['x1'], item['y1'])
            input_text_x.append(item['x1'])
            input_text_y.append(item['y1'])

    for item in selected_element_co_label:
        if(item is not None):
            #print("********************************************************",item['x1'], item['y1'])
            input_label_x.append(item['x1'])
            input_label_y.append(item['y1'])

    line_coordinates_x1 = []
    line_coordinates_y1 = []
    line_coordinates_x2 = []
    line_coordinates_y2 = []

    for item in line_co_ordinates:
        if(item is not None):
            line_coordinates_x1.append(item['x1'])
            line_coordinates_y1.append(item['y1'])
            line_coordinates_x2.append(item['x2'])
            line_coordinates_y2.append(item['y2'])

    for num in range(0, len(input_text)):
        print("_____________________________",input_text[num])
        print("******************************",input_label[num])

        #y_start_label = y_start_label+y_diff_label
        #y_start_value = y_start_value + y_diff_value

        #value = input_label[num]

        #print("--------------------------------------------------------------------------------",num)
        total_var =start_of_field +str(input_text_x[num])+","+str(input_text_y[num])+label_text_tag+input_text[num]+end_of_field +start_of_field +str(input_label_x[num])+","+str(input_label_y[num])+label_text_tag+ input_label[num] +end_of_field
        #print("-----------------------------  val in for loop----------------------------",total_var)
        code.append(total_var)

    items = ""
    #data for barcode
    for num in range(0, len(input_text)):
        item = input_text[num] + ":"+ input_label[num]
        items+= " "+item

    # y diff = < 5  ----> horizontal line   // y are same
    # x diff = <5 -------------> vertical line // x are same

    for num in range(0,len(line_coordinates_x1)):
        if((line_coordinates_x2[num] - line_coordinates_x1[num]) <= 10):
            # distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
            distance = math.sqrt((line_coordinates_x2[num] - line_coordinates_x1[num])**2 + (line_coordinates_y2[num]-line_coordinates_y1[num])**2)
            distance = "1," + str(distance)
            line = "^FO" + str(line_coordinates_x1[num]) + "," + str(line_coordinates_y1[num]) + "^GB"+ distance + ",1" +"^FS"
            code.append(line)
        else:
            distance = math.sqrt((line_coordinates_x2[num] - line_coordinates_x1[num])**2 + (line_coordinates_y2[num]-line_coordinates_y1[num])**2)
            distance = str(distance) + ",1"
            line = "^FO" + str(line_coordinates_x1[num]) + "," + str(line_coordinates_y1[num]) + "^GB"+ distance + ",1" +"^FS"
            code.append(line)

    line_coordinates_rect_x1 = []
    line_coordinates_rect_x2 = []
    line_coordinates_rect_y1 = []
    line_coordinates_rect_y2 = []

    for item in rect_co_ordinates:
        if(item is not None):
            print(item)
            line_coordinates_rect_x1.append(item['x1'])
            line_coordinates_rect_x2.append(item['x2'])
            line_coordinates_rect_y1.append(item['y1'])
            line_coordinates_rect_y2.append(item['y2'])

    print("line coordinates rect  x1 ",line_coordinates_rect_x1)
    print("line coordinates rect  x2 ",line_coordinates_rect_x2)
    print("line coordinates rect  y1 ",line_coordinates_rect_y1)
    print("line coordinates rect  y2 ",line_coordinates_rect_y2)

    for num in range(0,len(line_coordinates_rect_x1)):
        rectangle = "^FO" + str(line_coordinates_rect_x1[num]) + "," + str(line_coordinates_rect_y1[num]) + "^GB" + str(line_coordinates_rect_x2[num]) + "," + str(line_coordinates_rect_y2[num]) + "^FS"
        print("******************  rectangle *********************** ",rectangle)
        code.append(rectangle)

    if is_barcode == True:
        #zpl with barcode
        barcode =  "^FO"+str(x_start_label)+","+str(y_start_label+y_diff_value)+"^BY3" + "^BCN,100,Y,N,N" + items +"^FS"
        code.append(barcode)
    elif is_qrcode == True:
        barcode =  "^FO"+str(x_start_label)+","+str(y_start_label+y_diff_value)+"^BQN,2,4 ^FDMM"+items +"^FS"
        code.append(barcode)
    else:
        #zpl without qr barcode
        pass

    code.append(end)
    #total = start + change_font + code +end

    delimiter = ','  # Delimiter to be used between elements

    result_string = delimiter.join(code)
    print(result_string)

    f = open("label1.zpl", "w")
    f.write(result_string)
    f.close()

    return{"success":True}

def select_labels():
    """
    Query all rows in the tasks table
    :param conn: the Connection object
    :return:
    """
    conn = sqlite3.connect('database.db')
    print("Opened database successfully")
    cur = conn.cursor()
    cur.execute("SELECT * FROM labels_table")

    rows = cur.fetchall()

    print("rows",rows)

    conn.close()

    # Convert the results to a list of dictionaries
    columns = [col[0] for col in cur.description]
    list_of_dicts = [dict(zip(columns, row)) for row in rows]

    # Print the list of dictionaries
    for item in list_of_dicts:
        print(item)

    return {"success": True,"data":list_of_dicts}
    #return jsonify({'data':rows}), 200

def select_units():
    """
    Query all rows in the tasks table
    :param conn: the Connection object
    :return:
    """
    conn = sqlite3.connect('database.db')
    print("Opened database successfully")
    cur = conn.cursor()
    cur.execute("SELECT name FROM units_table")

    rows = cur.fetchall()

    columns = [col[0] for col in cur.description]
    list_of_dicts = [dict(zip(columns, row)) for row in rows]

    conn.close()

    # Print the list of dictionaries
    for item in list_of_dicts:
        print(item)

    return {"success": True,"data":list_of_dicts}

def select_labels():
    """
    Query all rows in the tasks table
    :param conn: the Connection object
    :return:
    """
    conn = sqlite3.connect('database.db')
    print("Opened database successfully")
    cur = conn.cursor()
    cur.execute("SELECT * FROM labels_table")

    rows = cur.fetchall()

    print("rows",rows)

    conn.close()

    # Convert the results to a list of dictionaries
    columns = [col[0] for col in cur.description]
    list_of_dicts = [dict(zip(columns, row)) for row in rows]

    # Print the list of dictionaries
    for item in list_of_dicts:
        print(item)

    return {"success": True,"data":list_of_dicts}
    #return jsonify({'data':rows}), 200

def select_units():
    """
    Query all rows in the tasks table
    :param conn: the Connection object
    :return:
    """
    conn = sqlite3.connect('database.db')
    print("Opened database successfully")
    cur = conn.cursor()
    cur.execute("SELECT name FROM units_table")

    rows = cur.fetchall()

    columns = [col[0] for col in cur.description]
    list_of_dicts = [dict(zip(columns, row)) for row in rows]

    conn.close()

    # Print the list of dictionaries
    for item in list_of_dicts:
        print(item)

    return {"success": True,"data":list_of_dicts}

def select_date_time():
    """
    Query all rows in the tasks table
    :param conn: the Connection object
    :return:
    """
    conn = sqlite3.connect('database.db')
    print("Opened database successfully")
    cur = conn.cursor()
    cur.execute("SELECT date FROM date_time_table")

    rows = cur.fetchall()

    columns = [col[0] for col in cur.description]
    list_of_dicts = [dict(zip(columns, row)) for row in rows]

    conn.close()

    # Print the list of dictionaries
    for item in list_of_dicts:
        print(item)

    return {"success": True,"data":list_of_dicts}


'''
Author: your name
Date: 2022-01-18 07:45:57
LastEditTime: 2022-02-12 15:22:22
LastEditors: Please set LastEditors
Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
FilePath: \Workspace\XML\block4\task2.py
'''

import rdflib

g1 = rdflib.Graph()
g2 = rdflib.Graph()
g = rdflib.Graph()
g4 = rdflib.Graph()

aut = g2.parse("C:\\Users\\ydzat\\OneDrive\\Workspace\\XML\\block4\\books.rdf")
lit = g1.parse("C:\\Users\\ydzat\\OneDrive\\Workspace\\XML\\block4\\authors.rdf")
trans = g.parse("C:\\Users\\ydzat\\OneDrive\\Workspace\\XML\\block4\\translators.rdf")
loc = g4.parse("C:\\Users\\ydzat\\OneDrive\\Workspace\\XML\\block4\\locations.rdf")

authorPaar = {}
authorAndBook = {}
bookPaar = {}

transPaar = {}
transAndBook = {}

authorAndLocation = {}

for s,p,o in g1:
    if "authorName" in str(p) and str(p) not in authorPaar:
        authorPaar[str(s)] = str(o)
    if "hasWritten" in str(p):
        if str(s) not in authorAndBook:
            authorAndBook[str(s)] = []
        authorAndBook[str(s)].append(str(o))

for s,p,o in g2:
    if "bookName" in str(p):
        bookPaar[str(s)] = str(o)

tempAB = {}

for i in authorAndBook.keys():
    #authorAndBook[authorPaar[i]] = tempAB.pop(i)
    tempAB[authorPaar[i]] = authorAndBook[i]
authorAndBook = tempAB

#print(authorAndBook)

for i in authorAndBook.keys():
    tempBook = []
    for j in authorAndBook[i]:
        tempBook.append(bookPaar[j])
        authorAndBook[i] = tempBook

for s,p,o in g:
    if "authorName" in str(p) and str(p) not in transPaar:
        transPaar[str(s)] = str(o)
    if "hasTranslated" in str(p):
        if str(s) not in transAndBook:
            transAndBook[str(s)] = []
        transAndBook[str(s)].append(str(o))

tempTB = {}
for i in transAndBook.keys():
    tempTB[transPaar[i]] = transAndBook[i]
transAndBook = tempTB

for i in transAndBook.keys():
    tempBook = []
    for j in transAndBook[i]:
        tempBook.append(bookPaar[j])
        transAndBook[i] = tempBook

def findTranslator(transAndBook, bookName):
    nameList = []
    for i in transAndBook.keys():
        if bookName in transAndBook[i]:
            nameList.append(i)
    return nameList

for i in authorAndBook.keys():
    print(i + "wrote:")
    for j in authorAndBook[i]:
        print("\t" + j)
        nameList = findTranslator(transAndBook, j)
        for k in range(len(nameList)):
            print("\t\t translated by: " + nameList[k])

# task 4 skip, falsch doc
#print(authorPaar)
# for s,p,o in g4:
#     print(authorPaar[str(s)])
    #authorAndLocation[authorPaar[str(s)]] = str(o)

# for i in authorAndBook.keys():
#     print(i + " wrote:")
#     for j in authorAndBook[i]:
#         print("  " + j)
#         for k in transAndBook.keys():
#             if j in transAndBook[k]:
#                 print("    translated by: " + k )
#     print()


from django.views import View
from django.shortcuts import render, get_object_or_404, redirect
from doniServer.models import Products, ProductCategory, ProductItem

class ProductPage(View):
    template_name = 'products.html'

    def get(self, request, *args, **kwargs):
        base_url = request.META.get('HTTP_HOST')
        all_products = Products.get_products_for_website(base_url)
        most_traded_count = ProductItem.objects.filter(price_on_website=True).count()
        context = {
            'most_traded_count': most_traded_count,
            'products': all_products,
            'categories': ProductCategory.get_category_for_website()
        }
        return render(request, self.template_name, context)

class SingleProductPage(View):
    template_name = 'single_product.html'

    def get(self, request, *args, **kwargs):
        product_id = request.GET.get("id")
        base_url = request.META.get('HTTP_HOST')
        product = Products.objects.get(id=product_id)
        context = {
            'product': product,
            'web_obj': product.get_product_single_website(base_url)
        }
        return render(request, self.template_name, context)


from toybox.interventions.base import *
from toybox.interventions.core import *
try:
  import ujson as json
except:
  import json
import typing
"""An API for interventions on Breakout."""

class Breakout(Game):

  expected_keys = Game.expected_keys + ['paddle', 'is_dead', 'balls', 'ball_radius', 'paddle_speed', 'reset', 'bricks', 'paddle_width']

  immutable_fields = ['balls', 'bricks', 'intervention']

  def __init__(self, intervention,
    score=None, lives=None, rand=None, level=None,
    paddle=None, paddle_width=None, paddle_speed=None,
    ball_radius=None, balls=None,
    bricks=None,
    reset=None, is_dead=None):

      super().__init__(intervention, score, lives, rand, level)
      self.paddle = Paddle.decode(intervention, paddle, Paddle)
      self.reset = reset
      self.ball_radius = ball_radius
      self.bricks = BrickCollection.decode(intervention, bricks, BrickCollection)
      self.balls = BallCollection.decode(intervention, balls, BallCollection)
      self.paddle_speed = paddle_speed
      self.paddle_width = paddle_width
      self.is_dead = is_dead
      self._in_init = False

  def __eq__(self, other) -> Either:
    names = {
      'score'       : (self.score,        other.score),
      'lives'       : (self.lives,        other.lives),
      'level'       : (self.level,        other.level),
      'paddle'      : (self.paddle,       other.paddle),
      'reset'       : (self.reset,        other.reset),
      'ball_radius' : (self.ball_radius,  other.ball_radius) ,
      'bricks'      : (self.bricks,       other.bricks),
      'balls'       : (self.balls,        other.balls),
      'paddle_speed': (self.paddle_speed, other.paddle_speed),
      'paddle_width': (self.paddle_width, other.paddle_width),
      'is_dead'     : (self.is_dead,      other.is_dead)
    }
    return eq_map(names)

    def __str__(self):
        return """
Breakout
==========
    score: {}
    lives: {}
    level: {}
    paddle: {}
    reset: {}
    ball_radius: {}
    bricks: {}
    balls: {}
    paddle_speed: {}
    paddle_width: {}
    is_dead: {}""".format(self.score, self.lives, self.level, str(self.paddle),
        self.reset, self.ball_radius, self.bricks.__str__(), self.balls.__str__(), self.paddle_speed,
        self.paddle_width, self.is_dead)

class Paddle(BaseMixin):

  expected_keys = ['velocity', 'position']
  immutable_fields = []

  def __init__(self, intervention, velocity, position):
    super().__init__(intervention)
    self.velocity = Vec2D.decode(intervention, velocity, Vec2D)
    self.position = Vec2D.decode(intervention, position, Vec2D)
    self._in_init = False

  def __eq__(self, other) -> Either:
    names = {
      'velocity': (self.velocity, other.velocity),
      'position': (self.position, other.position)
    }
    return eq_map(names)

  def __str__(self):
      return '<position: {}, velocity: {}>'.format(self.position, self.velocity)

class BrickCollection(Collection):

  def __init__(self, intervention, bricks):
    super().__init__(intervention, bricks, Brick)
    self._in_init = False

  def decode(intervention, bricks, clz):
    return BrickCollection(intervention, bricks)

class Brick(BaseMixin):

  expected_keys = ['destructible', 'depth', 'color', 'alive', 'points', 'size', 'position', 'row', 'col']
  immutable_fields = ['intervention']

  def __init__(self, intervention, destructible, depth, color, alive, points, size, position, row, col):
    super().__init__(intervention)
    self.destructible = destructible
    self.depth = depth
    self.color = Color.decode(intervention, color, Color)
    self.alive = alive
    self.points = points
    self.size = Vec2D.decode(intervention, size, Vec2D)
    self.position = Vec2D.decode(intervention, position, Vec2D)
    self.row = row
    self.col = col
    self._in_init = False

  def __eq__(self, other) -> Either:
    names = {
      'destructible': (self.destructible, other.destructible),
      'depth':        (self.depth,    other.depth),
      'color':        (self.color,    other.color),
      'alive':        (self.alive,    other.alive),
      'points':       (self.points,   other.points),
      'size':         (self.size,     other.size),
      'position':     (self.position, other.position),
      'row':          (self.row,      other.row),
      'col':          (self.col,      other.col)
    }
    return eq_map(names)

class BallCollection(Collection):

  def __init__(self, intervention, balls):
    super().__init__(intervention, balls, Ball)
    self._in_init = False

  def __str__(self):
    if len(self) == 1:
      return str(self[0])
    else:
      return '[{}]'.format(', '.join(str(b) for b in self))

class Ball(BaseMixin):

  expected_keys = ['position', 'velocity']
  immutable_fields = ['intervention']

  def __init__(self, intervention, position, velocity):
    super().__init__(intervention)
    self.position = Vec2D.decode(intervention, position, Vec2D)
    self.velocity = Vec2D.decode(intervention, velocity, Vec2D)
    self._in_init = False

  def __eq__(self, other) -> Either:
    names = {
        'position': (self.position, other.position),
        'velocity': (self.velocity, other.velocity)
    }
    return eq_map(names)

  def __str__(self):
    return 'Ball(position: {}, velocity: {})'.format(self.position, self.velocity)

class BreakoutIntervention(Intervention):

    def __init__(self, tb, game_name='breakout'):
        # check that the simulation in tb matches the game name.
        Intervention.__init__(self, tb, game_name, Breakout)

    def num_bricks_remaining(self):
        return sum([int(brick.alive) for brick in self.game.bricks])

    def num_bricks(self):
        return len(self.game.bricks)

    def num_rows(self):
        return len(self.config['row_scores'])

    def num_columns(self):
        """Returns the number of columns in the layout."""
        rows = self.num_rows()
        bricks = self.num_bricks()
        return bricks // rows

    def add_row(self, bricks, points, pre=None, post=None):
        """Adds the input row of bricks to the playing board.

        Parameters
        ====
        bricks: a list of brick objects
        value: the points associated with this row
        pre: add the list above
        post: add the list below
        """

        input_len = len(bricks)
        target_len = self.num_bricks()

        if input_len != target_len:
            raise ValueError('Input brick list length incorrect (is %d; should be %d)' % (input_len, target_len))

        if pre:
            for brick in bricks.reverse():
                self.bricks.insert(0, brick)

        elif post:
            self.bricks.extend(bricks)

        else:
            raise ValueError('Must provide one optional argument: pre or post.')

        self.config['row_scores'].append(points)
        self.dirty_config = True

    def is_stack(self, bricks):
        col = bricks[0].col
        return all([b.col == col for b in bricks])

    def is_channel(self, bricklist):
        """Predicate indicating whether the input list of bricks constitutes a channel."""
        col = bricklist[0].col
        for brick in bricklist:
            if brick.col != col: return False
            if brick.alive: return False
        return True

    def get_column(self, i):
        """Returns the ith column of bricks."""
        bricks = []
        for brick in self.game.bricks:
            if brick.col == i:
                bricks.append(brick)
        return bricks

    def channel_count(self):
        count = 0
        for i in range(self.num_columns()):
            channel = self.get_column(i)
            if self.is_channel(channel): count += 1
        return count

    def get_ball_position(self):
        """Returns a list of positions, if there is more than one ball, and a single Vec2D object otherwise.:"""
        nballs = len(self.game.balls)
        if nballs > 1:
            return [ball.position for ball in self.game.balls]
        else:
            return self.game.balls[0].position

    def get_ball_velocity(self):
        nballs = len(self.game.balls)
        if nballs > 1:
            return [ball.velocity for ball in self.game.balls]
        else:
            return self.game.balls[0].velocity

    def get_paddle_position(self):
        return self.game.paddle.position

    def get_paddle_velocity(self):
        return self.game.paddle.velocity

    def find_brick(self, pred):
        for i, b in enumerate(self.game.bricks):
            if pred(b):
                return i, b
        raise ValueError('No bricks that satisfy the input predicate found.')

    def add_channel(self, i):
        """Turns the ith column into a channel"""
        for brick in self.game.bricks:
            if brick.col == i and brick.alive:
                brick.alive = False

    def fill_column(self, i):
        """Fills the ith column, so that all bricks are now alive."""
        for brick in self.game.bricks:
            if brick.col == i and not brick.alive:
                brick.alive = True

    def find_channel(self):
        """Returns the first channel found."""
        for i in range(self.num_columns()):
            col = self.get_column(i)
            if self.is_channel(col):
                return i, col
        return -1, None

    def clear_board(self):
        """Clears the board of all bricks"""
        for brick in self.game.bricks:
            brick.alive = False

if __name__ == "__main__":
  import argparse
  from ctoybox import Toybox, Input

  parser = argparse.ArgumentParser(description='test Amidar interventions')
  parser.add_argument('--partial_config', type=str, default="null")
  parser.add_argument('--save_json', type=bool, default=False)
  args = parser.parse_args()

  with Toybox('breakout') as tb:

    fire = Input()
    fire.button1 = True
    noop = Input()
    tb.apply_action(fire)

    state = tb.to_state_json()
    config = tb.config_to_json()

    if args.save_json:
        # save a sample starting state and config
        with open('toybox/toybox/interventions/defaults/breakout_state_default.json', 'w') as outfile:
            json.dump(state, outfile)

        with open('toybox/toybox/interventions/defaults/breakout_config_default.json', 'w') as outfile:
            json.dump(config, outfile)

    with BreakoutIntervention(tb) as intervention:
        intervention.game.lives = 1
        assert intervention.dirty_state

    # remove and assert that the brick is gone
    with BreakoutIntervention(tb) as intervention:
        nbricks = intervention.num_bricks_remaining()
        intervention.game.bricks[0].alive = False
        nbricks_post = intervention.num_bricks_remaining()

        assert nbricks - 1 == nbricks_post

    # reset and assert that the brick is present
    with BreakoutIntervention(tb) as intervention:
        nbricks = intervention.num_bricks_remaining()
        intervention.game.bricks[0].alive = True
        nbricks_post = intervention.num_bricks_remaining()

        assert nbricks + 1 == nbricks_post

    # add a channel and assert that num_rows bricks have been removed
    with BreakoutIntervention(tb) as intervention:
        nbricks = intervention.num_bricks_remaining()
        intervention.add_channel(0)
        nbricks_post = intervention.num_bricks_remaining()
        assert nbricks_post == nbricks - intervention.num_rows()

        col, channel = intervention.find_channel()
        assert channel

        assert intervention.channel_count() == 1

    # remove a channel and assert that num_rows bricks have been added
    with BreakoutIntervention(tb) as intervention:
        nbricks = intervention.num_bricks_remaining()
        intervention.fill_column(0)
        nbricks_post = intervention.num_bricks_remaining()
        assert nbricks_post == nbricks + intervention.num_rows()

    # get ball position, even when multiple balls present
    with BreakoutIntervention(tb) as intervention:
        game = intervention.game
        assert len(game.balls) > 0

        ball = game.balls[0]
        game.balls.append(ball)
        ball_positions = intervention.get_ball_position()
        assert len(ball_positions) == 2
        ball_velocities = intervention.get_ball_velocity()
        assert len(ball_velocities) == 2
        game.balls.clear()
        game.balls.append(ball)
        # the line above should have triggered an error
        ball_positions = intervention.get_ball_position()

    # move ball diagonally by sqrt(2) pixels
    with BreakoutIntervention(tb) as intervention:
        ball_pos = intervention.get_ball_position()
        ball_pos.x = ball_pos.x + 1
        ball_pos.y = ball_pos.y + 1
    with BreakoutIntervention(tb) as intervention:
        ball_pos_post = intervention.get_ball_position()
        assert ball_pos_post.x == ball_pos.x
        ball_pos_post.x = ball_pos.x - 1
        ball_pos_post.y = ball_pos.y - 1
    with BreakoutIntervention(tb) as intervention:
        ball_pos_post_post = intervention.get_ball_position()
        assert ball_pos_post.x == ball_pos_post_post.x

    # change ball velocity
    with BreakoutIntervention(tb) as intervention:
        ball_vel = intervention.get_ball_velocity()
        ball_vel.x = ball_vel.x + 1
        ball_vel.y = ball_vel.y + 1
        ball_vel_post = intervention.get_ball_velocity()
        assert ball_vel_post.x == ball_vel.x

        ball_vel.x = ball_vel.x - 1
        ball_vel.y = ball_vel.y - 1
        ball_vel_post = intervention.get_ball_velocity()
        assert ball_vel_post.x == ball_vel.x

    # get paddle position and move
    with BreakoutIntervention(tb) as intervention:
        pos = intervention.get_paddle_position()
        assert pos.x == 120.0 and pos.y == 143.0

        pos.x = pos.x + 10
        pos_post = intervention.get_paddle_position()
        assert pos.x == pos_post.x


from django.test import TestCase
from unittest.mock import Mock
from django.shortcuts import resolve_url

mock_get = Mock()
mock_get.return_value.text = 'Hello World'
mock_get().text

class CrawlerTest(TestCase):

    def setUp(self):
        self.response = self.client.get(resolve_url('counter_word'))
        self.url = 'http://python.org'
        self.word = 'Python'

    def test_get(self):
        ''' GET / must return status code 200 '''
        self.assertEqual(200, self.response.status_code)

    def test_res(self):
        res = {'Python': 97}
        self.assertEqual({'Python': 97}, res)


from asyncio import iscoroutinefunction
from functools import partial
from web3.utils.filters import construct_event_filter_params
from web3.utils.events import get_event_data

class WebsocketFilterSet:
    def __init__(self, contract):
        self.contract = contract
        self.handlers = {}
        self.topic_to_event = {}
        self.topic_filters = []

    async def deliver(self, topic_hash, payload):
        if topic_hash in self.handlers:
            if iscoroutinefunction(self.handlers[topic_hash]):
                await self.handlers[topic_hash](payload)
            else:
                self.handlers[topic_hash](payload)

    def on_event(self, event_name, handler_func=None):
        def decorator(handler_func):
            event_abi = self.contract._find_matching_event_abi(event_name, {})
            _, event_filter_params = construct_event_filter_params(event_abi,
                contract_address=self.contract.address)

            if iscoroutinefunction(handler_func):
                async def decorated(payload):
                    event_data = get_event_data(event_abi, payload)
                    return await handler_func(self.contract, event_name, event_data)
            else:
                def decorated(payload):
                    event_data = get_event_data(event_abi, payload)
                    return handler_func(self.contract, event_name, event_data)

            self.topic_filters.append(event_filter_params)
            self.handlers[event_filter_params["topics"][0]] = decorated

            return decorated

        if handler_func is None:
            return decorator
        return decorator(handler_func)


import pandas as pd
import numpy as np
import MyMod
from flask import Flask
import os
from bs4 import BeautifulSoup
from selenium import webdriver
import requests
import re
import time
import random
import configparser
from bs4 import BeautifulSoup
from flask import Flask, request, abort
from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import *

app = Flask(__name__)

config = configparser.ConfigParser()
config.read("config.ini")
line_bot_api = LineBotApi(config['line_bot']['Channel_Access_Token'])
handler = WebhookHandler(config['line_bot']['Channel_Secret'])

@app.route('/')
def index():
    message = """Hello, My Friends!"""
    return message

@app.route("/callback", methods=['POST'])
def callback():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    # print("body:",body)
    app.logger.info("Request body: " + body)

    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)

    return 'ok'

@app.route('/op')
def op():
    table=MyMod.opweek()

    return table.to_html()

@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    print("event.reply_token:", event.reply_token)
    print("event.message.text:", event.message.text)

#簡單訊息測試
    if event.message.text == "hello":
        list=['嗶——',"歡迎使用選擇權自動裝置","本裝置提供的資訊是從網頁即時抓取，請耐心等候","使用服務請輸入「服務」"]
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text='\n\n'.join(list)))
    if event.message.text == "嗨":
        list=['嗶——',"歡迎使用選擇權自動裝置","本裝置提供的資訊是從網頁即時抓取，請耐心等候","使用服務請輸入「服務」"]
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text='\n\n'.join(list)))
    if event.message.text == "你好":
        list=['嗶——',"歡迎使用選擇權自動裝置","本裝置提供的資訊是從網頁即時抓取，請耐心等候","使用服務請輸入「服務」"]
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text='\n\n'.join(list)))

#服務選單
    if event.message.text == "服務":
        buttons_template = TemplateSendMessage(
            alt_text='服務選單',
            template=ButtonsTemplate(
                title='選擇服務',
                text='來賓請選擇',
                thumbnail_image_url='https://i.imgur.com/Hn2nJJN.jpg',
                actions=[
                    MessageTemplateAction(
                        label='週選擇權策略所需金額計算',
                        text='週選擇權策略所需金額計算'
                    ),
                    MessageTemplateAction(
                        label='月選擇權策略所需金額計算',
                        text='月選擇權策略所需金額計算'
                    ),
                    URITemplateAction(
                        label='選擇權不太即時報價表',
                        uri='https://rocky-beyond-10519.herokuapp.com/op'
                    ),

                    MessageTemplateAction(
                        label='淨化心靈的聲音',
                        text='播放'
                    )
                ]
            )
        )
        line_bot_api.reply_message(event.reply_token, buttons_template)

    if event.message.text == "播放":
        line_bot_api.reply_message(
            event.reply_token,
            AudioSendMessage(
            original_content_url='https://drive.google.com/uc?export=download&id=1e2J4zbWdTnMyAr0qmfTMATzzhq7W28Sb',
            duration=10000))

    if event.message.text == "來個每日心靈小語":
        content=MyMod.good_word()
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text=content))

    if event.message.text == "爬蟲爬起來爬起來":
        content=MyMod.good_word()
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text='https://rocky-beyond-10519.herokuapp.com/op'))

#週選策略金額計算

    if event.message.text == "週選擇權策略所需金額計算":
        buttons_template = TemplateSendMessage(
            alt_text='週選擇權策略所需金額計算',
            template=ButtonsTemplate(
                title='週選擇權策略所需金額計算',
                text='來賓請選擇',
                thumbnail_image_url='https://i.imgur.com/Hn2nJJN.jpg',
                actions=[
                    MessageTemplateAction(
                        label='跨式策略',
                        text='買入週選價平跨式'
                    ),
                    MessageTemplateAction(
                        label='勒式勿賭',
                        text='買入週選價平上下兩檔勒式'
                    ),
                    MessageTemplateAction(
                        label='多頭價差',
                        text='買入週選多頭價差，價平上下兩檔'
                    ),
                    MessageTemplateAction(
                        label='空頭價差',
                        text='買入週選空頭價差，價平上下兩檔'
                    )
                ]
            )
        )
        line_bot_api.reply_message(event.reply_token, buttons_template)

    if event.message.text == "買入週選多頭價差，價平上下兩檔":

        df=MyMod.opweek()
        content=MyMod.bullish_spread(df)
        a=['買入Call履約價為',str(content[0]),'\n\n',
           '權利金成本為',str(content[1]),'\n\n',
           '賣出Call履約價為',str(content[2]),'\n\n',
           '權利金收入為',str(content[3]),'\n\n',
           '所需保證金為',str(content[4])]

        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="".join(a)))

    if event.message.text == "買入週選空頭價差，價平上下兩檔":

        df=MyMod.opweek()
        content=MyMod.bearish_spread(df)
        a=['買入Call履約價為',str(content[0]),'\n\n',
           '權利金成本為',str(content[1]),'\n\n',
           '賣出Call履約價為',str(content[2]),'\n\n',
           '權利金收入為',str(content[3]),'\n\n',
           '所需保證金為',str(content[4])]

        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="".join(a)))

    if event.message.text == "買入週選價平跨式":

        df=MyMod.opweek()
        content=MyMod.triangle(df)
        a=['權利金成本為',str(content)]
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="".join(a)))

    if event.message.text == "買入週選價平上下兩檔勒式":

        df=MyMod.opweek()
        content=MyMod.square(df)
        a=['權利金成本為',str(content)]
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="".join(a)))

#月選策略金額計算

    if event.message.text == "月選擇權策略所需金額計算":
        buttons_template = TemplateSendMessage(
            alt_text='月選擇權策略所需金額計算',
            template=ButtonsTemplate(
                title='月選擇權策略所需金額計算',
                text='來賓請選擇',
                thumbnail_image_url='https://i.imgur.com/Hn2nJJN.jpg',
                actions=[
                    MessageTemplateAction(
                        label='跨式策略',
                        text='買入月選價平跨式'
                    ),
                    MessageTemplateAction(
                        label='勒式勿賭',
                        text='買入月選價平上下兩檔勒式'
                    ),
                    MessageTemplateAction(
                        label='多頭價差',
                        text='買入月選多頭價差，價平上下兩檔'
                    ),
                    MessageTemplateAction(
                        label='空頭價差',
                        text='買入月選空頭價差，價平上下兩檔'
                    )
                ]
            )
        )
        line_bot_api.reply_message(event.reply_token, buttons_template)

    if event.message.text == "買入月選多頭價差，價平上下兩檔":

        df=MyMod.opmonth()
        content=MyMod.bullish_spread(df)
        a=['買入Call履約價為',str(content[0]),'\n\n',
           '權利金成本為',str(content[1]),'\n\n',
           '賣出Call履約價為',str(content[2]),'\n\n',
           '權利金收入為',str(content[3]),'\n\n',
           '所需保證金為',str(content[4])]

        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="".join(a)))

    if event.message.text == "買入月選空頭價差，價平上下兩檔":

        df=MyMod.opmonth()
        content=MyMod.bearish_spread(df)
        a=['買入Call履約價為',str(content[0]),'\n\n',
           '權利金成本為',str(content[1]),'\n\n',
           '賣出Call履約價為',str(content[2]),'\n\n',
           '權利金收入為',str(content[3]),'\n\n',
           '所需保證金為',str(content[4])]

        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="".join(a)))

    if event.message.text == "買入月選價平跨式":

        df=MyMod.opmonth()
        content=MyMod.triangle(df)
        a=['權利金成本為',str(content)]
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="".join(a)))

    if event.message.text == "買入月選價平勒式":

        df=MyMod.opmonth()
        content=MyMod.square(df)
        a=['權利金成本為',str(content)]
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="".join(a)))

    return 0

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


#
# usage: python k75.py {file name}
#

import sys
from sentiment import SentimentSentences

if __name__ == '__main__':
    fn = sys.argv[1]

    data = SentimentSentences([l for l in open(fn)])
    data.feature_extraction()

    data.train()

    idx = data.model.coef_[0].argsort()

    print('high-weight:')
    for i in idx[:10]:
        print('\t', data.vec.get_feature_names()[i], sep='')

    print('low-weight:')
    for i in idx[-10:]:
        print('\t', data.vec.get_feature_names()[i], sep='')


"""
-*- coding: utf-8 -*-
@Time : 2021/10/25 下午 7:10
@Author : sunguoqi
@Website : https://sunguoqi.com
@Github: https://github.com/sun0225SUN
"""

from osgeo import gdal_array as gd
import operator
from functools import reduce

def histogram(a, bins=list(range(256))):
    fa = a.flat
    n = gd.numpy.searchsorted(gd.numpy.sort(fa), bins)
    n = gd.numpy.concatenate([n, [len(fa)]])
    hist = n[1:] - n[:-1]
    return hist

def stretch(a):
    hist = histogram(a)
    lut = []
    for b in range(0, len(hist), 256):
        step = reduce(operator.add, hist[b:b + 256]) / 255
        n = 0
        for i in range(256):
            lut.append(n / step)
            n += hist[i + b]
    gd.numpy.take(lut, a, out=a)
    return a

# NDVI
source = "./ndvi.tif"
target = "ndvi_color.tif"
ndvi = gd.LoadFile(source).astype(gd.numpy.uint8)
# NDVI
ndvi = stretch(ndvi)
# NDVI 3
rgb = gd.numpy.zeros((3, len(ndvi), len(ndvi[0])), gd.numpy.uint8)
# NDVI
classes = [58, 73, 110, 147, 184, 220, 255]

# lut RGB
lut = [[120, 69, 25], [255, 178, 74], [255, 237, 166], [173, 232, 94], [135, 181, 64], [3, 156, 0], [1, 100, 0]]

start = 1

for i in range(len(classes)):
    mask = gd.numpy.logical_and(start <= ndvi, ndvi <= classes[i])
    for j in range(len(lut[i])):
        rgb[j] = gd.numpy.choose(mask, (rgb[j], lut[i][j]))
        start = classes[i] + 1

# NDVI geotiff
output = gd.SaveArray(rgb, target, format="GTiff", prototype=source)
output = None
print('分类完成!')


#!/usr/bin/env python

#program to get the sequences that mapped entire protein sequence length and then extract the DNA from the refseq
#usage: python scriptname protein_sequence.fasta tblastn.out
import os, sys

basefilename=sys.argv[1].replace(".fasta", "")

def get_sequence_length(filename):

    os.system(" cat " + filename + " | awk '{if(NR%2==1){gsub(/^>/, \"\", $1); record_id=$1} else if(NR%2==0){print record_id\"\t\"length($0)} }' " + " > " + filename + ".length")

def contruct_length_dictionary(filename):

    lengths=dict()
    get_sequence_length(sys.argv[1])
    length_filename=open(filename + ".length")
    for line in length_filename:
        line=line.rstrip()
        seqid=line.split()[0]
        length=line.split()[1]
        lengths[seqid]=length

    return lengths

def get_full_mapped_sequences(protein_sequence, tblastn_out):
    # get the sequences that mapped full length from tblastn output results
    length_dictionary = contruct_length_dictionary(protein_sequence)
    query_added=[]

    full_length_sequences=open(basefilename + "_full_length.txt", "w")
    non_full_length_sequences=open(basefilename+ "_non_full_length.txt", "w")
    multiple=open(basefilename + "_multiple.txt", "w")

    tblastn_filename=open(tblastn_out)
    for line in tblastn_filename:
        line=line.rstrip()
        array=line.split()
        query=array[0]
        subject=array[1]
        query_map_start = array[6]
        query_map_end = array[7]
        subject_map_start = array[8]
        subject_map_end = array[9]
        if query_map_start == '1':

            if query_map_end == length_dictionary[query]:
                if query not in query_added:
                    #print "\t".join(array) + "  full length "  # full length sequences
                    query_added.append(query)
                    full_length_sequences.write("\t".join([subject, subject_map_start, subject_map_end, query, query_map_start, query_map_end]) + "\n")
                else:
                    #print "\t".join(array)  #already added
                    multiple.write("\t".join([subject, subject_map_start, subject_map_end, query, query_map_start, query_map_end]) + "\n")

            #else:
            #    if query not in query_added:
            #        #print "\t".join(array) + "  not full length" # not full length, but occurred only once
            #        query_added.append(query)

            #    else:
            #        continue
        #elif query_map_end == length_dictionary[query]:
        #    print "\t".join(array) + " ends at same length"

        else:
            non_full_length_sequences.write("\t".join([subject, subject_map_start, subject_map_end, query, query_map_start, query_map_end]) + "\n")
    full_length_sequences.close()
    non_full_length_sequences.close()
    multiple.close()

if __name__== "__main__":

    get_full_mapped_sequences(sys.argv[1], sys.argv[2])

exit(0)


from django.conf.urls import url

import programs.views.subprogram_views as subprograms
import programs.views.project_views as projects

urlpatterns = [
    url(r'^$', subprograms.list_subprograms, name='list_subprograms'),
    url(r'^nuevo', subprograms.create_subprogram, name='new_subprogram'),
    url(r'^ver/(?P<subprogram_id>\d+)/$', subprograms.view_subprogram, name='view_subprogram'),
    url(r'^ver/(?P<subprogram_id>\d+)/mapa/$', subprograms.view_map, name='map'),
    url(r'^(?P<subprogram_id>\d+)/nuevo-proyecto/$', projects.create_project, name='proj'),
    url(r'^(?P<subprogram_id>\d+)/reporte/$', subprograms.report, name='subprog_report'),
    url(r'^editar/(?P<subprogram_id>\d+)/', subprograms.update_subprogram, name='edit_subprogram'),

    #url(r'^bloquear/(?P<program_id>\d+)/', subprograms.toggle_lock, name='toggle_block_subprogram'),
]


"""
A série de Fibonacci é formada pela seqüência 0,1,1,2,3,5,8,13,21,34,55,...
Faça um programa que gere a série até que o valor seja maior que 500.
"""
x,y,z = 1,0,0

while(z <= 500):
    z = x + y
    y = x
    x = z
    print(z)


import requests

from test_APP.Common.Login_test import Login

# 到岗时间下拉

class Test_Arrival_Time():
    def test_arrival_time(self):
        url = "http://192.168.101.102/api/user/app/personal/resume/arrival-time"
        heasers = {
            "content-type": "application/x-www-form-urlencoded;charset=utf-8",
            "token": Login().Login_sms_test()

        }
        res = requests.get(url=url, headers=heasers)
        print(res.text)
        code = res.json()["code"]
        try:
            assert code == 0
            print("到岗下拉成功")
        except:
            assert code != 0
            print("到岗下拉失败")

if __name__ == '__main__':
    Test_Arrival_Time().test_arrival_time()


import colorsys
import hashlib
import random
from typing import List, Tuple

def get_colors_from_string(s: str, unique: bool = True) -> List[Tuple[int, int, int]]:
    """Calculates a color for every (unique) char in the input string."""
    # filter out identical chars if unique == True
    if unique:
        s = "".join(set(s))

    colors = []
    for char in s:
        hue = get_string_value(char)
        color = get_rgb_from_value(hue)
        colors.append(color)

    return colors

def get_rgb_from_value(v: float) -> Tuple[int, int, int]:
    """Returns a 3-tuple of rgb values based on the input float.

    The input float should be between 0 and 1 and is interpreted as the
    hue value in an HSL to RGB color conversion.
    """
    # colorsys returns rgb values between 0 and 1
    r, g, b = colorsys.hls_to_rgb(v, 0.5, 1)

    # multiply by 255 to get values between 0 and 255
    red = round(r * 255)
    green = round(g * 255)
    blue = round(b * 255)
    return red, green, blue

def get_string_value(s: str) -> float:
    """Calculates a float value for the given string between 0 and 1."""
    # save random state
    state = random.getstate()

    # seed random with md5sum of string
    md5sum = hashlib.md5(s.encode("utf-8")).digest()
    random.seed(md5sum)

    # get first value (reproducible because of known seed)
    value = random.random()

    # reset random state
    random.setstate(state)

    return value

class GeometricTransformation:
    """Geometric transformations from one coordinate system to another"""

    def __init__(
        self,
        input_x_axis: Tuple[float, float],
        input_y_axis: Tuple[float, float],
        output_x_axis: Tuple[float, float],
        output_y_axis: Tuple[float, float],
    ):
        """
        :param input_x_axis: The range of x values for inputs, given as a
            2-tuple with float values
        :param input_y_axis: The range of y values for inputs, given as a
            2-tuple with float values
        :param output_x_axis: The range of x values that input values are
            mapped to, given as a 2-tuple with float values
        :param output_y_axis: The range of y values that input values are
            mapped to, given as a 2-tuple with float values
        """
        self.input_x_axis = input_x_axis
        self.input_y_axis = input_y_axis
        self.output_x_axis = output_x_axis
        self.output_y_axis = output_y_axis

    def get(self, point: Tuple[float, float]) -> Tuple[float, float]:
        """Transforms a single point into the output coordinate system.

        :param point: The point to transform. Given as a 2-tuple with
            float values (x, y)
        """
        x = self.getx(point[0])
        y = self.gety(point[1])
        return x, y

    def getx(self, x: float) -> float:
        """Returns the transformed value on the x-axis for an input x"""
        input_x_min = self.input_x_axis[0]
        input_x_delta = self.input_x_axis[1] - self.input_x_axis[0]
        output_x_min = self.output_x_axis[0]
        output_x_delta = self.output_x_axis[1] - self.output_x_axis[0]

        axis_percent = (x - input_x_min) / input_x_delta
        return axis_percent * output_x_delta + output_x_min

    def gety(self, y: float) -> float:
        """Returns the transformed value on the y-axis for an input y"""
        input_y_min = self.input_y_axis[0]
        input_y_delta = self.input_y_axis[1] - self.input_y_axis[0]
        output_y_min = self.output_y_axis[0]
        output_y_delta = self.output_y_axis[1] - self.output_y_axis[0]

        axis_percent = (y - input_y_min) / input_y_delta
        return axis_percent * output_y_delta + output_y_min


from torch.utils.data import Subset
import torch.nn as nn
import torch
import torchvision
from torchvision import transforms
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt
image_path = './ch-13'
transform = transforms.Compose([transforms.ToTensor()])
mnist_dataset = torchvision.datasets.MNIST(
    root=image_path, train=True, transform=transform, download=False)

mnist_valid_dataset = Subset(mnist_dataset, torch.arange(10000))
mnist_train_dataset = Subset(
    mnist_dataset, torch.arange(10000, len(mnist_dataset)))

mnist_test_dataset = torchvision.datasets.MNIST(
    root=image_path, train=False, transform=transform, download=False)

batch_size = 64
torch.manual_seed(1)

train_dl = DataLoader(mnist_train_dataset, batch_size, shuffle=True)
valid_dl = DataLoader(mnist_valid_dataset, batch_size, shuffle=True)

model = nn.Sequential()
model.add_module('conv1', nn.Conv2d(
    in_channels=1, out_channels=32, kernel_size=5, padding=2))
model.add_module('relu1', nn.ReLU())
model.add_module('pool1', nn.MaxPool2d(kernel_size=2))
model.add_module('conv2', nn.Conv2d(
    in_channels=32, out_channels=64, kernel_size=5, padding=2))
model.add_module('relu2', nn.ReLU())
model.add_module('pool2', nn.MaxPool2d(kernel_size=2))
model.add_module('flatten', nn.Flatten())
model.add_module('fc1', nn.Linear(3136, 1024))
model.add_module('relu3', nn.ReLU())
model.add_module('dropout', nn.Dropout(p=0.5))
model.add_module('fc2', nn.Linear(1024, 10))
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
model.to('cuda')

def train(model, num_epochs, train_dl, valid_dl, device='cuda'):
    loss_hist_train = [0] * num_epochs
    accuracy_hist_train = [0] * num_epochs
    loss_hist_valid = [0] * num_epochs
    accuracy_hist_valid = [0] * num_epochs
    for epoch in range(num_epochs):
        model.train()
        for x_batch, y_batch in train_dl:
            x_batch = x_batch.to(device)
            y_batch = y_batch.to(device)
            pred = model(x_batch)
            loss = loss_fn(pred, y_batch)
            loss.backward()
            optimizer.step()
            optimizer.zero_grad()
            loss_hist_train[epoch] += loss.item()*y_batch.size(0)
            is_correct = (torch.argmax(pred, dim=1) == y_batch).float()
            accuracy_hist_train[epoch] += is_correct.sum().cpu()

        loss_hist_train[epoch] /= len(train_dl.dataset)
        accuracy_hist_train[epoch] /= len(train_dl.dataset)

        model.eval()
        with torch.no_grad():
            for x_batch, y_batch in valid_dl:
                x_batch = x_batch.to(device)
                y_batch = y_batch.to(device)
                pred = model(x_batch)
                loss = loss_fn(pred, y_batch)
                loss_hist_valid[epoch] += loss.item()*y_batch.size(0)
                is_correct = (torch.argmax(pred, dim=1) == y_batch).float()
                accuracy_hist_valid[epoch] += is_correct.sum().cpu()

        loss_hist_valid[epoch] /= len(valid_dl.dataset)
        accuracy_hist_valid[epoch] /= len(valid_dl.dataset)

        print(
            f'Epoch {epoch+1} accuracy: {accuracy_hist_train[epoch]:.4f} val_accuracy: {accuracy_hist_valid[epoch]:.4f}')
    return loss_hist_train, loss_hist_valid, accuracy_hist_train, accuracy_hist_valid

torch.manual_seed(1)
num_epochs = 5
hist = train(model, num_epochs, train_dl, valid_dl)

pred = model(mnist_test_dataset.data.to('cuda').unsqueeze(1) / 255.)
is_correct = (torch.argmax(pred, dim=1) ==
              mnist_test_dataset.targets.to('cuda')).float()
print(f'Test accuracy: {is_correct.mean():.4f}')

fig = plt.figure(figsize=(12, 4))
for i in range(12):
    ax = fig.add_subplot(2, 6, i+1)
    ax.set_xticks([])
    ax.set_yticks([])
    img = mnist_test_dataset[i][0][0, :, :]
    pred = model(img.unsqueeze(0).unsqueeze(1).to('cuda'))
    y_pred = torch.argmax(pred)
    ax.imshow(img, cmap='gray_r')
    ax.text(0.9, 0.1, y_pred.item(),
            size=15, color='blue',
            horizontalalignment='center',
            verticalalignment='center',
            transform=ax.transAxes)
plt.show()


from scipy.io import savemat

mdict = {'Config': 'parallel',
         'timeStep': 0.4,
         'BFIndexes': [0, 8, 1, 9],
         'Antennas': [2, 6, 7, 8],
         'arr00' : arr00,
         'arr01' : arr01,
         'arr08' : arr08,
         'arr09' : arr09,
         'arr11' : arr11,
         'arr18' : arr18,
         'arr19' : arr19,
         'arr88' : arr88,
         'arr89' : arr89,
         'arr99' : arr99}
filename = 'DRAO_CW_3700KHZ'
savemat(filename, mdict, do_compression=True)


from leaf_object import VenationPoint
from pylab import *
from math_stuff import translation, get_unit_vector,nearest_neigbour, get_distance, merge_pos, compute_dir

class Particle_set:
    """
    This object represent a set of Partciles object.
    """

    particles = []
    petiole = None

    def __init__(self, particles, petiole):
        self.particles = particles
        self.petiole = petiole
        self.init_venation()
        self.init_vector()

    def display_particles(self):
         for p in self.particles:
            p.display_particle()

    def init_venation(self):
        for p in self.particles:
            p.last_venation = VenationPoint(p.coord, [])

    def init_vector(self):
        for p in self.particles:
            p.dir_to_p = get_unit_vector(p.coord, self.petiole)

    def get_closest(self, particle):
        neighbours = list(self.particles)
        neighbours.remove(particle)
        return nearest_neigbour(particle, neighbours)

    def move_particles(self, stepsize, weight_n, weight_t):
        print(len(self.particles))
        if len(self.particles) == 4:
            return
        else:
            for p in self.particles:
                q = self.get_closest(p)
                if get_distance(p, q) < 0.1:
                    p.last_venation = VenationPoint(merge_pos(p, q), [p.last_venation, q.last_venation])
                    self.particles.remove(q)
                else:
                    dir_closer = get_unit_vector(p.coord, q.coord)
                    p.move(dir_closer, stepsize, weight_n, weight_t)

        self.init_vector()

    def get_venations(self):
        venations = []
        for p in self.particles:
            venations.append(p.last_venation)
        return venations

class Particle:
    """
    This object represent a Particle of light

    attributes:
        coord: currant position of the particle
        last_venation: VenationPoint object, corresponding to the last position of the particle
        dir_to_p: the direction to go to the petiole
    """
    dir_to_p = None
    coord = None
    last_venation = None

    def __init__(self, coord):
        self.coord = coord

    def display_particle(self):
        plot(self.coord[0], self.coord[1], 'ro')

    def move(self, dir_closer, stepsize, weight_n, weight_t):

        direction = compute_dir(self.dir_to_p, dir_closer, weight_n, weight_t)
        self.coord = translation(self.coord, direction, stepsize)
        self.last_venation = VenationPoint(self.coord, [self.last_venation])


"""
   Copyright 2019 Faisal Thaheem

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
"""

import argparse
import os
import sys
import sqlite3
import time
import pprint
import traceback
import logging
import numpy as np
import cv2
import shutil
import random
import math
from tqdm import tqdm

ap = argparse.ArgumentParser()
ap.add_argument("-ln", "--lite.names", required=True,
    help="comma seperated list of sqlite db files to look up image info from")
ap.add_argument("-dp", "--data.path", required=True,
    help="comma seperated list of folders containing images to process")
ap.add_argument('-output_dir', default = 'out.anchors', type = str,
    help='Output anchor directory\n' )
ap.add_argument('-num_clusters', default = 2, type = int,
    help='number of clusters\n' )
args = vars(ap.parse_args())

#create logger
logger = logging.getLogger('sqlite2anchors')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('sqlite2anchors.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)

sqlitedbs = args["lite.names"].split(',')
datapaths = args["data.path"].split(',')

logger.info("Will be looking up following databases for info...")
logger.info(str(sqlitedbs))

logger.info("And, will be deleting files from..")
logger.info(str(datapaths))

dbconns = {}
dbcursors = {}

def loadsqlitedbs():

    logger.info("Instantiating sqlite dbs")

    for db in sqlitedbs:
        logger.info("Opening database " + db)

        if os.path.exists(db):
            conn = sqlite3.connect(db)
            dbconns[db] = conn

            cursor = conn.cursor()
            dbcursors[db] = cursor

            logger.info("database [{}] opened".format(db))
        else:
            logger.warn("database [{}] does not exist, skipping".format(db))
            dbcursors[db] = None
            dbconns[db] = None

    logger.info("dbs opened")

def closedbs():

    logger.info("Closing dbs")

    for db in sqlitedbs:
        if dbcursors[db] is not None:
            dbcursors[db].close()

        if dbconns[db] is not None:
            dbconns[db].close()

    logger.info("DBs closed")

def lookupFile(nameWithoutExtension, filePath):

    y1,x1,y2,x2,width,height,classId,className = None,None,None,None,None,None,None,None
    global targetWidth, targetHeight, crop_height, crop_width, crop_enabled

    for db in sqlitedbs:
        try:
            cursor = dbcursors[db]
            if cursor is not None:
                #look up plate information for the requested name
                query = "SELECT y1,x1,y2,x2,width,height,imheight,imwidth FROM plates WHERE filename = '{}' and isdeleted = 0 and isbackground=0".format(nameWithoutExtension)
                cursor.execute(query)
                row = cursor.fetchone()
                if row is not None:
                    y1,x1,y2,x2,width,height,imheight,imwidth = int(row[0]),int(row[1]),int(row[2]),int(row[3]),int(row[4]),int(row[5]),int(row[6]),int(row[7])
                    break

        except:
            logger.error(traceback.format_exc())

    return y1,x1,y2,x2,width,height,classId,className

width_in_cfg_file = 640.
height_in_cfg_file = 480.

def IOU(x,centroids):
    similarities = []
    k = len(centroids)
    for centroid in centroids:
        c_w,c_h = centroid
        w,h = x
        if c_w>=w and c_h>=h:
            similarity = w*h/(c_w*c_h)
        elif c_w>=w and c_h<=h:
            similarity = w*c_h/(w*h + (c_w-w)*c_h)
        elif c_w<=w and c_h>=h:
            similarity = c_w*h/(w*h + c_w*(c_h-h))
        else: #means both w,h are bigger than c_w and c_h respectively
            similarity = (c_w*c_h)/(w*h)
        similarities.append(similarity) # will become (k,) shape
    return np.array(similarities)

def avg_IOU(X,centroids):
    n,d = X.shape
    sum = 0.
    for i in range(X.shape[0]):
        #note IOU() will return array which contains IoU for each centroid and X[i] // slightly ineffective, but I am too lazy
        sum+= max(IOU(X[i],centroids))
    return sum/n

def write_anchors_to_file(centroids,X,anchor_file):
    f = open(anchor_file,'w')

    anchors = centroids.copy()
    print(anchors.shape)

    for i in range(anchors.shape[0]):
        anchors[i][0]*=width_in_cfg_file/32.
        anchors[i][1]*=height_in_cfg_file/32.

    widths = anchors[:,0]
    sorted_indices = np.argsort(widths)

    print('Anchors = ', anchors[sorted_indices])

    for i in sorted_indices[:-1]:
        f.write('%0.2f,%0.2f, '%(anchors[i,0],anchors[i,1]))

    #there should not be comma after last anchor, that's why
    f.write('%0.2f,%0.2f\n'%(anchors[sorted_indices[-1:],0],anchors[sorted_indices[-1:],1]))

    f.write('%f\n'%(avg_IOU(X,centroids)))
    print("")

def kmeans(X,centroids,eps,anchor_file):

    N = X.shape[0]
    iterations = 0
    k,dim = centroids.shape
    prev_assignments = np.ones(N)*(-1)
    iter = 0
    old_D = np.zeros((N,k))

    while True:
        D = []
        iter+=1
        for i in range(N):
            d = 1 - IOU(X[i],centroids)
            D.append(d)
        D = np.array(D) # D.shape = (N,k)

        print("iter {}: dists = {}".format(iter,np.sum(np.abs(old_D-D))))

        #assign samples to centroids
        assignments = np.argmin(D,axis=1)

        if (assignments == prev_assignments).all() :
            print("Centroids = ",centroids)
            write_anchors_to_file(centroids,X,anchor_file)
            return

        #calculate new centroids
        centroid_sums=np.zeros((k,dim),np.float)
        for i in range(N):
            centroid_sums[assignments[i]]+=X[i]
        for j in range(k):
            centroids[j] = centroid_sums[j]/(np.sum(assignments==j))

        prev_assignments = assignments.copy()
        old_D = D.copy()

def processDataDir(datapath):

    logger.error("Processing data path [{}]".format(datapath))

    annotation_dims = []

    for root, dirs, files in os.walk(datapath):

        totalFiles = len(files)
        logger.error("Processing [{}] file(s) in root [{}]".format(totalFiles, root))

        for i in tqdm(range(0,totalFiles)):
            fileName = files[i]
            filePath = os.path.join(root,fileName)
            #logger.info("Processing.. {} [{} of {}]".format(filePath, i, totalFiles))

            #y1,x1,y2,x2,width,height = lookupFile(os.path.splitext(fileName)[0])
            y1,x1,y2,x2,width,height,classId,className = lookupFile(fileName, filePath)
            if y1 is None:
                logger.warn("Could not get information for [{}] @ [{}]".format(fileName,filePath))
                continue
            try:
                w = x2-x1
                h = y2-y1
                #print(w,h)

                annotation_dims.append((w,h))
            except:
                logger.error(traceback.format_exc())

    annotation_dims = np.array(annotation_dims)

    eps = 0.005

    if args['num_clusters'] == 0:
        for num_clusters in range(1,11): #we make 1 through 10 clusters
            anchor_file = os.path.join( args['output_dir'],'anchors%d.txt'%(num_clusters))

            indices = [ random.randrange(annotation_dims.shape[0]) for i in range(num_clusters)]
            centroids = annotation_dims[indices]
            kmeans(annotation_dims,centroids,eps,anchor_file)
            print('centroids.shape', centroids.shape)
    else:
        anchor_file = os.path.join( args['output_dir'],'anchors%d.txt'%(args['num_clusters']))
        indices = [ random.randrange(annotation_dims.shape[0]) for i in range(args['num_clusters'])]
        centroids = annotation_dims[indices]
        kmeans(annotation_dims,centroids,eps,anchor_file)
        print('centroids.shape', centroids.shape)

time_start = time.time()

loadsqlitedbs()

if not os.path.exists(args['output_dir']):
    os.mkdir(args['output_dir'])

for path in datapaths:
    processDataDir(path)

#clean up part
closedbs()
time_end = time.time()
logger.info("Took [{}] s to process request".format(time_end-time_start))


import os.path

import pygtk
import gobject
import gtk

from rabbitvcs.ui import InterfaceView
from rabbitvcs.ui.checkout import SVNCheckout
from rabbitvcs.ui.clone import GitClone
from rabbitvcs.ui.dialog import MessageBox
from rabbitvcs.ui.action import SVNAction, GitAction
import rabbitvcs.util.helper

from rabbitvcs import gettext
_ = gettext.gettext

class SVNExport(SVNCheckout):
    def __init__(self, path=None, revision=None):
        SVNCheckout.__init__(self, path, url=None, revision=revision)

        self.svn = self.vcs.svn()

        self.get_widget("Checkout").set_title(_("Export - %s") % path)

        # Determine behavior based on the given path
        if self.svn.is_in_a_or_a_working_copy(path):
            # If path is from a working copy, export FROM path and set revision
            # to working copy
            self.repositories.set_child_text(path)
            self.get_widget("destination").set_text("")
            if revision is None:
                self.revision_selector.set_kind_working()
        elif self.svn.is_path_repository_url(path):
            # If path is a repository, export FROM path
            self.repositories.set_child_text(path)
            self.get_widget("destination").set_text("")
        else:
            # Path is not a working copy so the user probably wants to export
            # TO this path
            self.repositories.set_child_text("")
            self.get_widget("destination").set_text(path)

    def on_ok_clicked(self, widget):
        url = self.repositories.get_active_text()
        path = self._get_path()
        omit_externals = self.get_widget("omit_externals").get_active()
        recursive = self.get_widget("recursive").get_active()

        if not url or not path:
            MessageBox(_("The repository URL and destination path are both required fields."))
            return

        if url.startswith("file://"):
            url = self._parse_path(url)

        # Cannot do:
        # url = os.path.normpath(url)
        # ...in general, since it might be eg. an http URL. Doesn't seem to
        # affect pySvn though.

        path = os.path.normpath(path)
        revision = self.revision_selector.get_revision_object()

        self.hide()
        self.action = SVNAction(
            self.svn,
            register_gtk_quit=self.gtk_quit_is_set()
        )

        self.action.append(self.action.set_header, _("Export"))
        self.action.append(self.action.set_status, _("Running Export Command..."))
        self.action.append(rabbitvcs.util.helper.save_repository_path, url)
        self.action.append(
            self.svn.export,
            url,
            path,
            force=True,
            recurse=recursive,
            revision=revision,
            ignore_externals=omit_externals
        )
        self.action.append(self.action.set_status, _("Completed Export"))
        self.action.append(self.action.finish)
        self.action.start()

class GitExport(GitClone):
    def __init__(self, path=None, revision=None):

        self.vcs = rabbitvcs.vcs.VCS()
        self.git = None
        guess = rabbitvcs.vcs.guess(path)
        if guess["vcs"] == rabbitvcs.vcs.VCS_GIT:
            self.git = self.vcs.git(path)
            export_to = ""
            export_from = path
        else:
            export_to = path
            export_from = ""

        GitClone.__init__(self, export_to, export_from)

        self.get_widget("Checkout").set_title(_("Export - %s") % path)

        self.revision_selector = rabbitvcs.ui.widget.RevisionSelector(
            self.get_widget("revision_container"),
            self.git,
            revision=revision,
            url_combobox=self.repositories,
            expand=True
        )

        self.get_widget("revision_selector_box").show()

    def on_ok_clicked(self, widget):
        url = self.repositories.get_active_text()
        path = self._get_path()

        if not url or not path:
            MessageBox(_("The repository URL and destination path are both required fields."))
            return

        if url.startswith("file://"):
            url = self._parse_path(url)

        # Cannot do:
        # url = os.path.normpath(url)
        # ...in general, since it might be eg. an http URL. Doesn't seem to
        # affect pySvn though.

        path = os.path.normpath(path)
        revision = self.revision_selector.get_revision_object()

        self.hide()
        self.action = GitAction(
            self.git,
            register_gtk_quit=self.gtk_quit_is_set()
        )

        self.action.append(self.action.set_header, _("Export"))
        self.action.append(self.action.set_status, _("Running Export Command..."))
        self.action.append(rabbitvcs.util.helper.save_repository_path, url)
        self.action.append(
            self.git.export,
            url,
            path,
            revision=revision
        )
        self.action.append(self.action.set_status, _("Completed Export"))
        self.action.append(self.action.finish)
        self.action.start()

    def on_repositories_changed(self, widget, data=None):
        # Do not use quoting for this bit
        url = self.repositories.get_active_text()
        tmp = url.replace("//", "/").split("/")[1:]
        append = ""
        prev = ""
        while len(tmp):
            prev = append
            append = tmp.pop()
            if append not in ("trunk", "branches", "tags"):
                break

            if append in ("http:", "https:", "file:", "svn:", "svn+ssh:"):
                append = ""
                break

        self.get_widget("destination").set_text(
            os.path.join(self.destination, append)
        )

        self.check_form()

classes_map = {
    rabbitvcs.vcs.VCS_SVN: SVNExport,
    rabbitvcs.vcs.VCS_GIT: GitExport
}

def export_factory(vcs, path, revision=None):
    if not vcs:
        guess = rabbitvcs.vcs.guess(path)
        vcs = guess["vcs"]

    if vcs == rabbitvcs.vcs.VCS_DUMMY:
        vcs = rabbitvcs.vcs.VCS_SVN

    return classes_map[vcs](path, revision)

if __name__ == "__main__":
    from rabbitvcs.ui import main, REVISION_OPT, VCS_OPT
    (options, paths) = main(
        [REVISION_OPT, VCS_OPT],
        usage="Usage: rabbitvcs export --vcs=[git|svn] [url_or_path]"
    )

    window = export_factory(options.vcs, paths[0], revision=options.revision)
    window.register_gtk_quit()
    gtk.main()


from jinja2.ext import Extension
from textwrap import dedent
from io import StringIO
import os
import sys
import re
import ctypes
from jinja2 import nodes, Environment
import contextlib

#
# From https://stackoverflow.com/a/55545295
class PythonExtension(Extension):
    # a set of names that trigger the extension.
    tags = {'py'}

    def __init__(self, environment: Environment):
        super().__init__(environment)

    def parse(self, parser):
        """
        Parse {% py %} blocks in templates.

        Inserts an appropriate CallBlock into the parse tree where a {% py %}
        block is found, so it can be executed when the template is rendered.

        No actual code execution happens here.
        """
        lineno = next(parser.stream).lineno
        # Get contents until an {% endpy %} declaration
        # drop_needle drops the {% endpy %} at the end
        body = parser.parse_statements(['name:endpy'], drop_needle=True)

        # Insert a CallBlock that'll call our `_exec_python` method with
        # the body of {% py %} when rendering
        return nodes.CallBlock(self.call_method('_exec_python',
                                                [nodes.ContextReference(), nodes.Const(lineno), nodes.Const(parser.filename)]),
                               [], [], body).set_lineno(lineno)

    def _exec_python(self, ctx, lineno, filename, caller):
        """
        Execute python code from inside a parsed {% py %} block.

        Anything printed to stdout from the code in the block will be substituted
        in the template output. Locals & imports persist between different {% py %}
        blocks in the same template.
        """

        # Remove excess indentation
        code = dedent(caller())

        # Compile the code in this block so it can be executed.  We prepend
        # enough newlines that when the code is compiled, the line numbers of
        # the code *just* in this compiled block match the line numbers of the
        # code in the template itself. This provides us with useful error
        # messages.
        compiled_code = compile("\n" * (lineno - 1) + code, filename, "exec")

        # when a pyhp file is executed, the cwd should be set to the directory the
        # file is in. Similarly, when it tries to import python files, we should
        # look for it in the directory the pyhp file is in, *not* the directory
        # where the server started. So we save the current values and restore them
        # when done.
        # FIXME: If the {% py %} block calls os.chdir, that will not persist across
        # other blocks in the file. Same for `sys.path` manipulation
        cur_cwd = os.getcwd()
        cur_sys_path = sys.path

        # Capture stdout from this code block
        sout = StringIO()
        try:
            # FIXME: Make sure this isn't allowing for path traversal attacks?
            file_dir = os.path.dirname(os.path.abspath(filename))
            os.chdir(file_dir)
            new_sys_path = sys.path.copy()
            # The first entry in sys.path will always (haha) be the current directory.
            # By setting it to the directory of our pyhp file, our pyhp file can import
            # other .py files there!
            new_sys_path[0] = file_dir
            sys.path = new_sys_path
            with contextlib.redirect_stdout(sout):
                # Execute the code, with globals & locals from our jinja2 context
                exec(compiled_code, ctx.parent, ctx.vars)
        finally:
            sys.path = cur_sys_path
            os.chdir(cur_cwd)

        # WARNING: Everything from below here is Yuvi's guess of what's actually
        # happening.

        # jinja2 generates python code for each template, and executes it.
        # This generated python code calls this method to execute our
        # {% py %} block. Once the code block executes, the following must
        # be true:
        #
        # 1. Any new top-level locals defined in our code block must be available
        #    for any new jinja2 blocks
        # 2. Any pre-existing top level locals modified in our code block must have
        #    their new values reflected in any further jinja2 blocks
        #
        # This is pretty messy!
        #
        # We will:
        #
        # 1. Peer into this generated code that is calling us, by looking
        #    two frames in the call stack below our current frame. This is
        #    probably very brittle, but it works for now.
        # 2. Find local variables declared there, by making use of the fact that
        #    local variables are defined in the jinja2 generated code of the
        #    form `l_\d+_<variable-name>`. Again, very brittle.
        # 3. If our block overrides any of those top level locals, we explicitly
        #    *modify this generated code frame* so their values point to our
        #    new values. This is pretty nuts.

        # Get list of all local variable names defined in the top level in
        # our code.
        code_names = set(compiled_code.co_names)

        #
        generated_code_frame = sys._getframe(2)

        for local_var_name in generated_code_frame.f_locals:
            # Look for variables that are jinja2 generated top-level locals
            match = re.match(r"l_(\d+)_(?P<var_name>.+)", local_var_name)

            if match:
                var_name = match.group('var_name')

                # If the variable name appears in our code block, and is also a top-level local,
                # we update it to match its new value
                if (var_name in code_names) and (var_name in ctx.vars):
                    # Copy the value to the frame's locals.
                    generated_code_frame.f_locals[local_var_name] = ctx.vars[var_name]
                    # Do some ctypes vodo to make sure the frame locals are actually updated.
                    ctx.exported_vars.add(var_name)
                    # https://pydev.blogspot.com/2014/02/changing-locals-of-frame-frameflocals.html
                    ctypes.pythonapi.PyFrame_LocalsToFast(
                        ctypes.py_object(generated_code_frame),
                        ctypes.c_int(1))

        # Return the captured text.
        return sout.getvalue()


import requests
import base64
import json
from typing import List, Tuple

class Tweet:
  def __init__(self, text: str, lang: str=None, retweet_count: int=0):
    self.text = text
    self.lang = lang
    self.retweet_count = retweet_count

class TwitterHandler:
  def __init__(self):
    f = open('secrets/twitter_api_key.json')
    twitter_api_key = json.load(f)
    f.close()

    api_key = twitter_api_key["API_KEY"]
    api_key_secret = twitter_api_key["API_KEY_SECRET"]

    credentials = api_key + ":" + api_key_secret
    credentials_base64 = base64.b64encode(credentials.encode('ascii'))
    basic_token = "Basic " + credentials_base64.decode('ascii')

    headers = {
      "Authorization": basic_token,
      "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
    }
    body = "grant_type=client_credentials"

    response = requests.post('https://api.twitter.com/oauth2/token',
     headers=headers, data=body)

    self.__bearer_token = "Bearer " + response.json()["access_token"]

  def get_tweets(self, keyphrase:str='') -> Tuple[List[Tweet], str]:
    """
    Returns a pair with the list of the last 10 most popular tweets containing
    the specified keyphrase and with the topic queried. If no keyphrase is
    specified, it will be the main trending topic. If max_results is greater
    than 100, it will only return 100.
    """
    max_results = 100
    if keyphrase == '':
      keyphrase = self.main_trend_topic()
      print("Using the main trend topic: " + keyphrase + "\n\n")

    headers = {"Authorization": self.__bearer_token}
    payload = {
      'q': keyphrase,
      'count': 100 if max_results > 100 else max_results,
      'result_type': 'popular',
      'lang': 'pt'
    }
    # response = requests.get('https://api.twitter.com/2/search/recent',
    #  params=payload, headers=headers)
    response = requests.get('https://api.twitter.com/1.1/search/tweets.json',
     params=payload, headers=headers)

    # print(response.json())

    # V2
    # if response.json()['meta']['result_count'] == 0:
    #   return []

    if response.json()['search_metadata']['count'] == 0:
      return []

    # V2
    # tweet_list = [Tweet(data['text'], data['lang']) for data in response.json()['data']]

    tweet_list = [Tweet(data['text'], data['lang'], data['retweet_count'])
     for data in response.json()['statuses']]

    # tweet_list.sort(key=lambda tweet: tweet.retweet_count, reverse=True)
    # tweet_list = tweet_list[0:10]

    return (tweet_list, keyphrase)

  def main_trend_topic(self):
    headers = {"Authorization": self.__bearer_token}
    payload = {
      'id': 23424768, # Worldwide: 1 UK: 23424975 Brazil: 23424768
       # Germany: 23424829 Mexico: 23424900 Canada: 23424775
       # United States: 23424977 New York: 2459115
      'exclude': "%23"
    }
    response = requests.get('https://api.twitter.com/1.1/trends/place.json',
     params=payload, headers=headers)

    trend_topics = []
    for data in response.json()[0]['trends']:
      trend_topics.append( ( 0 if data['tweet_volume'] is None
       else data['tweet_volume'], data['name']) )

    return trend_topics[0][1]


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('tasks', '0012_task_review_comments'),
    ]

    operations = [
        migrations.AddField(
            model_name='task',
            name='priority',
            field=models.CharField(default=b'normal', max_length=16),
        ),
    ]


from unittest import TestCase
import punctilious as pu
import punctilious.random_data as random_data

class TestDoubleNegationIntroduction(TestCase):
    def test_dni_success(self):
        import sample.sample_double_negation_introduction as test
        u: pu.UniverseOfDiscourse = test.u
        o1: pu.SimpleObjct = test.o1
        o2: pu.SimpleObjct = test.o2
        r1: pu.Connective = test.r1
        proposition_of_interest: pu.InferredStatement = test.proposition_of_interest
        self.assertTrue(
            proposition_of_interest.is_formula_syntactically_equivalent_to(phi=u.c1.lnot(u.c1.lnot(r1(o1, o2)))))
        self.assertEqual('not(not(r1(o1, o2)))', proposition_of_interest.rep_formula(pu.encodings.plaintext))
        self.assertEqual('¬(¬(𝑟₁(𝑜₁, 𝑜₂)))', proposition_of_interest.rep_formula(pu.encodings.unicode))

    def test_dni_failure(self):
        pu.configuration.echo_default = True
        u = pu.UniverseOfDiscourse()
        o1 = u.o.declare()
        o2 = u.o.declare()
        o3 = u.o.declare()
        r1 = u.c1.declare(2, signal_proposition=True)
        t = u.t.declare()
        a = u.a.declare(random_data.random_sentence())
        ap = t.include_axiom(a)
        phi1 = t.i.axiom_interpretation.infer_formula_statement(ap, r1(o1, o2))
        self.assertEqual('r1(o1, o2)', phi1.rep_formula(encoding=pu.encodings.plaintext))
        self.assertEqual('𝑟₁(𝑜₁, 𝑜₂)', phi1.rep_formula(encoding=pu.encodings.unicode))
        print(u.i.double_negation_introduction)
        print(t.inference_rule_inclusions.double_negation_introduction)
        # Trying to pass a formula that is not a valid formula-statement must raise an Exception
        with self.assertRaises(pu.PunctiliousException):
            phi2 = t.i.dni.infer_formula_statement(p=r1(o1, o3))


grocery_menu = {
	"products" : ["Apples","Banana","Grapes","Orange"],
	"cost"	   : [28,15,18,200],
	"stock"    : [20,40,30,10]
}

Receipt = {
	"Cart" : [],
	"cart_quan" : [],
	"single_cost" : []
}

_total_cost = int(0)

_exit = True
while(_exit):

	_exit = False
	print ("-------------------------> Welcome to Ramy's Groceries shop <-------------------------")
	print ("customer mode Enter 1")
	print ("Owner mode Enter 2")
	print ("Exit 0")
	print ("-------------------------")
	main_mode = int( input("enter your choice ") )

	if main_mode == 1 and _exit == False :

		print ("To list Available items press 1")
		print ("For Order page press 2 ")
		#print ("Print your bill Press 3")
		print ("Exit 0")
		print ("-------------------------")
		customer_mode = int( input("enter your choice ") )

		if customer_mode == 1 or customer_mode == 2  :
			print("#"+3 * " "+"ITEMS"+ 6 *" "+"PRICE")
			for i in range(4):
				print(i+1,"-",grocery_menu["products"][i],6 * " ",grocery_menu["cost"][i],"\n")
			if 	customer_mode == 1 :
				_buy = int(input("For buy page press 1\nTo Exit press 0\n"))
				if _buy == 0 : _exit = True
			if customer_mode == 2 or _buy == 1 :
				_add = True
				while (_add) :
					_add = False
					num_index= int(input("please write the index of the item "))
					quantity= int(input("please write the quantity in Kg "))
					Receipt["Cart"].append(grocery_menu["products"][num_index-1])
					Receipt["cart_quan"].append(quantity)
					grocery_menu["stock"][num_index-1] -= quantity
					_single_cost = (quantity * grocery_menu["cost"][num_index-1])
					Receipt["single_cost"].append(_single_cost )
					_add = int (input(" To add more press 1 , to Print Receipt press 0\n"))
					if _add == 0 :
						print("#"+3 * " "+"ITEMS"+ 6 *" "+"quantities"+ 6 *" "+"Cost")
						for i in range(len(Receipt["single_cost"])):
							print(i+1,"-",Receipt["Cart"][i],6 * " ",Receipt["cart_quan"][i],10 * " ",Receipt["single_cost"][i],"\n")
						_total_cost = sum(Receipt["single_cost"])
						print ( "Total cost= ", _total_cost )

		elif customer_mode == 0 :
			print(" Have a nice day")

	elif main_mode == 2 and _exit == False :
		pass_status = True
		while (pass_status):
			_pass=input("Please enter the password\n")
			if _pass == "1234" :
				print ("-------------------------")
				print("Welcome Back Mr.Ramy")
				print ("-------------------------")
				pass_status = False

			else :
				print ("Wrong Please try again")

		print ("Add New Product Press 1 ")
		print ("Show list of products Press 2 ")
		print ("Change cost of a product Press 3")
		print ("Exit 0")
		owner_mode = int( input("enter your choice ") )

		if owner_mode == 1 or owner_mode == 2:
			_exit = True
			print("#"+3 * " "+"ITEMS"+ 6 *" "+"PRICE" + 6 *" "+"Stock"  )
			for i in range(len(grocery_menu["products"])):
				print(i+1,"-",grocery_menu["products"][i],6 * " ",grocery_menu["cost"][i],6 * " ",grocery_menu["stock"][i],"\n")
			if owner_mode == 2 :
				_dis = int(input(" To add a new product Press 1 or To Exit 0 "))
				if _dis == 0 :
					_exit = True
			if owner_mode == 1 or _dis == 1 :
				_add_2 = True
				while(_add_2) :
					_add_2 = False
					_new_pro = str(input("Please enter the new product name "))
					_new_cost = int(input("Please enter the cost of the product "))
					_new_stock = int(input("Please enter the stock level of the product "))
					grocery_menu["products"].append(_new_pro)
					grocery_menu["cost"].append(_new_cost)
					grocery_menu["stock"].append(_new_stock)
					_add_2 = int (input(" To add more press 1 , to Exit press 0\n"))
				if _add_2 == 0 :
						print("#"+3 * " "+"ITEMS"+ 6 *" "+"PRICE" + 6 *" "+"Stock"  )
				for i in range(len(grocery_menu["products"])):
					print(i+1,"-",grocery_menu["products"][i],6 * " ",grocery_menu["cost"][i],6 * " ",grocery_menu["stock"][i],"\n")
		if owner_mode == 3 :
			_add_3 = True
			_exit = True
			while(_add_3) :
				_add_3 = False
				print("#"+3 * " "+"ITEMS"+ 6 *" "+"PRICE" + 6 *" "+"Stock"  )
				for i in range(len(grocery_menu["products"])):
					print(i+1,"-",grocery_menu["products"][i],6 * " ",grocery_menu["cost"][i],6 * " ",grocery_menu["stock"][i],"\n")
				_index_cost = int ( input("Please enter the index of the product "))
				_update_cost = int ( input("Please enter updated cost "))
				grocery_menu["cost"][_index_cost-1]=_update_cost
				_add_3 = int (input(" To add more press 1 , to Exit press 0\n"))
			if _add_3 == 0 :
				print("#"+3 * " "+"ITEMS"+ 6 *" "+"PRICE" + 6 *" "+"Stock"  )
				for i in range(len(grocery_menu["products"])):
					print(i+1,"-",grocery_menu["products"][i],6 * " ",grocery_menu["cost"][i],6 * " ",grocery_menu["stock"][i],"\n")

	elif main_mode == 0 and _exit == False :

		print(" Have a nice day")


import subprocess
import time
import sys
import re
import os

"""Use android debugger to dial phones and hang them up.
    This is for saving some time in the device testing process.
    (assumes android debugger is available)

    https://forum.xda-developers.com/showthread.php?t=2141817
    http://www.linuxtopia.org/online_books/android/devguide/guide/developing/tools/android_adb_commandsummary.html

    "%23" == "#" in strings
    """

class Dialer(object):
    """ init with quantity of dial tests and duration of call"""
    def __init__(self, reps=10, duration=35, timeout=20, wait=10, callers=None, logbook=None):
        self.devices = self.devicelist()
        self.wait = wait
        self.phonebook = dict()
        self.repetitions = reps
        self.duration = duration
        self.timeout = timeout
        self.callers = callers
        self.log_fn = logbook or os.path.join(os.getcwd(), "logbook.txt")
        self.current_caller = None

    def devicelist(self):
        """ return a list of device codes for the usb-plugged-in devices
         in the order they are given by calling 'adb devices' """
        raw = subprocess.run(["adb", "devices"], stdout=subprocess.PIPE).stdout.decode("utf-8").split(os.linesep)[1:]
        return [entry.split('\t')[0] for entry in raw if "\t" in entry]

    def obtain_number(self):
        """ user manually puts in dut phone numbers """
        print("{} device{} plugged in and registered with Android debugger.".format(len(self.devices),
                                                                                " is" if len(
                                                                                self.devices) == 1 else "s are"))
        print("Put in phone numbers for the devices below.\n "
              "Leave blank the single device you want to place all the calls,\n"
              "or, to make all the devices call each other, give them all valid phone numbers.")
        for device in self.devices:
            if len(device) > 3:  # ignore the stray linefeeds and tabs, keep the device serial numbers
                self.phonebook[device] = input("{}: ".format(device)).strip().replace("-", "").replace(".", "")
                entry_len = len(self.phonebook[device])
                if (entry_len > 11) or len(re.findall(r'\D', self.phonebook[device])):
                    print("The above does not appear to be a valid phone number: {}".format(self.phonebook[device]))
                    print(" ----  starting over -------")
                    self.obtain_number()
                    break
        return 1

    def assign_callers(self):
        for device, phone_number in self.phonebook.items():
            if phone_number is "":
                return [device]
        return self.phonebook.keys()

    def teardown_call(self, hangups, wait=None):
        """ hangups is a list of serial-ids to send the hangup message to via adb  """
        if wait is None:
            wait = self.wait
        if type(hangups) is not list:
            hangups = list((hangups,))
        sys.stdout.write("\r")
        for device in hangups:
            subprocess.call('adb -s {} wait-for-device shell input keyevent KEYCODE_ENDCALL'.format(device), shell=True)
        for j in range(wait, 0, -1):
            sys.stdout.write("\r")
            sys.stdout.write("Call teardown:{:2d}".format(j))
            sys.stdout.flush()
            time.sleep(1)
        print(" fin ")

    def call(self):
        """ needs to log results
        1) 20 second no pickup
        2) successful call-pickup-listen-hangup
        3) failure to ring  --  bonus! record gps of failure!
        $ adb shell dumpsys <service> """
        if self.callers is None:
            self.callers = self.assign_callers()
        for caller in self.callers:
            for callee, phone_number in self.phonebook.items():
                if caller == callee:
                    continue
                countdown = self.repetitions
                while countdown:
                    countdown -= 1
                    print('*** Begin call {}  to device {} ***'.format(self.repetitions - countdown, callee))
                    subprocess.call(
                        'adb -s {} wait-for-device shell am start -a android.intent.action.CALL -d tel:{}'.format(
                            caller, phone_number), shell=True)
                    self.call_found, self.call_answered = False, False
                    for i in range(self.duration, 0, -1):  # caller will maintain call for duration
                        sys.stdout.write("\r")
                        sys.stdout.write("{:2d}".format(i))
                        sys.stdout.flush()
                        time.sleep(1)
                        if not self.call_found:
                            self.call_found = self.lookforcall(callee)
                            if i < (self.duration - self.timeout):
                                print(" Call Timeout expired! device {} failed to call {}".format(caller, callee))
                        if self.call_found and (not self.call_answered):
                            self.answer_call(callee)
                            self.call_answered = True

                    self.teardown_call([caller, callee])
        print("Finished the call list!")

    def lookforcall(self, device):
        cmds = ['adb', '-s', '{}'.format(device), 'wait-for-device', 'shell', 'dumpsys', 'telephony.registry']
        blather = subprocess.run(cmds, stdout=subprocess.PIPE).stdout.decode("utf-8")
        incoming = [i for i in blather.split(os.linesep) if 'mCallIncomingNumber' in i][0].split('=')
        if len(incoming[1]) > 6:
            print("  incoming on {} device: {}".format(device, incoming))
            return incoming[1]
        return False

    def answer_call(self, device):
        subprocess.call('adb -s {} wait-for-device shell input keyevent KEYCODE_CALL'.format(device), shell=True)
        print(" device {} answers".format(device))

# main
if __name__ == "__main__":
    dialup = Dialer()
    dialup.obtain_number()
    dialup.call()


class SimpleGraph:
    def __init__(self):
        self.edges = {}

    def neighbors(self, id):
        return self.edges[id]

example_graph = SimpleGraph()
example_graph.edges = {
    'A': ['B','C'],
    'B': [ 'D','E'],
    'C': [],
    'D': [],
    'E': ['F','G'],
    'F': ['H','I'],
    'G': [],
    'H': [],
    'I': ['J','K'],
    'J': [],
    'K': ['L','M'],
    'L': []
}

import collections

class Queue:
    def __init__(self):
        self.elements = collections.deque()

    def empty(self):
        return len(self.elements) == 0

    def put(self, x):
        self.elements.append(x)

    def get(self):
        return self.elements.popleft()

#from implementation import *

def breadth_first_search_1(graph, start, goal):
    frontier = Queue()
    frontier.put(start)
    visited = {}
    visited[start] = True

    while not frontier.empty():
        current = frontier.get()
        print("Visiting %r" % current)
        if current == goal:
            break
        for next in graph.neighbors(current):
            if next not in visited:
                frontier.put(next)
                visited[next] = True

breadth_first_search_1(example_graph, 'A','M')


import sys; input = sys.stdin.readline
a,b,c,d = map(int, input().split())
ans = 0
st = 0
fi = max(b,c,d)
for _ in range(100):
    mid = (st+fi)/2
    if (b//mid) * (c//mid) * (d//mid) >= a:
        ans = max(ans,mid)
        st = mid
    else:
        fi = mid
print(ans)