import ffmpeg
import numpy
import sys
import random
import os
import cv2

def read_frame_as_jpeg(in_file, frame_num):
    """
    指定帧数读取任意帧
    """
    out, err = (
        ffmpeg.input(in_file)
              .filter('select', 'gte(n,{})'.format(frame_num))
              .output('pipe:', vframes=1, format='image2', vcodec='mjpeg')
              .run(capture_stdout=True)
    )
    return out

def read_frame_by_time(in_file, time):
    """
    指定时间节点读取任意帧
    """
    out, err = (
        ffmpeg.input(in_file, ss=time)
              .output('pipe:', vframes=1, format='image2', vcodec='mjpeg')
              .run(capture_stdout=True)
    )
    return out

def get_video_info(in_file):
    """
    获取视频基本信息
    """
    try:
        probe = ffmpeg.probe(in_file)
        video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
        if video_stream is None:
            print('No video stream found', file=sys.stderr)
            sys.exit(1)
        return video_stream
    except ffmpeg.Error as err:
        print(str(err.stderr, encoding='utf8'))
        sys.exit(1)

def main():
    file_path = './test.mp4'
    #file_path = './test.avi'
    #file_path = './monkey_video/test.MTS'
    video_info = get_video_info(file_path) # 视频信息字典
    print(video_info)
    width = video_info['width'] # 宽度
    height = video_info['height'] # 高度
    total_frames = video_info['nb_frames'] # 帧数
    total_duration = video_info['duration'] # 时长
    frame_rate = video_info['r_frame_rate'] # 帧率
    bitrate = video_info['bit_rate'] # 码率
    print('宽度：{}'.format(width))
    print('高度：{}'.format(height))
    print('帧数：{}'.format(total_frames))
    print('时长：{}s'.format(total_duration))
    print('帧率：{}'.format(frame_rate))
    print('比特率(码率)：{}bps'.format(bitrate))
    '''
    #指定帧数读取任意帧
    random_frame = random.randint(1,total_frames)
    print('随机帧索引：{}'.format(random_frame))
    out = read_frame_as_jpeg(file_path, random_frame)
    image_array = numpy.asarray(bytearray(out), dtype="uint8")
    image = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
    cv2.imshow('frame', image)
    cv2.waitKey()

    #指定时间读取任意帧
    random_time = random.randint(1, int(float(total_duration)) - 1) + random.random()
    print('随机时间：{}s'.format(random_time))
    out = read_frame_by_time(file_path, random_time)
    image_array = numpy.asarray(bytearray(out), dtype="uint8")
    image = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
    cv2.imshow('frame', image)
    cv2.waitKey()
    '''

if __name__ == '__main__':
    main()


import json
import logging
import os
import pytest
import yaml

from tests.common.helpers.assertions import pytest_assert
from tests.common import mellanox_data

pytestmark = [
    pytest.mark.topology('any')
]

SENSORS_DATA_FILE = "../../ansible/group_vars/sonic/sku-sensors-data.yml"

def to_json(obj):
    return json.dumps(obj, indent=4)

@pytest.fixture(scope='module')
def sensors_data():
    sensors_data_file_fullpath = os.path.join(os.path.dirname(os.path.realpath(__file__)), SENSORS_DATA_FILE)
    return yaml.safe_load(open(sensors_data_file_fullpath).read())

def test_sensors(duthosts, rand_one_dut_hostname, sensors_data):
    duthost = duthosts[rand_one_dut_hostname]
    # Get platform name
    platform = duthost.facts['platform']

    if mellanox_data.is_mellanox_device(duthost):
        hardware_version = mellanox_data.get_hardware_version(duthost, platform)
        if hardware_version:
            platform = platform + '-' + hardware_version

    # Prepare check list
    sensors_checks = sensors_data['sensors_checks']

    if platform not in list(sensors_checks.keys()):
        pytest.skip("Skip test due to not support check sensors for current platform({})".format(platform))

    logging.info("Sensor checks:\n{}".format(to_json(sensors_checks[platform])))

    # Gather sensor facts
    sensors_facts = duthost.sensors_facts(checks=sensors_checks[platform])['ansible_facts']

    logging.info("Sensor facts:\n{}".format(to_json(sensors_facts)))

    # Analyze sensor alarms
    is_sensor_alarm = sensors_facts['sensors']['alarm']
    sensor_alarms = sensors_facts['sensors']['alarms']

    pytest_assert(not is_sensor_alarm, "Sensor alarms:\n{}".format(to_json(sensor_alarms)))

    # Analyze sensor warnings
    is_sensor_warning = sensors_facts['sensors']['warning']
    sensor_warnings = sensors_facts['sensors']['warnings']

    if is_sensor_warning:
        logging.warning("Sensor warnings:\n{}".format(to_json(sensor_warnings)))


import numpy as np

def noise_2d( img, std ):
    row, col = img.shape
    mean = 0
    gauss = np.random.normal( mean, std ** 2, (row, col) )
    gauss = gauss.reshape( row, col )
    img_noise = img + gauss
    return img_noise / np.max( img_noise )

def noise( signal, mean ,std ):
    n = len( signal )
    return signal + np.gauss( mean, std ** 2, n )


"""
Déterminer si ce sont les ordinateurs Dell ou Acer qui ont le plus de reduction sur CDiscount (ie le taux de rabat)
Ce code ne fonctionne que pour les ordinateurs portables
"""

import urllib.request as req
from bs4 import BeautifulSoup

def get_soup(produit, numero_page):
    url = 'http://www.cdiscount.com/search/10/' + produit + '.html?TechnicalForm.SiteMapNodeId=0&TechnicalForm.DepartmentId=10&TechnicalForm.ProductId=&hdnPageType=Search&TechnicalForm.SellerId=&TechnicalForm.PageType=SEARCH_AJAX&TechnicalForm.LazyLoading.ProductSheets=False&NavigationForm.CurrentSelectedNavigationPath=f%2F1%2F0k&FacetForm.SelectedFacets.Index=0&FacetForm.SelectedFacets.Index=1&FacetForm.SelectedFacets.Index=2&FacetForm.SelectedFacets%5B2%5D=f%2F6%2F' + produit + '&FacetForm.SelectedFacets.Index=3&FacetForm.SelectedFacets.Index=4&FacetForm.SelectedFacets.Index=5&FacetForm.SelectedFacets.Index=6&FacetForm.SelectedFacets%5B6%5D=f%2F8%2Fordinateur+portable&FacetForm.SelectedFacets.Index=7&GeolocForm.ConfirmedGeolocAddress=&SortForm.SelectedSort=PERTINENCE&ProductListTechnicalForm.Keyword=' + produit +'&&page=' + numero_page + '_his_'
    html = req.urlopen(url).read()
    return BeautifulSoup(html, "html.parser")

def get_prix(produit, nombre_pages):
    liste_prix = []

    for i in range(1, nombre_pages + 1):
        soup = get_soup(produit, str(i))
        nombre_ordis = len(soup.select("div.prdtPrSt"))
        index = 0

        while (index < nombre_ordis):
            nom_ordi = soup.select("div.prdtBTit")[index].text
            ancien_prix = soup.select("div.prdtPrSt")[index].text.replace(",", ".")
            nouveau_prix = soup.select("span.price")[index].text.replace("€", ".")
            if not ancien_prix:
                ancien_prix = nouveau_prix
            ordi = {nom_ordi: {ancien_prix, nouveau_prix}}
            liste_prix.append((nom_ordi, float(ancien_prix), float(nouveau_prix)))
            index += 1
    return liste_prix

def calculate_reduction(liste_prix):

    montant_reduction_moyen_tout_portable = 0
    montant_reduction_moyen_portables_remises = 0

    prix_total_sans_reduction = 0
    prix_total_avec_reduction = 0
    nombre_ordis_total = 0
    nombre_ordis_remises = 0

    for prix in liste_prix:
        prix_total_sans_reduction += prix[1]
        prix_total_avec_reduction += prix[2]
        nombre_ordis_total += 1
        if prix[1] > prix[2]:
            nombre_ordis_remises += 1
    montant_reduction_moyen_tout_portable = (prix_total_sans_reduction - prix_total_avec_reduction) / nombre_ordis_total
    montant_reduction_moyen_portables_remises = (
                                              prix_total_sans_reduction - prix_total_avec_reduction) / nombre_ordis_remises

    return ({"Montant réduction moyen tout portable": montant_reduction_moyen_tout_portable,
             "Montant réduction moyen portables remises": montant_reduction_moyen_portables_remises})

if __name__ == '__main__':
    liste_prix_acer = get_prix("acer", 9)
    print("Pour acer voici les infos sur les réductions faites : {0}".format(calculate_reduction(liste_prix_acer)))

    liste_prix_acer = get_prix("dell", 20)
    print("Pour dell voici les infos sur les réductions faites : {0}".format(calculate_reduction(liste_prix_acer)))


from sfml import sf

class UIText(object):
    FONT  = sf.Font.from_file("Welbut.ttf")
    def __init__(self, font, text, color, position, size):
        self.font = font
        self.label = sf.Text()
        self.label.font = self.font
        self.text = text
        self.label.string = unicode(self.text)
        self.color = color
        self.label.color = self.color
        self.position = position
        self.size = size
        self.label.character_size = self.size
        self.hover_color = sf.Color.CYAN

        self.centerText()
        self.setPosition(self.position)

    def render(self, window, hovered = False):
        if(hovered):
            self.label.color = self.hover_color
        window.draw(self.label)
        self.label.color = self.color

    def setPosition(self, new_pos):
        self.position = new_pos
        self.label.position = self.position

    def setText(self, new_text):
        self.text = new_text
        self.label.string = unicode(self.text)

    def setSize(self, _size):
        self.size = _size
        self.label.character_size = self.size

    def centerText(self):
        text_rect = self.label.local_bounds
        self.label.origin = (text_rect.left + text_rect.width / 2.0, text_rect.top + text_rect.height / 2.0)


import pandas as pd
from BankClassify import BankClassify

def test_mintReader_returns_date_description_ammount():
    bc = BankClassify()
    df = bc._read_mint_csv('transactions.csv')

    columns = df.columns.values.tolist()
    assert 'date' in columns
    assert 'desc' in columns
    assert 'amount' in columns

def test_onlyTreeColumns():
    bc = BankClassify()
    df = bc._read_mint_csv('transactions.csv')

    assert len(df.columns.values.tolist()) == 3

def test_debitIsNegative_creditIsPositive():
    df = pd.read_csv('transactions.csv', skiprows=0)

    """Rename columns """
    # df.columns = ['date', 'desc', 'amount']
    df.rename(
        columns={
            "Date": 'date',
            "Original Description": 'desc',
            "Amount": 'amount',
            "Transaction Type": 'type'
        },
        inplace=True
    )

    bc = BankClassify()
    df_dut = bc._read_mint_csv('transactions.csv')

    baseline = df['type'] == 'debit'

    assert (df_dut.loc[baseline, 'amount'] < 0).all()
    assert (df_dut.loc[~baseline, 'amount'] >= 0).all()


"""
View-functions.
"""

from django.conf import settings
from django.db.models import F, Sum
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django_filters.rest_framework import DjangoFilterBackend
from djoser.views import UserViewSet as DjoserUserViewSet
from rest_framework import permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from recipes import models
from users.models import Subscription, User

from . import serializers
from .filters import IngredientFilter, RecipeFilter
from .paginations import CustomPagination
from .permissions import AdminOrReadOnly, AuthorAdminOrReadOnly

# -----------------------------------------------------------------------------
#                            Users app
# -----------------------------------------------------------------------------

