"""IngrafenApp URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from cotizacion import views
from . import settings
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path('admin/', admin.site.urls),
    path("",views.home,name="home"),
    path("solicitud/", views.solicitud_cot, name="solicitud"),
    path("registro/",views.creacion_usuario, name="creacion_usuario"),
    path("login/",views.user_login,name="login"),
    path("logout/", views.user_logout,name="logout"),
    path("solicitudes/",views.solicitudes_existentes, name="solicitudes_existentes"),
    path("cotizacion/",views.cotizaciones_completadas, name="cotizaciones_completadas"),
    path("crear_material/",views.creacion_material,name="crear_material"),
    path("crear_cliente/",views.creacion_cliente,name="crear_cliente"),
    path("crear_trabajo/",views.creacion_trabajo,name="crear_trabajo"),
    path("contactenos/",views.contactenos,name="contactenos"),
    path("compañia/", views.quienes_somos,name="quienes_somos"),
    path("servicios/",views.servicios,name="servicios"),
    path("reportes/",views.reportes,name="reportes"),
    path("solicitud_ot/",views.solicitud_ot,name="solicitud_ot"),
    path("ordenes_por_aperturar/",views.ordenes_por_aperturar,name="ordenes_por_aperturar"),
    path("ordenes_aperturadas/",views.ordenes_aperturadas,name="ordenes_aperturadas"),
    path("ordenes_en_proceso/",views.ordenes_en_proceso,name="ordenes_en_proceso"),
    path("ordenes_sin_fecha/",views.ordenes_sin_fecha,name="ordenes_sin_fecha"),
    path("error01/",views.error01,name="error01"),
    path("clientes_ot/",views.creacion_cliente_ot,name="creacion_cliente_ot"),
    path("bloqueo_clientes/",views.bloqueo_clientes,name="bloqueo_clientes"),
    path("confirmacion_material/",views.confirmacion_material,name="confirmacion_material"),
    path("cambio_contraseña/",views.change_password,name="cambio_contraseña"),
    path("eliminar_solicitud/",views.eliminar_solicitud,name="eliminar_solicitud"),
    path("solicitud_gigantografia",views.solicitud_gigantografia,name="solicitud_gigantografia"),
    path("crear_material_gig",views.creacion_material_gig,name="crear_material_gig"),
    path("crear_trabajo_gig",views.creacion_trabajo_gig,name="crear_trabajo_gig"),
    path("ordenes_por_aperturar_gig",views.ordenes_por_aperturar_gig,name="ordenes_por_aperturar_gig"),
    path("ordenes_en_proceso_gig/",views.ordenes_en_proceso_gig,name="ordenes_en_proceso_gig"),
    path("ordenes_sin_fecha_gig/",views.ordenes_sin_fecha_gig,name="ordenes_sin_fecha_gig"),
    path("ordenes_aperturadas_gig/",views.ordenes_aperturadas_gig,name="ordenes_aperturadas_gig"),
    path("bloqueo_usuario/",views.bloqueo_usuario,name="bloqueo_usuario"),
    path("cambio_vendedor/",views.cambio_vendedor,name="cambio_vendedor"),
    path("modificar/",views.modificar,name="modificar"),

]

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


import torch.nn as nn
import torch.nn.functional as F
from cnns.nnlib.pytorch_layers.conv_picker import Conv

def get_conv(args, in_channels, out_channels, kernel_size, stride=1,
             padding=0, bias=True):
    return Conv(kernel_sizes=[kernel_size], in_channels=in_channels,
                out_channels=[out_channels], strides=[stride],
                padding=[padding], args=args, is_bias=bias).get_conv()

class NetSynthetic(nn.Module):
    def __init__(self, args):
        super(NetSynthetic, self).__init__()
        self.args = args
        out_channels1 = 5
        self.conv1 = get_conv(args, in_channels=1, out_channels=out_channels1,
                              kernel_size=5, stride=1)
        self.out_channels2 = 10
        self.conv2 = get_conv(args, in_channels=out_channels1,
                              out_channels=self.out_channels2,
                              kernel_size=5, stride=1)

        self.fc1 = nn.Linear(4 * 4 * self.out_channels2, 500)
        self.fc2 = nn.Linear(500, 10)

    def forward(self, x):
        x = self.conv1(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2, 2)
        x = F.relu(self.conv2(x))
        x = F.max_pool2d(x, 2, 2)
        x = x.view(-1, 4 * 4 * self.out_channels2)
        x = F.relu(self.fc1(x))
        x = self.fc2(x)
        return F.log_softmax(x, dim=1)


# -*- coding: utf-8 -*-
from flask import request, jsonify
from . import api
from application import db
from application.models.menu import Menu
from application.models.mixin import SerializableModelMixin
from application.lib.rest.auth_helper import required_token, required_admin

# create - name, category
@api.route('/menus', methods=['POST'])
@required_token
def create_menus():
    request_params = request.get_json()
    name = request_params.get('name')
    category = request_params.get('category')

    # name이 제대로 입력이 안된 경우
    if name is None:
        return jsonify(
            userMessage="메뉴명을 기입해주세요."
        ), 400

    # category가 제대로 입력이 안된 경우
    if category is None:
        return jsonify(
            userMessage="카테고리 정보를 기입해주세요."
        ), 400

    # 이미 등록되어있는지 확인
    q = db.session.query(Menu).filter(Menu.name == name, Menu.category == category)
    if q.count() > 0:
        return jsonify(
            userMessage="이미 등록되어있는 메뉴입니다."
        ), 409

    try:
        for key in request_params.keys():
            request_params[SerializableModelMixin.to_snakecase(key)] = request_params.pop(key)

        menu = Menu(**request_params)
        db.session.add(menu)
        db.session.commit()

        return jsonify(
            data=menu.serialize()
        ), 200
    except:
        return jsonify(
            userMessage="오류가 발생했습니다. 관리자에게 문의해주세요."
        ), 403

# read
@api.route('/menus/<int:menu_id>', methods=['GET'])
@required_token
def get_menu_by_id(menu_id):
    try:
        menu = db.session.query(Menu).get(menu_id)
        return jsonify(
            data=menu.serialize()
        ), 200

    except:
        return jsonify(
            userMessage="해당 메뉴를 찾을 수 없습니다."
        ), 404

# read
@api.route('/menus', methods=['GET'])
@required_token
def get_menus():
    q = db.session.query(Menu)

    name = request.args.get('name')
    category = request.args.get('category')

    if name is not None:
        q = q.filter(Menu.name == name)

    if category is not None:
        q = q.filter(Menu.category == category)

    return jsonify(
        data=map(lambda obj: obj.serialize(), q)
    ), 200

# update
@api.route('/menus/<int:menu_id>', methods=['PUT'])
@required_token
def update_menu(menu_id):
    menu = db.session.query(Menu).filter(Menu.id == menu_id).one()

    if menu is None:
        return jsonify(
            userMessage="메뉴를 찾을 수 없습니다."
        ), 404

    request_params = request.get_json()
    if request_params.get('name'):
        name = request_params.get('name')
    else:
        name = menu.name

    if request_params.get('category'):
        category = request_params.get('category')
    else:
        category = menu.category

    q = db.session.query(Menu).filter(Menu.name == name, Menu.category == category)
    if q.count() > 0:
        if q.one() == menu:
            pass
        else:
            return jsonify(
                    userMessage="기존에 동일한 메뉴가 있습니다."
                )
    else:
        menu.name = name
        menu.category = category
        db.session.commit()

    return get_menu_by_id(menu_id)

# delete 필요없을듯하당
@api.route('/menus/<int:menu_id>', methods=['DELETE'])
@required_admin
def delete_menu(menu_id):
    try:
        menu = db.session.query(Menu).get(menu_id)

        try:
            db.session.delete(menu)
            db.session.commit()
            return jsonify(
                userMessage="삭제가 완료되었습니다."
            ), 200
        except:
            return jsonify(
                userMessage="삭제 실패."
            ), 403

    except:
        return jsonify(
            userMessage="메뉴를 찾을 수 없습니다."
        ), 404


import sys
import pandas as pd
import numpy as np
from scipy.stats import chi2_contingency
from scipy.stats import mannwhitneyu

OUTPUT_TEMPLATE = (
    '"Did more/less users use the search feature?" p-value:  {more_users_p:.3g}\n'
    '"Did users search more/less?" p-value:  {more_searches_p:.3g} \n'
    '"Did more/less instructors use the search feature?" p-value:  {more_instr_p:.3g}\n'
    '"Did instructors search more/less?" p-value:  {more_instr_searches_p:.3g}'
)

def main():
    searchdata_file = sys.argv[1]
    data = pd.read_json(searchdata_file,orient='records',lines=True)
    even = data[data['uid']%2 == 0].reset_index().drop(['index'],axis = 1)
    odd = data[data['uid']%2 != 0].reset_index().drop(['index'], axis=1)

    even_not_search = even[even['search_count'] == 0]
    even_search = even[even['search_count'] !=0 ]
    odd_not_search = odd[odd['search_count'] == 0]
    odd_search = odd[odd['search_count'] != 0]

    even_not_search_count = len(even_not_search)
    even_search_count = len(even_search)
    odd_not_search_count = len(odd_not_search)
    odd_search_count = len(odd_search)

    obs =  np.array([[even_search_count,even_not_search_count],
            [odd_search_count,odd_not_search_count]])

    stat, more_users_p, dof, expected = chi2_contingency(obs)
    more_searches_p = mannwhitneyu(even['search_count'],odd['search_count']).pvalue

    instr_even = even[even['is_instructor'] == True].reset_index().drop(['index'],axis = 1)
    instr_odd = odd[odd['is_instructor'] == True].reset_index().drop(['index'],axis = 1)

    instr_even_not_search = instr_even[instr_even['search_count'] == 0]
    instr_even_search = instr_even[instr_even['search_count'] !=0 ]
    instr_odd_not_search = instr_odd[instr_odd['search_count'] == 0]
    instr_odd_search = instr_odd[instr_odd['search_count'] != 0]

    instr_even_not_search_count = len(instr_even_not_search)
    instr_even_search_count = len(instr_even_search)
    instr_odd_not_search_count = len(instr_odd_not_search)
    instr_odd_search_count = len(instr_odd_search)

    instr_obs =  np.array([[instr_even_search_count,instr_even_not_search_count],
            [instr_odd_search_count,instr_odd_not_search_count]])

    instr_stat, more_instr_p, instr_dof, instr_expected = chi2_contingency(instr_obs)
    more_instr_searches_p = mannwhitneyu(instr_even['search_count'],instr_odd['search_count']).pvalue

    print(OUTPUT_TEMPLATE.format(
        more_users_p=more_users_p,
        more_searches_p=more_searches_p,
        more_instr_p=more_instr_p,
        more_instr_searches_p=more_instr_searches_p,
    ))

if __name__ == '__main__':
    main()


import numpy as np
from numpy import linalg
from matplotlib import pyplot as plt
import Rosenbrock

def EnsembleSampler(X0, N, L, alpha):
    # Functions to evaluate the density, grad log density, and Hessian of the
    # minus log density.
    log_pi = Rosenbrock.log_pi

    MCMC_chain = np.zeros((N+1, L, len(X0[0,:])))
    MCMC_chain[0,:,:] = X0 # Initialize the L walkers.

    X = X0
    accept = 0
    for k in range(1, N+1):
        for i in range(L):
            # Update the l-th walker.

            # Randomly select an index j != i
            j =  np.mod(i + 1 + np.random.randint(L-1), L)

            # Inverse transform sampling for Z.
            sa = np.sqrt(alpha)
            Z = ( (sa - 1/sa) * np.random.rand() + 1/sa )**2

            # Get the proposal.
            y = X[j,:] + Z*(X[i,:] - X[j,:])

            d = len(X[0,:]) # Get the dimension.
            # Compute the log of the acceptance probability.
            log_pacc = (d-1)*np.log(Z) + log_pi(y) - log_pi(X[i,:])

            # Metropolize.
            if np.log(np.random.rand()) <= log_pacc:
                accept += 1
                MCMC_chain[k,i,:] = y
            else:
                MCMC_chain[k,i,:] = X[i,:]

        X = MCMC_chain[k,:,:]

    return [MCMC_chain, accept/(N*L)]

def plot_trajectory(X0, N, L, alpha):
    [chain, accept] = EnsembleSampler(X0, N, L, alpha)

    print("\nAcceptance Rate = {:0.1f}%.\n".format(100*accept))

    pi = Rosenbrock.pi
    x1 = np.linspace(-4, 4, 100)
    x2 = np.linspace(-2, 10, 100)

    X1, X2 = np.meshgrid(x1, x2, sparse=True)

    Y = pi([X1, X2])

    plt.figure(1)
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')
    plt.contourf(x1, x2, Y)
    for l in range(L):
        plt.plot(chain[N,l,0], chain[N,l,1], 'r x')
    plt.xlabel('$x_1$')
    plt.ylabel('$x_2$')
    plt.title('Affine Invariant Ensemble Trajectories')
    plt.show()

L = 50
X0 = 0.5*np.random.randn(2*L)
X0 = X0.reshape((L, 2))
N = 100
alpha = 1.2
plot_trajectory(X0, N, L, alpha)


#!/usr/bin/python
from bmi_calc_core import get_bmi
from bmi_calc_core import capture_weight
from bmi_calc_core import capture_length
from bmi_calc_core import get_bmi_level

print("Exercise 19: BMI Calculator")
print("")
try:
  isInputCorrect = True
  weight = capture_weight()
  if weight < 0:
    print("The weight mut bee larger than 0!")
    isInputCorrect = False

  length = capture_length()
  if length < 0:
    print("The length must be larger than 0!")
    isInputCorrect = False

  if isInputCorrect:
    bmi = get_bmi(weight, length)
    print("Your BMI is %f" % (bmi))
    print(get_bmi_level(bmi))
except ValueError as ex:
  print("Enter a correct value for weight and length")


import pandas as pd
import numpy as np

traindata_df = pd.read_csv('adult.data.csv',skipinitialspace = True,header=None)
traindata_df.columns = ['age','workclass','fnlwgt','education','education-num','marital-status','occupation','relationship','race','sex','capital-gain','captial-loss','hours-per-week','native-country','label']
traindata_df = traindata_df.replace("?",np.nan)
traindata_df = traindata_df.dropna()

testdata_df = pd.read_csv('adult.test.csv',skipinitialspace = True,header=None,skiprows=1)
testdata_df.columns = ['age','workclass','fnlwgt','education','education-num','marital-status','occupation','relationship','race','sex','capital-gain','captial-loss','hours-per-week','native-country','label']
print(testdata_df)
testdata_df = testdata_df.replace("?",np.nan)
testdata_df = testdata_df.dropna()
print(testdata_df)
testdata_df['label'] = testdata_df['label'].str.rstrip('.') #remove the "." char from the end of the labels in test data only


"""Main script
"""

from application.process import Process
from application.app import App
from utils.data_reader import get_properties

properties = get_properties()

DEBUG = properties.get("DEBUG").data

def main():
    if DEBUG == "FALSE":
        proc = Process()
        proc.start()
    else:
        app = App()
        app.start()

if __name__ == "__main__":
    main()


import chainer
import chainer.functions as func #F
import chainer.links as links #L
from   chainer import training, datasets, iterators, optimizers
from   chainer.training import extensions
import numpy as np

batch_size = 10

class NMINT_Conv_NN(chainer.Chain):

    def __init__(self):
        super(NMINT_Conv_NN, self).__init__()
        with self.init_scope():
            self.conv1 = links.Convolution2D(1, 8, ksize = 3) #フィルタサイズ 3, 出力数8
            self.linear1 = links.Linear(1352, 10) # 出力数10

    def __call__(self, x, t = None, train = True):
        #畳み込みニューラルネットワークによる画像認証
        h1 = self.conv1(x)         # 畳み込み層
        h2 = func.relu(h1)         # 活性化関数
        h3 = func.max_pooling_2d(h2, 2) # プーリング層
        h4 = self.linear1(h3)      # 全結合層

        # 損失か結果を返す
        return func.softmax_cross_entropy(h4, t) if train else func.softmax(h4)

# 損失関数
model = NMINT_Conv_NN()
# データセットの取得
# ndmi:データの次元数(縦×横×色)
train, test = chainer.datasets.get_mnist(ndim = 3)

# イテレータの作成
# 教師用のイテレータ
train_iter = iterators.SerialIterator(train, batch_size, shuffle = True)
test_iter = iterators.SerialIterator(test, 1, repeat = False, shuffle = False)

# トレーナーの作成
optimizer = optimizers.Adam()
optimizer.setup(model)

# デバイスを選択してTrainerを作成する
updater = training.StandardUpdater(train_iter, optimizer, device = None)
trainer = training.Trainer(updater, (5, 'epoch'), out = "result")

# テストをTrainerに設定する
trainer.extend(extensions.Evaluator(test_iter, model, device = None))

# 学習の進展を表示するようにする
trainer.extend(extensions.ProgressBar())

# 教師データとテスト用データの正解率を表示する
trainer.extend(extensions.LogReport(),
trainer.extend(extensions.PrintReport( entries=['epoch', 'main/accuracy', 'validation/main/accuracy', 'elapsed_time' ])))

# 機械学習の実行
trainer.run()

# 学習結果を保存
chainer.serializers.save_hdf5('chapt02.hdf5', model)


import numpy as np
import femm
import matplotlib
from math import pi, sqrt, exp

class Wire:

    def __init__(self, diameter):
        '''
        Диаметр провода выбирается из ряда diameterList
        '''
        self.diameterList = [0.063, 0.071, 0.08, 0.09, 0.1, 0.112, 0.12, 0.125, 0.13, 0.14, 0.15, 0.16, 0.17,
        0.18, 0.19, 0.2, 0.21, 0.224, 0.236, 0.25, 0.265, 0.28, 0.3, 0.315, 0.335, 0.355, 0.38, 0.4, 0.425, 0.45,
        0.475, 0.5, 0.53, 0.56, 0.6, 0.63, 0.67, 0.69, 0.71, 0.75, 0.77, 0.8, 0.83, 0.85, 0.9, 0.93, 0.95,
        1, 1.06, 1.08, 1.12, 1.18, 1.25, 1.32, 1.4, 1.45, 1.5, 1.56, 1.6, 1.7, 1.8, 1.9, 2, 2.12, 2.24, 2.36,
        2.44, 2.5]
        self.diameter = diameter

    def area(self):
        return pi * self.diameter**2/4

class Coil:
    def __init__(self, outerDiameter, innerDiameter, length, wireDiameter, fillFactor = 57.3/100):
        '''
        здесь устанока атрибутов объекта и создание объектов Wire, Coil
        '''
        self.outerDiameter = outerDiameter
        self.innerDiameter = innerDiameter
        self.length = length
        self.fillFactor = fillFactor
        self.Wire = Wire(wireDiameter)

    def area(self):
        return (self.outerDiameter - self.innerDiameter) / 2 * self.length

    def windingNomber(self):
        return int(self.fillFactor * self.area() / self.Wire.area())

    def wireLength(self):
        return pi * self.windingNomber() * (self.outerDiameter + self.innerDiameter) / 2

    def resistanceAnalitical(self):
        """ Аналитический расчёт сопротивления катушки """
        rho20 = 0.0172e-6 # (Ohm*mm^2)/m
        return rho20 * self.wireLength() / self.Wire.area()

class PIG:
    def __init__(self, pipeOuterDiameter, pipeWall, modelName, voltage, freq = 22, meshsize = 1,
        materials = {'Сердечник':'1010 Steel', 'Дефектоскоп':'12H18N10T', 'Труба':'17G1S'}):
        '''
        Входные данные: pipeOuterDiameter, pipeWall в метрах
        Выходные данные: pointAt1mFromThePipe() возвращает координату X точки измерения поля на растоянии 1м от трубы
        '''
        self.pipeOuterDiameter = pipeOuterDiameter
        self.pipeWall = pipeWall
        self.modelName = modelName
        self.voltage = voltage
        self.freq = freq
        self.meshsize = meshsize
        self.materials = materials

    def pointAt1mFromThePipe(self):
        return self.pipeOuterDiameter/2 + 1

class OZO:
    def __init__(self, Coil, PIG):
        '''
        здесь устанока атрибутов объекта и создание объектов Coil, PIG
        '''
        self.Coil = Coil
        self.PIG = PIG

# Solving
    def calculateModel(self, inputCurrentFund):
#       =================== PreProcessing ===================
        femm.openfemm(1)
        femm.opendocument(self.PIG.modelName)
        modelNameTemp = self.PIG.modelName.split('.')[0]+'_temp'+'.fem'
        femm.mi_saveas(modelNameTemp)

        # (0) Установка частоты тока
        femm.mi_probdef(self.PIG.freq,'millimeters','axi',1e-8,0,30,0)

        # (1) Установка тока в обмотки
        inputCurrentM = inputCurrentFund * sqrt(2)
        femm.mi_setcurrent('New Circuit', inputCurrentM)

        # (2) Изменеие диаметра провода
        femm.mi_addmaterial(f'Wire d={self.Coil.Wire.diameter*1000:.2f} mm',
                            1,1,0,0,58,0,0,0,3,0,0,1,self.Coil.Wire.diameter*1000)

        # (3) Изменеие количества витков mi_setblockprop(’blockname’,  automesh,  meshsize,
        #’incircuit’,  magdir,  group,  turns)
        femm.mi_seteditmode('blocks')
        femm.mi_selectgroup(1)
        femm.mi_setblockprop(f'Wire d={self.Coil.Wire.diameter*1000:.2f} mm',  0,  0.5,
                             'New Circuit',  0,  1,  self.Coil.windingNomber())

        # (4) Назначение материала для групп блоков FEM модели
        femm.mi_zoom(0,-160,150,160)
        groups = [2,3,4]
        for index, group in enumerate(groups):
            femm.mi_seteditmode('blocks')
            femm.mi_clearselected()
            femm.mi_selectgroup(group)
            femm.mi_setblockprop(list(self.PIG.materials.values())[index],0,self.PIG.meshsize,0,0,group,0)
            femm.mi_refreshview()
        ## =================== Расчёт ===================
        femm.mi_analyze(1)
        femm.closefemm()
        print('----- Расчёт окончен! -----')
        print(f'Предварительная модель "{modelNameTemp}" готова (f = {self.PIG.freq:.1f}Hz)')
        return modelNameTemp

    def CalculateModel2Steps(self):
        # ============== <1-й прогон> ==============
        print(f'''<<<  1st step  ({self.Coil.Wire.diameter*1000:.3f} mm) x {self.Coil.windingNomber()} витков  >>>
        Материалы = {self.PIG.materials}
        Сопротивление обмотки аналитически = {self.Coil.resistanceAnalitical():.3} Ом, ({self.Coil.windingNomber()}витков)
        Длина провода = {self.Coil.wireLength():.2f}, Сечение обмотки = {self.Coil.area()*1e6:.1f} mm\u00b2
        ''')
        # Solve()
        tempModelName = self.calculateModel(inputCurrentFund = .05)

        # Post Processing
        # tempModelName = "OZO-500_Full_temp.fem"
        (coilFieldIntensityAt1m, coilInductatce, activeImpedanceNames, activeImpedance, activePowerLoss,
         coilVoltageDrop) = self.getImpedance(modelNameTemp = tempModelName)

        # ============== <2-й прогон> ==============
        # Задание режима по вычисленому импедансу
        print(f'<<<  2nd step  ({self.Coil.Wire.diameter*1000} mm) x {self.Coil.windingNomber()} витков  >>>')
        fullImpedance = abs(sum(activeImpedance)+1j*2*pi*self.PIG.freq*coilInductatce)
        Um = self.PIG.voltage / fullImpedance
        Ufund = Um / sqrt(2)
        nominalCurrent = Ufund
        print(f'''
        nominalCurrent = Ufund = {nominalCurrent:.3f} А, wireDiameter = {self.Coil.Wire.diameter*1000:.3f}
              ''')
        # Solve()
        tempModelName = self.calculateModel(nominalCurrent)
        # Post Processing
        (coilFieldIntensityAt1m, coilInductatce, activeImpedanceNames, activeImpedance, activePowerLoss,
         coilVoltageDrop) = self.getImpedance(modelNameTemp = tempModelName)
        self.PlotLosesPie(activeImpedanceNames,activePowerLoss)
        return (coilFieldIntensityAt1m, coilInductatce, activeImpedanceNames, activeImpedance, activePowerLoss,
                coilVoltageDrop, nominalCurrent)

# PostProcessing
    def calculateInductance(self, group):
        '''вычисление индуктивности через A · J
        '''
        from math import pi, sqrt
        inputCurrentM = femm.mo_getcircuitproperties('New Circuit')[0]
        currentFund = inputCurrentM / sqrt(2)
        femm.mo_groupselectblock(group)
        inductance = femm.mo_blockintegral(0) / inputCurrentM ** 2 # A·J
        femm.mo_clearblock()
        return inductance.real

    def calculateActiveImpedance(self, group):
        '''
        Функция возращает значение активного импеданса (R) и мощности потерь (TotalLoses)
        R, TotalLosses = calculateActiveImpedance(currentFund)
        '''
        from math import pi, sqrt
        inputCurrentM = femm.mo_getcircuitproperties('New Circuit')[0]
        currentFund = inputCurrentM / sqrt(2)
        femm.mo_groupselectblock(group)
        TotalLosses = femm.mo_blockintegral(6) #Total losses
        femm.mo_clearblock()
        return abs(TotalLosses / currentFund ** 2), abs(TotalLosses)

    def getImpedance(self, modelNameTemp):
#         from math import pi, sqrt
        femm.openfemm(1)
        femm.opendocument(modelNameTemp)
        # Get CoilCerrentM from model
        femm.mi_loadsolution()

        # Расчёт напряжённости магнитного поля на расстоянии 1 м от трубы
#         PipeDiameter = float(modelNameTemp.split('-')[1].split('_')[0])
        (Hr, Hz) = femm.mo_getpointvalues(self.PIG.pointAt1mFromThePipe()*1000,0)[5:7]
        coilFieldIntensityAt1m = abs(Hr + Hz)
        # Получение амплитуды магнитного поля в катушке для последующего расчёта компонет импеданса
        inputCurrentM = femm.mo_getcircuitproperties('New Circuit')[0]
        currentFund = inputCurrentM / sqrt(2)
        activeImpedanceNames = ['Обмотка', 'Сердечник', 'Дефектоскоп', 'Труба']
        (activeImpedance, activePowerLoss) = ([],[])
        for group in range(4):
#             print('group_{}. '.format(group))
            (activeImpedance_, activePowerLoss_) = self.calculateActiveImpedance(group+1) # calculateActiveImpedance
            activeImpedance.append(activeImpedance_)
            activePowerLoss.append(activePowerLoss_)
#             print('{}: activeImpedance = {:.3f} Ohm, activePowerLoss = {:.3f} W'.format(activeImpedanceNames[group],
#                                                                                activeImpedance_,
#                                                                                activePowerLoss_))
            if group == 0:
                coilInductatce = self.calculateInductance(group+1)
#                 print('coilInductatce = {:.1f} mH'.format(coilInductatce * 1000))
        print('----- Постобработка окончена! -----')
        coilVoltageDrop  = femm.mo_getcircuitproperties('New Circuit')[1]
#         print('voltage Drop = {}'.format(abs(coilVoltageDrop)))
        print(f'''=======================================================================
        Напряжённость поля на расстоянии 1 м от трубы = {coilFieldIntensityAt1m:.2e} А/м''')
        # print(f'''Индуктивность = {coilInductatce*1000:c4} мГн, Суммарный активный импеданс = {sum(activeImpedance):.3} Ом
        # Суммарные активные потери = {sum(activePowerLoss):.3} Вт
        # Падение напряжения на катушке = {abs(coilVoltageDrop):.3} В (ампл) {abs(coilVoltageDrop)/sqrt(2):.3} В (fund)
        # ''')
        femm.closefemm()
        return coilFieldIntensityAt1m, coilInductatce,\
        activeImpedanceNames , activeImpedance, activePowerLoss, coilVoltageDrop

    def PlotLosesPie(self, labels, loses):
        from math import pi, sqrt
        import matplotlib.pyplot as plt
        # Pie chart, where the slices will be ordered and plotted counter-clockwise:
        data = [abs(loses) for loses in loses]
        OveralLoses = abs(sum(data))
        sizes = [val/OveralLoses for val in data]
        explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

        fig1, ax1 = plt.subplots(figsize=(12, 9))
        ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
                shadow=True, startangle=90)
        ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
        ax1.set_title("Суммарные активные потери = {:.3f} Вт".format(OveralLoses))
        plt.show()

    def printTZ(self):
        modelNameTemp = self.PIG.modelName.split('.')[0]+'_temp'+'.fem'
        (coilFieldIntensityAt1m, coilInductatce, activeImpedanceNames, activeImpedance, activePowerLoss, coilVoltageDrop) = \
        self.getImpedance(modelNameTemp)
        print(f'''
1. Материалы
    {[key+': '+val for (key,val) in self.PIG.materials.items()]}
2. Геометрические параметры ОЗО
    2.1 Катушка
        Внешний диаметр катушки = {self.Coil.outerDiameter*1e3} мм
        Внутренний диаметр катушки = {self.Coil.innerDiameter*1e3} мм
        Длина катушки = {self.Coil.length*1e3} мм
    2.2 Труба
        Внешний диаметр трубы = {self.PIG.pipeOuterDiameter*1e3} мм
        Толщина стенки = {self.PIG.pipeWall*1e3} мм
3. Параметры обмотки
        Диаметр провода = {self.Coil.Wire.diameter*1e3:.3} мм
        Количество витков = {self.Coil.windingNomber():.0f}
        Длина провода = {self.Coil.wireLength():.1f} м
4. Источник питания
        Частота = {self.PIG.freq} Гц
        Амплитуда напряжения = {self.PIG.voltage} В
5. Параметры ОЗО
    5.1 Импеданс излучателя в трубе на снаряде
        Активный = {sum(activeImpedance):.3f} Ом
        Индуктивный = {coilInductatce*1000:.3f} мГн
    5.2 Мощность активных потерь = {sum(activePowerLoss):.3f} Вт (критерий < 0.329 Вт)
    5.3 Напряжённость магнитного поля на расстоянии 1 м от трубы = {coilFieldIntensityAt1m:.2e} А/м (критерий > 5.93e-02 А/м)
''')


import os
from io import open
from setuptools import setup

with open(os.path.join(os.path.dirname(__file__), 'README.rst'), encoding='utf-8') as readme:
    README = readme.read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name = 'django-wechat-pay',
    version = '0.0.6',
    packages = ['wechat_pay'],
    include_package_data = True,
    install_requires = ['django-wechat-base'],
    license = 'BSD License',
    description = 'django wechat pay, fixed view error',
    long_description = README,
    url = 'https://github.com/ChanMo/django-wechat-pay/',
    author = 'ChanMo',
    author_email = 'chen.orange@aliyun.com',
    classifiers = [
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License', # example license
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        # Replace these appropriately if you are stuck on Python 2.
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)


import torch
import torch.nn as nn
import math

class LSTM(nn.Module):
    def __init__(
        self,
        input_size,
        hidden_size,
    ):
        super().__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size

        # forget layer
        self.W_f = nn.Parameter(torch.Tensor(self.input_size + self.hidden_size, self.hidden_size))
        self.b_f = nn.Parameter(torch.Tensor(self.hidden_size))

        # input layer
        self.W_i = nn.Parameter(torch.Tensor(self.input_size + self.hidden_size, self.hidden_size))
        self.b_i = nn.Parameter(torch.Tensor(self.hidden_size))
        self.W_Ctilde = nn.Parameter(torch.Tensor(self.input_size + self.hidden_size, self.hidden_size))
        self.b_Ctilde = nn.Parameter(torch.Tensor(self.hidden_size))

        # output layer
        self.W_o = nn.Parameter(torch.Tensor(self.input_size + self.hidden_size, self.hidden_size))
        self.b_o = nn.Parameter(torch.Tensor(self.hidden_size))

        self.init_weights()

    def forward(self, x, hidden_states):
        # list with the outputs
        h = []

        # initialize the hidden_states if a empty array is received
        if hidden_states is None:
            h_t1 = torch.zeros(x.size()[1], self.hidden_size, device='cuda')
            C_t1 = torch.zeros(x.size()[1], self.hidden_size, device='cuda')
        else:
            h_t1 = hidden_states[0]
            C_t1 = hidden_states[1]

        for t in range(x.size()[0]):
            # the input
            x_t = x[t, :, :]

            # concatenate x_t with h_{t-1}
            x_t_h_t1 = torch.cat((h_t1, x_t), dim=1)

            # forget layer
            f_t = torch.sigmoid(torch.matmul(x_t_h_t1, self.W_f) + self.b_f)

            # input layer
            i_t = torch.sigmoid(torch.matmul(x_t_h_t1, self.W_i) + self.b_i)
            Ctilde_t = torch.tanh(torch.matmul(x_t_h_t1, self.W_Ctilde) + self.b_Ctilde)

            # update cell state
            C_t = f_t * C_t1 + i_t * Ctilde_t

            # output layer
            o_t = torch.sigmoid(torch.matmul(x_t_h_t1, self.W_o) + self.b_o)
            h_t = o_t * torch.tanh(C_t)

            # append the current output to the list of outputs
            h.append(h_t.unsqueeze(0))

            # the actual cell state should go in the previous cell state for the next iteration
            h_t1 = h_t
            C_t1 = C_t

        return torch.cat(h), [h_t, C_t]

    def init_weights(self):
        for parameter in self.parameters():
            nn.init.uniform_(parameter, -0.05, 0.05)


from Road.excel_py.road_excel_columns_port import *  # 不能删除
from Road.excel_py.road_excel_check_rules import *  # 不能删除
from Road.file_public.str_func import str_map_factory
from pandas import DataFrame
import pandas as pd
import os

class RoadExcel(object):
    def __init__(self, excel_name, excel_sheet=None):
        self.excel_name = excel_name
        self.excel_sheet = excel_sheet
        self.format_columns_class_and_excel_name_keys_dic = {
            'TfExcelFormatColumns()': [('土石方',)],
            'PsExcelFormatColumns()': [('排水工程', )],
            'FhExcelFormatColumns()': [('防护', )],
            'QbExcelFormatColumns()': [('耕地', )],
            'QtExcelFormatColumns()': [('桥头', )],
            'XjExcelFormatColumns()': [('新旧', )],
            'QlExcelFormatColumns()': [('桥梁', )],
            'RoadExcelFormatColumns()': [('',)],
        }  # 与road_excel_columns_port.py中类FormatColumns名称有耦合
        self.check_rules_function_and_excel_name_map_dic = {
            'RoadTfExcelCheckRules()': [('土石方',)],
            'RoadProtectExcelCheckRules()': [('防护',)],
            'RoadDrainExcelCheckRules()': [('排水工程',)],
            'RoadPavingExcelCheckRules()': [('路面工程',)],
            'RoadExcelFormatColumns()': [('',)],
        }  # 与road_excel_check_rules.py中类RoadExcelCheckRules名称有耦合
        self.data_df: DataFrame

    def get_format_columns(self):
        format_columns_class_and_excel_name_keys_dic = str_map_factory(self.excel_name, self.format_columns_class_and_excel_name_keys_dic)
        excel_format_columns_class = eval(format_columns_class_and_excel_name_keys_dic)
        excel_format_columns = excel_format_columns_class.columns
        return excel_format_columns

    def get_abbreviation_excel_name(self):
        from Road.excel_py.road_excel_settings import format_abbreviation_and_excel_name_keys_dic
        abbreviation_excel_name = str_map_factory(self.excel_name, format_abbreviation_and_excel_name_keys_dic)
        return abbreviation_excel_name

    def get_excel_data(self, *args, **kwargs):
        from Road.excel_py.pd_read_excel_strengthen import read_excel_strengthen
        from Road.excel_py.sheet_data_clean import clean_sheet_data
        from Road.chain_age import start_end_chainage_split_df
        data_df = read_excel_strengthen(*args, **kwargs)
        data_df = clean_sheet_data(data_df)
        # 格式化df中的列标签
        road_format_columns = self.get_format_columns()
        data_df.columns = pd.Series(list(data_df.columns)).apply(str_map_factory, map_dic=road_format_columns)

        data_df = start_end_chainage_split_df(data_df)
        self.data_df = data_df
        return data_df

    def check_dataframe_data(self, data_df: DataFrame, output_file):
        # check_rule格式{'exp': '检查用的表达式', 'columns': [结果中输出的columns列], 'rexg': '如果columns为空[]时，刚用正则划分columns'}
        import re
        import numpy as np
        check_rules_function_str = str_map_factory(self.excel_name, self.check_rules_function_and_excel_name_map_dic)
        check_rules_class = eval(check_rules_function_str)
        rules_of_check = check_rules_class.check_rules
        df = data_df.copy()

        # df.astype('float64')
        df.replace(np.nan, 0, inplace=True)
        # for col_index in df.iteritems():
        #     pd.to_numeric(df[col_index], errors='ignore')
        from Road.file_public.str_func import value_to_numeric
        df = df.applymap(value_to_numeric)
        # print(f'df_type:{df.dtypes}')
        # print(df.head())
        for check_rule in rules_of_check:
            if not check_rule['columns']:
                check_rule['columns'] = re.split(check_rule['regx'], check_rule['exp'])
            check_rule['columns'] = [_ for _ in check_rule['columns'] if _ in list(df.columns)]
            # print(f'check_rule:{check_rule}')
            res_df = df.query(check_rule['exp'])[check_rule['columns']]
            if res_df.empty:
                continue
            if not os.path.exists(output_file):
                res_df.to_excel(output_file)
                continue
            with pd.ExcelWriter(path=output_file, mode='a') as writer:
                res_df.to_excel(writer)

def demo(column_str):
    excel_name = r'SZYS06010111 每公里土石方数量表汇总表.xls'
    # excel_name = r'路基、路面排水工程数量表.xls'
    excel_name = r'公路病害治理工程数量表'
    sheet_name = ''
    road_excel = RoadExcel(excel_name, sheet_name)
    road_excel_columns = road_excel.get_format_columns()
    format_column = str_map_factory(column_str, road_excel_columns)
    return format_column

def check_demo():
    file_name = r"D:\lvcode\noteOnGithub\noteOnGithub\data\SZYS06010111 每公里土石方数量表汇总表.xls"
    sheet_name = "黄阁西互通"
    skiprows = 2
    header = [0, 1, 2]
    nrow = 67
    # data_df = read_excel_strengthen(file_name, sheet_name=sheet_name, skiprows=skiprows, header=header, usecols='A:AU', na_filter=0)
    # data_df = clean_sheet_data(data_df)
    # data_df = start_end_chainage_split_df(data_df)
    # output_path = os.path.dirname(file_name) + r'\check_out.xlsx'
    # check_dataframe_data(data_df, check_rules(), output_path)

    tf_sheet = RoadExcel(file_name, sheet_name)
    tf_sheet.get_excel_data(file_name, sheet_name, skiprows=skiprows, header=header, usecols='A:AU', na_filter=0, nrows=nrow)
    output_file_name = os.path.basename(file_name) + r'_check_out.xlsx'
    output_path = os.path.join(os.path.dirname(file_name), output_file_name)
    # output_path = os.path.dirname(file_name) + r'\check_out.xlsx'
    tf_sheet.check_dataframe_data(tf_sheet.data_df, output_path)

if __name__ == '__main__':
    # column_port = demo('zad')
    # print(column_port)

    check_demo()


from BCI_Interface import BCI
from Shell_Interface import Shell
from FTP_Interface import FTP
from N5180_Interface import N5180
from conman import Conman
from time import sleep
import datetime
from math import log
import csv
import re
import os
import argparse
import sys

VERSION = 4

## Argument parsing
parser = argparse.ArgumentParser()
parser.add_argument("band", help="hb/lb, highband or lowband")
parser.add_argument("rx", help="receiver 1/2")
parser.add_argument("board", help="board address")
parser.add_argument("mxg", help="mxg address, expected model N5180")
parser.add_argument("-s", "--step", help="step size, in hz", default = 1e6, type=float)
parser.add_argument("-b", "--bandwidth", help="bandwidth, in hz", default = 5e6, type=float)
parser.add_argument("--version", help="print out version and exit",
                    action='version', version='%(prog)s ' + str(VERSION))
parser.add_argument("-o", "--output", help="output filename" , default = None)

args = parser.parse_args() # Parse arguments

## Constants
conman = Conman("loss_profiles.yml", "band_info.yml") # Manages connections and other global state
band_info = dict(conman.storage["band_info"][args.band])

## Variable Configuration
board = args.board
mxgaddr = args.mxg
lofreq = band_info["lofreq"]
hifreq = band_info["hifreq"]
step = args.step
bandwidth = args.bandwidth
timestamp =  datetime.datetime.now().strftime('%Y-%m-%d_%H-%M')
csv_filename = args.output or "tx_lo_sweep_%s_%s_%s_%s.csv" % (args.band, args.tx, args.board, timestamp)
gain = -20

## Check that cable compensation entry exists
if not mxgaddr in conman.storage["loss_profiles_parsed"]:
    print("Cannot find loss profile, exiting.")
    sys.exit()

## Connections
bci = BCI(board, "lucent", "password")
sh = Shell()
ftp = FTP(board, "lucent", "password")
mxg = N5180(mxgaddr)
print("Connections established...")

## Setup

# Transmitter
rx_atten = band_info["rx_atten"]
if args.rx == "1":
    bci.set_atten(10, rx_atten)
    bci.set_atten(11, 235)
elif args.rx == "2":
    bci.set_atten(10, 235)
    bci.set_atten(11, rx_atten)

# Capture filename
pid = os.getpid()
filename = "rx_capture" + str(pid)

# Lock
bci.set_lo(2, lofreq)
assert bci.ensure_reference_pll_lock("EXT", 1)
print("Board configured...")

# MXG Setup
mxg.set_output(True)
print("MXG Configured...")

print("Initial Setup Completed...")

print("Writing to " + csv_filename)
with open(csv_filename, 'w') as csvfile:
    ## CSV Header
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(["tx_lo_sweep.py version: " + str(VERSION)])
    for member in [str(x) + ": " + str(y) for (x, y) in vars(args).items()]: # extract arguments, put in .csv file
        csvwriter.writerow([member])
    csvwriter.writerow(["RX Attenuation: " + str(rx_atten)])
    csvwriter.writerow([])
    csvwriter.writerow(["Frequency", "readrxpower", "Time-Domain Power",
                        "Freq-Domain Power", "Bandwidth Power"])

    # Data
    for freq in range(int(lofreq), int(hifreq) + 1, int(step)):
        bci.set_lo(2, freq)
        loss = "%0.2f" % conman.get_loss_at_freqs(freq, mxgaddr)[0]
        mxg.set_freq(freq)
        mxg.set_power(gain + float(loss))
        sleep(2)
        if int(freq) == int(lofreq): sleep(5)
        rxpower = bci.get_rx_power(1, 1, bandwidth)

        ## Capture
        sh.sendline("rm -f " + filename)
        for k in range(3): # Prevent repetition of data
            bci.do_rx_capture("/tmp/" + filename, args.rx)
        ftp.get("/tmp/" + filename)

        ## Octave
        pwrtime, pwrfreq, regionpwr = Conman.das_capture_power(sh, filename, 0, bandwidth)

        ## Bookkeeping
        row = [float(freq), float(rxpower), float(pwrtime), float(pwrfreq), float(regionpwr), float(loss)]
        print("Appending row " + str(row))
        csvwriter.writerow(row)

        ## Update files
        csvfile.flush()


import numpy as np
import matplotlib.pyplot as plt
from numpy.ma import log

a = .6
s = np.random.logseries(a, 10000)
count, bins, ignored = plt.hist(s)

def logseries(k, p):
    return -p ** k / (k * log(1 - p))

plt.plot(bins, logseries(bins, a) * count.max() /
         logseries(bins, a).max(), 'r')
plt.show()


#! /usr/bin/python

import numpy as np
import scipy.io.wavfile as wav
import pylab
import sys
import scikits.audiolab
import os

sys.path.append('/scratch2/nxs113020/pyknograms/code/tools/pykno')
from pyknogram_extraction import *

def mix_files(f1,f2):

    base1 = f1.split('/')[-1].split('.wav')[0]
    base2 = f2.split('/')[-1].split('.wav')[0]

    (fs,sig) = wav.read(f1)
    s1 = sig.reshape((len(sig),1))
    del sig
    (fs,sig) = wav.read(f2)
    s2 = sig.reshape((len(sig),1))
    del sig
    block_length = 5*fs
    s1_blocks = enframe(s1,block_length,block_length)
    s2_blocks = enframe(s2,block_length,block_length)
    del s1, s2

    nrg1 = 0.707*np.sqrt(np.sum(np.power(s1_blocks,2),axis=1))
    nrg2 = 0.707*np.sqrt(np.sum(np.power(s2_blocks,2),axis=1))

    for i in range(len(nrg1)):
        db1 = np.log(nrg1[i])
        db2 = np.log(nrg2[i])
        if (db1 >= 9) and (db2 >= 9) and (0.1 < abs(db1 - db2) < 5):
            sir = '%.2f' % (db1 - db2)
            ovl_name = '/erasable/nxs113020/wav_ovl/'+base1+'_'+base2+'_sir'+sir+'_'+str(i)+'.wav'
            overlapped = s1_blocks[i,:] + s2_blocks[i,:]
            nrg_ovl = 0.707*np.sqrt(np.sum(np.power(overlapped,2)))
            scikits.audiolab.wavwrite(overlapped/nrg_ovl, ovl_name, fs, 'pcm16')

if __name__=='__main__':
    train_file = open('lists/train.txt')
    cwd = '/scratch/nxs113020/hmm_overlap_detection'
    train_list = []
    for i in train_file:
        train_list.append(i.strip())
    train_file.close()

    fjobs = open('lists/mix_jobs.txt','w')
    for i in range(len(train_list)):
        wav1 = train_list[i]
        base1 = wav1.split('Headset')[0]
        for j in range(i,len(train_list)):
            wav2 = train_list[j]
            base2 = wav2.split('Headset')[0]
            if not(wav1 == wav2) and (base1 == base2):
                # the following command allows us to directly use a function from this module in bash.
                # Note: with this command, we don't need to have a separate bash script to use SGE.
                fjobs.write(""". ~/.bashrc; python -c \"import sys; sys.path.append(\'%s\'); import mix_channels; mix_channels.mix_files(\'%s\', \'%s\')\" \n"""%(cwd,wav1,wav2))
    fjobs.close()
    os.system('/home/nxs113020/bin/myJsplit -M 100 -b 3 -q 1 -n mix_ami lists/mix_jobs.txt')


