import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from PIL import Image
import io
import numpy as np
from torchvision.transforms.transforms import Grayscale

class View(nn.Module):
    """
    Simple module to `View` a tensor in a certain size

    Wrapper of the `torch.Tensor.View()` function into a forward module
    Args:
        size (tuple) output tensor size
    """

    def __init__(self, size):
        super(View, self).__init__()
        self.size = size

    def forward(self, tensor):
        return tensor.view(self.size)

# Network class
class Net(nn.Module):
    def __init__(self, input_size = (28,28), in_channels = 1, out_classes = 10,
                 kernel_size = 4, stride = 2, padding = 1, dilation = 1,
                 conv_layers = 2, linear_layers = 2, expansion = 5):
        """
        Simple class for a variable sized CNN, defaults to 4 layer MNIST classifier.

        Args:
            input_size (tuple, shape HxW): dimension of input image. default = (28,28), MNIST images.
            in_channels (int): number of channels of input images. default = 1, grayscale MNIST images.
            out_classes (int): number of classes in the classification problem. default = 10, MNIST classes.
            kernel_size (int): kernel size of the convolutional layers. default = 4.
            stride (int): stride of the convolutional layers. default = 2.
            padding (int): padding of the convolutional layers. default = 1.
            dilation (int): dilation of the convolutional layers. default = 1.
            conv_layers (int): number of convolutional layers. default = 2.
            linear_layers (int): number of linear layers. default = 2.
            expansion (int): expansion/reduction factor for channels in conv layers
                             and nodes in linear layers. default = 5 -> expands/reduces as powers of 5.
                             NOTE: for any CNN with more than 4 conv layers this expansion factor
                                   will be impractical. (1->5->25->125->625->3125), more suited expansion
                                   for large CNN is 2: i.e. for RGB images: 3 -> 3*2 -> 3*4 -> 3*8 ... -> 3*2^(n-1)
        """

        super(Net, self).__init__()

        # ===== Convolutional Layers ======
        conv = []
        H,W = input_size
        sizes = [input_size,]
        for c in range(conv_layers):
            H = (H+2*padding-dilation*(kernel_size-1)-1)/stride+1
            W = (W+2*padding-dilation*(kernel_size-1)-1)/stride+1
            sizes.append((H,W))
            conv.append(nn.Conv2d(in_channels*(expansion**c), expansion**(c+1), kernel_size, stride, padding))
            conv.append(nn.BatchNorm2d(expansion**(c+1)))
            if c<(conv_layers-1): #don't append ReLU or dropout on last conv layer
                conv.append(nn.ReLU(inplace=True))
                conv.append(nn.Dropout2d(p=0.1))

        self.conv = nn.Sequential(*conv)

        # ===== Reshape from BxCxHxW to BxN =====
        N = int(np.prod(sizes[-1]+(expansion**(c+1),)))
        self.view = View((-1,N))

        # ===== Linear Layers =====
        linear = []
        for l in range(linear_layers):
            if int(N/expansion)>out_classes:
                linear.append(nn.Linear(N,int(N/expansion)))
                linear.append(nn.ReLU(inplace=True))
                linear.append(nn.Dropout(p=0.5))
                N = int(N/expansion)
        linear.append(nn.Linear(N, out_classes))
        linear.append(nn.Sigmoid())

        self.linear = nn.Sequential(*linear)

    def forward(self, input_tensors):
        y = self.conv(input_tensors)
        y = self.view(y)
        y = self.linear(y)
        return y

# define device (CPU versus GPU)
use_cuda = torch.cuda.is_available()
device = torch.device("cuda:0" if use_cuda else "cpu")

# ====== FUNCTIONS TO BE USED BY app.py =======

# transfor uploaded image to tensor and preprocess it
class transformImage(object):
    def __init__(self, image_size = (28,28), normalisation = (0.1307, 0.3081)):
        self.transform = transforms.Compose([transforms.Grayscale(),
                                             transforms.ToTensor(),
                                             transforms.Resize(size=image_size), # default is PIL.Image.BILINEAR interpolation
                                             transforms.Normalize(*normalisation), # mean and std of training set
                                             ])

    def __call__(self, image_bytes):
        # 1 open image bytes
        image = Image.open(io.BytesIO(image_bytes))
        # 2 transform image
        tensor_image = self.transform(image)
        return tensor_image.unsqueeze(0)

class getPrediction(object):
    def __init__(self):
        checkpoint = torch.load("./models/MNIST.tar", map_location="cpu")
        model = Net()
        model.load_state_dict(checkpoint['model_state_dict'])
        model.to(device)
        model.eval()
        self.model = model

    def __call__(self, tensor_image):
        output = self.model(tensor_image)
        _, predicted = torch.max(output.data, 1)
        return predicted.item()


import torch
from torch_geometric.nn import TransformerConv, LayerNorm

class GTN(torch.nn.Module):
    def __init__(self, in_channels, hidden_channels, out_channels, heads=10):
        super().__init__()
        self.conv1 = TransformerConv(in_channels, hidden_channels, heads)
        self.ln1 = LayerNorm(hidden_channels*heads)
        self.conv2 = TransformerConv(hidden_channels * heads, out_channels, 1)
        self.ln2 = LayerNorm(out_channels)

    def forward(self, batch):
        x = batch.x
        x = batch.edge_data
        x = self.conv1(x, edge_index)
        x = self.ln1(x).relu()
        x = self.conv2(x, edge_index)
        x = self.ln2(x).relu()
        return x


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

from ..base.captcha_service import CaptchaService

class CoinHive(CaptchaService):
    __name__ = "CoinHive"
    __type__ = "anticaptcha"
    __version__ = "0.01"
    __status__ = "testing"

    __description__ = "CoinHive captcha service plugin"
    __license__ = "GPLv3"
    __authors__ = [("GammaC0de", "nitzo2001[AT]yahoo[DOT]com")]

    KEY_PATTERN = r'class=[\'"]coinhive-captcha[\'"].+?data-key\s*=[\'"](\w+?)[\'"]'
    HASHES_PATTERN = (
        r'class=[\'"]coinhive-captcha[\'"].+?data-hashes\s*=[\'"](\d+?)[\'"]'
    )

    COINHIVE_INTERACTIVE_SIG = (
        "792398cf130e9cb0d1c16363c87122a623d0bc7410bd981000f5cbfe1c6ec6708d16edf19bc2703b"
        + "04291697cfde5194c5dc290a23b10af5ad6a26606867a5e38031aa24d715c7ec48a5c61272d757a5"
        + "4835e77558933744a3f0ad245a72ea9447893284c4fd458544a9bff09c19b187321ec7b0f1b2b21e"
        + "246bef741b27f3058b2467a192c100b78bb311300e5da0ce95b331bb77215e261fb4a6b78acd89a7"
        + "13aefdc393fb19f3cdb4682b084c5747347f344fd49ed86bad7fba1ad2f059663ff1b800cffa8948"
        + "bb9c12dddf0ae96831b85c4f9526460cd2a4355c4f800aeb4b541b5c5bee62dc5bfb18c6656c0304"
        + "0b2a819edd07480911b6dadf430f6eb1"
    )

    COINHIVE_INTERACTIVE_JS = """
            while(document.children[0].childElementCount > 0) {
                document.children[0].removeChild(document.children[0].children[0]);
            }
            document.children[0].innerHTML = '
Loading Coinhive Captcha...
';

            gpyload.getFrameSize = function() {
                var divCoinHive = document.body.querySelector("iframe[src*='authedmine.com/captcha/']");
                if (divCoinHive !== null) {
                    var rect = divCoinHive.getBoundingClientRect();
                    return {top: Math.round(rect.top), right: Math.round(rect.right), bottom: Math.round(rect.bottom), left: Math.round(rect.left)};
                } else {
                    return {top: 0, right: 0, bottom: 0, left: 0};
                };
            };
            window.pyloadCaptchaFinishCallback = function(token){
                gpyload.submitResponse(token);
            }
            var js_script = document.createElement('script');
            js_script.type = "text/javascript";
            js_script.src = "https://authedmine.com/lib/captcha.min.js";
            js_script.async = true;
            document.getElementsByTagName('head')[0].appendChild(js_script);

            gpyload.activated();"""

    def detect_key(self, data=None):
        html = data or self.retrieve_data()

        m = re.search(self.KEY_PATTERN, html)
        if m is not None:
            self.key = m.group(1).strip()
            self.log_debug(f"Key: {self.key}")
            return self.key
        else:
            self.log_warning(self._("Key pattern not found"))
            return None

    def detect_hashes(self, data=None):
        html = data or self.retrieve_data()
        m = re.search(self.HASHES_PATTERN, html)
        if m is not None:
            self.hashes = m.group(1).strip()
            self.log_debug(f"Hashes: {self.hashes}")
            return self.hashes
        else:
            self.log_warning(self._("Hashes pattern not found"))
            return None

    def challenge(self, key=None, hashes=None, data=None):
        key = key or self.retrieve_key(data)
        hashes = hashes or self.detect_hashes(data)
        params = {
            "url": self.pyfile.url,
            "key": key,
            "hashes": hashes,
            "script": {
                "signature": self.COINHIVE_INTERACTIVE_SIG,
                "code": self.COINHIVE_INTERACTIVE_JS,
            },
        }

        result = self.decrypt_interactive(params, timeout=300)

        return result

# if __name__ == "__main__":
#     # Sign with the command `python -m pyload.plugins.captcha.CoinHive
#     # pyload.private.pem pem_passphrase`
#     import sys
#     from ..helpers import sign_string

#     if len(sys.argv) > 2:
#         with open(sys.argv[1]) as fp:
#             pem_private = fp.read()

#         print(
#             sign_string(
#                 CoinHive.COINHIVE_INTERACTIVE_JS,
#                 pem_private,
#                 pem_passphrase=sys.argv[2],
#                 sign_algo="SHA384",
#             )
#         )


from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render

from . import models

# Create your views here.
def list(request):
    if('class_name' in request.GET):
        schedule_list = []
        rclass = request.GET['class_name']
        classn = models.Class_Name.objects.all().filter(name=rclass)
        classn = models.Class_Name.objects.all().filter(name=rclass)
        for day_id in range(1, 6):
            Schedule = models.Schedule.objects.all().filter(id_day=day_id, id_class=classn[0].id)
            days = {}
            days['day_id'] = day_id
            days['schedule'] = Schedule
            schedule_list.append(days)
        return render(request, 'schedule_school/index.html', {'schedule_list': schedule_list, 'class_name': classn[0]})

        # return HttpResponse([print_schedule(s) for s in Schedule])
    else:
        return HttpResponse(f"Not enough parametrs")

@csrf_exempt
def add(request):

    if request.method == 'GET':
        fields = ('room_number', 'id_teacher', 'id_class', 'id_subject',
                  'id_day', 'lesson_number')
        fields = (room_number, id_teacher, id_class, id_subject, id_day,
                  lesson_number) = [request.GET.get(v) for v in fields]
        if not all(fields):
            return HttpResponse(f"Not enough parametrs")
        else:
            teacher = models.Teacher.objects.filter(name=id_teacher)
            id_class = models.Class_Name.objects.filter(name=id_class)
            id_subject = models.Subject.objects.filter(name=id_subject)
            id_day = models.Day.objects.filter(name=id_day)
            if not all([teacher, id_class, id_subject, id_day]):
                return HttpResponse("not found")
            s = models.Schedule(room_number=room_number,
                                id_teacher=teacher[0],
                                id_class=id_class[0],
                                id_subject=id_subject[0],
                                id_day=id_day[0],
                                lesson_number=lesson_number)
            s.save()
            return HttpResponse("ok")

def add_form(request):
    if request.method == 'GET':
        return render(request, 'schedule_school/add.html')


#Introduksjon til GUI programmering
#Grunnstruktur
#Med komponentene ledetekst, inndatafelt, utdatafelt og knapp

from tkinter import *
from typing import Collection
window=Tk()

#Vi gir vinduet ett navn
window.title('Lånekalkulator billån')

#Vi lager ledetekster for kjøpesum, egekapital og lånetilsagn
lbl_kjopesum=Label(window,text='Kjøpesum')
lbl_kjopesum.grid(row=0, column=0, padx=100, pady=15)

lbl_egenkapita=Label(window,text='Egenkapital')
lbl_egenkapita.grid(row=1,column=0, padx=100, pady=15)