class UserViewSet(DjoserUserViewSet):
    """
    Viewset for User model.

    Has standart pagination. Any users can gat safe methods.

    Action-methods: "subscription" and "subscribe" - to check
    users subscription, follow and unfollow authors.
    """

    queryset = User.objects.all()
    serializer_class = serializers.UserSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    pagination_class = CustomPagination
    http_method_names = ["get", "post", "delete", "head"]

    def get_permissions(self):
        if self.action == "me":
            self.permission_classes = (permissions.IsAuthenticated,)
        return super().get_permissions()

    @action(methods=["POST", "DELETE"],
            detail=True, )
    def subscribe(self, request, id):
        user = request.user
        author = get_object_or_404(User, id=id)
        subscription = Subscription.objects.filter(
            user=user, author=author)

        if request.method == "POST":
            if subscription.exists():
                return Response({"error": "Youre alredy subscribed"},
                                status=status.HTTP_400_BAD_REQUEST)
            if user == author:
                return Response({"error": "Unable to subscribe to yourself"},
                                status=status.HTTP_400_BAD_REQUEST)
            serializer = serializers.SubscribeSerializer(
                author,
                context={"request": request}
            )
            Subscription.objects.create(user=user, author=author)
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        if request.method == "DELETE":
            if subscription.exists():
                subscription.delete()
                return Response(status=status.HTTP_204_NO_CONTENT)
            return Response({"error": "Вы не подписаны на этого пользователя"},
                            status=status.HTTP_400_BAD_REQUEST)

    @action(detail=False, permission_classes=[permissions.IsAuthenticated])
    def subscriptions(self, request):
        user = request.user
        follows = User.objects.filter(following__user=user)
        page = self.paginate_queryset(follows)
        serializer = serializers.SubscribeSerializer(
            page, many=True,
            context={"request": request})
        return self.get_paginated_response(serializer.data)

# -----------------------------------------------------------------------------
#                            Recipe app
# -----------------------------------------------------------------------------

class TagViewSet(ModelViewSet):
    """
    Viewset for Tag model.

    Has no pagination. Only admin can change this model.
    """

    queryset = models.Tag.objects.all()
    serializer_class = serializers.TagSerializer
    permission_classes = (AdminOrReadOnly,)
    pagination_class = None

class IngredientViewSet(ModelViewSet):
    """
    Viewset for Ingredient model.

    Has no pagination. Only admin can change this model.
    Has searching by name without register sensitivity.
    """

    queryset = models.Ingredient.objects.all()
    serializer_class = serializers.IngredientSerializer
    permission_classes = (AdminOrReadOnly,)
    filter_backends = (DjangoFilterBackend,)
    filterset_class = IngredientFilter
    pagination_class = None

class RecipeViewSet(ModelViewSet):
    """
    Viewset for Recipe model.

    Has standart pagination. Author and admin can change this model.

    Can be filtred by author, tags, favorites and shopping cart.

    Has method "get_serializer_class" to select serializer by
    http method.
    """

    queryset = models.Recipe.objects.all()
    serializer_class = serializers.RecipeSerializer
    permission_classes = (AuthorAdminOrReadOnly,)
    filter_backends = (DjangoFilterBackend,)
    filterset_class = RecipeFilter
    pagination_class = CustomPagination

    def action_post_delete(self, pk, serializer_class):
        user = self.request.user
        recipe = get_object_or_404(models.Recipe, pk=pk)
        object = serializer_class.Meta.model.objects.filter(
            user=user, recipe=recipe
        )

        if self.request.method == "POST":
            serializer = serializer_class(
                data={"user": user.id, "recipe": pk},
                context={"request": self.request}
            )
            serializer.is_valid(raise_exception=True)
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        if self.request.method == "DELETE":
            if object.exists():
                object.delete()
                return Response(status=status.HTTP_204_NO_CONTENT)
            return Response({"error": "This recipe not in list."},
                            status=status.HTTP_400_BAD_REQUEST)

    @action(methods=["GET", "POST", "DELETE"], detail=True)
    def favorite(self, request, pk):
        """Add or delete recipe in favorite list."""

        return self.action_post_delete(pk, serializers.FavoriteSerializer)

    @action(methods=["GET", "POST", "DELETE"], detail=True)
    def shopping_cart(self, request, pk):
        """Add or delete recipe in shop list."""

        return self.action_post_delete(pk, serializers.ShoppingCartSerializer)

    @action(methods=["GET"], detail=False)
    def download_shopping_cart(self, request):
        """Dowload shop list in [FILE_NAME].txt file."""

        user = self.request.user
        if not user.shopping_cart.exists():
            return Response(status=status.HTTP_400_BAD_REQUEST)

        ingredients = models.RecipeIngredient.objects.filter(
            recipe__shopping_cart__user=request.user).values(
            name=F("ingredient__name"),
            measurement=F("ingredient__measurement_unit")
        ).annotate(amount=Sum("amount"))

        shopping_list = []

        for units in ingredients:
            shopping_list.append(
                f"{units['name']}: {units['amount']} {units['measurement']}"
            )
        shopping_list = "\n".join(shopping_list)
        response = HttpResponse(
            shopping_list, content_type="text.txt; charset=utf-8"
        )
        response["Content-Disposition"] = ("attachment; "
                                           + f"filename={settings.FILE_NAME}")
        return response


import math
import os

# *********************************** Define functions

# Define bit conversion

def bit_length(n):
    if n == 1:
        return 1
    elif n > 1:
        return math.ceil(math.log(n) / math.log(2))

# Define bit conversion

def int2binary(w, z):
    return bin(w)[2:].zfill(z)

# Define bit conversion

def binary_str2int(str_input):
    a = 0
    for x in range(0, len(str_input)):
        b = int(str_input[len(str_input) - x - 1]) * int(2 ** x)
        a += b
    return a

# ****** Define bit to str conversion *******

def bits2a(b):
    return ''.join(chr(int(''.join(x), 2)) for x in zip(*[iter(b)]*8))

# *********************************** Generic variables

output_file = "lena_converted.jpg"  # Must be the same file type in both files
output_file_binary = "data_flits_noc.txt"
output_file_header = "report.txt"  # Header parsing report
output_file_mismatch_report = "mismatch_report.txt"  # Flit mismatch report
input_data_file_noc = "data_header_noc.txt"  # Received data+header from NoC
input_data_file_python = "data_header.txt"  # Initial converted data+header from Python
input_packet_length_file = "packet_header_length.txt"
header_included = True  # header_included in the packet structure
max_x_dim = 4  # starting from 1  //  Must be the same in both files
max_y_dim = 4  # starting from 1  //  Must be the same in both files
max_z_dim = 3  # starting from 1  //  Must be the same in both files
flit_width = 32  # Must be the same in both files
max_packet_len = 31  # (number of flits + header_included) in a packet  //  Must be the same in both files

# *********************************** Internal variables

flit_padding_width = flit_width / 16  # Should not be changed
packet_length_line_counter = 0  # Should not be changed
f1_line_counter = 0  # Should not be changed
f2_line_counter = 0  # Should not be changed
line_counter = 0  # Should not be changed
data_line_counter = 1  # Should not be changed
total_packet_length = 0  # Should not be changed
data2save = ""
header2save = ""
header = ""
mismatch_report = ""
data_reconversion = []

# *******************************************************************************
# ********************************************************************* Main body

# ******************************************************************
# *********************************** Header parsing and make report

with open(input_data_file_noc) as f:
    input_data = f.readlines()

with open(input_packet_length_file) as f:
    packet_length = f.readlines()

line_num = sum(1 for line in open(input_packet_length_file))
x_width = bit_length(max_x_dim)
y_width = bit_length(max_y_dim)
z_width = bit_length(max_z_dim)
packet_length_width = bit_length(max_packet_len)
packet_id_width = math.ceil(math.log(line_num) / math.log(2))

header_total = int(flit_padding_width + packet_id_width + (2 * z_width) + (2 * y_width) + (2 * x_width) + packet_length_width)
header_num = math.ceil(header_total / flit_width)

flit_padding_lsb = (flit_width * header_num) - (packet_id_width + (2 * z_width) + (2 * y_width) + (2 * x_width) + packet_length_width)
flit_padding_msb = (flit_width * header_num) - (int(flit_padding_width) + packet_id_width + (2 * z_width) + (2 * y_width) + (2 * x_width) + packet_length_width)

packet_id_lsb = (flit_width * header_num) - ((2 * z_width) + (2 * y_width) + (2 * x_width) + packet_length_width)
packet_id_msb = (flit_width * header_num) - (packet_id_width + (2 * z_width) + (2 * y_width) + (2 * x_width) + packet_length_width)

source_add_lsb = (flit_width * header_num) - (z_width + y_width + x_width + packet_length_width)
source_add_msb = (flit_width * header_num) - ((2 * z_width) + (2 * y_width) + (2 * x_width) + packet_length_width)

dest_add_lsb = (flit_width * header_num) - packet_length_width
dest_add_msb = (flit_width * header_num) - (z_width + y_width + x_width + packet_length_width)

packet_length_lsb = (flit_width * header_num)
packet_length_msb = (flit_width * header_num) - packet_length_width

counter = 0
for y in range(0, line_num):
    packet_length_temp = packet_length[y]
    for x in range(total_packet_length, (total_packet_length + int(packet_length_temp))):
        if x == total_packet_length:
            for z in range(header_num, 0, -1):
                header += input_data[x+z-1]
            header = header.replace("\n", "")
            counter += 1
            flit_padding = binary_str2int(header[flit_padding_msb: flit_padding_lsb])
            packet_id = binary_str2int(header[packet_id_msb: packet_id_lsb])
            source_add = header[source_add_msb: source_add_lsb]
            dest_add = header[dest_add_msb: dest_add_lsb]
            packet_length_header = binary_str2int(header[packet_length_msb: packet_length_lsb]) - (header_num + int(header_included) - 1)
            header2save += "Flit Padding (Byte): " + str(flit_padding).ljust(10) + "| " + "Packet ID: " + \
                           str(packet_id).ljust(10) + "| " + "Source add (ZYX): " + str(source_add).ljust(15) + "| " + \
                           "Dest add (ZYX): " + str(dest_add).ljust(15) + "| " + "Packet length: " + \
                           str(packet_length_header).ljust(10) + "| " + "Header: " + header + "\n"
            header = ""
        elif (x > total_packet_length + header_num - 1) and (x < ((total_packet_length + int(packet_length_temp)) - 1)):
            data2save += str(input_data[x])
        elif x == (total_packet_length + int(packet_length_temp)) - 1:
            last_line = input_data[x]
            data2save += str(last_line[(flit_padding * 8): len(last_line) - 1]) + "\n"

    total_packet_length += int(packet_length_temp)

if os.path.exists(output_file_header):
    os.remove(output_file_header)

f = open(output_file_header, 'w')
f.write(header2save)
f.close()

if os.path.exists(output_file_binary):
    os.remove(output_file_binary)

f = open(output_file_binary, 'w')
f.write(data2save)
f.close()

# ******************************************************************
# ************************************************ Data Reconversion

input_file_2 = open(output_file_binary, 'r')
lines = input_file_2.read()

myList = [item for item in lines.split('\n')]
newString = ''.join(myList)

for i in range(0, len(newString), 8):
    a = binary_str2int(newString[i:i+8])
    data_reconversion.extend([a])
data_reconversion_bytes = bytes(data_reconversion)

if os.path.exists(output_file):
    os.remove(output_file)

f = open(output_file, 'wb')
f.write(data_reconversion_bytes)
f.close()

# ******************************************************************
# *************************** Compare line by line - Mismatch report

f1 = open(input_data_file_noc, "r")
f2 = open(input_data_file_python, "r")
for line1 in f1:
    f1_line_counter += 1
    for line2 in f2:
        f2_line_counter += 1
        if line1 != line2:
            mismatch_report += "Data mismatch at flit: " + str(f1_line_counter) + "\n"
            mismatch_report += "Input data flit from NoC:    " + str(line1)
            mismatch_report += "Input data flit from Python: " + str(line2)
            mismatch_report += "----------------------------------------------------------------------" + "\n"
        break