"""
Given the names and grades for each student in a Physics class of N students,
store them in a nested list and print the name(s) of any student(s)
having the second lowest grade.

"""
n = eval(input("Enter the Number of Student along with there name and marks\n"))
arr=[]
lst=[]
lst1=[]
dlst=[]
rlst=[]
for i in range (n):
    lst=[]
    arr.append(lst)
    for j in range (1):
        val=input()
        lst.append(val)
        for j in range (1):
            val=eval(input())
            lst.append(val)
arr.sort(key = lambda x:x[1])
for i in range(len(arr)):
    lst1.append(arr[i][1])
for i in range (len(lst1)):
    if lst1[i] not in dlst:
        dlst.append(lst1[i])
for i in range (len(arr)):
    if dlst[1] == arr[i][1]:
        rlst.append(arr[i])
rlst.sort()
for i in range (len(rlst)):
    print(rlst[i][0])


import os
import sys

def test_launch_test_0_basic1():
    from pycompss.runtime.launch import launch_pycompss_application

    current_path = os.path.dirname(os.path.abspath(__file__))
    app_path = os.path.join(
        current_path,
        "..",
        "..",
        "..",
        "..",
        "..",
        "..",
        "..",
        "..",
        "..",
        "tests",
        "sources",
        "local",
        "python",
        "0_basic1",
        "src",
    )
    app = os.path.join(app_path, "test_mp.py")
    sys.path.insert(0, app_path)
    launch_pycompss_application(
        app, "main_program", debug=True, app_name="test_0_basic1"
    )
    sys.path.pop(0)
    if os.path.exists("infile"):
        os.remove("infile")
    if os.path.exists("outfile"):
        os.remove("outfile")
    if os.path.exists("inoutfile"):
        os.remove("inoutfile")