lbl_lanetilsagn=Label(window,text='Lånetilsagn')
lbl_lanetilsagn.grid(row=3,column=0,padx=100,pady=15)

window.mainloop()

PRG1000/Forelesningsprogrammer/Forelesning 011121 - 2.py


from django.urls import path
from django.views.decorators.cache import cache_page

from .views import ProductCreate, \
    ProductUpdate, ProductDelete, subscriptions, ProductsList, ProductDetail

urlpatterns = [
    path('', ProductsList.as_view(), name='product_list'),
    path('<int:pk>/', cache_page(60)(ProductDetail.as_view()), name='product_detail'),
    # добавим кэширование на детали товара. Раз в 10 минут товар будет записываться в кэш для экономии ресурсов.
    path('create/', ProductCreate.as_view(), name='product_create'),
    path('<int:pk>/update/', ProductUpdate.as_view(), name='product_update'),
    path('<int:pk>/delete/', ProductDelete.as_view(), name='product_delete'),
    path('subscriptions/', subscriptions, name='subscriptions'),
]


from collections import Counter, defaultdict

class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n

    def find(self, a):
        if a == self.parent[a]:
            return a
        self.parent[a] = self.find(self.parent[a])
        return self.parent[a]

    def union(self, a, b):
        parent_a = self.find(a)
        parent_b = self.find(b)
        if parent_a != parent_b:
            if self.size[parent_a] < self.size[parent_b]:
                parent_a, parent_b = parent_b, parent_a
            self.parent[parent_b] = parent_a
            self.size[parent_a] += self.size[parent_b]

class Solution:
    def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int:
        n = len(vals)
        m = len(edges)
        dsu = DSU(n)
        for e in edges:
            e.append(max(vals[e[0]], vals[e[1]]))
        nodes = defaultdict(set)
        for i in range(n):
            nodes[vals[i]].add(i)
        edges.sort(key = lambda e: e[2])
        res = n
        i = 0
        for nodeval in sorted(set(vals)):
            while i < m and edges[i][2] <= nodeval:
                dsu.union(edges[i][0], edges[i][1])
                i += 1
            ctr = Counter()
            for x in nodes[nodeval]:
                res += ctr[dsu.find(x)]
                ctr[dsu.find(x)] += 1
        return res


# здесь мы будем выполнять проверку наличия 2 условий: 1 это находятся ли
# данные в таблице client, 2  не ходятся ла данные с такой же датай во второй таблице
# если эти два условия выполняются то мы добавляем в таблицу client этому клиенту +1
# к столбцу урока или 0.1 соответственно  и производим расчёт урока и добавляем данные
# в вторую таблицу

import sqlite3
from sqlite3 import Error
from dick_client import client_base
from nedel import ned
import re
def tabl2(link):
    conect = sqlite3.connect(link)
    def value(x):
        for i in x:
            for j in i:
                return j
    # функция проверки значений во второй таблице
    def nones(x):
        array = []
        for i in x:
            for j in i:
                array.append(j)
        for i in array:
            if i == None:
                return None
        return array
    def func(conect,reqest):
        cursor =  conect.cursor()
        try:
            value = cursor.execute(reqest)
            conect.commit()
            #print("Подключение к базе данных SQLite прошло успешно")
        except Error as e:
            return f"Произошла ошибка {e}"
        return value
    price_not = [250,275,310,350]  # 250 = 1 - 9 урок,275 = 10 - 19, 310 = 20 - 33,350 = 34+
    price_yes = [180,200,225] # 180 = 1- 19, 200 = 20 - 33, 225 = 34+
    f = ned()
    dates = client_base(f)
    for date in dates:                 # date это дата проведения урока
        for nomer in dates.get(date):     # nomer это номер клиента
            select = f"""SELECT nomer FROM client WHERE nomer = {nomer}"""
            select_client_day = f"""SELECT nomer FROM client_day WHERE nomer = {nomer} AND date = '{date}'"""
            f = func(conect,select)
            values = value(f)
            f1 = func(conect,select_client_day)
            values1 = nones(f1)
            # находятся ли данные в таблице client,не ходятся ла данные с такой же датай и номерам во второй таблице
            if values != None and values1 == []:
                client = f"SELECT praice FROM client WHERE nomer = {nomer}"
                f1 = func(conect,client)
                praice = value(f1)
                ### это добавление  к целым урокам
                if praice == 'yes' or praice == 'not':
                    lession = f"""UPDATE client SET number_of_lession = (SELECT number_of_lession FROM client WHERE nomer = {nomer}) + 1 WHERE nomer = {nomer} """
                    lession = func(conect,lession)
                elif praice == 'yes_50' or praice == 'not_50':
                    les = f'SELECT number_of_lession FROM client WHERE nomer = {nomer}'
                    ##### надо определять после запятой цифры в уроку чтобы правельно плюсовать
                    fq = func(conect,les)
                    rew = value(fq)
                    t = re.findall(r'\w+',str(rew))
                    if t[1] == '1':
                        l = f'SELECT number_of_lession FROM client WHERE nomer = {nomer}'
                        f1 = func(conect,l)
                        l = value(f1)
                        l = round(l + 0.1,1)
                        lession_50 = f"""UPDATE client SET number_of_lession = {l} WHERE nomer = {nomer} """
                        lession_50 = func(conect,lession_50)
                    elif t[1] == '2':
                        l = f'SELECT number_of_lession FROM client WHERE nomer = {nomer}'
                        f1 = func(conect,l)
                        l = value(f1)
                        l = round((l - 0.1)+1,1)
                        lession_50 = f"""UPDATE client SET number_of_lession = {l} WHERE nomer = {nomer} """
                        lession_50 = func(conect,lession_50)
            ######## код для расчета цены за урок#############################
                praice = f"""SELECT praice FROM client WHERE nomer = {nomer}"""
                lession = f"""SELECT number_of_lession FROM client WHERE nomer = {nomer}"""
                base = func(conect,praice)
                praice = value(base)
                lession = func(conect,lession)
                lession = value(lession)
                if (praice == 'not' or praice == "not_50") and (lession > 0 and lession < 10):
                    price = 250
                elif (praice == 'not' or praice == "not_50") and (lession > 9 and lession < 20):
                    price = 275
                elif (praice == 'not' or praice == "not_50") and (lession > 19 and lession < 34):
                    price = 310
                elif (praice == 'not' or praice == "not_50") and lession >= 34 :
                    price = 350
                elif (praice == 'yes' or praice == "yes_50") and (lession > 0 and lession < 20):
                    price = 180
                elif (praice == 'yes' or praice == "yes_50") and (lession > 19 and lession < 34):
                    price = 200
                elif (praice == 'yes' or praice == "yes_50") and lession >= 34:
                    price = 225
                    #### разобраться в прайсах
                mother = f"""SELECT mother FROM client WHERE nomer = {nomer}"""  ### имя матери
                base = func(conect,mother)
                mother = value(base)
                id = f"""SELECT id FROM client WHERE nomer = {nomer}"""     ### id матери
                base = func(conect,id)
                id = value(base)
                ### добавление во вторую таблицу
                if praice == "yes" or praice == "not":
                    update_client = f"""INSERT INTO client_day ('nomer','mother','date','number_of_lession','price_lesson','praice','client_id')
                    VALUES ('{nomer}','{mother}','{date}','{lession}','{price}','{praice}','{id}')"""
                    base = func(conect,update_client)
                if praice == 'not_50' or praice == "yes_50":
                    lessi = lession %  1
                    if round(lessi,1) == 0.2:
                        update_client = f"""INSERT INTO client_day ('nomer','mother','date','number_of_lession','price_lesson','praice','client_id')
                        VALUES ('{nomer}','{mother}','{date}','{lession}','{price}','{praice}','{id}')"""
                        base = func(conect,update_client)
                    elif round(lessi,1) == 0.1:
                        update_client = f"""INSERT INTO client_day ('nomer','mother','date','number_of_lession','price_lesson','praice','client_id')
                        VALUES ('{nomer}','{mother}','{date}','{lession}',0,'{praice}','{id}')"""
                        base = func(conect,update_client)


from numpy import array, arange
from numpy.linalg import norm
from scipy.integrate import odeint
from scipy.optimize import fmin
import matplotlib.pyplot as plt
from .logger import logger
from ..utils.get_config import dict_config

class ModelSIR:
    # I am not the author of this piece of code. It is adapted from:
    # https://github.com/pcaressa/note-epidemie/blob/master/epidemie.ipynb

    def __init__(self):
        self.name = "SIR"
        logger.debug("Model initialized.")

    def __fun_SIR(self, y, t, beta, gamma):
            return [ -beta*y[0]*y[1]/self.N0,
                     beta*y[0]*y[1]/self.N0-gamma*y[1],
                     gamma*y[1] ]

    def __m(self, params):
        if self.fit_start:
            SIR0 = self.SIR0
        else:
            SIR0 = params[:3]
        y = odeint(
            self.__fun_SIR,
            SIR0,
            self.array_steps,
            args=tuple(params[3:])
        )
        return norm(y[-self.n_history:] - self.array_SIR[-self.n_history:])

    def fit(self, N0, array_I, array_R, n_history, fit_start=True):
        self.fit_start = fit_start
        if n_history is None:
            n_history = len(array_I)
        self.n_history = n_history
        self.N0 = N0
        self.array_I = array(array_I)
        self.array_R = array(array_R)
        self.array_S = N0 - self.array_I - self.array_R
        self.array_SIR = array([ \
            [self.array_S[i], \
             self.array_I[i], \
             self.array_R[i]] \
            for i in range(len(array_I))])
        self.SIR0 = self.array_SIR[0]
        self.array_steps = arange(len(array_I))
        self.optimal_parms = fmin(self.__m, (self.SIR0[0], self.SIR0[1], self.SIR0[2], 0.1, 0.1), disp=0) # beta and gamma
        logger.debug("Model trained.")

    def forecast(self, n_forecast):
        if self.fit_start:
            SIR0 = self.SIR0
        else:
            SIR0 = self.optimal_parms[:3]
        self.array_steps_forecast = arange(len(self.array_I) + n_forecast)
        y = odeint(self.__fun_SIR, SIR0, self.array_steps_forecast, \
            args=tuple(self.optimal_parms[3:]))
        self.array_S_forecast = y[:, 0]
        self.array_I_forecast = y[:, 1]
        self.array_R_forecast = y[:, 2]
        return self.array_S_forecast, \
            self.array_I_forecast, \
            self.array_R_forecast

    def plot(
        self,
        label_I="Totale infetti (dato reale)",
        label_S_forecast="Suscettibili (proiezione)",
        label_I_forecast="Infetti (proiezione)",
        label_R_forecast="Deceduti o guariti (proiezione)",
        title="Proiezioni secondo il modello SIR, dati normalizzati sul numero di tamponi",
        ylim=[0,1]
    ):
        fig = plt.figure(figsize=(10, 6))
        plt.grid()
        plt.plot(arange(len(self.array_I)), self.array_I, 'ro', label=label_I)
        plt.plot(self.array_steps_forecast, self.array_S_forecast, "g", label=label_S_forecast)
        plt.plot(self.array_steps_forecast, self.array_I_forecast, "b", label=label_I_forecast)
        plt.plot(self.array_steps_forecast, self.array_R_forecast, "r", label=label_R_forecast)
        plt.title(title)
        plt.legend()
        plt.ylim(ylim)
        plt.close(fig)
        return fig


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

"""

 CERN@school - Profiling Mafalda Time Information.

 See the README.md file and the GitHub wiki for more information.

 http://cernatschool.web.cern.ch

"""

# Import the code needed to manage files.
import os, glob

#...for parsing the arguments.
import argparse

#...for the logging.
import logging as lg

#...for the binary handling.
import struct

#...for the MATH.
import math