if mismatch_report == "":
    mismatch_report = "No mismatch in data!"
if f1_line_counter != f2_line_counter:
    print("Data line counter mismatch!")
f1.close()
f2.close()

if os.path.exists(output_file_mismatch_report):
    os.remove(output_file_mismatch_report)

f = open(output_file_mismatch_report, 'w')
f.write(mismatch_report)
f.close()


import numpy as np
import pandas as pd
import time
from collections import Counter
import optimizeTopicVectors as ot
from preprocess import *
from sklearn.feature_extraction.text import TfidfTransformer

def sampleFromDirichlet(alpha):
    return np.random.dirichlet(alpha)

def sampleFromCategorical(theta):
    # theta = theta / np.sum(theta)
    return np.random.multinomial(1, theta).argmax()

def word_indices(doc_sent_word_dict, sent_index):
    """
    :param doc_sent_word_dict:
    :param sent_index:
    :return:
    """
    sentence = doc_sent_word_dict[sent_index]
    for idx in sentence:
        yield idx

class ASUM_Embedding:
    def __init__(self, review_label, wordVectors, sentimentVector, numTopics, alpha, beta, gamma, binary=0.5, numSentiments=2):
        self.review_label = review_label # 각 문서의 긍정(0), 부정(1) label
        self.wordVectors = wordVectors # (V x H)
        self.numTopics = numTopics
        self.alpha = alpha
        self.beta = beta
        self.gamma = gamma
        self.numSentiments = numSentiments
        self.binary = binary
        self.sentimentVector = sentimentVector # (L x H)

    def build_dataset(self, reviews):
        """
        :param reviews: 리뷰 데이터 [ [[문서1의 문장1],[문서1의 문장2]], [[문서2의 문장1],[문서2의 문장2]], ...]]
        :return:
        word2idx - key: word, value: index
        idx2word - key: index, value: word
        doc_sent_word_dict -
        """
        corpus = [word for review in reviews for sentence in review for word in sentence]
        text = nltk.Text(corpus)
        freq = nltk.FreqDist(text)
        keywords = [tup[0] for tup in freq.most_common(self.wordVectors.shape[0])]  # 많이 등장한 단어 선택
        word2idx = {}  # key : 단어, value : index
        for index, key in enumerate(keywords):
            word2idx[key] = index

        idx2word = dict(zip(word2idx.values(), word2idx.keys()))  # key : index, value : 단어
        doc_sent_word_dict = {}  # key: 문서 index, value : [[list of sent1 단어의 index], [list of sent2 단어의 index]...]
        numSentence = {}  # key : 문서 index, value : 해당 문서의 문장수
        wordCountSentence = {}  # key : 문서 index, value : 해당 문서의 각 문장별 word count
        for index, review in enumerate(reviews):
            doc_sent_lst = []
            doc_sent_count = []
            for sent in review:
                word_indices = [word2idx[word] for word in sent if word in word2idx]
                doc_sent_lst.append(word_indices)
                counts = Counter(word_indices)
                doc_sent_count.append(counts)
            numSentence[index] = len(doc_sent_lst)
            doc_sent_word_dict[index] = doc_sent_lst
            wordCountSentence[index] = doc_sent_count

        return word2idx, idx2word, doc_sent_word_dict, wordCountSentence, numSentence

    def _initialize_(self, reviews):
        self.word2idx, self.idx2word, self.doc_sent_word_dict, self.wordCountSentence, \
        self.numSentence = self.build_dataset(reviews)
        self.numDocs = len(self.doc_sent_word_dict.keys())
        self.vocabSize = len(self.word2idx.keys())

        # Pseudocounts
        self.n_wkl = np.zeros((self.vocabSize, self.numTopics, self.numSentiments))  # 단어 i가 topic k, senti l로 할당된 수
        self.n_kl = np.zeros((self.numTopics, self.numSentiments))  # topic k, senti l로 할당된 단어 수
        self.ns_d = np.zeros((self.numDocs))  # 문서 d의 문장 수
        self.ns_dkl = np.zeros((self.numDocs, self.numTopics, self.numSentiments))  # 문서 d에서 topic k, sentiment l로 할당된 문장 수
        self.ns_dl = np.zeros((self.numDocs, self.numSentiments))  # 문서 d에서 topic k로 할당된 문장 수
        self.topics = {}
        self.sentiments = {}
        self.senti_score_dict = {}

        alphaVec = self.alpha * np.ones(self.numTopics)
        gammaVec = self.gamma * np.ones(self.numSentiments)

        for d in range(self.numDocs):
            topicDistribution = sampleFromDirichlet(alphaVec)
            sentimentDistribution = np.zeros((self.numTopics, self.numSentiments))

            for t in range(self.numTopics):
                sentimentDistribution[t, :] = sampleFromDirichlet(gammaVec)

            for m in range(self.numSentence[d]):
                t = sampleFromCategorical(topicDistribution)
                pos_score = np.dot(self.sentimentVector,
                                   self.wordVectors[self.doc_sent_word_dict[d][m]].T).sum(axis=1)
                s = np.argmax(pos_score)
                self.senti_score_dict[(d, m)] = ot.softmax(pos_score)
                self.topics[(d, m)] = t  # d 문서의 m번째 문장의 topic
                self.sentiments[(d, m)] = s  # d 문서의 m 번째 문장의 sentiment
                self.ns_d[d] += 1
                self.ns_dkl[d, t, s] += 1
                self.ns_dl[d, s] += 1
                for i, w in enumerate(word_indices(self.doc_sent_word_dict[d], m)):  # d번째 문서의 m번째 문장의 단어를 돌면서
                    self.n_wkl[w, t, s] += 1  # w번째 단어가 topic은 t, sentiment s로 할당된 개수
                    self.n_kl[t, s] += 1  # topic k, senti l로 할당된 단어 수

    def inference(self, d, m):
        t = self.topics[(d, m)]
        s = self.sentiments[(d, m)]
        self.ns_d[d] -= 1
        self.ns_dkl[d, t, s] -= 1
        self.ns_dl[d, s] -= 1
        for i, w in enumerate(word_indices(self.doc_sent_word_dict[d], m)):
            self.n_wkl[w, t, s] -= 1  # w번째 단어가 topic은 t, sentiment s로 할당된 개수
            self.n_kl[t, s] -= 1  # topic k, senti l로 할당된 단어 수

        firstFactor = np.ones((self.numTopics, self.numSentiments))

        word_count = self.wordCountSentence[d][m]
        for t in range(self.numTopics):
            for s in range(self.numSentiments):
                beta0 = self.n_kl[t][s] + self.beta
                m0 = 0
                for word in word_count.keys():
                    betaw = self.n_wkl[word, t, s] + self.beta
                    cnt = word_count[word]
                    for i in range(cnt):
                        firstFactor[t][s] *= (betaw + i) / (beta0 + m0)
                        m0 += 1

        secondFactor = (self.ns_dkl[d, :, :] + self.alpha) / \
                       (self.ns_dl[d] + self.numTopics * self.alpha)[np.newaxis, :]  # dim(K x L)

        thirdFactor = (self.ns_dl[d] + self.gamma) / \
                      (self.ns_d[d] + self.numSentiments * self.gamma)  # (L,)

        prob = np.ones((self.numTopics, self.numSentiments))
        prob *= firstFactor * secondFactor
        prob *= thirdFactor[np.newaxis, :]
        prob /= np.sum(prob)

        #원래대로 돌려놓음
        self.topics[(d, m)] = t
        self.sentiments[(d, m)] = s
        self.ns_d[d] += 1
        self.ns_dkl[d, t, s] += 1
        self.ns_dl[d, s] += 1
        for i, w in enumerate(word_indices(self.doc_sent_word_dict[d], m)):
            self.n_wkl[w, t, s] += 1  # w번째 단어가 topic은 t, sentiment s로 할당된 개수
            self.n_kl[t, s] += 1  # topic k, senti l로 할당된 단어 수

        ind = sampleFromCategorical(prob.flatten())
        t, s = np.unravel_index(ind, prob.shape)

        senti_score = self.senti_score_dict[(d, m)]
        s2 = sampleFromCategorical(senti_score.flatten())
        gamma = np.random.binomial(1, self.binary) #binary가 0이면 항상 0만 추출
        s = (1 - gamma) * s + gamma * s2
        return t, s

    def sampling(self, d, m):
        t = self.topics[(d, m)]
        s = self.sentiments[(d, m)]
        self.ns_d[d] -= 1
        self.ns_dkl[d, t, s] -= 1
        self.ns_dl[d, s] -= 1
        for i, w in enumerate(word_indices(self.doc_sent_word_dict[d], m)):
            self.n_wkl[w, t, s] -= 1  # w번째 단어가 topic은 t, sentiment s로 할당된 개수
            self.n_kl[t, s] -= 1  # topic k, senti l로 할당된 단어 수

        firstFactor = np.ones((self.numTopics, self.numSentiments))

        word_count = self.wordCountSentence[d][m]
        for t in range(self.numTopics):
            for s in range(self.numSentiments):
                beta0 = self.n_kl[t][s] + self.beta
                m0 = 0
                for word in word_count.keys():
                    betaw = self.n_wkl[word, t, s] + self.beta
                    cnt = word_count[word]
                    for i in range(cnt):
                        firstFactor[t][s] *= (betaw + i) / (beta0 + m0)
                        m0 += 1

        secondFactor = (self.ns_dkl[d, :, :] + self.alpha) / \
                       (self.ns_dl[d] + self.numTopics * self.alpha)[np.newaxis,:]  # dim(K x L)

        thirdFactor = (self.ns_dl[d] + self.gamma) / \
                      (self.ns_d[d] + self.numSentiments * self.gamma) #(L,)

        prob = np.ones((self.numTopics, self.numSentiments))
        prob *= firstFactor * secondFactor
        prob *= thirdFactor[np.newaxis,:]
        prob /= np.sum(prob)

        ind = sampleFromCategorical(prob.flatten())
        t, s = np.unravel_index(ind, prob.shape)

        senti_score = self.senti_score_dict[(d, m)]
        s2 = sampleFromCategorical(senti_score.flatten())
        gamma = np.random.binomial(1, self.binary)
        s = (1-gamma) * s + gamma * s2
        self.topics[(d, m)] = t
        self.sentiments[(d, m)] = s
        self.ns_d[d] += 1
        self.ns_dkl[d, t, s] += 1
        self.ns_dl[d, s] += 1
        for i, w in enumerate(word_indices(self.doc_sent_word_dict[d], m)):
            self.n_wkl[w, t, s] += 1  # w번째 단어가 topic은 t, sentiment s로 할당된 개수
            self.n_kl[t, s] += 1  # topic k, senti l로 할당된 단어 수

    def calculatePhi(self):
        firstFactor = (self.n_wkl + self.beta) / \
                      np.expand_dims(self.n_kl + self.n_wkl.shape[0] * self.beta, axis=0)
        firstFactor /= firstFactor.sum()
        return firstFactor

    def calculateTheta(self):
        secondFactor = (self.ns_dkl + self.alpha) / \
                       np.expand_dims(self.ns_dl + self.numTopics * self.alpha, axis=1)  # dim(K x 1)
        secondFactor /= secondFactor.sum()
        return secondFactor

    def calculatePi(self):
        thirdFactor = (self.ns_dl + self.gamma) / \
                      np.expand_dims(self.ns_d + self.numSentiments * self.gamma, axis=1)
        thirdFactor /= thirdFactor.sum()
        return thirdFactor

    def getTopicSentimentDist(self, d):
        theta = self.calculateTheta()[d]
        return theta

    def getDocSentimentDist(self, d):
        pi = self.calculatePi()[d]
        pi /= pi.sum()
        return pi

    def classify_senti(self):
        inference = np.argmax(self.calculatePi(), axis=1)  # (D x L)
        answer = np.array(self.review_label)
        return np.mean(inference == answer)

    def save(self, iteration, path):
        """
        phi, theta, pi 및 probWords 추출.
        probWords는 phi를 이용하여 각 토픽에서 해당 단어가 등장한 빈도를 상대적으로 많이 등장한 단어(TF-IDF)로 추출
        :param iteration: 몇번째에서 저장했는지
        :param path: 저장 path
        :return:
        """
        phi = self.calculatePhi()
        theta = self.calculateTheta()
        pi = self.calculatePi()
        name = path + "T{:d}-B{:.1f}-I{:d}".format(self.numTopics, self.binary, iteration)
        np.save(name + "_phi", phi)
        np.save(name + "_theta", theta)
        np.save(name + "_pi", pi)

        total_topic_num = self.numTopics * self.numSentiments
        count = np.zeros((total_topic_num, self.vocabSize))
        col_name = []
        idx = 0
        for l in range(self.numSentiments):
            for t in range(self.numTopics):
                name = 'T' + str(t) + '-' + 'S' + str(l)
                count[idx] = self.n_wkl[:, t, l]
                idx += 1
                col_name.append(name)
        # TF-IDF
        transformer = TfidfTransformer()
        tfidf = transformer.fit_transform(count)
        score_result = tfidf.toarray()

        max_vocab_size = len(self.idx2word.keys())
        word_list = [self.idx2word[idx] for idx in range(max_vocab_size)] #max vocab size
        df_result = pd.DataFrame()
        for i in range(total_topic_num):
            scores = score_result[i]
            word_score_list = []
            for word, score in zip(word_list, scores):
                word_score = tuple((word, score))
                word_score_list.append(word_score)
            word_score_list = sorted(word_score_list, key=lambda x: -x[1])
            df_result[col_name[i]] = word_score_list
        name = path + "T{:d}-B{:.1f}-I{:d}".format(self.numTopics, self.binary, iteration)
        df_result.to_csv(name + "_probWords.csv", index=False)
        print("%s model saved"%name)

    def run(self, save_path, print_iter=2, maxIters=10):
        for iteration in range(maxIters):
            start = time.time()
            if (iteration + 1) % print_iter == 0:
                print("Starting iteration %d of %d:" % (iteration + 1, maxIters))
                print(self.classify_senti())

            for d in range(self.numDocs):
                for m in range(self.numSentence[d]):
                    self.sampling(d, m)
            end = time.time()
            print("iteration %s, time %.4f" % (iteration+1,end-start))
        self.save(iteration, save_path)

    # def updateTopicVectors(self, lamda = 0.01):
    #     t = self.topicVectors # (K, H)
    #     for i in range(self.numTopics):
    #         x0 = t[i, :]
    #         x, f, d = fmin_l_bfgs_b(ot.loss, x0, fprime=ot.grad, args=(self.n_wkl, self.wordVectors, lamda), maxiter=15000)
    #         t[i, :] = x
    #     self.topicVectors = t

    # topic_similarity = ot.softmax(np.dot(self.topicVectors,
    #                                      self.wordVectors[
    #                                          self.doc_sent_word_dict[d][m]].T))  # ( K x num words in sentence)
    # senti_similarity = ot.softmax(np.dot(self.sentimentVector,
    #                                      self.wordVectors[
    #                                          self.doc_sent_word_dict[d][m]].T))  # ( L x num words in sentence)
    # vector_similarity = ot.softmax(np.dot(topic_similarity, senti_similarity.T))

    # senti_similarity = np.dot(self.sentimentVector,
    #                           self.wordVectors[self.doc_sent_word_dict[d][m]].T).sum(axis=1)  # ( L, )