import itertools

n = int(input())

nails = []
for i in range(n):
    x, y = map(int, input().split())
    nails.append((x, y))

max_area = 0

for corners in itertools.combinations(nails, 4):
    x_values = [c[0] for c in corners]
    y_values = [c[1] for c in corners]
    if len(set(x_values)) == 2 and len(set(y_values)) == 2:
        x1 = min(x_values)
        y1 = min(y_values)
        x2 = max(x_values)
        y2 = max(y_values)
        area = (x2 - x1) * (y2 - y1)
        if area > max_area:
            max_area = area

print(max_area)


import dataclasses
import logging

from lib.targetop import TargetOp
from lib import util

logger = logging.getLogger(__name__)

@dataclasses.dataclass
class Device:
    name: str
    flash_size: int
    page_size: int
    eeprom_size: int

DEVICE_SIGNATURES = {
    (0x1e, 0x91, 0x0a): Device("attiny2313", 2**11, 32, 128),
    (0x1e, 0x94, 0x03): Device("atmega16a", 2**14, 128, 512),
    (0x1e, 0x95, 0x02): Device("atmega32a", 2**15, 128, 1024),
}

RESET = "RESET"
SCK = "SCK"
MISO = "MISO"
MOSI = "MOSI"

TWD_FLASH = 4.5e-3
TWD_FUSE = 4.5e-3
TWD_EEPROM = 9e-3
TWD_ERASE = 9e-3