if __name__ == "__main__":

    print("*")
    print("*==========================================*")
    print("* CERN@school - time information profiling *")
    print("*==========================================*")

    # Get the datafile path from the command line.
    parser = argparse.ArgumentParser()
    parser.add_argument("inputPath",       help="Path to the input dataset.")
    parser.add_argument("outputPath",      help="The path for the output files.")
    parser.add_argument("numFrames",       help="The number of frames to process (-1 for all).")
    parser.add_argument("startFrame",      help="The starting frame.")
    parser.add_argument("-v", "--verbose", help="Increase output verbosity", action="store_true")
    args = parser.parse_args()

    ## The path to the data file.
    datapath = args.inputPath

    ## The output path.
    outputpath = args.outputPath

    # Check if the output directory exists. If it doesn't, quit.
    if not os.path.isdir(outputpath):
        raise IOError("* ERROR: '%s' output directory does not exist!" % (outputpath))

    ## The number of frames to process.
    n_frames_to_process = int(args.numFrames)

    ## The start frame.
    start_frame_number = int(args.startFrame)

    # Set the logging level.
    if args.verbose:
        level=lg.DEBUG
    else:
        level=lg.INFO

    # Configure the logging.
    lg.basicConfig(filename=os.path.join(outputpath, 'log_profile-time-info.log'), filemode='w', level=level)

    print("*")
    print("* Input path          : '%s'" % (datapath))
    print("* Output path         : '%s'" % (outputpath))
    print("*")

    ## The total number of frames.
    n_frames = os.path.getsize(datapath) / 8

    # Error handling.
    if n_frames_to_process == -1:
        n_frames_to_process = n_frames
    #
    if start_frame_number > n_frames:
        raise IOError("* ERROR! Starting frame number greater than the number of frames.")

    lg.info(" * Profiling: '%s'" % (datapath))
    lg.info(" *")
    lg.info(" * File size                : % 15d [B]" % (os.path.getsize(datapath)))
    lg.info(" * Number of frames         : % 15d"     % (n_frames))
    lg.info(" *")

    # Read the information from the binary profile file.
    with open(datapath, "rb") as bf:

        ## Frame counter.
        frame_count = 0

        while True:

            ## The eight bytes representing the next frame.
            bs = bf.read(8)

            # Skip frames before the start frame (FIXME).
            if frame_count < start_frame_number:
                frame_count += 1
                continue

            # Quit if we're at the end of the file or frame count.
            if not bs or frame_count > (n_frames_to_process + start_frame_number - 1): break

            ## The frame's data - 8 bytes, eh? Nice.
            data = struct.unpack("IhH", bs)

            ## The start time (seconds since epoch) - 4 byte unsigned integer.
            start_time_s = data[0]

            ## The acquisition time (decoded 2 byte signed integer).
            acq_time = math.pow(10, int(data[1]))

            ## The number of hit pixels (2 byte unsigned integer).
            n_pixels = int(data[2])

            # DO NOT UNCOMMENT THIS FOR THE WHOLE RUN!
            # You'll end up with a massive log file. No-one likes a massive
            # log.
            #lg.info(" * Frame % 12d: %d % f % 10d" % (frame_count, start_time_s, acq_time, n_pixels))

            frame_count += 1


from django.shortcuts import render
from django.utils.safestring import mark_safe
import json
from json import dumps
from django.http import JsonResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.template.loader import render_to_string
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from django.contrib.auth.models import User
from .models import ChatRoom, ChatMessage
from forum.models import ChatNotification

def index(request):
    chat_rooms = ChatRoom.objects.filter(users=request.user).order_by('-latest_message_date')

    # Create two-dimensional list [[chat_room, notification_count], ..] for easier filtering
    user_chat_rooms = []
    for user_chat_room in chat_rooms:
        count = ChatNotification.objects.filter(recipient=request.user, chat_room=user_chat_room, read=False).count()
        user_chat_rooms.append([user_chat_room, count])

    context =  {
        'user_chat_rooms': user_chat_rooms
    }

    if request.is_ajax():
        html = render_to_string('chat/index.html', context, request=request)
        return JsonResponse({'chat_index': html})

    return render(request, 'chat/index.html', context)

def room(request, room_name):
    chat_id = int(room_name)
    recipient_id = chat_id - request.user.id
    recipient = User.objects.get(id=recipient_id)

    # Verify if the current room is an existing chat room
    if ChatRoom.objects.filter(number=chat_id).exists():
        exisiting_room = ChatRoom.objects.get(number=chat_id)
        saved_messages = ChatMessage.objects.filter(room=exisiting_room).order_by('timestamp')

        # Set any unread messages as read when user visits chat room
        ChatNotification.objects.filter(recipient=request.user, chat_room=exisiting_room).update(read=True)

        content = {
            'room_name': room_name,
            'user': request.user,
            'other_user': recipient,
            'messages': saved_messages,
        }

    # Create a new chat room if current room does not exist
    else:
        new_room = ChatRoom.objects.create(
            name=request.user.username + '/' + recipient.username,
            number=chat_id,
            sender=request.user,
            receiver=recipient)
        new_room.users.add(request.user)
        new_room.users.add(recipient)

        content = {
            'room_name': room_name,
            'user': request.user,
            'other_user': recipient,
            'user_chat_room': new_room,
            'chat_room_id': str(chat_id),
        }

        if request.is_ajax():
            new_chat_room = render_to_string('chat/prepend_new_chat_room.html', content, request=request)
            html = render_to_string('chat/room_popup_ajax.html', content, request=request)
            return JsonResponse({'form': html, 'new_chat_room': new_chat_room})

    # Filter out the chat rooms that the current user is a part of
    chat_rooms = ChatRoom.objects.filter(users=request.user).order_by('-latest_message_date')
    content['chat_room_id'] = str(chat_id)

    # Create two-dimensional list [[chat_room, notification_count], ..] for easier filtering
    user_chat_rooms = []
    for user_chat_room in chat_rooms:
        count = ChatNotification.objects.filter(recipient=request.user, chat_room=user_chat_room, read=False).count()
        user_chat_rooms.append([user_chat_room, count])

    content['user_chat_rooms'] = user_chat_rooms

    if request.is_ajax():
        html = render_to_string('chat/room_popup_ajax.html', content, request=request)
        return JsonResponse({'form': html})

    return render(request, 'chat/room.html', content)

def prepend_new_chat(request, room_name):
    chat_id = int(room_name)
    chat_room = ChatRoom.objects.get(number=chat_id)

    context = {
        'user_chat_room': chat_room
    }

    new_chat_room = render_to_string('chat/prepend_new_chat_room.html', context, request=request)
    return JsonResponse({'new_chat_room': new_chat_room})

def start_new_chat(request):
    if request.is_ajax():
        users_followings = request.user.profile.followings.all()
        ajax_context = {
            'followings': users_followings,
        }

        html = render_to_string('chat/start_new_chat.html', ajax_context, request=request)
        return JsonResponse({'form': html})

def find_user(request, input):
    if request.is_ajax():
        print(input)
        matched_users = User.objects.filter(username__icontains=input)

        ajax_context = {
            'matched_users': matched_users
        }

        html = render_to_string('chat/matched_users.html', ajax_context, request=request)
        return JsonResponse({'matched_users': html})


from spack import *
from glob import glob
from llnl.util.filesystem import LibraryList
import os

class Cuda(Package):
    """CUDA is a parallel computing platform and programming model invented
    by NVIDIA. It enables dramatic increases in computing performance by
    harnessing the power of the graphics processing unit (GPU).

    Note: This package does not currently install the drivers necessary
    to run CUDA. These will need to be installed manually. See:
    https://docs.nvidia.com/cuda/ for details."""

    homepage = "https://developer.nvidia.com/cuda-zone"

    version('10.2.89',
            sha256='560d07fdcf4a46717f2242948cd4f92c5f9b6fc7eae10dd996614da913d5ca11',
            expand=False,
            url='http://developer.download.nvidia.com/compute/cuda/10.2/Prod/local_installers/cuda_10.2.89_440.33.01_linux.run')
    version('10.1.243',
            sha256='e7c22dc21278eb1b82f34a60ad7640b41ad3943d929bebda3008b72536855d31',
            expand=False,
            url="https://developer.download.nvidia.com/compute/cuda/10.1/Prod/local_installers/cuda_10.1.243_418.87.00_linux.run")
    version('10.0.130', sha256='92351f0e4346694d0fcb4ea1539856c9eb82060c25654463bfd8574ec35ee39a', expand=False,
            url="https://developer.nvidia.com/compute/cuda/10.0/Prod/local_installers/cuda_10.0.130_410.48_linux")
    version('9.2.88', sha256='8d02cc2a82f35b456d447df463148ac4cc823891be8820948109ad6186f2667c', expand=False,
            url="https://developer.nvidia.com/compute/cuda/9.2/Prod/local_installers/cuda_9.2.88_396.26_linux")
    version('9.1.85', sha256='8496c72b16fee61889f9281449b5d633d0b358b46579175c275d85c9205fe953', expand=False,
            url="https://developer.nvidia.com/compute/cuda/9.1/Prod/local_installers/cuda_9.1.85_387.26_linux")
    version('9.0.176', sha256='96863423feaa50b5c1c5e1b9ec537ef7ba77576a3986652351ae43e66bcd080c', expand=False,
            url="https://developer.nvidia.com/compute/cuda/9.0/Prod/local_installers/cuda_9.0.176_384.81_linux-run")
    version('8.0.61', sha256='9ceca9c2397f841024e03410bfd6eabfd72b384256fbed1c1e4834b5b0ce9dc4', expand=False,
            url="https://developer.nvidia.com/compute/cuda/8.0/Prod2/local_installers/cuda_8.0.61_375.26_linux-run")
    version('8.0.44', sha256='64dc4ab867261a0d690735c46d7cc9fc60d989da0d69dc04d1714e409cacbdf0', expand=False,
            url="https://developer.nvidia.com/compute/cuda/8.0/prod/local_installers/cuda_8.0.44_linux-run")
    version('7.5.18', sha256='08411d536741075131a1858a68615b8b73c51988e616e83b835e4632eea75eec', expand=False,
            url="http://developer.download.nvidia.com/compute/cuda/7.5/Prod/local_installers/cuda_7.5.18_linux.run")
    version('6.5.14', sha256='f3e527f34f317314fe8fcd8c85f10560729069298c0f73105ba89225db69da48', expand=False,
            url="http://developer.download.nvidia.com/compute/cuda/6_5/rel/installers/cuda_6.5.14_linux_64.run")

    # macOS Mojave drops NVIDIA graphics card support -- official NVIDIA
    # drivers do not exist for Mojave. See
    # https://devtalk.nvidia.com/default/topic/1043070/announcements/faq-about-macos-10-14-mojave-nvidia-drivers/
    # Note that a CUDA Toolkit installer does exist for macOS Mojave at
    # https://developer.nvidia.com/compute/cuda/10.1/Prod1/local_installers/cuda_10.1.168_mac.dmg,
    # but support for Mojave is dropped in later versions, and none of the
    # macOS NVIDIA drivers at
    # https://www.nvidia.com/en-us/drivers/cuda/mac-driver-archive/ mention
    # Mojave support -- only macOS High Sierra 10.13 is supported.
    conflicts('arch=darwin-mojave-x86_64')

    def setup_environment(self, spack_env, run_env):
        run_env.set('CUDA_HOME', self.prefix)

    def install(self, spec, prefix):
        runfile = glob(join_path(self.stage.source_path, 'cuda*_linux*'))[0]
        chmod = which('chmod')
        chmod('+x', runfile)
        runfile = which(runfile)

        # Note: NVIDIA does not officially support many newer versions of
        # compilers.  For example, on CentOS 6, you must use GCC 4.4.7 or
        # older. See:
        # http://docs.nvidia.com/cuda/cuda-installation-guide-linux/#system-requirements
        # https://gist.github.com/ax3l/9489132
        # for details.

        # CUDA 10.1+ has different cmdline options for the installer
        arguments = [
            '--silent',         # disable interactive prompts
            '--override',       # override compiler version checks
            '--toolkit',        # install CUDA Toolkit
        ]
        if spec.satisfies('@10.1:'):
            arguments.append('--installpath=%s' % prefix)   # Where to install
        else:
            arguments.append('--verbose')                   # Verbose log file
            arguments.append('--toolkitpath=%s' % prefix)   # Where to install

        runfile(*arguments)

    @property
    def libs(self):
        libs = find_libraries('libcuda', root=self.prefix, shared=True,
                              recursive=True)

        filtered_libs = []
        # CUDA 10.0 provides Compatability libraries for running newer versions
        # of CUDA with older drivers. These do not work with newer drivers.
        for lib in libs:
            if 'compat' not in lib.split(os.sep):
                filtered_libs.append(lib)
        return LibraryList(filtered_libs)


from enum import Enum, auto