from django.db import models

# Create your models here.

class Measuretype(models.Model):
    measure_type_id = models.AutoField(db_column='MeasureTypeID', primary_key=True)  # Field name made lowercase.
    measure_name = models.CharField(db_column='MeasureName', max_length=128)  # Field name made lowercase.
    modify_time = models.DateTimeField(db_column='ModifyTime', auto_now=True, null=True, blank=True, editable=False)  # Field name made lowercase. This field type is a guess.
    reduced_vulnerability_defult = models.FloatField(db_column='ReducedVulnerabilityDefault', blank=True, null=True)
    reduced_l1_rate_default = models.FloatField(db_column='ReducedL1RateDefault', blank=True, null=True)
    reduced_l2_rate_default = models.FloatField(db_column='ReducedL2RateDefault', blank=True, null=True)
    is_valid = models.BooleanField(db_column='isValid', blank=True, null=True)  # Field name made lowercase.

    class Meta:
        managed = False
        db_table = 'MeasureType'

    def __str__(self):
        return self.measure_name


def count_pairs_with_sum_and_product(arr, x, y):
    count_sum = 0
    count_product = 0
    n = len(arr)
    freq = {}

    for num in arr:
        freq[num] = freq.get(num, 0) + 1

    for num in arr:
        complement = x - num
        if complement in freq:
            count_sum += freq[complement]
            if complement == num:
                count_sum -= 1

        if y % num == 0:
            complement_product = y // num
            if complement_product in freq:
                count_product += freq[complement_product]
                if complement_product == num:
                    count_product -= 1

    return count_sum // 2 - count_product // 2

def solve_queries(test_cases):
    results = []
    for t in test_cases:
        n = t[0]
        arr = t[1]
        q = t[2]
        queries = t[3]

        result = []
        for query in queries:
            x, y = query
            result.append(count_pairs_with_sum_and_product(arr, x, y))

        results.append(result)
    return results

# Input
t = int(input())
test_cases = []
for _ in range(t):
    n = int(input())
    arr = list(map(int, input().split()))
    q = int(input())
    queries = [tuple(map(int, input().split())) for _ in range(q)]
    test_cases.append((n, arr, q, queries))

# Solve queries
results = solve_queries(test_cases)

# Output
for result in results:
    print(*result)


import tensorflow as tf

# So, the placeholder is just like the variables but the purpose of usage is different
# Vaiables are supposed to be used for trainiable quantities only i.e weights and biases whereas the placeholders are used for
# the quantities which can be fed at the runtime i.e. dataset

#Let's declare a few 1-D place holders
x = tf.placeholder(dtype= tf.float32, shape=None)
y = tf.placeholder(dtype= tf.float32, shape=None)

#Declaring N-D place holders
a = tf.placeholder(dtype=tf.float32, shape=(2,1))
b = tf.placeholder(dtype=tf.float32, shape= (2,1))

#Implementing some operations
out = tf.multiply(x,y,name='1-D_Mult')
out_mat = tf.matmul(a,b,transpose_b=True, name='N-D_Mult')

#let's run this operations
with tf.Session() as sess:
    tensorboard = tf.summary.FileWriter("..\Log", sess.graph)
    print(sess.run(out, feed_dict={x:4, y:5}))
    print(sess.run(out_mat, feed_dict={a:[[2], [4]], b:[[4], [5]]}))
    tensorboard.close()


import datetime
import logging
import urllib3
from os import makedirs
from os.path import join
from pywinauto import actionlogger
from selenium.webdriver.remote.remote_connection import LOGGER

def setup_logger() -> None:
    root_folder = r'C:\Users\robot.ad\PycharmProjects\Salyk\logs'
    makedirs(root_folder, exist_ok=True)
    actionlogger.enable()
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)

    formatter = logging.Formatter('%(asctime).19s %(levelname)s %(name)s %(threadName)s : %(message)s')

    file_handler = logging.FileHandler(
        join(root_folder, f'{datetime.date.today().strftime("%d.%m.%y")}.log'),
        encoding='utf-8'
    )
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(formatter)

    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.DEBUG)
    stream_handler.setFormatter(formatter)

    httpcore_logger = logging.getLogger('httpcore')
    httpcore_logger.setLevel(logging.INFO)

    logger.addHandler(file_handler)
    logger.addHandler(stream_handler)

    urllib3.disable_warnings()

    LOGGER.setLevel(logging.WARNING)


# 입력값 인수가 복수개일 경우...
def many(*moji):
    sum = 0
    for i in moji:
        sum = sum+i
    return sum # 0, sum 바로 밑에서 리턴
v = many('a','b') # TypeError: for +: 'int' and 'str'
print(v)

def many(*muji):
    sum = 0
    for i in muji:
        sum = sum+i
    return sum # 55, for 전체를 리턴
v = many(0,1,2,3,4,5,6,7,8,9,10)
print(v)

# 인수 가지고 if 만들어 보기
def ifthen(a):
    if a == 1:
        val = 'One'
    elif a == 2:
        val = 'Two'
    elif a == 3:
        val = 'Three'
    return val
print(ifthen(1),ifthen(2),ifthen(3)) # One Two Three

# 인수 하나는 텍스트 하나는 숫자로 if 만들기
def textnum(a,*b):
    if a == 'sum':
        v = 0
        for i in b:
            v = v+i
    elif a == 'mul':
        v = 1
        for i in b:
            v = v*i
    return v
print(textnum('sum',1,2,3,4),textnum('mul',1,2,3,4)) # 10 24

# 리턴을 콤마로 여러개 식을 넣어버릴 경우, 리턴 수식엔 a,b,c 모두 없어도 되지만 활용문 (summul(n1,n2,n3)에선 3자리수 맞춰야 함
def summul(a,b,c):
    return a+b+c, a*b*c, c-a
print(summul(1,2,4)) # 7, 8, 3

# 7,8,3 을 각각 출력값으로 받으려면 -
t,g,f = summul(1,2,4) # 변수를 콤마로 자리 수 3개 맞춰서 각각 출력하면 된다
print(t) # 7
print(g) # 8
print(t-g)

# * return을 두줄로 써도 한 줄의 리턴만 먹는다, return문을 만나는 순간 결과값을 돌려주고 함수를 빠져나온다. *
def summul(a,b,c):
    return a+b+c
    return a*b
print(summul(1,2,3)) # 출력값은 6만 나온다

# 리턴으로 함수 끝내기 (빠져나오기)
def exit(nick):
    if nick == 'me':
        return
print(exit('me')) # 인수로 me가 들어오면 함수를 종료한다


# Complete the latestStudent function below.
def latestStudent(attendanceData):
    if(len(attendanceData)):
        dict = {}
        for row in attendanceData:
            key = row[0]+":"+row[2]
            latness = int(row[3])-int(row[2])
            if(latness<0):
                latness = 0
            if key in dict:
                n = len(dict[key].keys())-1
                dict[key]['sum'] += latness
                dict[key][row[1]] = latness
                dict[key]['avg'] = dict[key]['sum']/n
            else:
                dict[key] = {}
                dict[key]['sum'] = latness
                dict[key][row[1]] = latness
                dict[key]['avg'] = latness
        students = {}
        for key, value in dict.items():
            avg = dict[key]['avg']
            del dict[key]['avg']
            del dict[key]['sum']
            for student in dict[key]:
                if student not in students:
                    if dict[key][student]>avg:
                        students[student] = dict[key][student]-avg
                    else:
                        students[student] = 0
                else:
                    if dict[key][student]>avg:
                        students[student] += (dict[key][student]-avg)
        max_late = -1
        max_value = max(students.itervalues())
        max_keys = [k for k in students if students[k] == max_value]
        return min(max_keys)
    else:
        return ""


#!/usr/bin/env python3