PROGRAMMING_ENABLED = 0x53
SPI_PROGRAMMING_ENABLE =        "1010 1100 0101 0011 ____ ____ ____ ____"
SPI_CHIP_ERASE =                "1010 1100 1000 0000 xxxx xxxx xxxx xxxx"
SPI_READ_PROGRAM_MEMORY =       "0010 h000 aaaa aaaa aaaa aaaa 0000 0000"
SPI_LOAD_PROGRAM_MEMORY_PAGE =  "0100 h000 00__ ____ __aa aaaa iiii iiii"
SPI_WRITE_PROGRAM_MEMORY_PAGE = "0100 1100 00aa aaaa aaaa aaaa ____ ____"
SPI_READ_SIGNATURE_BYTE =       "0011 0000 0000 0000 0000 00aa 0000 0000"

class Avr:
    def __init__(self, pinproxy, progressbar):
        self.pinproxy = pinproxy
        self.progressbar = progressbar
        self.device = None

    def read_flash(self):
        self._open()
        for address in range(self.device.flash_size):
            self.progressbar.update(address, self.device.flash_size)
            spi_command = util.cmd(
                SPI_READ_PROGRAM_MEMORY,
                h=address & 1,
                a=address >> 1)
            self._spi(spi_command, range(24, 32))
        return dict(enumerate(self.pinproxy.pop_fetched(MISO)))

    def write_flash(self, mem):
        self._open()
        if max(mem) >= self.device.flash_size:
            logger.warning(f"device flash size ({self.device.flash_size}) < "
                            f"input data max address ({max(mem)})")  # TODO fixme >=
            mem = {a: v for a, v in mem.items() if a < self.device.flash_size}

        page_size = self.device.page_size
        for page in util.split_to_pages(mem, page_size):
            for byte_address, value in page.items():
                offset = byte_address % page_size
                spi_command = util.cmd(
                    SPI_LOAD_PROGRAM_MEMORY_PAGE,
                    h=offset & 1,
                    a=offset >> 1,
                    i=value)
                self._spi(spi_command)
                self.progressbar.update(byte_address, self.device.flash_size)
            wpage = byte_address // page_size * page_size // 2
            self._spi(util.cmd(SPI_WRITE_PROGRAM_MEMORY_PAGE, a=wpage))
            self.pinproxy.wait(TWD_FLASH)

    def chip_erase(self):
        self._open()
        self._spi(util.cmd(SPI_CHIP_ERASE))
        self.progressbar.update(1, 2)
        self.pinproxy.wait(TWD_ERASE)

    def _open(self):
        if self.device:
            return

        p = self.pinproxy
        p.set_as_input(MISO)
        for pin in (RESET, SCK, MOSI):
            p.set_as_output(pin)
            p.reset_pin(pin)
        p.set_pin(RESET)
        p.wait(0.01)
        p.reset_pin(RESET)
        p.wait(0.025)

        self._spi(util.cmd(SPI_PROGRAMMING_ENABLE), range(16, 24))
        is_sync = self.pinproxy.pop_fetched(MISO)[0]
        if is_sync != PROGRAMMING_ENABLED:
            raise Exception(f"Out of sync ({is_sync:02x})!")
        logger.info("Programming enabled")

        for i in range(3):
            cmd = util.cmd(SPI_READ_SIGNATURE_BYTE, a=i)
            self._spi(cmd, range(24, 32))
        sigbytes = self.pinproxy.pop_fetched(MISO)
        self.device = DEVICE_SIGNATURES[tuple(sigbytes)]
        logger.info(f"Detected: {self.device}")

    def _spi(self, command, read_range=()):
        assert len(command) == 32
        set_pin = self.pinproxy.set_pin
        fetch_pin = self.pinproxy.fetch_pin
        wait = self.pinproxy.wait

        for i, bit in enumerate(command):
            wait(500e-9)
            set_pin(MOSI, bit)
            wait(500e-9)
            set_pin(SCK, True)
            wait(500e-9)
            if i in read_range:
                fetch_pin(MISO)
            wait(500e-9)
            set_pin(SCK, False)