class GeometryType(Enum):
    """Enum for geometry types."""

    vertex = auto()
    curve = auto()
    surface = auto()
    volume = auto()

    def get_cubit_string(self):
        """Return the string that represents this item in cubit."""

        if self == self.vertex:
            return "vertex"
        elif self == self.curve:
            return "curve"
        elif self == self.surface:
            return "surface"
        elif self == self.volume:
            return "volume"
        else:
            raise ValueError("Got unexpected type {}!".format(self))

    def get_dat_bc_section_string(self):
        """
        Return the string that represents this item in a dat file section.
        """

        if self == self.vertex:
            return "POINT"
        elif self == self.curve:
            return "LINE"
        elif self == self.surface:
            return "SURF"
        elif self == self.volume:
            return "VOL"
        else:
            raise ValueError("Got unexpected type {}!".format(self))

class FiniteElementObject(Enum):
    """Enum for finite element objects."""

    hex = auto()
    tet = auto()
    face = auto()
    triangle = auto()
    edge = auto()
    node = auto()

    def get_cubit_string(self):
        """Return the string that represents this item in cubit."""

        if self == self.hex:
            return "hex"
        elif self == self.tet:
            return "tet"
        elif self == self.face:
            return "face"
        elif self == self.triangle:
            return "tri"
        elif self == self.edge:
            return "edge"
        elif self == self.node:
            return "node"

    def get_dat_bc_section_string(self):
        """
        Return the string that represents this item in a dat file section.
        Currently this only makes sense for the node type, when explicitly
        defining boundary conditions on nodes.
        """
        if self == self.node:
            return "POINT"
        else:
            raise ValueError("Got unexpected type {}!".format(self))

class CubitItems(Enum):
    """Enum for cubit internal items such as groups."""

    group = auto()

class ElementType(Enum):
    """Enum for finite element shape types."""

    hex8 = auto()
    hex20 = auto()
    hex27 = auto()
    tet4 = auto()
    tet10 = auto()
    hex8sh = auto()
    hex8_fluid = auto()
    quad4 = auto()

    def get_cubit_names(self):
        """
        Get the strings that are needed to mesh and describe this element in
        cubit.
        """

        # Get the element type parameters.
        if self == self.hex8 or self == self.hex8sh or self == self.hex8_fluid:
            cubit_scheme = "Auto"
            cubit_element_type = "HEX8"
        elif self == self.hex20:
            cubit_scheme = "Auto"
            cubit_element_type = "HEX20"
        elif self == self.hex27:
            cubit_scheme = "Auto"
            cubit_element_type = "HEX27"
        elif self == self.tet4:
            cubit_scheme = "Tetmesh"
            cubit_element_type = "TETRA4"
        elif self == self.tet10:
            cubit_scheme = "Tetmesh"
            cubit_element_type = "TETRA10"
        elif self == self.quad4:
            cubit_scheme = "Auto"
            cubit_element_type = "QUAD4"
        else:
            raise ValueError("Got wrong element type {}!".format(self))

        return cubit_scheme, cubit_element_type

    def get_baci_name(self):
        """Get the name of this element in baci."""

        # Get the element type parameters.
        if self == self.hex8:
            return "SOLIDH8"
        elif self == self.hex20:
            return "SOLIDH20"
        elif self == self.hex27:
            return "SOLIDH27"
        elif self == self.tet4:
            return "SOLIDT4"
        elif self == self.tet10:
            return "SOLIDT10"
        elif self == self.hex8sh:
            return "SOLIDSH8"
        elif self == self.hex8_fluid:
            return "FLUID"
        if self == self.quad4:
            return "WALL"
        else:
            raise ValueError("Got wrong element type {}!".format(self))

    def get_baci_section(self):
        """Get the correct section name of this element in baci."""

        if self == self.hex8_fluid:
            return "FLUID"
        elif (
            self == self.hex20
            or self == self.hex8
            or self == self.hex20
            or self == self.hex27
            or self == self.tet4
            or self == self.hex8sh
            or self == self.tet10
            or self == self.quad4
        ):
            return "STRUCTURE"
        else:
            raise ValueError("Got wrong element type {}!".format(self))

    def get_baci_type(self):
        """Get the correct element shape name of this element in baci."""

        if self == self.hex8 or self == self.hex8sh or self == self.hex8_fluid:
            return "HEX8"
        elif self == self.hex20:
            return "HEX20"
        elif self == self.hex27:
            return "HEX27"
        elif self == self.tet4:
            return "TET4"
        elif self == self.tet10:
            return "TET10"
        elif self == self.quad4:
            return "QUAD4"
        else:
            raise ValueError("Got wrong element type {}!".format(self))

    def get_default_baci_description(self):
        """
        Get the default text for the description in baci after the material
        string.
        """

        # Get the element type parameters.
        if self == self.hex8:
            return "KINEM nonlinear EAS none"
        elif (
            self == self.hex20
            or self == self.hex27
            or self == self.tet4
            or self == self.tet10
        ):
            return "KINEM nonlinear"
        elif self == self.hex8sh:
            return "KINEM nonlinear EAS none ANS none THICKDIR auto"
        elif self == self.hex8_fluid:
            return "NA ALE"
        else:
            raise ValueError("Got wrong element type {}!".format(self))

class BoundaryConditionType(Enum):
    """Enum for boundary conditions types."""

    dirichlet = auto()
    neumann = auto()
    point_coupling = auto()
    beam_to_solid_volume_meshtying = auto()
    beam_to_solid_surface_meshtying = auto()
    beam_to_solid_surface_contact = auto()
    solid_to_solid_surface_contact = auto()
    fsi_coupling = auto()
    ale_dirichlet = auto()

    def get_dat_bc_section_header(self, geometry_type):
        """
        Get the header string for the boundary condition input section in the
        dat file.
        """

        if self == self.dirichlet or self == self.neumann:
            if self == self.dirichlet:
                self_string = "DIRICH"
            else:
                self_string = "NEUMANN"

            return "DESIGN {} {} CONDITIONS".format(
                geometry_type.get_dat_bc_section_string(), self_string
            )
        elif (
            self == self.beam_to_solid_volume_meshtying
            and geometry_type == GeometryType.volume
        ):
            return "BEAM INTERACTION/BEAM TO SOLID VOLUME MESHTYING VOLUME"
        elif (
            self == self.beam_to_solid_surface_meshtying
            and geometry_type == GeometryType.surface
        ):
            return "BEAM INTERACTION/BEAM TO SOLID SURFACE MESHTYING SURFACE"
        elif (
            self == self.beam_to_solid_surface_contact
            and geometry_type == GeometryType.surface
        ):
            return "BEAM INTERACTION/BEAM TO SOLID SURFACE CONTACT SURFACE"
        elif self == self.point_coupling and (
            geometry_type == GeometryType.vertex
            or geometry_type == FiniteElementObject.node
        ):
            return "DESIGN POINT COUPLING CONDITIONS"
        elif self == self.solid_to_solid_surface_contact and (
            geometry_type == GeometryType.surface
            or geometry_type == FiniteElementObject.node
        ):
            return "DESIGN SURF MORTAR CONTACT CONDITIONS 3D"
        elif self == self.fsi_coupling and (
            geometry_type == GeometryType.surface
            or geometry_type == FiniteElementObject.node
        ):
            return "DESIGN FSI COUPLING SURF CONDITIONS"
        elif self == self.ale_dirichlet and (
            geometry_type == GeometryType.surface
            or geometry_type == FiniteElementObject.node
        ):
            return "DESIGN SURF ALE DIRICH CONDITIONS"
        else:
            raise ValueError(
                "No implemented case for {} and {}!".format(self, geometry_type)
            )


class School:
    # 생성자 (초기값을 지정)
    def __init__(self, school="Jejuelementary", grade = "6학년"):
        self.school = school
        self.grade = grade
    # 정보 출력 함수
    def info(self):
        print("{} grade in {} school".format(self.grade, self.school))

# 객체 생성(인스턴스)
person1 = School() # 초기 생성자 유지
person2 = School("seoulelementary", "3학년")
person1.info() # info함수 불러오기
person2.info()


# check for prime numbers
a = int(input("Enter a number: "))
if a <= 1:
    print("Enter a number greater than 1")
else:
    # zkousej delit cislo a cisly od 2 do a-1
    for i in range(2, a):
        # pokud je zbytek po deleni 0, tak to neni prvocislo
        if (a % i) == 0:
            print(a, "is not a prime number")
            break
    else:
        print(a, "is a prime number")
        # pokud vyzkousime vsechna cisla a zadne nevydeli a, tak je to prvocislo


#!/usr/bin/python

import latticex.rosetta as rtt

import tensorflow as tf
import sys, time
import numpy as np
np.set_printoptions(suppress=True)

rtt.activate("SecureNN")

# xa = tf.Variable(rtt.private_input(0,
#     [
#         [0.12345678, 0.234567890],
#         [0.34567890, 0.03],
#         [1.3, 1.89],
#         [-1.3, -1.89],
#         [2.2, -2.2],
#         [-4.0, 4.0]
#     ]
# ))

xa = tf.constant(np.full(102400, 2.2))
wa = tf.Variable(rtt.private_input(0, np.full(102400, 2.2)))

ret = wa # tf.multiply(xa, wa)

print("xa:\n", xa)

#
init = tf.compat.v1.global_variables_initializer()
sess = tf.compat.v1.Session()
sess.run(init)

# print("X:\n", sess.run(xa * 2))
###########
print("=========================== tf op sigmoid 1")
xc = tf.sigmoid(ret)
# xc = tf.nn.sigmoid(ret)
xcc = sess.run(xc)
print("=========================== tf op sigmoid 2")
print(xcc)

# print("=========================== mpc op sigmoid 1")
start = time.time()
xc = rtt.SecureReveal(tf.sigmoid(ret))
xcc = sess.run(xc)
print("secure_sigmoid cost: ", time.time()-start)
# print("=========================== mpc op sigmoid 2")
print(xcc)

# print("=========================== mpc op sigmoidV2 1")
start = time.time()
xc = rtt.SecureReveal(rtt.SecureSigmoidV2(ret))
xcc = sess.run(xc)
print("secure_sigmoid_6Pieces_Python cost: ", time.time()-start)
# print("=========================== mpc op sigmoid 2")
print(xcc)

# print("=========================== mpc op sigmoidV2 1")
start = time.time()
xc = rtt.SecureReveal(rtt.SecureSigmoidV3(ret))
xcc = sess.run(xc)
print("secure_sigmoid_3Pieces_Python cost: ", time.time()-start)
# print("=========================== mpc op sigmoid 2")
print(xcc)

# print("=========================== mpc op sigmoidV2 1")
start = time.time()
xc = rtt.SecureReveal(rtt.SecureSigmoidChebyshev(ret))
xcc = sess.run(xc)
print("secure_Sigmoid_Chebyshev_Python cost: ", time.time()-start)
print("=========================== mpc op sigmoid 2")
print(xcc)

###########
rtt.deactivate()


# coding=utf-8
import re
import requests
import pandas as pd
from bs4 import BeautifulSoup
from lxml import etree
import time

headers = {
    'cookie': 'sessid=F3C5048F-5EFC-7DC2-D706-171B3F342202; aQQ_ajkguid=E6473576-0CFA-547A-EF66-9729C7E5C2C4; lps=http%3A%2F%2Fwww.anjuke.com%2F%7Chttps%3A%2F%2Fwww.sogou.com%2Flink%3Furl%3DDSOYnZeCC_q7j7wj5mgOqD1S3J7oRWO3; ctid=18; twe=2; __xsptplusUT_8=1; 58tj_uuid=eba8ad5e-f054-41aa-b36a-c28a5c2a062e; init_refer=https%253A%252F%252Fwww.sogou.com%252Flink%253Furl%253DDSOYnZeCC_q7j7wj5mgOqD1S3J7oRWO3; new_uv=1; als=0; new_session=0; wmda_uuid=4007ce9d02b60083c9b2c096f2e5dc8a; wmda_new_uuid=1; wmda_session_id_6289197098934=1545017039830-dffe50e6-70d0-7706; wmda_visited_projects=%3B6289197098934; __xsptplus8=8.1.1545017036.1545017044.3%233%7Cwww.sogou.com%7C%7C%7C%7C%23%23k4--hgzAYsNToYCPD0_3M1ppGohhWYm5%23',
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'
}