from textBox import *

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class fifthPageWidget(QWidget):
	def __init__(self):
		QWidget.__init__(self)

		"""*****************************************************************"""
		"""CREATE ALL LABELS, LAYOUTS, BUTTONS AND TEXT BOXES FOR FIFTH PAGE"""
		"""*****************************************************************"""
		self.boldFont = QFont()
		self.boldFont.setBold(True)

		self.customFont = QFont("Serif", 12, QFont.Bold)

		self.label = QLabel("Input the words you want to use for the story!")
		self.label.setFont(self.customFont)
		self.fifthPageLayout = QVBoxLayout(self)

		self.generateMadLib = QPushButton("Generate Mad Lib!")
		self.generateMadLib.setFont(self.boldFont)
		self.generateMadLib.setFixedSize(150, 50)

		self.textbox1 = textBoxCreator("Mans Name")

		self.textbox2 = textBoxCreator("Occupation")

		self.textbox3 = textBoxCreator("Noun")

		self.textbox4 = textBoxCreator("Noun")

		self.textbox5 = textBoxCreator("Noun")

		self.textbox6 = textBoxCreator("Shape")

		self.textbox7 = textBoxCreator("Mans Name")

		self.textbox8 = textBoxCreator("Verb")

		self.textbox9 = textBoxCreator("Womans Name")

		self.textbox10 = textBoxCreator("Body Part")

		self.textbox11 = textBoxCreator("Verb")

		self.textbox12 = textBoxCreator("Noun")

		self.textbox13 = textBoxCreator("Noun")

		self.textbox14 = textBoxCreator("Restaurant Name")

		self.textbox15 = textBoxCreator("Historic Monument")

		self.textbox16 = textBoxCreator("Verb")

		self.textbox17 = textBoxCreator("Noun")

		self.textbox18 = textBoxCreator("Noun")

		self.textbox19 = textBoxCreator("Noun")

		self.textbox20 = textBoxCreator("Verb")

		self.textbox21 = textBoxCreator("Noun")

		self.textbox22 = textBoxCreator("Adjective")

		self.textbox23 = textBoxCreator("Adjective")

		self.textbox24 = textBoxCreator("Emotion")

		self.textbox25 = textBoxCreator("Verb")

		self.textbox26 = textBoxCreator("Noun")

		self.textbox27 = textBoxCreator("Noun")

		self.textbox28 = textBoxCreator("Verb")

		self.textboxList = [self.textbox1, self.textbox2, self.textbox3, self.textbox4, self.textbox5, self.textbox6, self.textbox7, self.textbox8, self.textbox9, self.textbox10, self.textbox11, self.textbox12, self.textbox13, self.textbox14, self.textbox15, self.textbox16, self.textbox17, self.textbox18, self.textbox19, self.textbox20, self.textbox21, self.textbox22, self.textbox23, self.textbox24, self.textbox25, self.textbox26, self.textbox27, self.textbox28]
		"""*************************"""
		"""ADD WIDGETS TO FIFTH PAGE"""
		"""*************************"""

		self.fifthPageLayout.addWidget(self.label, alignment = Qt.AlignCenter)

		for textbox in self.textboxList:
			self.fifthPageLayout.addWidget(textbox)

		self.fifthPageLayout.addWidget(self.generateMadLib, alignment = Qt.AlignCenter)

		"""*******************"""
		"""GETTERS AND SETTERS"""
		"""*******************"""

	def getTextBoxData(self):
		textList = []

		for textbox in self.textboxList:
			textList.append(textbox.text())

		return(textList)

	def setTextBoxData(self):

		for textbox in self.textboxList:
			textbox.clear()

	def setOpenData(self, textList):
		i = 0
		for textbox in self.textboxList:
			if(textList[i] != ""):
				textbox.setText(textList[i])
				textbox.textMod()
			i = i+1


import logging
import sys
import os

DEFAULT_LOGGING_LEVEL = os.environ.get('LOGGING_LEVEL') or logging.INFO