@TargetOp
def read_flash(pinproxy, progressbar):
    return Avr(pinproxy, progressbar).read_flash()

@TargetOp
def write_flash(pinproxy, progressbar, mem):
    return Avr(pinproxy, progressbar).write_flash(mem)

@TargetOp
def chip_erase(pinproxy, progressbar):
    return Avr(pinproxy, progressbar).chip_erase()


import os
import torch
from torch.utils.ffi import create_extension

this_file = os.path.dirname(__file__)

sources = ['src/my_lib.c']
headers = ['src/my_lib.h']
defines = []
with_cuda = False

if torch.cuda.is_available():
    print('Including CUDA code.')
    sources += ['src/my_lib_cuda.c']
    headers += ['src/my_lib_cuda.h']
    defines += [('WITH_CUDA', None)]
    with_cuda = True

#creates and configures a cffi.FFI object, that builds PyTorch extension
ffi = create_extension(
    '_ext.my_lib',  #name--package name. Can be a nested module e.g. "._ext.my_lib"
    headers=headers,  #header(str or List[str]--list of headers, that contain only exported functions
    sources=sources,  #sources(List[str])--list of sources to compile
    define_macros=defines,
    relative_to=__file__, #path of the build file. Required when "package is True". It's best to use "__file__" for this argument.,
    with_cuda=with_cuda,
    extra_compile_args=["-std=c99"]
)