def store_info():
    output_file_name = 'ajk.xlsx'
    df = pd.DataFrame(get_from_ajk())
    df.to_excel(output_file_name, index=False)

def get_detail_from(url):
    time.sleep(3)

    print('正在获取'+url)
    content = requests.get(url,headers=headers)

    soup = BeautifulSoup(content.text, 'lxml')

    detail = {
        'price': soup.select('div.title-basic-info > span')[0].get_text(),
        'type': soup.select('div.title-basic-info > span')[1].get_text(),
        'area': soup.select('div.title-basic-info > span')[2].get_text(),
        'phone': get_ajax_phone(url)
    }

    return detail

def get_from_ajk():
    url = 'https://sz.zu.anjuke.com/fangyuan/shiyan/fx1-p1/'

    content = requests.get(url,headers=headers)

    soup = BeautifulSoup(content.text, 'lxml')

    house_detail_list = []

    for item in soup.select('div.zu-info'):
        href = item.select('a')[0].get('href')
        title = item.select('a')[0].get_text()
        des = item.select('p')[0].get_text()
        location = str(item.select('address.details-item')[0].get_text()).replace(' ', '')

        basic = {
            'href': href,
            'title': title,
            'des': des,
            'location': location
        }

        house_detail = {}
        house_detail.update(basic)
        house_detail.update(get_detail_from(href))
        house_detail_list.append(house_detail)

    return house_detail_list

def get_ajax_phone(j):
    # 定制请求头，必须保存cookie信息，否则无法获取手机号
    headers = {
        'cookie': 'sessid=F3C5048F-5EFC-7DC2-D706-171B3F342202; aQQ_ajkguid=E6473576-0CFA-547A-EF66-9729C7E5C2C4; lps=http%3A%2F%2Fwww.anjuke.com%2F%7Chttps%3A%2F%2Fwww.sogou.com%2Flink%3Furl%3DDSOYnZeCC_q7j7wj5mgOqD1S3J7oRWO3; ctid=18; twe=2; __xsptplusUT_8=1; 58tj_uuid=eba8ad5e-f054-41aa-b36a-c28a5c2a062e; init_refer=https%253A%252F%252Fwww.sogou.com%252Flink%253Furl%253DDSOYnZeCC_q7j7wj5mgOqD1S3J7oRWO3; new_uv=1; als=0; new_session=0; wmda_uuid=4007ce9d02b60083c9b2c096f2e5dc8a; wmda_new_uuid=1; wmda_session_id_6289197098934=1545017039830-dffe50e6-70d0-7706; wmda_visited_projects=%3B6289197098934; __xsptplus8=8.1.1545017036.1545017044.3%233%7Cwww.sogou.com%7C%7C%7C%7C%23%23k4--hgzAYsNToYCPD0_3M1ppGohhWYm5%23',
        'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'
    }

    # 随便获取一个详情界面的链接吧
    # j = "https://sz.zu.anjuke.com/fangyuan/1286839211"

    # 获取网页源码
    xq_link = requests.get(j, headers=headers)
    xq_html = etree.HTML(xq_link.text, etree.HTMLParser())

    # 利用正则获取参数
    # 匹配出参数所在的代码
    phone_data1 = xq_html.xpath('/html/body/div[3]/script[9]/text()')
    # 第一个参数
    regexp = r"broker_id:\'(.*?)\',"
    res1 = re.findall(regexp, phone_data1[0])
    req1 = res1[0]
    # print(req1[0])
    # 第二个参数
    regexp = r"token: \'(.*?)\',"
    res2 = re.findall(regexp, phone_data1[0])
    req2 = res2[0]
    # print(req2[0])
    # 第三个参数，发现这个参数是房屋编号，便使用xpath提取出来吧
    phone_data3 = xq_html.xpath('//*[@id="houseCode"]/text()')
    regexp = r'：(.*?)，'
    res3 = re.findall(regexp, phone_data3[0])
    req3 = res3[0]
    # print(req3)

    # 拼凑获取手机号的url
    url = "https://hz.zu.anjuke.com/v3/ajax/getBrokerPhone/?broker_id={}&token={}&prop_id={}"
    # 将刚才的参数填到url中
    phone_url = url.format(req1, req2, req3)
    # 获取手机号
    data1 = requests.get(phone_url, headers=headers)
    # print(data1.text)
    # 手机号码的正则匹配公式
    regexp = r'"val":"(.*?)"}'
    # 正则匹配
    res = re.findall(regexp, data1.text)
    phone = res[0]
    return phone

if __name__ == '__main__':
    print(store_info())


import sys
input = sys.stdin.readline

N = int ( input() )
for i in range ( N ) :
    data = int(input())

    arr = [0] * ( data+1 )
    if data in [1,2,3] :
        temp = [0,1,2,4]
        print(temp[data])
        continue
    if data >= 4 :
        arr[1] = 1
        arr[2] = 2
        arr[3] = 4

    for i in range ( 4 , data+1 ) :
        arr[i] = arr[i-1] + arr[i-2] + arr[i-3]

    print ( arr[data] )


#Darryl Alexander Fleurantin
#02/28/2022
#CSC 110 Homework 4 Working with Python Functions ~ Part 1

#function to store toy name, price, and how many was sold
def getToys():
    toyNum = int(input("How many toys are in your catalog? "))
    toyName = []
    toyPrice = []
    toySold = []
    for i in range(toyNum):
        name = input("Enter toy name: ")
        price = float(input("Enter toy price: "))
        sold = int(input("Enter number sold: "))
        toyName.append(name)
        toyPrice.append(price)
        toySold.append(sold)
    return toyName, toyPrice, toySold

#function to check toy search by returning its index
def searchToy(toyName, search):
    searchIndex = -1
    for i in range(len(toyName)):
        if toyName[i] == search:
            searchIndex = i
    return searchIndex

#function to check what was sold more than the toy at the index
def soldMore(toyName, toySold, searchIndex):
    soldmoreList = []
    for i in range(len(toySold)):
        if toySold[searchIndex] < toySold[i]:
            soldmoreList.append(toyName[i])
    return soldmoreList

#prints if toy is not identified or if it is it prints the price of the toy with how many toys sold more if any
def printResults(searchIndex, toyName, toyPrice, soldmoreList):
    if searchIndex != -1:
        print("The price of ", toyName[searchIndex], "is $", "{:,.2f}".format(toyPrice[searchIndex]))
        if len(soldmoreList) != 0:
            print("The toys that have more sold than ", toyName[searchIndex], "are: ")
            print(*soldmoreList, sep = '\n')
        else:
            print("No toys have sold more than ", toyName[searchIndex])
    else:
        print("The toy name you entered is not in our catalog.")
    return

def main():
    toyName, toyPrice, toySold = getToys()
    search = input("Enter a toy to find the price of: ")
    searchIndex = searchToy(toyName, search)
    soldmoreList = soldMore(toyName, toySold, searchIndex)
    printResults(searchIndex, toyName, toyPrice, soldmoreList)


"""Toy data generators."""

import numpy as np
import sklearn
import sklearn.datasets