def initialize_simple_logger():
    logging_level = DEFAULT_LOGGING_LEVEL
    logger = logging.getLogger('Integrations')
    logger.setLevel(logging_level)
    handler = logging.StreamHandler(stream=sys.stdout)
    formatter = logging.Formatter('[LEVEL:%(levelname)s] %(asctime)s %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger

logger = initialize_simple_logger()


#!/usr/bin/python3
"""Defines a function pascal_triangle(n)"""

def pascal_triangle(n):
    """This function returns the list of lists of integers representing"""

    if n <= 0:
        return []
    if n == 1:
        return [[1]]

    le = [[1]]
    for row in range(n-1):
        le.append([i+j for i, j in
                   zip([0]+le[-1], le[-1] + [0])])
    return le


#!/usr/bin/python3

if __name__ == "__main__":
    from calculator_1 import add, sub, mul, div
    import sys as s

    operators = {"+": add, "-": sub, "*": mul, "/": div}

    if len(s.argv) - 1 != 3:
        print("Usage: ./100-my_calculator.py <a> <operator> <b>")
        s.exit(1)

    if s.argv[2] not in list(operators.keys()):
        print("Unknown operator. Available operators: +, -, * and /")
        s.exit(1)

    a = int(s.argv[1])
    b = int(s.argv[3])
    print("{} {} {} = {}".format(a, s.argv[2], b, operators[s.argv[2]](a, b)))


# python 3
# coding=utf-8

##############################################
#
# define point placement as type
# point generation
# points serialization
# placement estimation
# find best placement
# visualization
##############################################

import sys
import matplotlib.pyplot as plt
import math
import numpy as np
import time

from binary_tree import BinaryTree
import binary_tree_algo as tree_algo

from generator import generate_points

import geometry
from geometry import Point

import estimator

from representation import draw_binary_tree

import binary_tree_creation as btc
from tree_colorization import BinaryTreePainter

def make_point_numbers(points):
	return {p:i for i,p in enumerate(points)}

def show_tree(tree : BinaryTree, point_numbers):
	painter = BinaryTreePainter()
	color_map = painter.make_point_colors(tree)
	draw_binary_tree(tree, point_numbers, color_map)

def create_point_placement_by_bsp(points):
	tree_builder = btc.BSPTreeBuilder()
	tree = tree_builder.make_tree(points)
	tree_algo.minimize_distance_between_subtree_leafs(tree, geometry.quad_euclidean_distance)
	tree_algo.turn_tree_to_order_left_and_right_leafs_by_x(tree)
	oredered_points = list(tree_algo.iterate_leaf_from_left_to_right(tree))
	point_numbers = make_point_numbers(oredered_points)
	#print ("BSP tree:\n", tree)
	#show_tree(tree, point_numbers)

def create_point_placement_by_clustering(points):
	distance_between_clusters = btc.DistanceBetweenClusterCenters(geometry.quad_euclidean_distance)
	clusterizer = btc.HierarchicalClusterBuilder(distance_between_clusters)
	tree = clusterizer.make_tree(points)
	tree_algo.minimize_distance_between_subtree_leafs(tree, geometry.quad_euclidean_distance)
	tree_algo.turn_tree_to_order_left_and_right_leafs_by_x(tree)
	oredered_points = list(tree_algo.iterate_leaf_from_left_to_right(tree))
	point_numbers = make_point_numbers(oredered_points)
	#print("Cluster tree:\n", tree)
	#show_tree(tree, point_numbers)

def binary_tree_test():
	# TODO: check empty point collection and one point collection
	point_count = 1000
	print ('Point count = ', point_count)
	points = generate_points(point_count)

	# find best point placement
	errors_counter = estimator.DiscontinuityErrorCounter(geometry.euclidean_distance)
	#min_error_count = estimator.find_few_errors_point_permutation(points, errors_counter)
	#print ("Best posible score:", min_error_count)

	plt.subplot(211)
	print("Starting...")
	start = time.time()
	cluster_ordered_points = create_point_placement_by_clustering(points)
	print("Finished. Spended time = ", time.time() - start)

	plt.subplot(212)
	print("Starting...")
	start = time.time()
	bsp_ordered_points = create_point_placement_by_bsp(points)
	print("Finished. Spended time = ", time.time() - start)

	# estimate point placement
	#print ("Cluster score: ", errors_counter(cluster_ordered_points))
	#print ("Bsp score: ", errors_counter(bsp_ordered_points))

	#plt.show()

def main():
	binary_tree_test()

if __name__ == "__main__":
	main()


from typing import List, Optional
from queue import PriorityQueue
from heapq import heappush, heappop

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def mergeKLists(lists: List[Optional[ListNode]]) -> Optional[ListNode]:
    """
    LC 23: You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
    Merge all the linked-lists into one sorted linked-list and return it.

    Note: Compare every k nodes (head of every linked list) and get the node with the smallest value, time is O(KN),
    since almost every selection of node in final linked costs O(k) (k-1 times comparison).

    -->   Optimize the comparison process by priority queue,
          Time: O(Nlog(K)). each comparison (insertion/deletion): O(logK); get the min: O(1)
          Space: O(N) create new lined list; O(k) create priority queue
    """
    res = None  # res: new sorted linklist
    cur = None  # pointer the last element in new sorted linklist
    h = []      # heap: (val, lists index)
    for i, l in enumerate(lists):
        if not l:
            continue
        ###################################
        # don't make heappush(h, (l.val, l)) because heap may compare second element `l` in a tuple
        # if l.val is not unique. so we put `l.val` and index `i` in the tuple.
        heappush(h, (l.val, i))
        lists[i] = lists[i].next
    while h:
        v, i = heappop(h)
        if not res:
            cur = res = ListNode(v)
        else:
            cur.next = ListNode(v)
            cur = cur.next
        if lists[i]:
            heappush(h, (lists[i].val, i))
            lists[i] = lists[i].next
    return res

if __name__ == "__main__":
    mergeKLists([ListNode(5), ListNode(3), ListNode(9), ListNode(2),  ListNode(4), ListNode(8)])


import json
import pytest
import requests
import globalvariables as globalvar
import WeGuardlogger as WeGuard
import test_GETutils as utils
import cases_validations as config

user = "enterprise/rest/users/user"
@pytest.mark.parametrize('url', [""])
@pytest.mark.skipif(config.run_tc_001__get_users == 0, reason= "test is skipped")
@pytest.mark.positivetest
@pytest.mark.devicespage
@pytest.mark.sanitytest
@pytest.mark.regressiontest
@pytest.mark.usualtest
@pytest.mark.run(order=10011)
def test_tc_006_get_users(url):
    if globalvar.bearerToken == '':
        pytest.skip("Empty Bearer token Skipping test")
    try :
        apiUrl = globalvar.BaseURL + user
        print("\n\n--------------------------- Device count ---------------------------")
        header = 'Bearer' + ' ' + globalvar.bearerToken
        res = requests.get(url=apiUrl, headers={'Authorization': header})
        curl_str1 = utils.getCurlEquivalent(res)
        print(curl_str1)
        WeGuard.logger.debug("\n" + " Response headers: " + str(res.headers) + " apiUrl: " + apiUrl + " Response code: " + str(res.status_code)  + "\n" + " Response: " + str(res.content))
        assert res.status_code == 200
    except BaseException as e:
        WeGuard.logger.error("Exception : " + str(e))
        WeGuard.logger.error("--------------------------- TC 006 no users ---------------------------\n\n")
        assert False


import sys
import datetime
import Adafruit_DHT

sensorNumber = 22
port = 4

def get(data=None):
    humidity, temperature = Adafruit_DHT.read_retry(sensorNumber, port)
    date = str(datetime.datetime.now())
    return [{
        "type": 'temperature',
        "value": temperature,
        "date": date
    }, {
        "type": 'humidity',
        "value": humidity,
        "date": date
    }]


import requests

# https://stackoverflow.com/questions/12601316/how-to-make-python-requests-work-via-socks-proxy
# pip install pysocks

proxies = {
    'http': 'socks5h://72.210.208.101:4145',
    'https': 'socks5h://72.210.208.101:4145',
}

session = requests.Session()
session.proxies.update(proxies)

res = session.get('http://ident.me/', timeout=300)

print(res.text)


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from cli_args_parser import cli_args
from func import *

current_balance = 0

def trade(coin_to_buy, coin_to_sell):
    global current_balance
    symbol = coin_to_buy + coin_to_sell

    while True:
        no_open_order = len(get_open_orders(symbol)) == 0

        if no_open_order:
            # After hours of tests the best limitation in second between orders creations
            time.sleep(2)

            coin_to_sell_balance = get_free_balance_of(coin_to_sell)

            # Sometimes Binance API doesn't provide a correct balance after completed order
            # When your order completed Binance shows old balance
            # In that case wait additional second before continuing the trading process
            if current_balance > coin_to_sell_balance:
                log('Old balance returned from API, waiting a second')
                time.sleep(1)
                return trade(coin_to_buy, coin_to_sell)

            current_balance = coin_to_sell_balance

            # In case if you sell USDT to buy another coin, transaction price should be more than $10
            if coin_to_sell == 'USDT' and coin_to_sell_balance <= 10:
                log('Not enough resources: ' + str(coin_to_sell_balance))

            log('Current balance: ' + str(coin_to_sell_balance) + coin_to_sell)
            money_to_spend = coin_to_sell_balance / 2

            create_buy_order(coin_to_buy, coin_to_sell, symbol, money_to_spend)

def main():
    coin_to_buy = cli_args.buy.upper()
    coin_to_sell = cli_args.sell.upper()
    trade(coin_to_buy, coin_to_sell)
    return 0

if __name__ == "__main__":
    main()


import os
import os.path as osp
from uuid import uuid4
from datetime import datetime

from glamconv.cli.commands import batch_ead2_to_ape

from cubicweb import Binary

from cubicweb_francearchives.dataimport.ead import compute_ape_relpath

add_cube("oaipmh")
add_attribute("FindingAid", "ape_ead_file")

def generate_ape_ead(cnx):
    appfiles_dir = cnx.vreg.config["appfiles-dir"]
    batch_arguments = []
    fa2apepath = {}
    for fa_eid, fspath, service_code in cnx.execute(
        "Any X, FSPATH(D), SC WHERE X findingaid_support F, F data D, "
        'F data_format "application/xml", X service S, S code SC'
    ):
        input_path = fspath.getvalue()
        output_path = osp.join(
            appfiles_dir, compute_ape_relpath(input_path, {"code": service_code})
        )
        fa2apepath[fa_eid] = output_path
        batch_arguments.append((input_path, output_path))
    batch_ead2_to_ape(batch_arguments)
    # now generate ape-XML for PDF, dc_based and OAI based finding aids
    other_fas = cnx.execute(
        """
      (Any X, XID WHERE X eadid XID, NOT EXISTS(X findingaid_support F))
    UNION
      (Any X, XID WHERE X eadid XID, X findingaid_support F, NOT F data_format "application/xml")
    """
    )
    for fa in other_fas.entities():
        service_code = fa.service[0].code
        output_path = osp.join(appfiles_dir, compute_ape_relpath(fa.eadid, {"code": service_code}))
        xml_dumper = fa.cw_adapt_to("OAI_EAD")
        if xml_dumper is not None:
            ape_xml = xml_dumper.dump()
            output_dir = osp.dirname(output_path)
            if not osp.isdir(output_dir):
                os.makedirs(output_dir)
            with open(output_path, "w") as outf:
                outf.write(ape_xml)
            fa2apepath[fa.eid] = output_path

    cnx.transaction_data["fs_importing"] = True
    # File must exist on disk, even if fs_importing is True because
    # ``source.storages.BFSS.entity_added()`` will try to read file from
    # disk to build the Binary object.
    with cnx.deny_all_hooks_but():
        _now = datetime.now()
        admin = cnx.find("CWUser", login="admin").one()
        for fa_eid, output_path in list(fa2apepath.items()):
            cnx.drop_entity_cache()
            if osp.isfile(output_path):
                uuid = str(uuid4().hex)
                ape_file = cnx.create_entity(
                    "File",
                    cwuri=uuid,
                    modification_date=_now,
                    creation_date=_now,
                    created_by=admin,
                    owned_by=admin,
                    data=Binary(output_path),
                    uuid=uuid,
                    data_format="application/xml",
                    data_name=osp.basename(output_path).decode("utf-8"),
                    reverse_ape_ead_file=fa_eid,
                )
    cnx.commit()

if confirm("generate ape ead files ?"):
    generate_ape_ead(cnx)


import os
from tkinter import *
from PIL import ImageTk, Image

import wingedsheep
from wingedsheep.carcassonne.carcassonne_game_state import CarcassonneGameState
from wingedsheep.carcassonne.objects.meeple_position import MeeplePosition
from wingedsheep.carcassonne.objects.meeple_type import MeepleType
from wingedsheep.carcassonne.objects.side import Side
from wingedsheep.carcassonne.objects.tile import Tile

class CarcassonneVisualiser:

    meeple_icons = {
        MeepleType.NORMAL: ["blue_meeple.png", "red_meeple.png", "black_meeple.png", "yellow_meeple.png", "green_meeple.png", "pink_meeple.png"],
        MeepleType.ABBOT: ["blue_abbot.png", "red_abbot.png", "black_abbot.png", "yellow_abbot.png", "green_abbot.png", "pink_abbot.png"]
    }
    tile_size = 60
    meeple_size = 15
    big_meeple_size = 25

    meeple_position_offsets = {
        Side.TOP: (tile_size / 2, (meeple_size / 2) + 3),
        Side.RIGHT: (tile_size - (meeple_size / 2) - 3, tile_size / 2),
        Side.BOTTOM: (tile_size / 2, tile_size - (meeple_size / 2) - 3),
        Side.LEFT: ((meeple_size / 2) + 3, tile_size / 2),
        Side.CENTER: (tile_size / 2, tile_size / 2),
        Side.TOP_LEFT: (tile_size / 4, (meeple_size / 2) + 3),
        Side.TOP_RIGHT: ((tile_size / 4) * 3, (meeple_size / 2) + 3),
        Side.BOTTOM_LEFT: (tile_size / 4, tile_size - (meeple_size / 2) - 3),
        Side.BOTTOM_RIGHT: ((tile_size / 4) * 3, tile_size - (meeple_size / 2) - 3)
    }

    big_meeple_position_offsets = {
        Side.TOP: (tile_size / 2, (big_meeple_size / 2) + 3),
        Side.RIGHT: (tile_size - (big_meeple_size / 2) - 3, tile_size / 2),
        Side.BOTTOM: (tile_size / 2, tile_size - (big_meeple_size / 2) - 3),
        Side.LEFT: ((big_meeple_size / 2) + 3, tile_size / 2),
        Side.CENTER: (tile_size / 2, tile_size / 2),
        Side.TOP_LEFT: (tile_size / 4, (big_meeple_size / 2) + 3),
        Side.TOP_RIGHT: ((tile_size / 4) * 3, (big_meeple_size / 2) + 3),
        Side.BOTTOM_LEFT: (tile_size / 4, tile_size - (big_meeple_size / 2) - 3),
        Side.BOTTOM_RIGHT: ((tile_size / 4) * 3, tile_size - (big_meeple_size / 2) - 3)
    }

    def __init__(self):
        root = Tk()
        self.canvas = Canvas(root, width=2300, height=1300, bg='white')
        self.canvas.pack(fill='both', expand=True)
        self.images_path = os.path.join(wingedsheep.__path__[0], 'carcassonne', 'resources', 'images')
        self.meeple_image_refs = {}
        self.tile_image_refs = {}

    def draw_game_state(self, game_state: CarcassonneGameState):
        self.canvas.delete('all')
        for row_index, row in enumerate(game_state.board):
            for column_index, tile in enumerate(row):
                tile: Tile
                if tile is not None:
                    self.__draw_tile(column_index, row_index, tile)

        for player, placed_meeples in enumerate(game_state.placed_meeples):
            meeple_position: MeeplePosition
            for meeple_position in placed_meeples:
                self.__draw_meeple(player, meeple_position)

        self.canvas.update()

    def __draw_meeple(self, player_index: int, meeple_position: MeeplePosition):
        image = self.__get_meeple_image(player=player_index, meeple_type=meeple_position.meeple_type)

        if meeple_position.meeple_type == MeepleType.BIG:
            x = meeple_position.coordinate_with_side.coordinate.column * self.tile_size + self.big_meeple_position_offsets[meeple_position.coordinate_with_side.side][0]
            y = meeple_position.coordinate_with_side.coordinate.row * self.tile_size + self.big_meeple_position_offsets[meeple_position.coordinate_with_side.side][1]
        else:
            x = meeple_position.coordinate_with_side.coordinate.column * self.tile_size + self.meeple_position_offsets[meeple_position.coordinate_with_side.side][0]
            y = meeple_position.coordinate_with_side.coordinate.row * self.tile_size + self.meeple_position_offsets[meeple_position.coordinate_with_side.side][1]

        self.canvas.create_image(
            x,
            y,
            anchor=CENTER,
            image=image
        )

    def __flattenAlpha(self, img):
        alpha = img.split()[-1]  # Pull off the alpha layer
        ab = alpha.tobytes()  # Original 8-bit alpha

        checked = []  # Create a new array to store the cleaned up alpha layer bytes

        # Walk through all pixels and set them either to 0 for transparent or 255 for opaque fancy pants
        transparent = 50  # change to suit your tolerance for what is and is not transparent

        p = 0
        for pixel in range(0, len(ab)):
            if ab[pixel] < transparent:
                checked.append(0)  # Transparent
            else:
                checked.append(255)  # Opaque
            p += 1

        mask = Image.frombytes('L', img.size, bytes(checked))

        img.putalpha(mask)

        return img

    def __draw_tile(self, column_index, row_index, tile):
        image_filename = tile.image
        reference = f"{image_filename}_{str(tile.turns)}"
        if reference in self.tile_image_refs:
            photo_image = self.tile_image_refs[reference]
        else:
            abs_file_path = os.path.join(self.images_path, image_filename)
            image = Image.open(abs_file_path).resize((self.tile_size, self.tile_size), Image.ANTIALIAS).rotate(
                -90 * tile.turns)
            image = self.__flattenAlpha(image)
            height = image.height
            width = image.width
            crop_width = max(0, width - height) / 2
            crop_height = max(0, height - width) / 2
            image.crop((crop_width, crop_height, crop_width, crop_height))
            photo_image = ImageTk.PhotoImage(image)
        self.tile_image_refs[f"{image_filename}_{str(tile.turns)}"] = photo_image
        self.canvas.create_image(column_index * self.tile_size, row_index * self.tile_size, anchor=NW, image=photo_image)

    def __get_meeple_image(self, player: int, meeple_type: MeepleType):
        reference = f"{str(player)}_{str(meeple_type)}"

        if reference in self.meeple_image_refs:
            return self.meeple_image_refs[reference]

        icon_type = MeepleType.NORMAL
        if meeple_type == MeepleType.ABBOT:
            icon_type = meeple_type

        image_filename = self.meeple_icons[icon_type][player]
        abs_file_path = os.path.join(self.images_path, image_filename)

        photo_image = None
        if meeple_type == MeepleType.NORMAL or meeple_type == MeepleType.ABBOT:
            image = Image.open(abs_file_path).resize((self.meeple_size, self.meeple_size), Image.ANTIALIAS)
            image = self.__flattenAlpha(image)
            photo_image = ImageTk.PhotoImage(image)
        elif meeple_type == MeepleType.BIG:
            image = Image.open(abs_file_path).resize((self.big_meeple_size, self.big_meeple_size), Image.ANTIALIAS)
            image = self.__flattenAlpha(image)
            photo_image = ImageTk.PhotoImage(image)
        elif meeple_type == MeepleType.FARMER:
            image = Image.open(abs_file_path).resize((self.meeple_size, self.meeple_size), Image.ANTIALIAS).rotate(-90)
            image = self.__flattenAlpha(image)
            photo_image = ImageTk.PhotoImage(image)
        elif meeple_type == MeepleType.BIG_FARMER:
            image = Image.open(abs_file_path).resize((self.big_meeple_size, self.big_meeple_size), Image.ANTIALIAS).rotate(-90)
            image = self.__flattenAlpha(image)
            photo_image = ImageTk.PhotoImage(image)
        else:
            print(f"ERROR LOADING IMAGE {abs_file_path}!")
            exit(1)

        self.meeple_image_refs[f"{str(player)}_{str(meeple_type)}"] = photo_image
        return photo_image


import cv2
from deepface import DeepFace
import numpy as np
import time
import requests
import json

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
video = cv2.VideoCapture(0)

start_time = time.time()
express_server_url = 'http://127.0.0.1:3000'  # Replace with your Express.js server endpoint

while video.isOpened():
    _, frame = video.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    face = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)

    for x, y, w, h in face:
        img = cv2.rectangle(frame, (x, y), (x+w, y+w), (0, 0, 255), 1)
        try:
            analyze = DeepFace.analyze(frame, actions=['emotion'])
            current_time = time.time()
            if current_time - start_time >= 5:
                detected_emotion = analyze[0]['dominant_emotion']
                print(detected_emotion)

                payload = {'emotion': detected_emotion}
                headers = {'Content-Type': 'application/json'}
                response = requests.post(express_server_url, data=json.dumps(payload), headers=headers)
                print("Emotion sent to server:", response.text)

                start_time = current_time  # Reset the start time
        except Exception as e:
            print(f"Error: {e}")

    cv2.imshow('Frame', frame)
    key = cv2.waitKey(1)
    if key == ord('q'):
        break