if __name__ == '__main__':
    ffi.build()


import torch
import torch.nn as nn
from typing import Optional, Tuple

from foldacc.model.modules.ops import Linear, LayerNorm
from foldacc.model.modules.utils import one_hot, chunk_layer

class InputEmbedder(nn.Module):
    def __init__(
        self,
        tf_dim: int,
        msa_dim: int,
        d_pair: int,
        d_msa: int,
        relpos_k: int,
        use_chain_relative: bool = False,
        max_relative_chain: Optional[int] = None,
        low_mem = False,
        chunk_size = None,
        dtype = torch.float,
        **kwargs,
    ):
        super(InputEmbedder, self).__init__()

        self.tf_dim = tf_dim
        self.msa_dim = msa_dim

        self.d_pair = d_pair
        self.d_msa = d_msa

        self.low_mem = low_mem
        self.chunk_size = chunk_size
        self.dtype = dtype

        self.linear_tf_z_i = Linear(tf_dim, d_pair)
        self.linear_tf_z_j = Linear(tf_dim, d_pair)
        self.linear_tf_m = Linear(tf_dim, d_msa)
        self.linear_msa_m = Linear(msa_dim, d_msa)

        # RPE stuff
        self.relpos_k = relpos_k
        self.use_chain_relative = use_chain_relative
        self.max_relative_chain = max_relative_chain
        if not self.use_chain_relative:
            self.num_bins = 2 * self.relpos_k + 1
        else:
            self.num_bins = 2 * self.relpos_k + 2
            self.num_bins += 1  # entity id
            self.num_bins += 2 * max_relative_chain + 2

        self.linear_relpos = Linear(self.num_bins, d_pair)

    def _relpos_indices(
        self,
        res_id: torch.Tensor,
        sym_id: Optional[torch.Tensor] = None,
        asym_id: Optional[torch.Tensor] = None,
        entity_id: Optional[torch.Tensor] = None,
    ):

        max_rel_res = self.relpos_k
        rp = res_id[..., None] - res_id[..., None, :]
        rp = rp.clip(-max_rel_res, max_rel_res) + max_rel_res
        if not self.use_chain_relative:
            return rp
        else:
            asym_id_same = asym_id[..., :, None] == asym_id[..., None, :]
            rp[~asym_id_same] = 2 * max_rel_res + 1
            entity_id_same = entity_id[..., :, None] == entity_id[..., None, :]
            rp_entity_id = entity_id_same.type(rp.dtype)[..., None]

            rel_sym_id = sym_id[..., :, None] - sym_id[..., None, :]

            max_rel_chain = self.max_relative_chain

            clipped_rel_chain = torch.clamp(
                rel_sym_id + max_rel_chain, min=0, max=2 * max_rel_chain
            )

            clipped_rel_chain[~entity_id_same] = 2 * max_rel_chain + 1
            return rp, rp_entity_id, clipped_rel_chain

    def _chain_relpos_emb(
        self,
        rp,
        rp_entity_id,
        rp_rel_chain,
    ):
        rp = one_hot(rp, num_classes=(2 * self.relpos_k + 2), dtype=self.dtype)
        rp_entity_id = rp_entity_id.type(self.dtype)
        rp_rel_chain = one_hot(
            rp_rel_chain, num_classes=(2 * self.max_relative_chain + 2), dtype=self.dtype
        )
        return self.linear_relpos(
            torch.cat([rp, rp_entity_id, rp_rel_chain], dim=-1)
        )

    def _chunk_relpos_emb(
        self,
        rp,
        rp_entity_id,
        rp_rel_chain
    ):
        return chunk_layer(
            self._chain_relpos_emb,
            {"rp":rp, "rp_entity_id":rp_entity_id, "rp_rel_chain":rp_rel_chain},
            chunk_size=self.chunk_size,
            no_batch_dims=len(rp.shape[:2]),
        )

    def relpos_emb(
        self,
        res_id: torch.Tensor,
        sym_id: Optional[torch.Tensor] = None,
        asym_id: Optional[torch.Tensor] = None,
        entity_id: Optional[torch.Tensor] = None,
        num_sym: Optional[torch.Tensor] = None,
    ):

        dtype = self.linear_relpos.weight.dtype
        if not self.use_chain_relative:
            rp = self._relpos_indices(res_id=res_id)
            return self.linear_relpos(
                one_hot(rp, num_classes=self.num_bins, dtype=dtype)
            )
        else:
            rp, rp_entity_id, rp_rel_chain = self._relpos_indices(
                res_id=res_id, sym_id=sym_id, asym_id=asym_id, entity_id=entity_id
            )
            if self.low_mem and self.chunk_size is not None:
                return self._chunk_relpos_emb(rp, rp_entity_id, rp_rel_chain)
            else:
                return self._chain_relpos_emb(rp, rp_entity_id, rp_rel_chain)

    def forward(
        self,
        tf: torch.Tensor,
        msa: torch.Tensor,
    ) -> Tuple[torch.Tensor, torch.Tensor]:
        # [*, N_res, d_pair]
        if self.tf_dim == 21:
            # multimer use 21 target dim
            tf = tf[..., 1:]
        # convert type if necessary
        tf = tf.type(self.linear_tf_z_i.weight.dtype)
        msa = msa.type(self.linear_tf_z_i.weight.dtype)
        n_clust = msa.shape[-3]

        msa_emb = self.linear_msa_m(msa)
        # target_feat (aatype) into msa representation
        tf_m = (
            self.linear_tf_m(tf)
            .unsqueeze(-3)
            .expand(((-1,) * len(tf.shape[:-2]) + (n_clust, -1, -1)))  # expand -3 dim
        )
        msa_emb += tf_m

        tf_emb_i = self.linear_tf_z_i(tf)
        tf_emb_j = self.linear_tf_z_j(tf)
        pair_emb = tf_emb_i[..., None, :] + tf_emb_j[..., None, :, :]

        return msa_emb, pair_emb

class TemplatePairEmbedder(nn.Module):
    def __init__(
        self,
        d_in: int,
        v2_d_in: list,
        d_out: int,
        d_pair: int,
        v2_feature: bool = False,
        low_mem = False,
        chunk_size = None,
        **kwargs,
    ):
        super(TemplatePairEmbedder, self).__init__()

        self.d_out = d_out
        self.v2_feature = v2_feature
        self.low_mem = low_mem
        self.chunk_size = chunk_size
        if self.v2_feature:
            self.d_in = v2_d_in
            self.linear = nn.Sequential()
            for d_in in self.d_in:
                self.linear.append(Linear(d_in, self.d_out, init="relu"))
            self.z_layer_norm = LayerNorm(d_pair)
            self.z_linear = Linear(d_pair, self.d_out, init="relu")
        else:
            self.d_in = d_in
            self.linear = Linear(self.d_in, self.d_out, init="relu")

    def _v2_feature_forward(self, x, z):
        t = 0
        for i, s in enumerate(x):
            dtype = self.z_linear.weight.dtype
            t += self.linear[i](s.type(dtype))
        t += self.z_linear(self.z_layer_norm(z))
        return t

    def _chunk(self, x, z):
        return chunk_layer(
            self._v2_feature_forward,
            {"x":x, "z":z},
            chunk_size=self.chunk_size,
            no_batch_dims=len(z.shape[:2]),
        )

    def forward(
        self,
        x,
        z,
    ) -> torch.Tensor:
        if not self.v2_feature:
            x = self.linear(x.type(self.linear.weight.dtype))
        else:
            if self.low_mem and self.chunk_size is not None:
                x = self._chunk(x, z)
            else:
                x = self._v2_feature_forward(x, z)
        return x


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon May 21 17:53:10 2018