def inf_train_gen(data, rng=None, batch_size=200):
  """Sample batch of synthetic data."""
  if rng is None:
    rng = np.random.RandomState()

  if data == "swissroll":
    data = sklearn.datasets.make_swiss_roll(n_samples=batch_size, noise=1.0)[0]
    data = data.astype("float32")[:, [0, 2]]
    data /= 5
    return data

  elif data == "circles":
    data = sklearn.datasets.make_circles(
        n_samples=batch_size, factor=.5, noise=0.08)[0]
    data = data.astype("float32")
    data *= 3
    return data

  elif data == "moons":
    data = sklearn.datasets.make_moons(n_samples=batch_size, noise=0.1)[0]
    data = data.astype("float32")
    data = data * 2 + np.array([-1, -0.2])
    return data

  elif data == "8gaussians":
    scale = 4.
    centers = [
        (1, 0), (-1, 0), (0, 1), (0, -1),
        (1. / np.sqrt(2), 1. / np.sqrt(2)),
        (1. / np.sqrt(2), -1. / np.sqrt(2)),
        (-1. / np.sqrt(2), 1. / np.sqrt(2)),
        (-1. / np.sqrt(2), -1. / np.sqrt(2))
        ]
    centers = [(scale * x, scale * y) for x, y in centers]

    dataset = []
    for _ in range(batch_size):
      point = rng.randn(2) * 0.5
      idx = rng.randint(8)
      center = centers[idx]
      point[0] += center[0]
      point[1] += center[1]
      dataset.append(point)
    dataset = np.array(dataset, dtype="float32")
    dataset /= 1.414
    return dataset

  elif data == "pinwheel":
    radial_std = 0.3
    tangential_std = 0.1
    num_classes = 5
    num_per_class = batch_size // 5
    rate = 0.25
    rads = np.linspace(0, 2 * np.pi, num_classes, endpoint=False)

    features = rng.randn(
        num_classes * num_per_class, 2) * np.array([radial_std, tangential_std])
    features[:, 0] += 1.
    labels = np.repeat(np.arange(num_classes), num_per_class)

    angles = rads[labels] + rate * np.exp(features[:, 0])
    rotations = np.stack([np.cos(angles), -np.sin(angles),
                          np.sin(angles), np.cos(angles)])
    rotations = np.reshape(rotations.T, (-1, 2, 2))

    return 2 * rng.permutation(np.einsum("ti,tij->tj", features, rotations))

  elif data == "2spirals":
    n = np.sqrt(np.random.rand(batch_size // 2, 1)) * 540 * (2 * np.pi) / 360
    d1x = -np.cos(n) * n + np.random.rand(batch_size // 2, 1) * 0.5
    d1y = np.sin(n) * n + np.random.rand(batch_size // 2, 1) * 0.5
    x = np.vstack((np.hstack((d1x, d1y)), np.hstack((-d1x, -d1y)))) / 3
    x += np.random.randn(*x.shape) * 0.1
    return x

  elif data == "checkerboard":
    x1 = np.random.rand(batch_size) * 4 - 2
    x2_ = np.random.rand(batch_size) - np.random.randint(0, 2, batch_size) * 2
    x2 = x2_ + (np.floor(x1) % 2)
    return np.concatenate([x1[:, None], x2[:, None]], 1) * 2

  elif data == "line":
    x = rng.rand(batch_size) * 5 - 2.5
    y = x
    return np.stack((x, y), 1)
  elif data == "cos":
    x = rng.rand(batch_size) * 5 - 2.5
    y = np.sin(x) * 2.5
    return np.stack((x, y), 1)
  else:
    raise NotImplementedError

class OnlineToyDataset(object):
  """Wrapper of inf_datagen."""

  def __init__(self, data_name):
    self.dim = 2
    self.data_name = data_name
    self.rng = np.random.RandomState()

    rng = np.random.RandomState(1)
    samples = inf_train_gen(self.data_name, rng, 5000)
    self.f_scale = np.max(np.abs(samples)) + 1
    self.int_scale = 2 ** 15 / (self.f_scale + 1)
    print("f_scale,", self.f_scale, "int_scale,", self.int_scale)

  def gen_batch(self, batch_size):
    return inf_train_gen(self.data_name, self.rng, batch_size)

  def data_gen(self, batch_size):
    while True:
      yield self.gen_batch(batch_size)

class OurOnlineToyDataset(object):
  """Wrapper of inf_datagen."""

  def __init__(self, data_name, vocab_size, discrete_dim):
    self.dim = vocab_size
    self.data_name = data_name
    self.rng = np.random.RandomState()

    rng = np.random.RandomState(1)
    samples = inf_train_gen(self.data_name, rng, 5000)
    self.f_scale = np.max(np.abs(samples)) + 1
    self.int_scale = self.dim ** (discrete_dim // 2 - 1) / (self.f_scale + 1)
    print("f_scale,", self.f_scale, "int_scale,", self.int_scale)

  def gen_batch(self, batch_size):
    return inf_train_gen(self.data_name, self.rng, batch_size)

  def data_gen(self, batch_size):
    while True:
      yield self.gen_batch(batch_size)

class OurPosiOnlineToyDataset(object):
  """Wrapper of inf_datagen."""

  def __init__(self, data_name, vocab_size, discrete_dim):
    self.dim = vocab_size
    self.data_name = data_name
    self.rng = np.random.RandomState()

    rng = np.random.RandomState(1)
    samples = inf_train_gen(self.data_name, rng, 5000)
    self.f_scale = np.max(np.abs(samples)) + 1
    self.int_scale = self.dim ** (discrete_dim // 2) / (self.f_scale + 1)
    print("f_scale,", self.f_scale, "int_scale,", self.int_scale)

  def gen_batch(self, batch_size):
    return inf_train_gen(self.data_name, self.rng, batch_size)

  def data_gen(self, batch_size):
    while True:
      yield self.gen_batch(batch_size)


#!/usr/bin/python
"""
This script modifies IntelliJ IDEA's workspace.xml so that it has the following Maven Import preferences:

  <component name="MavenImportPreferences">
    <option name="importingSettings">
      <MavenImportingSettings>
        <option name="downloadDocsAutomatically" value="true" />
        <option name="downloadSourcesAutomatically" value="true" />
        <option name="importAutomatically" value="true" />
      </MavenImportingSettings>
    </option>
  </component>

If the element exists previously, it is updated. However, if it previously contains any other options than
importAutomatically, it doesn't modify the settings file.

Usage: just run ./updater --help
"""
import logging
import xml.etree.ElementTree as ET
from optparse import OptionParser
from shutil import copyfile
from shutil import move
import glob
from os.path import isfile
import sys

__author__ = 'JuhoAutio'

# XML chunk being added

DOWNLOAD_DOCS_AUTOMATICALLY = \
    '        <option name="downloadDocsAutomatically" value="true" />\n'
DOWNLOAD_SOURCES_AUTOMATICALLY = \
    '        <option name="downloadSourcesAutomatically" value="true" />\n'
IMPORT_AUTOMATICALLY = \
    '        <option name="importAutomatically" value="true" />\n'
IMPORT_SETTINGS = \
    '\n    <option name="importingSettings">\n\
      <MavenImportingSettings>\n\
        ' + DOWNLOAD_DOCS_AUTOMATICALLY + '\
        ' + DOWNLOAD_SOURCES_AUTOMATICALLY + '\
        ' + IMPORT_AUTOMATICALLY + '\
      </MavenImportingSettings>\n\
    </option>\n'

def addDownloadDocs(struct):
    struct.append(ET.fromstring('<option name="downloadDocsAutomatically" value="true" />'))
    logging.info("added downloadDocsAutomatically=true")

def addDownloadSources(struct):
    struct.append(ET.fromstring('<option name="downloadSourcesAutomatically" value="true" />'))
    logging.info("added downloadSourcesAutomatically=true")

def addImportAutomatically(struct):
    struct.append(ET.fromstring('<option name="importAutomatically" value="true" />'))
    logging.info("added importAutomatically=true")

def addMavenImportPreferencestEl(project):
    project.append(ET.fromstring('\n<component name="MavenImportPreferences">\n\
    ' + IMPORT_SETTINGS + '\
  </component>\n'))
    logging.info("added MavenImportPreferences")

def addImportSettings(project):
    project.append(ET.fromstring(IMPORT_SETTINGS))
    logging.info("added importingSettings")

def allOptionsInPlace(options):
    all = ['importAutomatically', 'downloadDocsAutomatically', 'downloadSourcesAutomatically']
    return set(all) == set(map(lambda node: node.attrib['name'], options))

def writeFiles(file, xml):
    # write to a temporary file
    tempfile = file + "-temp"
    xml.write(tempfile)
    # copy the original into a backup
    copyfile(file, file + "-bak")
    # move the newly written file over the actual file
    move(tempfile, file)

def conditionalWrite(file, xml, write, message):
    if write:
        writeFiles(file, xml)
    return message

def update(file, write):

    try:
        xml = ET.parse(file)
    except ET.ParseError as err:
        print("ERROR: Couldn't parse file %s. Parsing failed with message '%s'." % (file, err.message))
        sys.exit(1)

    project = xml.getroot()
    if project.tag != 'project':
        print("ERROR: XML file with path %s doesn't have a <project> root element."
              " This doesn't seem to be an IDEA workspace file?" % file)
        sys.exit(1)

    maven = project.find("component[@name='MavenImportPreferences']")

    if not maven:

        # TODO test this case
        # add everything in one chunk
        addMavenImportPreferencestEl(project)
        return conditionalWrite(file, xml, write, "Update succeeded")

    elif len(maven) == 1:

        importingSettings = maven.find("option[@name='importingSettings']")

        if not importingSettings:

            # TODO test this case
            # add almost everything in one chunk
            addImportSettings(project)
            return conditionalWrite(file, xml, write, "Update succeeded")

        if len(importingSettings) != 1:

            # TODO test this case
            return "Skipping file '" + file + "' because it already contains: \n" + ET.tostring(importingSettings)

        else:

            options = importingSettings.find("MavenImportingSettings")

            if not options:

                # TODO test this case
                return "Skipping file '" + file + "' because didn't expect to not find MavenImportingSettings" \
                    "in this case.. This is not implemented, although it would be possible."

            elif len(options) == 1 and options[0].tag == 'option' and options[0].attrib['name'] == 'importAutomatically':

                logging.info("found importAutomatically option")

                addDownloadDocs(options)
                addDownloadSources(options)

                return conditionalWrite(file, xml, write, "added docs and sources")

            elif len(options) == 0:

                logging.info("found empty MavenImportingSettings")

                addDownloadDocs(options)
                addDownloadSources(options)
                addImportAutomatically(options)

                # TODO test this case
                return conditionalWrite(file, xml, write, "added docs, sources & import")

            elif allOptionsInPlace(options):

                return "All options already in place: \n" + ET.tostring(options)

            else:

                return "Skipping file '" + file + "' because it already contains: \n" + ET.tostring(options)

    else:

        # TODO test this case
        return "Skipping file '" + file + "' because it already contains: \n" + ET.tostring(maven)

# class access for unit testing
class Updater:

    def updateFile(self, file, write):
        return update(file, write)

#
# Script scope
#

def updateFiles(files):
    count = 0
    for file in files:
        if not isfile(file):
            print("ERROR: File doesn't exist with path %s" % file)
            sys.exit(1)
        logging.info('updating ' + file)
        result = update(file, True)
        if (not result and not (
            result.startswith("All options already in place")
            or result.startswith("Update succeeded")
            or result.startswith("added docs and sources")
        )):
            print(result)
        else:
            count += 1
            logging.info(result)
    print("updated %s files out of %s" % (count, len(files)))

# The commandline script runs here
if __name__ == '__main__':

    parser = OptionParser()
    parser.add_option("-d", "--directory", dest="directory",
                      help="directory of IDEA projects to scan & update. All immediate sub-folders are scanned for \
                           .idea/workspace.xml", metavar="DIRECTORY")
    parser.set_usage('%prog [<workspace file(s)>] [options]')
    (options, args) = parser.parse_args()

    # initialize info level logging to console
    logging.basicConfig(level=logging.WARNING)

    if args:
        updateFiles(args)
    elif options and options.directory:
        scanPattern = options.directory + "/*/.idea/workspace.xml";
        logging.info('scanning ' + scanPattern)
        files = glob.glob(scanPattern)
        if not files:
            logging.error('No workspace files found in the provided directory')
        else:
            updateFiles(files)
    else:
        print("\nERROR: No options or args provided.\n")
        parser.print_help()
        sys.exit(1)


def eva_class_arg(t37):
    if t37 == 1:
        eva_class_arg = 1
    elif t37 == 2:
        eva_class_arg = 1.3
    elif t37 == 3:
        eva_class_arg = 1.2
    elif t37 == 4:
        eva_class_arg = 1.5
    return eva_class_arg
# eva_class_arg评价类别系数由37评价类别决定

def job_number_arg(t39):
    if 1 <= t39 < 10:
        job_number_arg = 0
    elif 11 < t39 < 15:
        job_number_arg = 0.1
    elif 16 < t39 < 20:
        job_number_arg = 0.2
    elif 21 < t39 < 25:
        job_number_arg = 0.3
    elif 26 < t39 < 30:
        job_number_arg = 0.4
    elif 31 < t39 < 35:
        job_number_arg = 0.5
    elif t39 > 36:
        job_number_arg = 0.6
    return job_number_arg
# job_number_arg工作量系数由39接害岗位数量决定

def region_coefficient_arg(t40):
    if t40 == 0:
        region_coefficient_arg = 0
    elif t40 == 1:
        region_coefficient_arg = 0.1
    return region_coefficient_arg
# region_coefficient_arg地区系数由40地区系数决定

def type_num_arg(t41):
    if t41 == 1:
        type_num_arg = 0
    elif t41 == 2:
        type_num_arg = 0.3
    elif t41 == 3:
        type_num_arg = 0.5
    elif t41 == 4:
        type_num_arg = 0.6
    return type_num_arg
# type_num_arg多行业系数由41涉及行业类型决定

def tech_base_arg(t42):
    if t42 == 1:
        tech_base_arg = 700
    elif t42 == 2:
        tech_base_arg = 1100
    elif t42 == 3:
        tech_base_arg = 1200
    elif t42 == 4:
        tech_base_arg = 1300
    elif t42 == 5:
        tech_base_arg = 1500
    elif t42 == 6:
        tech_base_arg = 1700
    elif t42 == 7:
        tech_base_arg = 1800
    elif t42 == 8:
        tech_base_arg = 2000
    return tech_base_arg
# tech_base_arg提成基数由42行业类型（技术）决定

def dete_num_arg(t36,t43):
    if t36 == 1:
        if t43 < 20:
            dete_num_arg = 0.75
        elif  20<= t43 <= 60:
            dete_num_arg = 1
        elif t43 > 60:
            dete_num_arg = t43/60
    if t36 == 2:
        if t43 < 60:
            dete_num_arg = 0.75
        elif 60 <= t43 <= 200:
            dete_num_arg = 1
        elif t43 > 200:
            dete_num_arg = t43/200
    return dete_num_arg
# dete_num_arg样品系数由36业务分类和43检测样品数决定

def industry_arg(t44):
    if t44 == 1:
        industry_arg = 1
    elif t44 == 2:
        industry_arg = 2
    return industry_arg
# industry_arg行业系数由行业系数决定(实验室行业系数默认为1）

def dete_base_arg(t36):
    if t36 == 1:
        dete_base_arg = 3500
    if t36 == 2:
        dete_base_arg = 15000
    return dete_base_arg
# dete_base_arg提成基数由36业务分类决定

def dete_commission_percentage(t36):
    if t36 == 1:
        dete_commission_percentage = 0.05
    if t36 == 2:
        dete_commission_percentage = 0.025
    return dete_commission_percentage
# dete_commission_percentage由36业务分类决定

def lab_commission_percentage(t36):
    if t36 == 1:
        lab_commission_percentage = 0.035
    if t36 == 2:
        lab_commission_percentage = 0.018
    return lab_commission_percentage
# lab_commission_percentage由36业务分类决定


import ast

from flake8.options.manager import OptionManager

from flake8_fine_pytest import __version__ as version
from flake8_fine_pytest.watchers.modules_structure import ModulesStructureWatcher
from flake8_fine_pytest.watchers.unique_test_names import UniqueTestNamesWatcher
from flake8_fine_pytest.watchers.xfail_decorator import XfailWatcher
from flake8_fine_pytest.watchers.xfail_until_argument_watcher import (
    XfailUntilArgumentWatcher,
)
from flake8_fine_pytest.watchers.signature_complexity import SignatureComplexityWatcher
from flake8_fine_pytest.watchers.assert_count import AssertCountWatcher
from flake8_fine_pytest.watchers.usefixtures import UsefixturesWatcher
from flake8_fine_pytest.common_types import CheckResult

class FinePytestChecker:
    name = 'flake8-fine-pytest'
    version = version
    options = None

    _watchers = (
        XfailWatcher,
        ModulesStructureWatcher,
        SignatureComplexityWatcher,
        AssertCountWatcher,
        XfailUntilArgumentWatcher,
        UsefixturesWatcher,
        UniqueTestNamesWatcher,
    )

    def __init__(self, tree: ast.AST, filename: str):
        self.filename = filename
        self.tree = tree

    @classmethod
    def add_options(cls, parser: OptionManager) -> None:
        parser.add_option(
            '--allowed-test-directories',
            comma_separated_list=True,
            parse_from_config=True,
            default=['test_unit', 'test_integration'],
            help='Comma-separated list of allowed test directories',
        )
        parser.add_option(
            '--allowed-test-arguments-count',
            type=int,
            parse_from_config=True,
            default=6,
            help='Allowed arguments in test signature',
        )
        parser.add_option(
            '--allowed-assert-count',
            type=int,
            parse_from_config=True,
            default=6,
            help='Allowed assert statement count in test',
        )
        parser.add_option(
            '--xfail-check-until',
            action='store_true',
            default=True,
            parse_from_config=True,
            help='Check that xfail has until parameter',
        )
        parser.add_option(
            '--xfail-check-reason',
            action='store_true',
            default=True,
            parse_from_config=True,
            help='Check that xfail has reason parameter',
        )
        parser.add_option(
            '--force-unique-test-names',
            action='store_true',
            parse_from_config=True,
            default=True,
            help='Enforce unqiue test names',
        )
        parser.add_option(
            '--force-usefixtures',
            action='store_true',
            parse_from_config=True,
            default=True,
            help='Enforce usefixtures validator',
        )

    @classmethod
    def parse_options(cls, options: str) -> None:
        cls.options = options

    def run(self) -> CheckResult:
        for watcher_class in self._watchers:
            watcher = watcher_class(self.options, self.filename, self.tree)

            if watcher.should_run():
                watcher.run()

            yield from (  # type: ignore
                (*error, type(self))
                for error in watcher.errors
            )


import searchForTokens
import settings
import tokenizer
import math
import heapq

def calculate_cosine_sim_slow(doc_vec, query):
    wt = 0.0
    score = 0.0
    product = 0.0
    for key in doc_vec:
        tfidf = (1 + math.log(doc_vec[key])) * math.log((settings.total_files/settings.doc_freq[key]))
        wt = wt+ tfidf**2
        if key in query:
           product = product + tfidf**2
    ## add query tfidf
    return product

def calculate_cosine_sim(doc_vec, query):
    wt = doc_vec[0]
    vec = doc_vec[1]
    cos_prod = 0.0
    for key in query:
        cos_prod = cos_prod + vec.get(key,0)**2
    return (cos_prod/wt)

def rank_docs(doc_ids, query):
    ordered_results = []
    for doc_id in doc_ids:
        doc_vec = settings.read_json(settings.file_tf_path+doc_id+".json")
        score = calculate_cosine_sim(doc_vec, query)
        if(len(ordered_results) > 100):
            heapq.heappushpop(ordered_results,(-score, doc_id))
        else:
            heapq.heappush(ordered_results, (-score, doc_id))
    return ordered_results

def print_results(ranked_doc):
    while ranked_doc:
        (score, doc_id) = heapq.heappop(ranked_doc)
        print('score: '+str(score)+' url: '+ settings.code2url[doc_id])

if __name__ == "__main__":
    settings.load_data()
    query = 'artificial intelligence'
    _, doc_ids, query = searchForTokens.process_query(query)
    ranked_doc = rank_docs(doc_ids, query)
    print_results(ranked_doc)


import gramfuzz
from gramfuzz.fields import *
from gramfuzz.rand import *

class NRef(Ref):
    cat = "rtf_def"
class NDef(Def):
    cat = "rtf_def"

Def("rtf", And("{", NRef("header"), NRef("document")," }"), cat="rtf", sep=" ")

NDef("header", And("\\rtf1 ", Opt("\\fbidis "), NRef("character set"), Opt(NRef("from")), NRef("deffont"),
    NRef("deflang"), Opt(NRef("listtables"))))
NDef("document", "{fuzzer}")

NDef("character set", Or("\\ansi ", "\\mac ", "\\pc ", "\\pca "))
NDef("from", Or("\\fromtext ", "\\fromhtml "))
NDef("deffont", Or("\\deff1 ", "\\adeff1 "))
NDef("deflang", Or("\\deflang1 ", "\\adeflang1 "))
NDef("listtables", And("{\\*", "\\listtable ", Opt(NRef("listpicture")), STAR(NRef("list"), max=10), "}"))
NDef("listpicture", And("{\\*\\listpicture ", String(min=1, max=2), "}"))

NDef("list", And("\\list ", "\\listtemplateid ", Or("\\listsimple ", "\\listhybrid"),
    STAR(NRef("listlevel")), "\\listrestarthdn ", "\\listid" + str(randint(10)), "\\listname ", data(20, "\x80\x90khoanx?"), ";"))
NDef("listlevel", "\\listlevel ")


import numpy as np

def compute_fitness_scores_list(population, distance_matrix, flow_matrix):
    matrices_size = distance_matrix.shape[0]
    fitness_scores_list = []
    for chromosome in population:
        assert len(chromosome) == len(set(chromosome))
        chromosome_fitness_sum = 0
        for x in range(matrices_size):
            for y in range(matrices_size):
                chromosome_fitness_sum += distance_matrix[x, y] * flow_matrix[chromosome[x] - 1, chromosome[y] - 1]
        fitness_scores_list.append(chromosome_fitness_sum)

    return fitness_scores_list

def compute_fitness_scores(chromosome, distance_matrix, flow_matrix):
    matrices_size = distance_matrix.shape[0]
    chromosome_fitness_sum = 0
    for x in range(matrices_size):
        for y in range(matrices_size):
            chromosome_fitness_sum += distance_matrix[x, y] * flow_matrix[chromosome[x] - 1, chromosome[y] - 1]
    return chromosome_fitness_sum

def get_normalized_result_of_fitness_function_scores_list(fitness_scores_list):
    map_to_minimization_problem = list(map(lambda value: 1. / value, fitness_scores_list))
    normalized_results = np.array(map_to_minimization_problem) / np.sum(map_to_minimization_problem)
    return normalized_results


'''
    Jose Manuel Perez Puig -
    -1- Crear una base de datos SQLite con una tabla libros.
        libros(id, titulo, autor, genero, altura, editor)
    -2- Crear una función que lea los datos de los libros contenidos en el archivo libros.csv
        y los inserte en la tabla libros de la base de datos.
    -3- Obtener sendos resumenes de la BD. Uno por editorial y otro por autor
'''
import os
from clase_crud_sqlite import Sqlite
from clase_csv2Sqlite import Csv2TableSqlite

BASE_DATOS = 'libreria.db'
TABLA = 'libros'

def leer_datos_csv_a_tabla():
    '''
        Se crea la base de datos. Se crea la tabla y se llena con el contenido del csv.
    '''
    carga = Csv2TableSqlite('libros.csv', BASE_DATOS, TABLA)
    return carga.ejecutar()

def resumen_por_autor(filtro=None):
    '''
        Proporciona el conjunto de filas de la tabla agrupadas por autor con el numero de libros del mismo.
        Opcionalmente podemos filtrar esos resultados por el numero de libros. Debe ser un número > 0
    '''
    cadena = ''
    if filtro:
        cadena = f'(con más de {filtro} libros)'
        consulta_conteo = f'''select Autor, count(*) as num_libros
                            from {TABLA}
                            group by Autor
                            having num_libros > {filtro}
                            order by count(*) desc'''
    else:
        consulta_conteo = f'select Autor, count(*) as num_libros from {TABLA} group by Autor order by count(*) desc'
    print('')
    print(f'DATOS DE LA BIBLIOTECA: libros por autor ' + cadena)
    print('-------------------------------------------------------------------------')
    db = Sqlite(BASE_DATOS)
    return db.leer_tabla_condicion_cuenta(consulta_conteo)

def resumen_por_editorial(filtro=None):
    '''
        Proporciona el conjunto de filas de la tabla agrupadas por la editorial con el numero de libros de la misma.
        Opcionalmente podemos filtrar esos resultados por el numero de libros. Debe ser un número > 0
    '''
    cadena = ''
    if filtro:
        cadena = f'(con más de {filtro} libros)'
        consulta_conteo = f'''select Editor, count(*) as num_libros
                            from {TABLA}
                            group by Editor
                            having num_libros > {filtro}
                            order by count(*) desc'''
    else:
        consulta_conteo = f'select Editor, count(*) as num_libros from {TABLA} group by Editor order by count(*) desc'
    print('')
    print(f'DATOS DE LA BIBLIOTECA: libros por editorial ' + cadena)
    print('---------------------------------------------------------------------------')
    db = Sqlite(BASE_DATOS)
    return db.leer_tabla_condicion_cuenta(consulta_conteo)

def mostrar_resumen(resp):
    '''
        Muestra por pantalla los datos asociados al resumen pedido (resp)
    '''
    print('')
    for elem in resp:
        if elem[0] != '':
            print(f'{elem[0]}         {elem[1]}')

def main():
    '''
        Código de la aplicación principal
    '''
    os.system('clear')
    num = leer_datos_csv_a_tabla()
    print(f'Se cargaron {num} registros en la tabla {TABLA} de la base de datos {BASE_DATOS}')

    sigamos = True
    while sigamos:
        print('')
        print('¿Qué datos quiere revisar de nuestra biblioteca?\n')
        print('-1- Resumen de libros por Autor')
        print('-2- Resumen de libros por Editorial')
        print('')
        valor = input(f'Por favor, introduzca el número asociado a su selección: (Enter para salir)\n')
        if valor == '1':
            fil = input(f'Por favor, indique un numero mínimo de libros (>1, Enter para "todos"): ')
            if fil == '':
                filtro = 0
            else:
                filtro = int(fil)
            os.system('clear')
            resp = resumen_por_autor(filtro)
            mostrar_resumen(resp)
        elif valor == '2':
            fil = input(f'Por favor, indique un numero mínimo de libros (>1, Enter para "todos"): ')
            if fil == '':
                filtro = 0
            else:
                filtro = int(fil)
            os.system('clear')
            resp = resumen_por_editorial(filtro)
            mostrar_resumen(resp)
        elif valor == '':
            sigamos = False

# ==========================================
main()


from collections import defaultdict

# The built-in enumerate() function can iterate over a sequence, and keep
# track of which element of the sequence is currently being processed.
my_list = ['a', 'b', 'c']
for idx, val in enumerate(my_list):
    print(idx, val)

# Pass in a start argument.
for idx, val in enumerate(my_list, 1):
    print(idx, val)

word_summary = defaultdict(list)
with open('somefile.txt', 'r') as f:
    lines = f.readlines()
for idx, line in enumerate(lines):
    # Create a list of words in current line.
    words = [w.strip().lower() for w in line.split()]
    for word in words:
        word_summary[word].append(idx)
print(word_summary)

# Unpacking tuples when applying enumerate() to a sequence of tuples.
data = [(1, 2), (3, 4), (5, 6), (7, 8)]
for n, (x, y) in enumerate(data):
    print(n, x, y)
try:
    for n, x, y in enumerate(data):
        print(n, x, y)
except ValueError as e:
    print(e)


#!/usr/bin/env python3
# coding: utf-8
"""
@author: Ping Qiu  qiuping1@genomics.cn
@last modified by: Ping Qiu
@file:scatter.py
@time:2021/04/14

change log:
    2021/07/12 params change. by: qindanhua.
"""
from matplotlib.cm import get_cmap
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, to_hex, Normalize, LinearSegmentedColormap
from matplotlib import gridspec
import numpy as np
import pandas as pd
from typing import Optional, Union
import seaborn as sns
from ..stereo_config import stereo_conf

def base_scatter(
        x: Optional[Union[np.ndarray, list]],
        y: Optional[Union[np.ndarray, list]],
        hue: Optional[Union[np.ndarray, list]] = None,
        ax=None,
        title: str = None,
        x_label: str = None,
        y_label: str = None,
        color_bar: bool = False,
        color_bar_reverse: bool = False,
        bad_color: str = "lightgrey",
        dot_size: int = None,
        palette: Optional[Union[str, list]] = 'stereo',
        invert_y: bool = True,
        legend_ncol=2,
        show_legend=True,
        show_ticks=False,
        vmin=None,
        vmax=None,
        SegmentedColormap=None,
):  # scatter plot, Expression matrix spatial distribution after clustering
    """
    scatter plotter

    :param invert_y: whether to invert y-axis.
    :param x: x position values
    :param y: y position values
    :param hue: each dot's values, use for color set, eg. ['1', '3', '1', '2']
    :param ax: matplotlib Axes object
    :param title: figure title
    :param x_label: x label
    :param y_label: y label
    :param color_bar: show color bar or not, color_values must be int array or list when color_bar is True
    :param color_bar_reverse: if True, reverse the color bar, defaults to False
    :param bad_color: the name list of clusters to show.
    :param dot_size: marker size.
    :param palette: customized colors
    :param legend_ncol: number of legend columns
    :param show_legend
    :param show_ticks
    :param vmin:
    :param vmax:

    :return: matplotlib Axes object

    color_values must be int array or list when color_bar is True

    """
    if not ax:
        _, ax = plt.subplots(figsize=(7, 7))
    dot_size = 120000 / len(hue) if dot_size is None else dot_size
    # add a color bar
    if color_bar:
        colors = stereo_conf.linear_colors(palette, reverse=color_bar_reverse)
        cmap = ListedColormap(colors)
        cmap.set_bad(bad_color)

        sns.scatterplot(x=x, y=y, hue=hue, ax=ax, palette=cmap, size=hue, linewidth=0, marker="s",
                        sizes=(dot_size, dot_size), vmin=vmin, vmax=vmax)
        if vmin is None and vmax is None:
            norm = plt.Normalize(hue.min(), hue.max())
            sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
            sm.set_array([])
            ax.figure.colorbar(sm)
        ax.legend_.remove()
    else:
        from natsort import natsorted
        import collections
        g = natsorted(set(hue))
        colors = stereo_conf.get_colors(palette)
        color_dict = collections.OrderedDict(dict([(g[i], colors[i]) for i in range(len(g))]))
        sns.scatterplot(x=x, y=y, hue=hue, hue_order=g, linewidth=0, marker="s",
                        palette=color_dict, size=hue, sizes=(dot_size, dot_size), ax=ax)
        handles, labels = ax.get_legend_handles_labels()
        ax.legend_.remove()
        ax.legend(handles, labels, ncol=legend_ncol, bbox_to_anchor=(1.02, 1),
                  loc='upper left', borderaxespad=0, frameon=False)
        for lh in ax.legend_.legendHandles:
            lh.set_alpha(1)
            lh._sizes = [40]
    if invert_y:
        ax.invert_yaxis()
    if not show_legend:
        ax.legend_.remove()

    if not show_ticks:
        ax.set_aspect('equal', adjustable='datalim')
    ax.set_title(title, fontsize=18, fontweight='bold')
    ax.set_ylabel(y_label, fontsize=15)  # set y-axis labels
    ax.set_xlabel(x_label, fontsize=15)  # set x-axis labels
    if not show_ticks:
        ax.set_yticks([])
        ax.set_xticks([])
    return ax.get_figure()

def multi_scatter(
        x,
        y,
        hue: Union[np.ndarray, list] = None,
        ncols: int = 2,
        title: Union[list, np.ndarray] = None,
        x_label: Union[list, np.ndarray] = None,
        y_label: Union[list, np.ndarray] = None,
        color_bar: bool = False,
        color_bar_reverse: bool = False,
        bad_color: str = "lightgrey",
        dot_size: int = None,
        palette: Optional[Union[np.ndarray, list, str]] = 'stereo',
        vmin=None,
        vmax=None,
):
    """
    plot multiple scatters

    :param x: x position values
    :param y: y position values
    :param hue: each dot's values, use for color set, eg. ['1', '3', '1', '2']
    :param ncols number of figure columns
    :param title: figure title
    :param x_label: x label
    :param y_label: y label
    :param color_bar: show color bar or not, color_values must be int array or list when color_bar is True
    :param bad_color: the name list of clusters to show.
    :param dot_size: marker size.
    :param palette: customized colors
    :param vmin:
    :param vmax:

    :return: matplotlib Axes object

    """
    ncols = min(ncols, len(hue))
    nrows = np.ceil(len(hue) / ncols).astype(int)
    # each panel will have the size of rcParams['figure.figsize']
    fig = plt.figure(figsize=(ncols * 10, nrows * 8))
    left = 0.2 / ncols
    bottom = 0.13 / nrows
    axs = gridspec.GridSpec(
        nrows=nrows,
        ncols=ncols,
        left=left,
        right=1 - (ncols - 1) * left - 0.01 / ncols,
        bottom=bottom,
        top=1 - (nrows - 1) * bottom - 0.1 / nrows,
        # hspace=hspace,
        # wspace=wspace,
    )
    for i, cv in enumerate(hue):
        ax = fig.add_subplot(axs[i])  # ax = plt.subplot(axs[i]) || ax = fig.add_subplot(axs[1, 1]))
        base_scatter(x, y, cv,
                     ax=ax,
                     title=title[i] if title else None,
                     x_label=x_label[i] if x_label else None,
                     y_label=y_label[i] if y_label else None,
                     color_bar=color_bar,
                     color_bar_reverse=color_bar_reverse,
                     bad_color=bad_color,
                     dot_size=dot_size,
                     palette=palette,
                     vmin=vmin,
                     vmax=vmax,
                     )
    return fig

def volcano(
        data: Optional[pd.DataFrame], x: Optional[str], y: Optional[str], hue: Optional[str],
        hue_order=('down', 'normal', 'up'),
        palette=("#377EB8", "grey", "#E41A1C"),
        alpha=1, s=15,
        label: Optional[str] = None, text_visible: Optional[str] = None,
        x_label='log2(fold change)', y_label='-log10(pvalue)',
        vlines=True, cut_off_pvalue=0.01, cut_off_logFC=1,
):
    """
    volcano plot

    :param data: data frame
    :param x: key in data, variables that specify positions on the x axes.
    :param y: key in data, variables that specify positions on the y axes.
    :param hue: key in data, variables that specify maker gene.
    :param hue_order:
    :param palette: color set
    :param alpha: visible alpha
    :param s: dot size
    :param label: key in data, variables that specify dot label
    :param text_visible: key in data, variables that specify to show this dot's label or not
    :param x_label:
    :param y_label:
    :param cut_off_pvalue: used when plot vlines
    :param cut_off_logFC: used when plot vlines
    :param vlines: plot vlines or not
    :return:
    """
    ax = sns.scatterplot(
        data=data,
        x=x, y=y, hue=hue,
        hue_order=hue_order,
        palette=palette,
        alpha=alpha, s=s,
    )
    ax.spines['right'].set_visible(False)  # remove right border
    ax.spines['top'].set_visible(False)  # remove top border
    ax.set_ylabel(y_label, fontweight='bold')  # set y-axis labels
    ax.set_xlabel(x_label, fontweight='bold')  # set x-axis labels

    if vlines:
        xmin = int(data['x'].min())
        xmax = int(np.percentile(np.array(data['x']), [90])[0])
        ymin = int(data['y'].min())
        ymax = int(np.percentile(np.array(data['y']), [90])[0])
        ax.vlines(-cut_off_logFC, ymin, ymax, color='dimgrey', linestyle='dashed', linewidth=1)  # draw vertical lines
        ax.vlines(cut_off_logFC, ymin, ymax, color='dimgrey', linestyle='dashed', linewidth=1)  # draw vertical lines
        ax.hlines(-np.log10(cut_off_pvalue), xmin, xmax, color='dimgrey', linestyle='dashed', linewidth=1)  # draw vertical lines
        # ax.set_xticks(range(xmin, xmax, 4))# set x-axis labels
        # ax.set_yticks(range(ymin, ymax, 2))# set y-axis labels
    if label and text_visible:
        for line in range(0, data.shape[0]):
            if data[text_visible][line]:
                ax.text(
                    data[x][line] + 0.01,
                    data[y][line],
                    data[label][line],
                    horizontalalignment='left',
                    size='medium',
                    color='black',
                    # weight='semibold'
                )
    return ax.get_figure()

def marker_gene_volcano(
        data,
        text_genes=None,
        cut_off_pvalue=0.01,
        cut_off_logFC=1,
        **kwargs
):
    df = data
    if 'log2fc' not in df.columns or 'pvalues' not in df.columns:
        raise ValueError(f'data frame should content log2fc and pvalues columns')
    df['x'] = df['log2fc']
    df['y'] = -df['pvalues'].apply(np.log10)
    df.loc[(df.x > cut_off_logFC) & (df.pvalues < cut_off_pvalue), 'group'] = 'up'
    df.loc[(df.x < -cut_off_logFC) & (df.pvalues < cut_off_pvalue), 'group'] = 'down'
    df.loc[(df.x >= -cut_off_logFC) & (df.x <= cut_off_logFC) | (df.pvalues >= cut_off_pvalue), 'group'] = 'normal'
    if text_genes is not None:
        # df['text'] = df['group'] == 'up'
        df['label'] = df['genes'].isin(text_genes)
        fig = volcano(df, x='x', y='y', hue='group', label='genes', text_visible='label',
                     cut_off_pvalue=cut_off_pvalue,
                     cut_off_logFC=cut_off_logFC,
                     **kwargs)
    else:
        fig = volcano(df, x='x', y='y', hue='group',
                     cut_off_pvalue=cut_off_pvalue, cut_off_logFC=cut_off_logFC,
                     **kwargs)
    return fig

def highly_variable_genes(
        data: Optional[pd.DataFrame]
):
    """
    scatter of highly variable genes

    :param data: pd.DataFrame

    :return: figure object
    """
    seurat_v3_flavor = "variances_norm" in data.columns
    if seurat_v3_flavor:
        y_label = 'variances'
    else:
        y_label = 'dispersions'
    data['gene type'] = ['highly variable genes' if i else 'other genes' for i in data['highly_variable']]
    fig = plt.figure(figsize=(12, 6))
    ax1 = fig.add_subplot(121)
    ax2 = fig.add_subplot(122)
    sns.scatterplot(x="means", y=y_label + '_norm',
                    hue='gene type',
                    hue_order=('highly variable genes', 'other genes'),
                    palette=("black", "#ccc"),
                    alpha=1,
                    s=15,
                    data=data, ax=ax1
                    )
    sns.scatterplot(x="means", y=y_label,
                    hue='gene type',
                    hue_order=('highly variable genes', 'other genes'),
                    palette=("black", "#ccc"),
                    alpha=1,
                    s=15,
                    data=data, ax=ax2
                    )
    ax1.set_xlabel('mean expression of genes', fontsize=15)
    ax1.set_ylabel('dispersions of genes (normalized)', fontsize=15)
    ax2.set_xlabel('mean expression of genes', fontsize=15)
    ax2.set_ylabel('dispersions of genes (not normalized)', fontsize=15)
    return fig


from time import ctime
from evaluate import classify
from naive_bayes import *
from io_utils import *

def main():
    print("==> Main app start at:", ctime())

    print("==> File reading phase start at:", ctime())
    data_list = read_training_data('../input/training_data.csv')
    labels_list = read_training_labels('../input/training_labels.csv')
    test_list = read_test_data('../input/test_data.csv')
    print("<== File reading phase end at:", ctime())

    print("==> training phase start at:", ctime())
    classes = stat_classes(labels_list)
    ratio = cal_class_ratio(labels_list, classes)
    probs = cal_prob_classes(data_list, labels_list, classes)
    print("<== training phase end at :", ctime())

    print("==> test phase start at :", ctime())
    results = classify(test_list, probs, classes, ratio)
    print("<== test phase end at :", ctime())
    output_test_result(results, '../output/predicted_labels.csv')
    print("<== Main app end at:", ctime())

if __name__ == "__main__":
    main()


import wolframalpha
import tkinter as tk

# wolfram stuff
client = wolframalpha.Client("G4H2VA-496G3827Y9")

# GUI
HEIGHT = 100
WIDTH = 600

root = tk.Tk()
root.title("Robby")

canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

frame = tk.Frame(root, bg='#ff4d4d', bd='4')
frame.place(relx=0.0, rely=0.0, relwidth=1, relheight=0.4)

labelFrame = tk.Frame(root, bg='#ff6666')
labelFrame.place(rely=0.5, relwidth=1, relheight=0.5)

# Query entry
entry = tk.Entry(frame, bg='#ff6666', fg='white', font='12')
entry.place(relwidth=0.8, relheight=1)

# Test label
output = tk.StringVar()
label = tk.Label(labelFrame, textvariable=output)
label.place(relwidth=1, relheight=1)

# Enter button

def readText():
    res = client.query(entry.get())
    output.set(next(res.results).text)
    print(next(res.results).text)
    entry.delete(0, 'end')

enterBttn = tk.Button(frame, text="Enter",
                      command=readText, bg='#ff4d4d',  font='15', fg='white')
enterBttn.place(relx=0.84, rely=.1, relwidth=0.15, relheight=0.8)

root.mainloop()