video.release()
cv2.destroyAllWindows()


from app.models import db, Question, Post, Comment, Vote

def populate():
    question_map = {
        'is-usc-worth-it': {
            'title': 'Is USC worth $50,000?',
            'url_string': 'is-usc-worth-it',
        },
        'is-usc-healthy': {
            'title': 'Is USC Healthy?',
            'url_string': 'is-usc-healthy',
        }
    }

    answers_map = {
        'is-usc-worth-it': {
            "yes": {
                'title': 'USC is actually worth it.',
                'contents': 'Yes, blah blah blah. Yes blah, blah yes. Mostly blah and definitely blah.',
                'author_first': 'Calvin',
                'author_last': 'LeGassick',
            },
            'maybe': {
                'title': 'It may take time to know if USC is actually worth it.',
                'contents': 'Maybe, blah blah blah. Maybe blah, blah maybe. Mostly blah and definitely blah.',
                'author_first': 'Marc',
                'author_last': 'Pakravan',
            },
            'no': {
                'title': 'I promise you, USC is most definitely not worth it.',
                'contents': 'No, blah blah blah. No blah, blah no. Mostly blah and definitely blah.',
                'author_first': 'Nathan',
                'author_last': 'Wallace',
            }
        },
        'is-usc-healthy': {
            "yes": {
                'title': 'USC is actually healhy.',
                'contents': 'Yes, blah blah blah. Yes blah, blah yes. Mostly blah and definitely blah.',
                'author_first': 'Rachel',
                'author_last': 'Perry',
            },
            'maybe': {
                'title': 'It may take time to know if USC is actually healthy.',
                'contents': 'Maybe, blah blah blah. Maybe blah, blah maybe. Mostly blah and definitely blah.',
                'author_first': 'Josh',
                'author_last': 'Lurie',
            },
            'no': {
                'title': 'I promise you, USC is most definitely not healthy it.',
                'contents': 'No, blah blah blah. No blah, blah no. Mostly blah and definitely blah.',
                'author_first': 'Joseph',
                'author_last': 'Chen',
            }
        }
    }

    for question in question_map.keys():
        q_map = question_map[question]
        q_map["image_url"] = "http://lorempixel.com/400/400/"
        q = Question(**q_map)
        db.session.add(q)
        for answer in answers_map[question]:
            for option in ["yes", "maybe", "no"]:
                a_map = answers_map[question][option]
                a_map["answer"] = option
                a_map["question_id"] = q.id
                a = Post(**a_map)
                db.session.add(a)

        q.is_live = True
        db.session.add(q)
        db.session.commit()


# -*- coding: utf-8 -*-
"""
Created on Thu Jul 16 20:59:48 2020

@author: 86178
"""

class Settings():
    '''储存《外星人入侵》的所有设置的类'''

    def __init__(self):

        # 屏幕设置
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color = (230,230,230)

        # 飞船设置
        self.ship_limit = 3

        # 子弹设置
        self.bullet_width = 3
        self.bullet_height = 15
        self.bullet_color = (60, 60, 60)
        self.bullets_allowed = 10

        # 外星人设置
        self.fleet_drop_speed = 10
        # 击败一个外星人获得分数的提高速度
        self.score_scale = 1.5

        # 以什么样的速度加快游戏节奏
        self.speedup_scale = 1.3

        # 最高得分
        self.high_score = 0

        self.initialize_dynamic_settings()

    def initialize_dynamic_settings(self):
        '''初始化随游戏进行而变化的设置'''
        self.ship_speed_factor = 2
        self.bullet_speed_factor = 1
        self.alien_speed_factor = 1

        # 记分
        self.alien_points = 50

        # fleet_direction为1表示向右移，为-1表示左移
        self.fleet_direction = 1
        '''随游戏的进行，我们将提高这些速度，而每当玩家开始新游戏时，都将重置这些速度。'''

    def increase_speed(self):
        '''提高速度设置 和 外星人点数'''
        self.ship_speed_factor *= self.speedup_scale
        self.bullet_speed_factor *= self.speedup_scale
        self.alien_speed_factor *= self.speedup_scale

        self.alien_points = int(self.score_scale * self.alien_points)

'''
每次给游戏添加新功能时，通常也将引入一些新设置。下面来编写一个名为settings的模块，
其中包含一个名为Settings的类，用于将所有设置存储在一个地方，以免在代码中到处添加设置。
这样，我们就能传递一个设置对象，而不是众多不同的设置。另外，这让函数调用更简单，且在
项目增大时修改游戏的外观更容易：要修改游戏，只需修改settings.py中的一些值，而无需查找
散布在文件中的不同设置。
'''


from Utils import *
import os.path as p
import os
import pandas
import numpy as np
from transformers import PegasusTokenizer, BartTokenizer

base = '/home/ubuntu/CNNDM_v2/'
traininingSet_location = base+'train.csv'
test_set_location = base+'test.csv'
validation_set_location = base + 'validation.csv'

traininingSet = pandas.read_csv(traininingSet_location)
testingSet = pandas.read_csv(test_set_location)
validationSet = pandas.read_csv(validation_set_location)

model_type = 'BART'
prertained_model_name = 'facebook/bart-large'
if model_type == 'PEGASUS':
    tokenizer = PegasusTokenizer.from_pretrained(prertained_model_name, do_lower_case=False)
elif model_type == 'BART':
    tokenizer = BartTokenizer.from_pretrained(prertained_model_name, do_lower_case=False)

def Tokenize_Input(text, max_length = 1024):
    #print(len(text))
    #first_encoded = tokenizer.encode(first_sentence,add_special_tokens=False)
    text_encoded = tokenizer.encode(text, truncation=True, padding=True, add_special_tokens=True, max_length= max_length)
    return text_encoded

def get_attention_masks(X,sourceOrSummary):
    attention_masks = []

    # For each sentence...
    for sent in X:
        # Create the attention mask.
        #   - If a token ID is 0, then it's padding, set the mask to 0.
        #   - If a token ID is > 0, then it's a real token, set the mask to 1.
        att_mask = [int(token_id != tokenizer.pad_token_id) for token_id in sent]
        #if sourceOrSummary =='summary':
           # att_mask.insert(0, 0)#(index,value)
        # Store the attention mask for this sentence.
        att_mask = np.asarray(att_mask)
        attention_masks.append(att_mask)
    attention_masks = np.asarray(attention_masks)
    return attention_masks

def pad_seq(seq,max_len,pad_idx):
    if len(seq)>max_len:
        end_idx = seq[-1]
        seq = seq[0:max_len-1]
        seq.append(end_idx)
    while len(seq) != max_len:
        seq.append(pad_idx)
    return seq

def prepare_all_data(output_location, source_max_length, summary_max_length):
    if p.exists(output_location) == False:
        os.mkdir(output_location)

    X_train_source = traininingSet.apply(lambda x: Tokenize_Input(x['source'], max_length = source_max_length), axis=1)
    X_train_summary = traininingSet.apply(lambda x: Tokenize_Input(x['summary'], max_length = summary_max_length), axis=1)

    X_test_source = testingSet.apply(lambda x: Tokenize_Input(x['source'], max_length = source_max_length), axis=1)
    X_test_summary = testingSet.apply(lambda x: Tokenize_Input(x['summary'], max_length = summary_max_length), axis=1)

    X_valid_source = validationSet.apply(lambda x: Tokenize_Input(x['source'], max_length = source_max_length), axis=1)
    X_valid_summary = validationSet.apply(lambda x: Tokenize_Input(x['summary'], max_length = summary_max_length), axis=1)

    X_train_source = pandas.Series(X_train_source)
    X_train_summary = pandas.Series(X_train_summary)

    X_test_source = pandas.Series(X_test_source)
    X_test_summary = pandas.Series(X_test_summary)

    X_valid_source = pandas.Series(X_valid_source)
    X_valid_summary = pandas.Series(X_valid_summary)

    max_len_source = 0
    max_len_summary = 0
    for x in X_train_source:
        if len(x) > max_len_source:
            max_len_source = len(x)
    for x in X_train_summary:
        if len(x) > max_len_summary:
            max_len_summary = len(x)

    print('max', max_len_source, max_len_summary)

    X_train_source = X_train_source.apply(pad_seq, max_len=max_len_source, pad_idx=tokenizer.pad_token_id)
    X_train_summary = X_train_summary.apply(pad_seq, max_len=max_len_summary, pad_idx=tokenizer.pad_token_id)

    X_test_source = X_test_source.apply(pad_seq, max_len=max_len_source, pad_idx=tokenizer.pad_token_id)
    X_test_summary = X_test_summary.apply(pad_seq, max_len=max_len_summary, pad_idx=tokenizer.pad_token_id)

    X_valid_source = X_valid_source.apply(pad_seq, max_len=max_len_source, pad_idx=tokenizer.pad_token_id)
    X_valid_summary = X_valid_summary.apply(pad_seq, max_len=max_len_summary, pad_idx=tokenizer.pad_token_id)

    X_train_source = np.array(X_train_source.values.tolist())
    X_train_summary = np.array(X_train_summary.values.tolist())

    X_test_source = np.array(X_test_source.values.tolist())
    X_test_summary = np.array(X_test_summary.values.tolist())

    X_valid_source = np.array(X_valid_source.values.tolist())
    X_valid_summary = np.array(X_valid_summary.values.tolist())

    att_mask_train_source= get_attention_masks(X_train_source,'source')
    att_mask_train_summary = get_attention_masks(X_train_summary, 'summary')

    att_mask_test_source = get_attention_masks(X_test_source,'source')
    att_mask_test_summary = get_attention_masks(X_test_summary, 'summary')

    att_mask_valid_source = get_attention_masks(X_valid_source,'source')
    att_mask_valid_summary = get_attention_masks(X_valid_summary, 'summary')

    save_data(X_train_source, output_location + 'X_train_source.pkl')
    save_data(X_train_summary, output_location + 'X_train_summary.pkl')

    save_data(X_test_source, output_location + 'X_test_source.pkl')
    save_data(X_test_summary, output_location + 'X_test_summary.pkl')

    save_data(X_valid_source, output_location + 'X_valid_source.pkl')
    save_data(X_valid_summary, output_location + 'X_valid_summary.pkl')

    save_data(att_mask_train_source, output_location + 'att_mask_train_source.pkl')
    save_data(att_mask_train_summary, output_location + 'att_mask_train_summary.pkl')

    save_data(att_mask_test_source, output_location + 'att_mask_test_source.pkl')
    save_data(att_mask_test_summary, output_location + 'att_mask_test_summary.pkl')

    save_data(att_mask_valid_source, output_location + 'att_mask_valid_source.pkl')
    save_data(att_mask_valid_summary, output_location + 'att_mask_valid_summary.pkl')

    print(X_train_source.shape, att_mask_train_source.shape)
    print(X_train_summary.shape, att_mask_train_summary.shape)

    print(X_test_source.shape, att_mask_test_source.shape)
    print(X_test_summary.shape, att_mask_test_summary.shape)

    print(X_valid_source.shape, att_mask_valid_source.shape)
    print(X_valid_summary.shape, att_mask_valid_summary.shape)