@author: niharika-shimona
"""
from IPython import get_ipython
get_ipython().magic('reset -sf')
import sys,os
import numpy as np
import pickle
import matplotlib
# matplotlib.use('Agg')
from matplotlib import pyplot as plt
# plt.ioff()
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import Pipeline
from sklearn.metrics import mean_squared_error,explained_variance_score,mean_absolute_error,r2_score,make_scorer
from sklearn.model_selection import GridSearchCV, KFold

import scipy.io as sio
from Data_Extraction import Split_class,create_dataset
from sklearn.decomposition import PCA as sklearnPCA

df_aut,df_cont = Split_class()
task  = 'SRS.TotalRaw.Score'
ds = '0'

x_aut,y_aut,x_cont,y_cont = create_dataset(df_aut,df_cont,task,'/home/niharika-shimona/Documents/Projects/Autism_Network/code/patient_data/')

if ds == '0':
 	x = x_cont
 	y= np.ravel(y_cont)
 	fold = 'cont'

elif ds == '1':
 	x = x_aut
 	y= np.ravel(y_aut)
 	fold = 'aut'

else:
 	x =np.concatenate((x_cont,x_aut),axis =0)
 	y = np.ravel(np.concatenate((y_cont,y_aut),axis =0))
 	fold = 'aut_cont'

#pathname = '/media/nsalab/Users/ndsouza4/Schizophrenia/'
#task = 'NCC_eig'
#cas = 'buf'
#filename = pathname + task +'.mat'
#
#data = sio.loadmat(filename)
#subtx = 'x_'+ cas
#data_eg_corr = data[subtx]
#
#x = data_eg_corr
#subty = 'y_'+ cas
#y =np.ravel(data[subty])

rf_reg = RandomForestRegressor(n_estimators=1000,oob_score= True)

pca = sklearnPCA()
cast = 'pca'
pipeline = Pipeline([('PCA',pca), ('rf_reg',rf_reg)])
n_comp = [5,10,15,20,25,30]
min_samples_split = np.int16(np.linspace(2,16,8))

p_grid = [{'PCA__n_components': n_comp, 'rf_reg__min_samples_split': min_samples_split}]

kf_total = KFold(n_splits=10,shuffle=False, random_state=6)
my_scorer = make_scorer(explained_variance_score)

lrgs = GridSearchCV(estimator=pipeline, param_grid=p_grid, cv =kf_total, scoring =my_scorer, n_jobs=-1)
lrgs.fit(x,y)
param_best = lrgs.best_params_

y_train =[]
y_test = []
y_train_AF =[]
y_test_AF =[]
r2_test = []
mse_test =[]
learnt_models =[]
i = 0

for train,test in kf_total.split(x,y):

    model = pipeline.set_params(**param_best)
    model.fit(x[train],y[train])
    y_pred_train = model.predict(x[train])
    y_pred_test = model.predict(x[test])
    r2_test.append(r2_score(y[test],y_pred_test))
    mse_test.append(mean_squared_error(y[test],y_pred_test))

    y_train_AF = np.concatenate((y_train_AF,y_pred_train),axis =0)
    y_train = np.concatenate((y_train,y[train]),axis =0)
    y_test_AF = np.concatenate((y_test_AF,y_pred_test),axis =0)
    y_test = np.concatenate((y_test,y[test]),axis =0)

    learnt_models.append(model)

newpath = r'/home/niharika-shimona/Documents/Projects/Autism_Network/Results/Sanity_Check/Comparative_Analysis/PCA/' + cast +'/' + task + '/'
if not os.path.exists(newpath):
 	os.makedirs(newpath)
os.chdir(newpath)

fig,ax =plt.subplots(figsize=(10,6))
font = {'family' : 'normal',
         'weight' : 'bold',
         'size'   : 14}
matplotlib.rc('font', **font)

ax.scatter(y_train,y_train_AF,color ='red',label = 'train')
#ax.plot([y_test.min(),y_test.max()], [y_test.min(),y_test.max()], 'k--', lw=4)
ax.plot([y_test.min()-2,y_test.max()+2], [y_test.min()-2, y_test.max()+2], 'k--', lw=4)
data_mean = np.mean(y_train)
ax.plot([y_test.min()-2,y_test.max()+2], [data_mean,data_mean], 'k--', lw=3)
plt.ylim(ymax = y_test.max()+5, ymin = y_test.min()-5)
# plt.ylim(ymax = 29, ymin = 5)
# plt.xlim(xmax =25, xmin = 5)
ax.scatter(y_test,y_test_AF,color ='darkcyan',label = 'test')
ax.legend(loc='best')

ax.set_xlabel('Measured',fontsize =14)
ax.set_ylabel('Predicted',fontsize =14)

ax.legend(loc='upper left')
matplotlib.rc('font', **font)
plt.show()

figname = 'fig_test_pres.png'
fig.savefig(figname)   # save the figure to fil
plt.close(fig)

sio.savemat('Metrics_full.mat',{'r2_test':r2_test,'mse_test':mse_test,'y_pred':y_test_AF,'y_test':y_test,'y_pred_train':y_train_AF,'y_train':y_train})
pickle.dump(learnt_models, open('Models.p', 'wb'))
pickle.dump(kf_total, open('Kfold.p', 'wb'))


import pandas as pd
import numpy as np
data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],
        'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],
        'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}

labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

df = pd.DataFrame(data, index=labels)
print(df)
#1.根据给定的 DataFrame 中取出索引为 3, 4, 8 的 animal 和 age 字段。
#索引3：animal - dog age - nan
#索引4：animal - dog age - 5.0
#索引8：animal - dog age - 7.0
for i in range(len(df)):
        if  i == 3 or i==4 or i==8:
                print(df.animal[i])
                print(df.age[i])
#2.请将 dataFrame 所有字串都变成是大写开头。
df = pd.DataFrame([
    ['tom', 'mark', 'mary'],
    ['bob', 'alice', 'john']
])
print(df)
df[0] = df[0].str.title()
df[1] = df[1].str.title()
df[2] = df[2].str.title()
print(df)


from django.urls import path, include
from website.views import index, cadastro_candidato, cadastro_empresa, login, cadastro_cv, pagina_candidato, pagina_empresa, informacao_candidato

app_name = 'curriculos'

urlpatterns = [
    path('', index),
    path('login', login),
    path('cadastro_empresa', cadastro_empresa),
    path('cadastro_candidato', cadastro_candidato),
    path('cadastro_cv', cadastro_cv),
    path('pagina_candidato', pagina_candidato),
    path('pagina_empresa', pagina_empresa),
    path('candidato/<int:id>', informacao_candidato, name ='curriculo')
]


import numpy as np
import cv2

cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG2()
title_window = "Substraction"
slider_max = 255
learning_rate = 0.5
cv2.namedWindow(title_window, cv2.WINDOW_NORMAL)
ret, frame = cap.read()
rows,cols,channels = frame.shape

def on_trackbar(val):
    global learning_rate
    learning_rate = float(val)/slider_max
    print(f"Using learning rate {learning_rate}")
cv2.createTrackbar('Learning Rate Trackbar', title_window , 0, slider_max, on_trackbar)

while(1):
    ret, frame = cap.read()
    grey_image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    fgmask = fgbg.apply(grey_image, None, learning_rate)
    background = fgbg.getBackgroundImage()
    cv2.imshow('Original', grey_image)
    cv2.imshow(title_window, fgmask)
    cv2.imshow('Background', background)
    if cv2.waitKey(30) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()


#입력의 첫 줄은 국가의 수 N(1 ≤ N ≤ 1,000)과 등수를 알고 싶은 국가 K(1 ≤ K ≤ N)가 빈칸을 사이에 두고 주어진다. 각 국가는 1부터 N 사이의 정수로 표현된다. 이후 N개의 각 줄에는 차례대로 각 국가를 나타내는 정수와 이 국가가 얻은 금, 은, 동메달의 수가 빈칸을 사이에 두고 주어진다. 전체 메달 수의 총합은 1,000,000 이하이다.
#각각의 구분을 두고 금메달에 100을 곱하고 은메달에는 10을 곱하고 동메달에는 1을 곱해서 각 합을 구해준다. 그 합을 비교로 하고 k는 그 기준점으로 값을 출력한다
#따라서 필요한 건 어떻게 각각의 것을 분류해줄 것인지 하고 그걸 어떻게 더해줄지이다.

n, k = map(int, input().split())
s = [1, 0, 0, 0, 0, 1, 0, 1, 0, 1, ]
for i in range(0, n):
  a, b, c, d = map(int, input().split())
  s[i] = b*100 + c*10 + d

alpha = 1
for i in range(0, n):
  if s[k-1] < s[i]:
    alpha += 1

print(alpha)


"""01. Match Tickets"""
# budget = float(input())
# category = input()
# number_of_fans = int(input())
#
# transport = 0
# price = 0
#
# if 1 <= number_of_fans <= 4:
#     transport = budget * 0.75
# elif 5 <= number_of_fans <= 9:
#     transport = budget * 0.60
# elif 10 <= number_of_fans <= 24:
#     transport = budget * 0.50
# elif 25 <= number_of_fans <= 49:
#     transport = budget * 0.40
# elif number_of_fans >= 50:
#     transport = budget * 0.25
#
# if category == "VIP":
#     price = 499.99
# elif category == "Normal":
#     price = 249.99
#
# total = transport + (price * number_of_fans)
#
# if total <= budget:
#     print(f"Yes! You have {budget - total:.2f} leva left.")
# else:
#     print(f"Not enough money! You need {total - budget:.2f} leva.")
##################################################################################################
"""02. Bike Race"""
# juniors = int(input())
# seniors = int(input())
# trail_type = input()
#
# juniors_price = 0
# seniors_price = 0
#
# if trail_type == "trail":
#     juniors_price = 5.50 * juniors
#     seniors_price = 7 * seniors
# elif trail_type == "cross-country":
#     juniors_price = 8 * juniors
#     seniors_price = 9.50 * seniors
#     if juniors + seniors >= 50:
#         juniors_price *= 0.75
#         seniors_price *= 0.75
# elif trail_type == "downhill":
#     juniors_price = 12.25 * juniors
#     seniors_price = 13.75 * seniors
# elif trail_type == "road":
#     juniors_price = 20 * juniors
#     seniors_price = 21.50 * seniors
#
# total = juniors_price + seniors_price
# total *= 0.95
#
# print(f"{total:.2f}")
##################################################################################################
"""03. Flowers"""
# chrysanthemums = int(input())
# roses = int(input())
# tulips = int(input())
# season = input()
# holiday = input()
#
# total = 0
#
# if season == "Spring" or season == "Summer":
#     total = (chrysanthemums * 2) + (roses * 4.10) + (tulips * 2.50)
# elif season == "Autumn" or season == "Winter":
#     total = (chrysanthemums * 3.75) + (roses * 4.50) + (tulips * 4.15)
#
# if holiday == "Y":
#     total *= 1.15
#
# if season == "Spring" and total > 7:
#     total *= 0.95
# elif season == "Winter" and roses >= 10:
#     total *= 0.90
#
# if (chrysanthemums + roses + tulips) > 20:
#     total *= 0.80
#
# total += 2
#
# print(f"{total:.2f}")
####################################################################################################
"""04. Car To Go"""
# budget = float(input())
# season = input()
#
# car_type = ""
# rent_class = ""
# car_price = 0
#
# if budget <= 100:
#     rent_class = "Economy class"
#     if season == "Summer":
#         car_type = "Cabrio"
#         car_price = budget * 0.35
#     elif season == "Winter":
#         car_type = "Jeep"
#         car_price = budget * 0.65
#
# elif 100 < budget <= 500:
#     rent_class = "Compact class"
#     if season == "Summer":
#         car_type = "Cabrio"
#         car_price = budget * 0.45
#     elif season == "Winter":
#         car_type = "Jeep"
#         car_price = budget * 0.80
#
# elif budget > 500:
#     rent_class = "Luxury class"
#     car_type = "Jeep"
#     car_price = budget * 0.90
#
# print(f"{rent_class}")
# print(f"{car_type} - {car_price:.2f}")
###################################################################################################
"""05. Vacation"""
# budget = float(input())
# season = input()
#
# place = ""
# country = ""
# price = 0
#
# if budget <= 1000:
#     place = "Camp"
#     if season == "Winter":
#         country = "Morocco"
#         price = budget * 0.45
#     elif season == "Summer":
#         country = "Alaska"
#         price = budget * 0.65
#
# elif 1000 < budget <= 3000:
#     place = "Hut"
#     if season == "Winter":
#         country = "Morocco"
#         price = budget * 0.60
#     elif season == "Summer":
#         country = "Alaska"
#         price = budget * 0.80
#
# elif budget > 3000:
#     place = "Hotel"
#     price = budget * 0.90
#     if season == "Winter":
#         country = "Morocco"
#     elif season == "Summer":
#         country = "Alaska"
#
# print(f"{country} - {place} - {price:.2f}")
################################################################################################
""""06. Truck Driver"""
# season = input()
# distance = float(input())
#
# price = 0
#
# if 10000 < distance <= 20000:
#     price = distance * 1.45
#
# elif season == "Spring" or season == "Autumn":
#     if distance <= 5000:
#         price = distance * 0.75
#     elif 5000 < distance <= 10000:
#         price = distance * 0.95
#
# elif season == "Summer":
#     if distance <= 5000:
#         price = distance * 0.90
#     elif 5000 < distance <= 10000:
#         price = distance * 1.10
#
# elif season == "Winter":
#     if distance <= 5000:
#         price = distance * 1.05
#     elif 5000 < distance <= 10000:
#         price = distance * 1.25
#
# total = (price * 4) * 0.90
#
# print(f"{total:.2f}")
################################################################################################
"""07. School Camp"""
# season = input()
# group_type = input()
# number_of_students = int(input())
# nights = int(input())
#
# price = 0
# sport = ""
#
# if season == "Winter":
#     if group_type == "boys" or group_type == "girls":
#         price = nights * 9.60
#         if group_type == "boys":
#             sport = "Judo"
#         elif group_type == "girls":
#             sport = "Gymnastics"
#     elif group_type == "mixed":
#         price = nights * 10
#         sport = "Ski"
#
# elif season == "Spring":
#     if group_type == "boys" or group_type == "girls":
#         price = nights * 7.20
#         if group_type == "boys":
#             sport = "Tennis"
#         elif group_type == "girls":
#             sport = "Athletics"
#     elif group_type == "mixed":
#         price = nights * 9.50
#         sport = "Cycling"
#
# elif season == "Summer":
#     if group_type == "boys" or group_type == "girls":
#         price = nights * 15
#         if group_type == "boys":
#             sport = "Football"
#         elif group_type == "girls":
#             sport = "Volleyball"
#     elif group_type == "mixed":
#         price = nights * 20
#         sport = "Swimming"
#
# total = price * number_of_students
#
# if number_of_students >= 50:
#     total *= 0.50
# elif 10 <= number_of_students < 20:
#     total *= 0.95
# elif 20 <= number_of_students < 50:
#     total *= 0.85
#
# print(f"{sport} {total:.2f} lv.")
#################################################################################################
"""08. Point on Rectangle Border"""
# x1 = float(input())
# y1 = float(input())
# x2 = float(input())
# y2 = float(input())
# x = float(input())
# y = float(input())
#
# if (x == x1 or x == x2) and (y1 <= y<= y2):
#     print("Border")
# elif (y == y1 or y == y2) and (x1 <=x <= x2):
#     print("Border")
# else:
#     print("Inside / Outside")
#################################################################################################
"""09. Numbers from 1 to 10"""
# for number in range(1, 11):
#     print(number)
#################################################################################################
"""10. Multiply by 2"""
while True:
    number = float(input())

    if number < 0:
        print(f"Negative number!")
        break
    else:
        number *= 2
        print(f"Result: {number:.2f}")