print(prertained_model_name, 'cased')
output_location = base + 'BART_large/'

prepare_all_data(output_location, 1024,140)


import pytest
import datetime
from freezegun import freeze_time
from django.utils.timezone import make_aware

from users.tests.factories import UserFactory
from onboarding.tests.factories import OnboardingInfoFactory
from project.tests.util import strip_locale
from loc.tests.factories import LetterRequestFactory, LandlordDetailsFactory
from hpaction.tests.factories import (
    HPActionDocumentsFactory,
    HPActionDetailsFactory,
    DocusignEnvelopeFactory,
)
from airtable.record import Fields, apply_annotations_to_user

@pytest.mark.django_db
def test_from_user_works_with_minimal_user():
    user = UserFactory(phone_number="5551234567", full_legal_name="Bobby Denver")
    fields = Fields.from_user(user)
    assert fields.pk == user.pk
    assert fields.first_name == "Bobby"
    assert fields.last_name == "Denver"
    assert fields.admin_url == f"https://example.com/admin/users/justfixuser/{user.pk}/change/"
    assert fields.phone_number == "5551234567"
    assert fields.onboarding_info__can_we_sms is False
    assert fields.onboarding_info__lease_type == ""
    assert fields.onboarding_info__borough == ""
    assert fields.letter_request__created_at is None
    assert fields.landlord_details__name == ""
    assert fields.landlord_details__address == ""
    assert fields.letter_request__will_we_mail is False
    assert fields.letter_request__letter_sent_at is None
    assert fields.letter_request__rejection_reason == ""
    assert fields.letter_request__tracking_number == ""
    assert fields.hp_latest_documents_date is None
    assert fields.hp_action_details__sue_for_repairs is False
    assert fields.hp_action_details__sue_for_harassment is False

@pytest.mark.django_db
def test_from_user_works_with_onboarded_user():
    info = OnboardingInfoFactory(can_we_sms=True)
    fields = Fields.from_user(info.user)
    assert fields.onboarding_info__can_we_sms is True
    assert (
        fields.onboarding_info__address_for_mailing == "150 court street\nApartment 2\nBrooklyn, NY"
    )
    assert fields.onboarding_info__lease_type == "RENT_STABILIZED"
    assert fields.onboarding_info__borough == "BROOKLYN"

    info.can_we_sms = False
    info.save()
    fields = Fields.from_user(info.user)
    assert fields.onboarding_info__can_we_sms is False

@pytest.mark.django_db
def test_from_user_works_with_letter_request():
    lr = LetterRequestFactory(
        letter_sent_at=make_aware(datetime.datetime(2018, 5, 6)),
        rejection_reason="INCRIMINATING",
        tracking_number="boop",
    )
    fields = Fields.from_user(lr.user)
    assert fields.letter_request__will_we_mail is True
    assert fields.letter_request__created_at == datetime.datetime.utcnow().date().isoformat()
    assert (
        strip_locale(fields.letter_request__admin_pdf_url)
        == f"https://example.com/loc/admin/{lr.user.pk}/letter.pdf"
    )
    assert fields.letter_request__letter_sent_at == "2018-05-06"
    assert fields.letter_request__rejection_reason == "INCRIMINATING"
    assert fields.letter_request__tracking_number == "boop"

@pytest.mark.django_db
def test_from_user_works_with_landlord_details():
    ld = LandlordDetailsFactory()
    fields = Fields.from_user(ld.user)
    assert fields.landlord_details__name == "Landlordo Calrissian"
    assert fields.landlord_details__address == "1 Cloud City"

@pytest.mark.django_db
def test_from_user_works_with_hp_action(django_file_storage):
    details = HPActionDetailsFactory(sue_for_repairs=True, sue_for_harassment=True)
    with freeze_time("2018-03-04"):
        HPActionDocumentsFactory(user=details.user)
    fields = Fields.from_user(details.user)
    assert fields.hp_latest_documents_date == "2018-03-04"
    assert fields.hp_action_details__sue_for_repairs is True
    assert fields.hp_action_details__sue_for_harassment is True

@pytest.mark.django_db
def test_from_user_works_with_emergency_hp_action(django_file_storage):
    with freeze_time("2018-03-04"):
        de = DocusignEnvelopeFactory()
    user = de.docs.user
    fields = Fields.from_user(user)
    assert fields.ehp_num_filings == 0
    assert fields.ehp_latest_filing_date is None

    de.status = "SIGNED"
    de.save()
    fields = Fields.from_user(user, refresh=True)
    assert fields.ehp_num_filings == 1
    assert fields.ehp_latest_filing_date == "2018-03-04"

@pytest.mark.django_db
def test_from_user_works_with_partial_hp_action():
    details = HPActionDetailsFactory(sue_for_repairs=True, sue_for_harassment=True)
    fields = Fields.from_user(details.user)
    assert fields.hp_latest_documents_date is None
    assert fields.hp_action_details__sue_for_repairs is True
    assert fields.hp_action_details__sue_for_harassment is True

class TestApplyAnnotationsToUser:
    def test_it_does_nothing_if_annotations_exist(self):
        u = UserFactory.build()
        setattr(u, "boop", 1)
        apply_annotations_to_user(u, {"boop": "this value should never be used"})

    def test_it_applies_annotations_if_they_do_not_exist(self, db):
        from django.db.models import F
        from django.db.models.functions import Upper

        u = UserFactory(first_name="hallo")
        apply_annotations_to_user(u, {"boop": Upper(F("first_name"))})
        assert u.boop == "HALLO"


import sys
from itertools import permutations

input = sys.stdin.readline

n = int(input().rstrip())
k = int(input().rstrip())

num = []
number = []

for _ in range(n):
    num.append(input().rstrip())

for i in permutations(num, k):
    number.append(list(i))

for j in range(len(number)):
    number[j] = ''.join(number[j])

number = list(set(number))

print(len(number))


# main.py

from app import app
from forms import ProductSelectForm
from flask import flash, render_template, request, redirect
import json
from product import run_ims

# init_db()

@app.route('/', methods=['GET', 'POST'])
def index():
    form = ProductSelectForm(request.form)
    if request.method == 'POST':
        return search_results(form)

    return render_template('index.html', form=form)

@app.route('/results')
def search_results(form):
    results = {}
    output = run_ims(form)

    if not output:
        flash('No results found!')
        return redirect('/')
    else:
        # display results
        return render_template('results.html' , results = output ) #results=json.dumps(results))

if __name__ == '__main__':
    import os
    if 'WINGDB_ACTIVE' in os.environ:
        app.debug = False
    app.debug = True
    app.run(port=5003)


f = open('input.txt', 'r')

inputArray = []
elfCalorie = [0]
curElf = 0

for line in f.readlines():
    inputArray.append(line)
    if line == "\n":
        curElf += 1
        elfCalorie.append(0)
    else:
        elfCalorie[curElf] += int(line)

sortedElves = sorted(elfCalorie)
print(len(inputArray))
print(curElf)

print(elfCalorie[0])
print(sortedElves[248] + sortedElves[247] + sortedElves[246])


import json
from typing import Union
from CodingChallengeModule.Classes import Employee, Manager

class JsonDataReader:

    # Constructor
    def __init__(self, hierarchyFileName : str):

        # Guard clauses to ensure parameters are valid
        if hierarchyFileName is None:
            raise ValueError('ERROR :: value for "hierarchyFileName" is NONE!')
        if hierarchyFileName == '':
            raise ValueError('ERROR :: value for "hierarchyFileName" is empty!')
        if hierarchyFileName.lower().endswith('.json') == False:
            raise ValueError('ERROR :: "hierarchyFileName" must be a .JSON file!')

        # Assign instance variables
        self.hierarchyFileName = hierarchyFileName

    # Public method that builds the python represenation of the employee hierarchy
    #   Input: N/A
    #   Output: rootManager : Manager
    def Read(self):

        # Load Employee Hierarchy Data from JSON file
        with open(self.hierarchyFileName, 'r') as jsonFile:
            jsonData = json.load(jsonFile)

            # Build root 'Manager' object from JSON data
            rootManager = self.__ReadRecursive(jsonData)

        # return root manager object
        return rootManager

    # Public method that builds the python represenation of the employee hierarchy
    #   Input: jsonData - Python object representing json data read from employee hierarchy json file
    #   Output: employee : Union[Employee, Manager]
    def __ReadRecursive(self, jsonData):

        # Check the employee type for the current employee
        employeeType = jsonData['EmployeeType']

        # if the current employee is a 'Manager'
        if employeeType == 'Manager':

            managerData = jsonData['EmployeeData']      # Get employee data
            directReports = []                          # create a list to add their direct reports to

            # Iterate through the Manager's list of employees / direct reports
            for person in jsonData['DirectReports']:

                # if the current direct reporting employee is a 'Manager'
                if person['EmployeeType'] == 'Manager':

                    # Call this method recursively
                    newManagerEmployee = self.__ReadRecursive(person)

                    # Add the new manager employee to the current manager's list of direct reports
                    directReports.append(newManagerEmployee)

                # else if the current direct employee is an 'Employee'
                elif person['EmployeeType'] == 'Employee':

                    # Create a new 'Employee' object
                    newEmployee = Employee(
                        person['EmployeeData']['Name'],
                        person['EmployeeData']['Salary'],
                    )

                    # Add the new employee to the current manager's list of direct reports
                    directReports.append(newEmployee)

            # Create a new 'Employee' object to store the current manager's employee data
            managerEmployee = Employee(
                managerData['Name'],
                managerData['Salary']
            )

            # Create a new 'Manager' object to decorate the managerEmployee object and store
            #   list of current manager's employees / direct reports
            newManager = Manager(
                managerEmployee,
                directReports
            )

            # return the 'Manager' object
            return newManager

        # Else if the current employee is an 'Employee
        elif employeeType == 'Employee':

            # Create a new 'Employee' object to store the employee's data
            newEmployee = Employee(
                jsonData['EmployeeData']['Name'],
                jsonData['EmployeeData']['Salary'],
            )

            # return the 'Employee' object
            return newEmployee

        # Else, dealing with an unhandled type
        else:
            raise ValueError(f'ERROR :: type "{employeeType}" is not supported!')


from mrjob.job import MRJob

class MRAnagram(MRJob):

    def mapper(self, _, line):
        # On convertit les mots en liste de lettre minuscule puis on ordonne cette liste
        letters = list(str(line).lower())
        letters.sort()

        # on utilise comme clé la liste de lettre ordonnée
        yield letters, line

    def reducer(self, _, words):
        # on renvoie les mots ayant au moins 2 anagrames en matchant par liste ordonnée
        anagrams = [w for w in words]
        if len(anagrams) > 1:
            yield len(anagrams), anagrams

if __name__ == "__main__":
    MRAnagram.run()


## what is the probability of 4 coin toss 3Head  1Tail
'''more the number of experiments is, the closer will be this probability,
determined by repeated experiments (simulation), to the actual probability
(determined using combinatorics)'''

from random import randint
successes = 0
attempts = 10000       #experiments
for i in range(attempts):
        if randint(0,1)+randint(0,1)+randint(0,1)+randint(0,1) == 3:
                successes += 1
print("No. Of attempts is" , attempts)
print("No. Of successes is", successes)
prob = successes  / attempts
print("the probability of success is" ,prob)