import pandas as pd
import numpy as np

from utils import paths, read, save
from utils.consts import features, datasets, n_candidates, undersampling_percentages

def check_features(feats, cands):
    """Checks if the candidates dataframe is the same as the features
    dataframe after merging (e.g., if there are no repeated entries)
    """
    same_size = len(cands) == len(feats)
    same_dups = set(cands.dup_id) == set(feats.dup_id)
    same_rels = set(cands.candidate_id) == set(feats.candidate_id)

    return same_size and same_dups and same_rels

def make_test(ds, feats):
    """Creates a test dataset by joining features to the test candidate pairs"""
    cands = read(paths.test_candidate_pairs(ds))
    test = merge_features(ds, cands.copy(), feats)

    assert check_features(
        test, cands
    ), "The test dataset is different from its candidates!"
    assert not test.isna().any().any(), "The test dataset has NaNs!"

    save(test, paths.test_set(ds))

def make_train(ds, n, p, feats):
    """Creates a train dataset by joining features to one of the train candidate pairs set"""
    cands = read(paths.train_candidate_pairs(ds, n, p))
    train = merge_features(ds, cands.copy(), feats)

    assert check_features(
        train, cands
    ), f"The train dataset ({n}, {p}) is different from its candidates!"
    assert not train.isna().any().any(), f"The train dataset ({n}, {p}) has NaNs!"

    save(train, paths.train_set(ds, n, p))

def merge_features(ds, cands, feats):
    """Merges the features with the candidate pairs for a give dataset"""
    # only keeps the relevant columns for the feature set
    # score will later be used to truncate the test set and allow for
    # evaluation on a different number of candidates
    cands = cands[["dup_id", "candidate_id", "score", "is_dup"]]
    for f in feats:
        df_feat = read(paths.feature(ds, f))
        cands = cands.merge(df_feat, on=["candidate_id", "dup_id"], how="left")
    return cands

def make_train_multi(ds, ns, ps, feats):
    """Creates train sets of features for all combinations of candidate pairs and
    undersampling percentages
    """
    for n in ns:
        for p in ps:
            print(f"- Making train set ({n}, {p})")
            make_train(ds, n, p, feats)

def make_sets_multi(datasets, ns, ps, feats):
    """Creates train and test sets of features for all combinations of candidate pairs and
    undersampling percentages for the given datasets
    """
    for ds in datasets:
        print(f"Creating train and test sets for {ds}")
        make_train_multi(ds, ns, ps, feats)
        make_test(ds, feats)

def make_sets(datasets, n, p, feats):
    """Creates train and test sets of features for one value of candidate pairs and
    undersampling percentages for the given datasets
    """
    for ds in datasets:
        print(f"Creating train and test sets for {ds}")
        make_train(ds, n, p, feats)
        make_test(ds, feats)

if __name__ == "__main__":
    make_sets_multi(datasets, n_candidates, undersampling_percentages, features)


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 21 23:05:06 2019

@author: PereiraJoao
"""
import math as m

def TwistEqForShear(qb_1, qb_2, qb_3, qb_4, qb_5):

    #INPUTS AND GENERAL INFO ON GEOMETRIES------------------------------
    C_a = 0.547 #chord length
    h_a = 0.225 #Spar height
    R = h_a/2. # Radius arc (half the length of spar)
    A1 = (m.pi*R**2)/2 #Area cell leading
    A2 = ((C_a-R)*R)/2 #Area cell trailing
    G = 28*(10**9) #Shear modulus [Gpa]
    t_skin = 0.0011 #skin thikness [m]
    t_spar = 0.0029 #spar thikness [m]

    l_arc = 2*m.pi*(R)*(90./360.) #half the length of the leading edge arc
    l_panel = m.sqrt((C_a-(R))**2. + (R)**2.) #airfoil panel length

    # TWIST RATE EQUATION FOR CELL 1 (FORWARD CELL)----------------------

    #Terms from the base shear flows
    intqb_1 = 0 #Integral for top half of the leading edge arc
    for i in range(len(qb_1)):
        intqb_1 += qb_1[i] * (l_arc/len(qb_1)) / t_skin

    intqb_4 = 0 #Integral for the bottom half of the leading edge arc
    for i in range(len(qb_4)):
        intqb_4 += qb_4[i] * (l_arc/len(qb_4)) / t_skin

    intqb_3 = 0 #Integral for the spar
    for i in range(len(qb_3)):
        intqb_3 += qb_3[i] * (h_a/len(qb_3)) / t_spar

    sum_int_cell1 = (1/(2*A1*G)) * (intqb_1 + intqb_3 - intqb_4)

    #Terms for complimentary shear flows
    C11 = (1/(2*A1*G)) * ((l_arc*2)/t_skin + h_a/t_spar)
    C12 = (1/(2*A1*G)) * (h_a/t_spar)

    # TWIST RATE EQUATION FOR CELL 2 (AFT CELL)--------------------------

    #Terms from the base shear flows
    intqb_2 = 0 #Integral for the top panel
    for i in range(len(qb_2)):
        intqb_2 += qb_2[i] * (l_panel/len(qb_2)) / t_skin

    intqb_5 = 0 #Integral for the bottom panel
    for i in range(len(qb_5)):
        intqb_5 += qb_5[i] * (l_panel/len(qb_5)) / t_skin

    #intqb_3 ---> this integral is used again, it is the same as calculated for cell1

    sum_int_cell2 = (1/(2*A2*G)) * (-intqb_2 + intqb_5 - intqb_3) #before -+

    #Terms for complimentary shear flows
    C21 = (1/(2*A2*G)) * (2*l_panel/t_skin + h_a/t_spar)
    C22 = (1/(2*A2*G)) * (h_a/t_spar)

    #OBTAINING ALL TWIST EQUATION COEFFICIENTS WHEN THE 2 EQUATIONS (FOR CELL 1 & 2) ARE EQUALIZED

    D1 = C11-C21
    D2 = C12 - C22
    D0 =  sum_int_cell1 - sum_int_cell2
    D = [D0, D1, D2]  #coefficients in the form 0 = D1*qs01 + D2*qs02 + D0

    return D