from lxml import etree
import random
import math
import copy
import argparse
from collections import namedtuple

class Tree:
  def __init__(self, id_in, pose_in, scale_in, mesh_num_in):
    self.id = 'tree' + str(id_in)
    self.pose = pose_in
    self.scale = scale_in
    self.mesh_num = mesh_num_in

class GenXML:
  def __init__(self):
    self.root = etree.Element('world',name='default')

    #add ground
    include_el = etree.Element('include')
    ground_el = etree.Element('uri')
    ground_el.text = 'model://ground_plane'
    include_el.append(ground_el)
    self.root.append(include_el)

    #add sun
    include_el = etree.Element('include')
    sun_el = etree.Element('uri')
    sun_el.text = 'model://sun'
    include_el.append(sun_el)
    self.root.append(include_el)

    #disable shadows
    scene_el= etree.Element('scene')
    shadows_el = etree.Element('shadows')
    shadows_el.text = '0'
    scene_el.append(shadows_el)
    self.root.append(scene_el)

    #create the forest base model
    model_el = etree.Element('model', name = 'forest')
    static_el = etree.Element('static')
    static_el.text = 'true'
    model_el.append(static_el)
    self.root.append(model_el)

    #plugins
    self.add_plugins()

    #physics
    self.add_physics()

  def add_model(self, name_in, pose_in, scale_in, mesh_num_in, models_type):

    link_el = etree.Element('link', name = name_in)

    pose_el = etree.Element('pose')
    pose_el.text = ''.join(str(e) + ' ' for e in pose_in)
    link_el.append(pose_el)

    visual_el = etree.Element('visual', name = 'visual')
    geometry_el = etree.Element('geometry')
    mesh_el = etree.Element('mesh')
    uri_el = etree.Element('uri')
    uri_el.text = 'file://' + models_type + '/Tree' + str(mesh_num_in) + '.dae'
    mesh_el.append(uri_el)
    scale_el = etree.Element('scale')
    scale_el.text = str(scale_in) + ' ' + str(scale_in) + ' ' + str(scale_in)
    mesh_el.append(scale_el)
    geometry_el.append(mesh_el)
    visual_el.append(geometry_el)
    link_el.append(visual_el)

    collision_el = etree.Element('collision', name = 'collision')
    collision_el.append(copy.deepcopy(geometry_el))
    contacts_el = etree.Element('max_contacts')
    contacts_el.text = '0'
    collision_el.append(contacts_el)
    link_el.append(collision_el)

    self.root.find('model').append(link_el)

  def add_plugins(self):
    #start plugin section
    plugins_comment_el = etree.Comment(' Plugins ')
    self.root.append(plugins_comment_el)

    #add octomap plugin
    oct_plug_el = etree.Element('plugin', name = 'gazebo_octomap',
                                filename = 'librotors_gazebo_octomap_plugin.so')
    self.root.append(oct_plug_el)

    #add rotors interface plugin
    rotors_plug_el = etree.Element('plugin', name = 'ros_interface_plugin',
                                   filename =
                                   'librotors_gazebo_ros_interface_plugin.so')
    self.root.append(rotors_plug_el)

  def add_physics(self):
    #start physics section
    physics_comment_el = etree.Comment(' Physics ')
    self.root.append(physics_comment_el)

    #physics
    physics_el = etree.Element('physics', name = 'default_physics',
                               default = '0', type = 'ode')
    max_step_size_el = etree.SubElement(physics_el, 'max_step_size')
    max_step_size_el.text = '0.01'
    real_time_factor_el = etree.SubElement(physics_el, 'real_time_factor')
    real_time_factor_el.text = '1'
    real_time_update_rate_el = etree.SubElement(physics_el,
                                                'real_time_update_rate')
    real_time_update_rate_el.text = '100'
    gravity_el = etree.SubElement(physics_el, 'gravity')
    gravity_el.text = '0 0 -9.8'
    magnetic_field_el = etree.SubElement(physics_el, 'magnetic_field')
    magnetic_field_el.text = '6e-06 2.3e-05 -4.2e-05'

    #ode
    ode_el = etree.SubElement(physics_el, 'ode')
    #solver
    solver_el = etree.SubElement(ode_el, 'solver')
    type_el = etree.SubElement(solver_el, 'type')
    type_el.text = 'quick'
    iters_el = etree.SubElement(solver_el, 'iters')
    iters_el.text = '1000'
    sor_el = etree.SubElement(solver_el, 'sor')
    sor_el.text = '1.3'
    use_dynamic_moi_rescaling = etree.SubElement(solver_el,
                                                 'use_dynamic_moi_rescaling')
    use_dynamic_moi_rescaling.text = '0'
    #constraints
    constraints_el = etree.SubElement(ode_el, 'constraints')
    cfm_el = etree.SubElement(constraints_el, 'cfm')
    cfm_el.text = '0'
    erp_el = etree.SubElement(constraints_el, 'erp')
    erp_el.text = '0.2'
    contact_max_correcting_vel_el = etree.SubElement(constraints_el,
                                                  'contact_max_correcting_vel')
    contact_max_correcting_vel_el.text = '100'
    contact_surface_layer_el = etree.SubElement(constraints_el,
                                                  'contact_surface_layer')
    contact_surface_layer_el.text = '0.001'
    self.root.append(physics_el)

  def output_xml(self):
    sdf = etree.Element('sdf',version='1.4')
    sdf.append(self.root)

    return '<?xml version="1.0"?>\n' + etree.tostring(sdf, pretty_print=True)

class World:
  TOTAL_NUM_MESHES = 6

  def __init__(self, world_length, use_high_res):
    self.world_length = world_length
    self.trees = []

    if(use_high_res):
      self.models_type = 'models_high_res'
    else:
      self.models_type = 'models_low_res'

  def _gen_random_tree(self):
    id_num = len(self.trees)
    x = random.uniform(-self.world_length/2, self.world_length/2)
    y = random.uniform(-self.world_length/2, self.world_length/2)
    angle = random.uniform(0, 2*math.pi)
    scale = random.uniform(0.3, 1)
    mesh_num = random.randint(1, self.TOTAL_NUM_MESHES)

    return Tree(id_num, [x,y,0,0,0,angle], scale, mesh_num)

  def add_trees(self, num_trees):
    for i in range(num_trees):
      self.trees.append(self._gen_random_tree())

  def save_world(self, filename):

    xml = GenXML()
    for tree in self.trees:
      xml.add_model(tree.id,
                    tree.pose,
                    tree.scale,
                    tree.mesh_num,
                    self.models_type)

    text_file = open(filename, "w")
    text_file.write(xml.output_xml())
    text_file.close()

def gen_worlds(save_path, num_worlds, world_length, num_trees, use_high_res):
  for i in range(num_worlds):
    world = World(world_length, use_high_res)
    world.add_trees(num_trees)
    world.save_world(save_path + '/forest' + str(i) + '.world')

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Generate a random gazebo forest.')
    parser.add_argument('--num_worlds', type=int, help='Number of worlds to generate')
    parser.add_argument('--world_length', type=int, help='Length and width of world in m')
    parser.add_argument('--tree_density', type=float, help='Number of trees per m^2')
    parser.add_argument('--high_res', type=int, help='Use high res tree models')
    args = parser.parse_args()

    gen_worlds('./worlds', args.num_worlds, args.world_length,
               int(args.world_length*args.world_length*args.tree_density),
               bool(args.high_res))


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

ERR_SUCCESS = 0
ERR_FAILED = 1
ERR_CLOSE_SOCKET = 2
ERR_UNKNOWN_REQUEST = 100
ERR_UNREGISTERED_CLIENT_ID = 101
ERR_UNSUPPORTED_PROTOCOL = 102
ERR_URL_EXISTED = 103
ERR_CLIENT_ID_NOT_EXIST = 104

MSG = {
    ERR_SUCCESS: "Success",
    ERR_FAILED: "Failed with internal error",
    ERR_CLOSE_SOCKET: "Error, should close socket",
    ERR_UNKNOWN_REQUEST: "Unknown request type",
    ERR_UNREGISTERED_CLIENT_ID: "This connection has no login",
    ERR_UNSUPPORTED_PROTOCOL: "Unsupported protocol",
    ERR_URL_EXISTED: "url existed",
    ERR_CLIENT_ID_NOT_EXIST: "client id not exist in server",
}

def get_err_msg(err):
    if err not in MSG:
        return None
    else:
        return MSG[err]


'''
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额，返回 -1。

示例 1:

输入: coins = [1, 2, 5], amount = 11
输出: 3
解释: 11 = 5 + 5 + 1
示例 2:

输入: coins = [2], amount = 3
输出: -1
说明:
你可以认为每种硬币的数量是无限的。
'''

# Solution1:递归解法
# 这种递归属于多路径递归,人脑不可能人肉模拟完整的递和归过程,只能通过递归树和假设子问题已经得到解决的方式来写递推公式
def coinChange(coins, amount):
    def helper(value):
        if value == 0: return 0
        res = float('inf')
        for coin in coins:
            if value - coin < 0: continue
            sub_res = helper(value-coin)
            if sub_res == -1: continue
            res = min(res, helper(value-coin)+1)
        return res if res != float('inf') else -1

    return helper(amount)

# Solution2:加备忘录的递归解法
def coinChange(coins, amount):
    def helper(value):
        if value in d: return d[value]
        if value == 0: return 0
        res = float('inf')
        for coin in coins:
            if value - coin < 0: continue
            sub_res = helper(value-coin)
            if sub_res == -1: continue
            res = min(res, sub_res+1)
        d[value] = res if res != float('inf') else -1
        return d[value]

    d = {}
    return helper(amount)

# Solution3:动态规划
# 递归的解法思路是把大数值一直拆分递归到小数值,即要找到递归的终止条件
# 动态规划的解法思路是从小数值开始,推算出大数值的求值规律
def coinChange(coins, amount):
    if not coins or not coins[0]: return -1
    cache = [amount+1] * (amount+1)
    cache[0] = 0
    for i in range(1, amount+1):
        for coin in coins:
            if coin <= i:
                cache[i] = min(cache[i], cache[i-coin]+1)
    return -1 if cache[amount] > amount else cache[amount]

if __name__ == '__main__':
    print(coinChange([408, 186, 83, 419], 6249))
    # print(coinChange([1, 2, 5, 10], 27))


"""
Assignment 4-1
Name: 蘇柏瑜
Student Number: 107201522
Course 2020-CE1001
"""
f=open('score.txt','r')
fline=f.readlines()
text=fline[0]
for i in range(1,len(fline)):
    string=str(fline[i])
    text=text+string.split("\n")[0]
    a=string.split(" ")
    ascore = int(a[1])
    for k in range(1,len(a)):
        score=int(a[k])
        if  k+1<len(a):
            ascore=ascore+int(a[k+1])
        if  k==len(a)-1:
            k=ascore/4
    text=text+" "+str(k)+"\n"
print(text)
filename=('score_107201522.txt','w')
f1=open('score_107201522.txt','w')
f1.write(text)
f1.close()


from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
from six.moves import range

import numpy as np
import librosa
import librosa.filters

def get_speech_features_from_file(
    filename,
    num_features,
    features_type='magnitude',
    window_size=1024,
    window_stride=256,
    mag_power=2,
    feature_normalize=False,
    mean=0.,
    std=1.
):
  """ Helper function to retrieve spectrograms from wav files

  Args:
    filename (string): WAVE filename.
    num_features (int): number of speech features in frequency domain.
    features_type (string): 'magnitude' or 'mel'.
    window_size (int): size of analysis window in samples.
    window_stride (int): stride of analysis window in samples.
    mag_power (int): power to raise magnitude spectrograms (prior to dot product
      with mel basis)
      1 for energy spectrograms
      2 fot power spectrograms
    feature_normalize(bool): whether to normalize the data with mean and std
    mean(float): if normalize is enabled, the mean to normalize to
    std(float): if normalize is enabled, the deviation to normalize to

  Returns:
    np.array: np.array of audio features with shape=[num_time_steps,
      num_features].
  """
  # load audio signal
  signal, fs = librosa.core.load(filename, sr=None)
  return get_speech_features(
      signal, fs, num_features, features_type, window_size,
      window_stride, mag_power, feature_normalize, mean, std
  )

def get_speech_features(
    signal,
    fs,
    num_features,
    features_type='magnitude',
    n_window_size=1024,
    n_window_stride=256,
    mag_power=2,
    feature_normalize=False,
    mean=0.,
    std=1.
):
  """ Helper function to retrieve spectrograms from loaded wav

  Args:
    signal: signal loaded with librosa.
    fs (int): sampling frequency in Hz.
    num_features (int): number of speech features in frequency domain.
    features_type (string): 'magnitude' or 'mel'.
    window_size (int): size of analysis window in samples.
    window_stride (int): stride of analysis window in samples.
    mag_power (int): power to raise magnitude spectrograms (prior to dot product
      with mel basis)
      1 for energy spectrograms
      2 fot power spectrograms
    feature_normalize(bool): whether to normalize the data with mean and std
    mean(float): if normalize is enabled, the mean to normalize to
    std(float): if normalize is enabled, the deviation to normalize to

  Returns:
    np.array: np.array of audio features with shape=[num_time_steps,
      num_features].
  """
  if features_type == 'magnitude':
    complex_spec = librosa.stft(y=signal, n_fft=n_window_size)
    mag, _ = librosa.magphase(complex_spec, power=mag_power)
    features = np.log(np.clip(mag, a_min=1e-5, a_max=None)).T
    assert num_features <= n_window_size // 2 + 1, \
        "num_features for spectrogram should be <= (fs * window_size // 2 + 1)"

    # cut high frequency part
    features = features[:, :num_features]
  elif features_type == 'mel':
    features = librosa.feature.melspectrogram(
        y=signal,
        sr=fs,
        n_fft=n_window_size,
        hop_length=n_window_stride,
        n_mels=num_features,
        power=mag_power
    )
    features = np.log(np.clip(features, a_min=1e-5, a_max=None)).T
  else:
    raise ValueError('Unknown features type: {}'.format(features_type))

  if feature_normalize:
    features = normalize(features, mean, std)

  return features

def get_mel(
    log_mag_spec,
    fs=22050,
    n_fft=1024,
    n_mels=80,
    power=2.,
    feature_normalize=False,
    mean=0,
    std=1,
    mel_basis=None
):
  """
  Method to get mel spectrograms from magnitude spectrograms

  Args:
    log_mag_spec (np.array): log of the magnitude spec
    fs (int): sampling frequency in Hz
    n_fft (int): size of fft window in samples
    n_mels (int): number of mel features
    power (float): power of the mag spectrogram
    feature_normalize (bool): whether the mag spec was normalized
    mean (float): normalization param of mag spec
    std (float): normalization param of mag spec
    mel_basis (np.array): optional pre-computed mel basis to save computational
      time if passed. If not passed, it will call librosa to construct one

  Returns:
    np.array: mel_spec with shape [time, n_mels]
  """
  if mel_basis is None:
    mel_basis = librosa.filters.mel(fs, n_fft, n_mels=n_mels)
  log_mag_spec = log_mag_spec * power
  mag_spec = np.exp(log_mag_spec)
  mel_spec = np.dot(mag_spec, mel_basis.T)
  mel_spec = np.log(np.clip(mel_spec, a_min=1e-5, a_max=None))
  if feature_normalize:
    mel_spec = normalize(mel_spec, mean, std)
  return mel_spec

def inverse_mel(
    log_mel_spec,
    fs=22050,
    n_fft=1024,
    n_mels=80,
    power=2.,
    feature_normalize=False,
    mean=0,
    std=1,
    mel_basis=None
):
  """
  Very hacky method to reconstruct mag spec from mel

  Args:
    log_mel_spec (np.array): log of the mel spec
    fs (int): sampling frequency in Hz
    n_fft (int): size of fft window in samples
    n_mels (int): number of mel features
    power (float): power of the mag spectrogram that was used to generate the
      mel spec
    feature_normalize (bool): whether the mel spec was normalized
    mean (float): normalization param of mel spec
    std (float): normalization param of mel spec
    mel_basis (np.array): optional pre-computed mel basis to save computational
      time if passed. If not passed, it will call librosa to construct one

  Returns:
    np.array: mag_spec with shape [time, n_fft/2 + 1]
  """
  if mel_basis is None:
    mel_basis = librosa.filters.mel(fs, n_fft, n_mels=n_mels)
  if feature_normalize:
    log_mel_spec = denormalize(log_mel_spec, mean, std)
  mel_spec = np.exp(log_mel_spec)
  mag_spec = np.dot(mel_spec, mel_basis)
  mag_spec = mag_spec * 876
  mag_spec = np.power(mag_spec, 1. / power)
  return mag_spec

def normalize(features, mean, std):
  """
  Normalizes features with the specificed mean and std
  """
  return (features - mean) / std

def denormalize(features, mean, std):
  """
  Normalizes features with the specificed mean and std
  """
  return features * std + mean


import pptk
import numpy as np
def graph(points, f = None):

    if f is not None:
        points = []
        with open(f, 'r') as doc:
            line = doc.readline()
            while line:
                ls = line.split(',')
                ls[2] = ls[2].strip('\n')
                points.append(ls)
                line = doc.readline()
    v = pptk.viewer(points)
    input()

graph(None, f="t.txt")


from django.shortcuts import render
from django.core.cache import cache
from . import utils

def index(request):
    return render(request, "index_page.html")

def words_list(request):
    words = utils.get_words_for_table()
    return render(request, "show_word_list_page.html",
                  context={"words": words})

def add_word(request):
    return render(request, "add_word_page.html")

def send_word_add(request):
    if request.method == "POST":
        cache.clear()
        email = request.POST.get("email")
        word = request.POST.get("word", "")
        translation = request.POST.get("translation", "")
        context = {}
        utils.add_word(word, translation, email)
        return render(request, "add_word_res_page.html", context)
    else:
        add_word(request)

def find_word(request):
    return render(request, "find_word_page.html")

def send_word_translate(request):
    if request.method == "POST":
        cache.clear()
        search_type = request.POST.get("search_type")
        search_object = request.POST.get("search_object")
        context = {"search_type_word": (search_type == 'word'),
                   "search_object": search_object,
                   "results": utils.find_word(search_type, search_object)}
        if len(context["results"]) == 0:
            context["success"] = False
        else:
            context["success"] = True
        return render(request, "find_word_res_page.html", context)
    else:
        find_word(request)

def show_stats(request):
    stats = utils.get_words_stats()
    return render(request, "show_stats_page.html", stats)


from reportlab.lib import colors
from Bio.Graphics import GenomeDiagram
from Bio import SeqIO

# Recebendo o arquivo
arquivo = SeqIO.read("NC_017108.gbk", "genbank")

# Configuracoes basicas
gd_diagram = GenomeDiagram.Diagram("Marcadores")
gd_track_for_features = gd_diagram.new_track(1, name="Anotacoes")
gd_feature_set = gd_track_for_features.new_set()

# Imprime as features de maneira intercalada
for feature in arquivo.features:

	if feature.type == "rRNA":
		color = colors.blue
		gd_feature_set.add_feature(feature, color=color, label=True)

	elif feature.type == "tRNA":
		color = colors.green
		feature.qualifiers['locus_tag'] = feature.qualifiers['product']
		gd_feature_set.add_feature(feature, color=color, label=True)

	elif feature.type == "gene":

		if len(gd_feature_set) % 2 == 0:
			color = colors.HexColor('#BBBBBB')
		else:
			color = colors.HexColor('#DDDDDD')

		gd_feature_set.add_feature(feature, color=color, label=False)

	else:
		continue

# Desenhando
gd_diagram.draw(format="circular", circular=True, pagesize=(20*cm,20*cm),start=0, end=len(arquivo), circle_core=0.7)

# Salvand em 2 formatos: PDF e PNG
gd_diagram.write("completo.pdf", "PDF")
gd_diagram.write("completo.png", "PNG")


x = 1
while x < 5:
    print(x)
    x += 1

while True:  # этот цикл сам по себе не закончится никогда потому как всегда будет True
    user_say = input('Скажи что-нибудь:/n ')
    if user_say == 'Пока':
        print('Ну пока')
        break
    else:
        print('Сам ты {}'.format(user_say))


import pandas as pd
import streamlit as st
import matplotlib.pyplot as plt
import utils

# Read data of MS
df = utils.read_csv()

# Title
st.title('Números da COVID-19 no Brasil')

# DataEnd and DataStart
date_end = df['data'].iloc[-1].date()
date_start = df['data'].iloc[0].date()

# Input users
date = st.date_input('Selecione a Data', date_end, date_start,
                     date_end, help='Coloque a data que queira gerar o relatório.')

# Cod. UF
list_uf = [11, 12, 13, 14, 15, 16, 17, 21, 22, 23, 24, 25,
           26, 27, 28, 29, 31, 32, 33, 35, 41, 42, 43, 50, 51, 53, 76]

# Dataframe Final
df_processed = pd.DataFrame(columns=['Data', 'Estado', 'CasosAcumulado', 'MediaMovelCasosAtual', 'MediaMovelCasosAnterior',
                                     'Situacao', 'Percentual', 'ObitosAcumulado', 'MediaMovelObitosAtual', 'MediaMovelObitosAnterior', 'Situacao', 'Percentual'])

# Calculate to all UF
for uf in list_uf:
    df_mask = df['coduf'] == uf
    filtered_df = df[df_mask]
    # only columns important
    filtered_df = filtered_df.iloc[:, lambda df: [
        1, 3, 7, 8, 9, 10, 11, 12, 13, 14, 15]]
    filtered_df = filtered_df.sort_values(by=['data'])
    # call function to calculate all itens
    list_data = utils.itens_calculate(
        filtered_df, date, date_start, uf)
    df_processed.loc[len(df_processed)] = list_data

# Divide dataframe
df_processed_casos = df_processed.iloc[:, lambda df: [0, 1, 2, 3, 4, 5, 6]]
df_processed_obitos = df_processed.iloc[:, lambda df: [0, 1, 7, 8, 9, 10, 11]]

# show dataframe - Casos
st.header('Número de Casos de COVID-19 no Brasil')
st.dataframe(df_processed_casos)

# Graph 01
st.header('Casos de COVID-19 x Estado')
df_ordenado = df_processed_casos.sort_values(
    by=['CasosAcumulado'], ascending=True)
fig, ax = plt.subplots()
ax.barh(df_ordenado['Estado'][:-1],
        df_ordenado['CasosAcumulado'][:-1])
st.pyplot(fig)

# Graph 02
st.header('Média Móvel de Casos x Estado')
df_ordenado = df_processed_casos.sort_values(
    by=['MediaMovelCasosAtual'], ascending=True)
fig, ax = plt.subplots()
ax.barh(df_ordenado['Estado'][:-1],
        df_ordenado['MediaMovelCasosAtual'][:-1])
st.pyplot(fig)

# show dataframe - Mortes
st.header('Número de Mortes de COVID-19 no Brasil')
st.dataframe(df_processed_obitos)

# Graph 03
st.header('Óbitos por COVID-19 x Estado')
df_ordenado = df_processed_obitos.sort_values(
    by=['ObitosAcumulado'], ascending=True)
fig, ax = plt.subplots()
ax.barh(df_ordenado['Estado'][:-1],
        df_ordenado['ObitosAcumulado'][:-1])
st.pyplot(fig)

# Graph 04
st.header('Média Móvel de Óbitos x Estado')
df_ordenado = df_processed_obitos.sort_values(
    by=['MediaMovelObitosAtual'], ascending=True)
fig, ax = plt.subplots()
ax.barh(df_ordenado['Estado'][:-1],
        df_ordenado['MediaMovelObitosAtual'][:-1])
st.pyplot(fig)


import tensorflow as tf
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import Embedding
from keras.layers import Conv1D, Input, GlobalMaxPooling1D, Multiply, Lambda, Permute,MaxPooling1D, Flatten, LSTM, Bidirectional, GRU, GlobalAveragePooling1D

from keras.datasets import imdb
from keras.objectives import binary_crossentropy
from keras.metrics import binary_accuracy as accuracy
from keras.optimizers import RMSprop
from keras import backend as K
from keras.preprocessing import sequence
from keras.callbacks import ModelCheckpoint
from keras.models import Model
import os, itertools, math

def construct_original_network(emb, data,trainable=True):
	if data in ['imdbcnn']:
		filters = 250
		kernel_size = 3
		hidden_dims = 250

		net = Dropout(0.2, name = 'dropout_1')(emb)

		# we add a Convolution1D, which will learn filters
		# word group filters of size filter_length:
		net = Conv1D(filters,
						 kernel_size,
						 padding='valid',
						 activation='relu',
						 strides=1,
						 name = 'conv1d_1',trainable=trainable)(net)

		# net = Activation('relu', name = 'activation_1')(net)
		# we use max pooling:
		net = GlobalMaxPooling1D(name = 'global_max_pooling1d_1')(net)

		# We add a vanilla hidden layer:
		net = Dense(hidden_dims, name = 'dense_1',trainable=trainable)(net)
		net = Dropout(0.2, name = 'dropout_2')(net)
		net = Activation('relu', name = 'activation_2')(net)

		# We project onto a single unit output layer, and squash it with a sigmoid:
		net = Dense(2, name = 'dense_2',trainable=trainable)(net)
		preds = Activation('softmax', name = 'activation_3')(net)
		return preds

class TextModel():
	def __init__(self, data, train = False):
		self.data = data
		if data in ['imdbcnn']:

			filters = 250
			hidden_dims = 250
			self.embedding_dims = 50
			self.maxlen = 400
			self.num_classes = 2
			self.num_words = 20002
			self.type = 'word'
			if not train:
				K.set_learning_phase(0)

			X_ph = Input(shape=(self.maxlen,), dtype='int32')
			emb_layer = Embedding(self.num_words, self.embedding_dims,
				input_length=self.maxlen, name = 'embedding_1')
			emb_out = emb_layer(X_ph)

			if train:
				preds = construct_original_network(emb_out, data)

			else:
				emb_ph = Input(shape=(self.maxlen,self.embedding_dims), dtype='float32')

				preds = construct_original_network(emb_ph, data)

			if not train:
				model1 = Model(X_ph, emb_out)
				model2 = Model(emb_ph, preds)
				pred_out = model2(model1(X_ph))
				pred_model = Model(X_ph, pred_out)
				pred_model.compile(loss='categorical_crossentropy',
							  optimizer='adam',
							  metrics=['accuracy'])
				self.pred_model = pred_model
				grads = []
				for c in range(self.num_classes):
					grads.append(tf.gradients(preds[:,c], emb_ph))

				grads = tf.concat(grads, axis = 0)
				# [num_classes, batchsize, maxlen, embedding_dims]

				approxs = grads * tf.expand_dims(emb_ph, 0)
				# [num_classes, batchsize, maxlen, embedding_dims]
				self.sess = K.get_session()
				self.grads = grads
				self.approxs = approxs
				self.input_ph = X_ph
				self.emb_out = emb_out
				self.emb_ph = emb_ph
				weights_name = 'original.h5'#[i for i in os.listdir('imdblstm/models/') if i.startswith('original')][0]
				model1.load_weights('{}/models/{}'.format(data, weights_name),
					by_name=True)
				model2.load_weights('{}/models/{}'.format(data, weights_name),
					by_name=True)
				print('Model constructed.')
				# For validating the data.
				emb_weights = emb_layer.get_weights()
				emb_weights[0][0] = np.zeros(50)
				emb_layer.set_weights(emb_weights)
			else:
				pred_model = Model(X_ph, preds)

				pred_model.compile(loss='categorical_crossentropy',
							  optimizer='adam',
							  metrics=['accuracy'])
				self.pred_model = pred_model
				from load_data import Data
				dataset = Data(self.data)
				self.train(dataset)
				print('Training is done.')

	def train(self, dataset):
		if self.data in ['imdbcnn']:
			epochs = 5
			batch_size = 40
			filepath = '{}/models/original.h5'.format(self.data)
			checkpoint = ModelCheckpoint(filepath, monitor='val_acc',
				verbose=1, save_best_only=True, mode='max')
			callbacks_list = [checkpoint]
			# embedding_matrix = np.load('data/embedding_matrix.npy')
			self.pred_model.fit(dataset.x_train, dataset.y_train, validation_data=(dataset.x_val, dataset.y_val),callbacks = callbacks_list, epochs=epochs, batch_size=batch_size)

	def predict(self, x, verbose=0):
		if self.data in ['imdbcnn']:
			if type(x) == list or x.shape[1] < self.maxlen:
				x = np.array(sequence.pad_sequences(x, maxlen=self.maxlen))

			return self.pred_model.predict(x, batch_size = 2500,
				verbose = verbose)


from menu import products
from management import product_handler, tab_handler

def main():
    product = {
        "title": "Feijão",
        "price": 5.0,
        "rating": 7,
        "description": "Feijão bonitão camilo",
        "type": "bakery",
    }
    tab = [
        {"_id": 10, "amount": 3},
        {"_id": 20, "amount": 2},
        {"_id": 21, "amount": 5},
    ]
    required_keys = (
        "description",
        "price",
        "rating",
        "title",
        "type",
    )

    # res = product_handler.get_product_by_id(2)
    # res = product_handler.get_products_by_type("fruit")
    # res = product_handler.add_product(products, product)
    # res = tab_handler.calculate_tab(tab)
    # res = product_handler.menu_report()
    # res = product_handler.add_product_extra(products, *required_keys, **product)

    # print(res)

if __name__ == "__main__":
    main()


"""Tests for Scenarios in BBC interview doc"""
import pytest
from app.hand import Hand
from app.deck import Card, Deck, Suit, Face
from app.game import Game

def test_scenario_one():
    """Test that 2 cards for the single player"""
    game = Game.create_game(1, 0)  # 1 player
    pytest.shared.game = game  # Store hand in Pytest's local test memory for recall later
    game.initial_hand()
    player_hand = game[0].hand
    assert len(player_hand) == 2

def test_scenario_two():
    """if hand is valid take another card"""
    game = pytest.shared.game
    player_hand: Hand = game[0].hand
    if player_hand.valid():
        initial_score = int(player_hand)
        game.hit(0)
        assert initial_score != int(player_hand)
    else:
        pytest.skip(f"Skipped Test: Hand not valid {player_hand.values()}")

# We don't test scenario three (if stand) due having no stand function due to my implementation of game

def test_scenario_four_and_five():
    """if hand is valid and score of 21"""
    game = pytest.shared.game
    player_hand: Hand = game[0].hand
    if int(player_hand) <= 21:
        assert player_hand.valid()
    elif int(player_hand) > 21:
        assert not player_hand.valid()

def test_scenario_six():
    """Test value when hand has a king and ace"""
    hand = Hand()
    hand.add_card(Card(Suit.DIAMONDS, Face.KING))  # 10
    hand.add_card(Card(Suit.HEARTS, Face.ACE))  # 11
    assert int(hand) == 21

def test_scenario_seven():
    """Test value when hand has a king, queen and ace"""
    hand = Hand()
    hand.add_card(Card(Suit.DIAMONDS, Face.KING))  # 10
    hand.add_card(Card(Suit.DIAMONDS, Face.QUEEN))  # 10
    hand.add_card(Card(Suit.HEARTS, Face.ACE))  # 1
    assert int(hand) == 21

def test_scenario_eight():
    """Test value when hand has a king, queen and ace"""
    hand = Hand()
    hand.add_card(Card(Suit.DIAMONDS, 9))  # 10
    hand.add_card(Card(Suit.DIAMONDS, Face.ACE))  # 10
    hand.add_card(Card(Suit.HEARTS, Face.ACE))  # 1
    assert int(hand) == 21


# -*- coding: utf-8 -*-

# Scrapy settings for Poi_Gaode project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
#     http://doc.scrapy.org/en/latest/topics/settings.html
#

BOT_NAME = 'Poi_Gaode'

SPIDER_MODULES = ['Poi_Gaode.spiders']
NEWSPIDER_MODULE = 'Poi_Gaode.spiders'
DOWNLOAD_DELAY = 1
DOWNLOAD_TIMEOUT = 30

ITEM_PIPELINES = ['Poi_Gaode.pipelines.PoiGaodePipeline']
CONCURRENT_ITEMS = 100
CONCURRENT_REQUESTS_PER_SPIDER = 64
CONCURRENT_SPIDERS = 128

RANDOMIZE_DOWNLOAD_DELAY = True
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'Poi_Gaode (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.54 Safari/536.5'

DOWNLOADER_MIDDLEWARES = {
    'scrapy.contrib.downloadermiddleware.httpproxy.HttpProxyMiddleware': 110,
    'Poi_Gaode.middlewares.ProxyMiddleware': 100,
    }

RETRY_ENABLED = True
RETRY_TIMES = 2 # initial response + 2 retries = 3 requests
RETRY_HTTP_CODES = [500, 503, 504, 400, 404, 408]
RETRY_PRIORITY_ADJUST = -1

CONCURRENT_REQUESTS = 5
COOKIES_ENABLED = False


from fastapi import FastAPI
from pydantic import BaseModel, Field

class Name(BaseModel):
    name: str = Field(description="Name")
    year: int = Field(description="The year I born")

app = FastAPI(
    title="Data Analyst",
    description="I am a 6 years of Data Analyst",
    servers=[
        {"url": "https://perfume-warm-zambia-tahoe.trycloudflare.com"}
    ]
)

@app.get(
    "/name",
    summary="get my name",
    description="introduces my name",
    response_description="name(string)",
    response_model=Name
)
def get_analyze():
    return {"name": "Hyeonghwan", "year": 1992}


import glob
import os
import subprocess
import difflib
import sys

exectedOutputDir = "ExpectedOutputs/"

def main():
    # Make everything relative to our location.
    ourLocation = os.path.dirname(os.path.abspath(__file__))
    os.chdir(ourLocation)

    # run make on all programs.
    subprocess.call(["make"])
    allSame = True

    for cProgram in glob.glob("*.c"):
        prog = cProgram.split(".")[0]

        # Call program under dettrace!
        try:
            print("========= Testing \"{}\"=========".format(prog))
            output = runProgram(prog)

            # Read reference version from file.
            if prog == "callSshKeygen" :
                # Call program twice instead of using file
                compare = runProgram(prog)
            else:
                compare = open(exectedOutputDir + prog + ".output", "r").read()

            # Compare
            if(output != compare):
                print("Failure\n")
                # Failed diff, find difference.
                allSame = False

                # print raw output, useful for constructing expected output for failing tests
                #sys.stdout.write("{"+output+"}")

                print("File diff:")
                diff = difflib.ndiff(output.splitlines(keepends=True),
                                     compare.splitlines(keepends=True))
                print(''.join(diff), end="")

            else:
                print("Success\n")

        except subprocess.CalledProcessError as e:
            print("Program failed to run!)")
        except IOError:
            print("Failed to open file: {}".format(exectedOutputDir + prog))

    if not allSame:
        exit(1)
    else:
        exit(0)

def runProgram(prog):
    # Run and get output in this machine.
    try:
        outputBin = subprocess.check_output(["../../bin/dettrace", "./" + prog], \
                                            stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as cpe:
        # sometimes test "failures" are expected, e.g., with system calls we don't handle
        outputBin = cpe.output
    # From binary to string.
    return outputBin.decode(encoding='UTF-8')

if __name__ == "__main__":
    main()


s=(input().lower())
n=s.split()
c=0
l=[]
for i in n:
    for j in i:
        l.append(j)
for i in 'abcdefghijklmnopqrstuvwxyz':
    if i not in l:
        c+=1
if c==0:
    print(True)
else:
    print(False)


import comma.extras
import comma.helpers  # for comma.helpers.MAX_SAMPLE_CHUNKSIZE

import pytest

# noinspection PyProtectedMember
class TestDetectCsvType:

    SOME_EMPTY_STRING = ""

    SOME_STRING = "0,1,2\n"

    # fields expected in the dictionary returned by this method
    EXPECTED_FIELDS = [
        "dialect", "simple_dialect", "has_header", "line_terminator"]

    def test_fields_available_in_default(self):
        """
        Checks that the internal method, which uses the default Python
        `csv` package returns the expected kind of dictionary, with all
        expected fields.
        """

        result = comma.extras._default_detect_csv_type(sample=self.SOME_STRING)
        for fieldname in self.EXPECTED_FIELDS:
            assert fieldname in result

    def test_fields_available(self):
        """
        Checks that the publicly available `detect_csv_type()` method returns
        the expected kind of dictionary, with all expected fields.
        """

        result = comma.extras.detect_csv_type(sample=self.SOME_STRING)
        for fieldname in self.EXPECTED_FIELDS:
            assert fieldname in result

    def test_clevercsv(self):
        """
        Checks either that the `clevercsv` module is unavailable, or if it
        is available, it has been used to compute the CSV dialect heuristic
        (by checking that its specific dialect format, provided by the
        "simple_dialect" key in the returned dictionary, is defined).
        """

        try:
            import clevercsv
        except ImportError or ModuleNotFoundError:
            assert True
            return

        result = comma.extras.detect_csv_type(sample=self.SOME_STRING)

        # make sure "simple_dialect" is not None
        assert result.get("simple_dialect") is not None

    def test_empty(self):
        result = comma.extras.detect_csv_type(sample=self.SOME_EMPTY_STRING)
        assert result is not None
        assert "has_header" in result and not result["has_header"]

    def test_empty_default(self):
        result = comma.extras._default_detect_csv_type(sample=self.SOME_EMPTY_STRING)
        assert result is not None
        assert "has_header" in result and not result["has_header"]

# noinspection PyProtectedMember
class TestIsBinaryString:

    class BogusClass:
        pass

    SOME_BINARY_STRING_1 = (
        b"PK\x03\x04\x14\x00\x00\x00\x08\x00\x9dftD\x8d5\xdbe\r"
        b"\x13|\x00\x10\x1a=\x02\n\x00\x1c\x00itcont.txtUT\t\x00"
        b"\x03\xe9\x1c+S\xe8\x1c+Sux\x0b\x00\x01\x04e\x00\x00\x00"
        b"\x04d\x00\x00\x00\xbc\\\xdb\x92\xa3\xb8\xb2}?_\xa1\xa7"
        b"\xd9/\xdd\xb1\x11w\x1ee\x90\x8d\xca\x80\xd8\x02\xca\xe3"
        b"\xfe\x16}\xfc")  # from a ZIP file

    SOME_BINARY_STRING_2 = (
        b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00H\x00"
        b"H\x00\x00\xff\xe1\x00\xb2Exif\x00\x00MM\x00*\x00\x00\x00"
        b"\x08\x00\x06\x01\x12\x00\x03\x00\x00\x00\x01\x00\x01\x00"
        b"\x00\x01\x1a\x00\x05\x00\x00\x00\x01\x00\x00\x00V\x01\x1b"
        b"\x00\x05\x00\x00\x00\x01\x00\x00\x00^\x01(\x00\x03\x00\x00"
        b"\x00\x01\x00\x02\x00\x00\x01;\x00\x02\x00\x00\x00\x19\x00"
        b"\x00\x00f")  # from a JPG file

    SOME_NON_BINARY_STRING = (
        b"\xe5\xb7\x9d\xe6\x9c\x88\xe6\x9c\xa8\xe5\xbf\x83\xe7"
        b"\x81\xab\xe5\xb7\xa6\xe5\x8c\x97\xe4\xbb\x8a\xe5\x90"
        b"\x8d\xe7\xbe\x8e\xe8\xa6\x8b\xe5\xa4\x96\xe6\x88\x90"
        b"\xe7\xa9\xba\xe6\x98\x8e\xe9\x9d\x99\xe6\xb5\xb7\xe9"
        b"\x9b\xb2\xe6\x96\xb0\xe8\xaa\x9e\xe9\x81\x93\xe8\x81"
        b"\x9e\xe5\xbc\xb7\xe9\xa3\x9b")  # also the Kanji string

    TRUE_CASES = [SOME_BINARY_STRING_1, SOME_BINARY_STRING_2]
    FALSE_CASES = [SOME_NON_BINARY_STRING]
    EDGE_CASES = [None, "", b"", BogusClass()]

    @pytest.mark.parametrize("bytestring", TRUE_CASES)
    def test_helper_internal_true(self, bytestring):
        assert comma.extras._is_binary_string_internal(bytestring)  # pylint: disable=protected-access

    @pytest.mark.parametrize("bytestring", FALSE_CASES)
    def test_helper_internal_false(self, bytestring):
        assert not comma.extras._is_binary_string_internal(bytestring)  # pylint: disable=protected-access

    @pytest.mark.parametrize("bytestring", TRUE_CASES)
    def test_helper_true(self, bytestring):
        assert comma.extras._is_binary_string(bytestring)  # pylint: disable=protected-access

    @pytest.mark.parametrize("bytestring", FALSE_CASES)
    def test_helper_false(self, bytestring):
        assert not comma.extras._is_binary_string(bytestring)  # pylint: disable=protected-access

    @pytest.mark.parametrize("value", EDGE_CASES)
    def test_edge_cases(self, value):
        assert not comma.extras.is_binary_string(value)

    def test_truncate(self, mocker):
        # construct a value larger than accepted
        max_size = comma.helpers.MAX_SAMPLE_CHUNKSIZE
        long_value = "\0" * (max_size + 10)

        mocker.patch("comma.extras._is_binary_string", return_value=True)

        # we expected return_value=True (even/especially since it shouldn't
        # and wouldn't if the method had not been patched)
        assert comma.extras.is_binary_string(long_value, truncate=True)

        # noinspection PyUnresolvedReferences
        comma.extras._is_binary_string.assert_called_once_with(
            long_value[:max_size])

# noinspection PyProtectedMember
class TestDetectEncoding:

    SOME_MADE_UP_ENCODING = "native-9"

    SOME_UTF8_STRING_KANJI = (
        b"\xe5\xb7\x9d\xe6\x9c\x88\xe6\x9c\xa8\xe5\xbf\x83\xe7"
        b"\x81\xab\xe5\xb7\xa6\xe5\x8c\x97\xe4\xbb\x8a\xe5\x90"
        b"\x8d\xe7\xbe\x8e\xe8\xa6\x8b\xe5\xa4\x96\xe6\x88\x90"
        b"\xe7\xa9\xba\xe6\x98\x8e\xe9\x9d\x99\xe6\xb5\xb7\xe9"
        b"\x9b\xb2\xe6\x96\xb0\xe8\xaa\x9e\xe9\x81\x93\xe8\x81"
        b"\x9e\xe5\xbc\xb7\xe9\xa3\x9b").decode("utf-8")  # utf-8 encoded

    SOME_UTF8_STRING_FRENCH_NAME = b"J\xc3\xa9r\xc3\xa9mie Lumbroso".decode("utf-8")

    SOME_UTF8_STRINGS = [SOME_UTF8_STRING_KANJI,
                         SOME_UTF8_STRING_FRENCH_NAME]

    ENCODINGS_GUESSABLE_BY_BOM = [
        "utf-8-sig",

        "utf-16",
        "utf-16-le",
        "utf-16-be",

        "utf-32",
        "utf-32-le",
        "utf-32-be",
    ]

    ENCODINGS_GUESSABLE_BY_CHARDET = [
        "latin-1",
        "iso-8859-9",
    ]

    @pytest.mark.parametrize("original_string", SOME_UTF8_STRINGS)
    @pytest.mark.parametrize("encoding", ENCODINGS_GUESSABLE_BY_BOM)
    def test_detect_by_bom(self, original_string, encoding):
        """
        Checks that the (deterministic) encoding detection method
        for Unicode compatible encodings (UTF-8, UTF-16, UTF-32, etc.)
        works on a test string encoded in each of those encodings.
        """

        # checking that this works
        encoded_string = original_string.encode(encoding)
        decoded_string = encoded_string.decode(encoding)

        # check the result is what it should be
        assert original_string == decoded_string

        # now checking we would detect this encoding properly with BOM
        guessed_encoding = (
            comma.extras._detect_encoding_by_bom(encoded_string))  # pylint: disable=protected-access
        assert (guessed_encoding == encoding or guessed_encoding is None)

        # now check that this is the same output produced by detect_encoding
        if guessed_encoding is not None:
            assert (guessed_encoding == comma.extras.detect_encoding(
                sample=encoded_string,
                default=None))

    def test_detect_by_bom_failing(self):
        """
        Checks whether
        """
        # this is a made up BOM which happens to have 3 nulls (like the BOM for
        # UTF-32); it was chosen to pass all tests of the BOM detection except
        # the last one
        bogus_bom = (
            comma.extras._null +
            '\x13'.encode('ascii') +
            comma.extras._null +
            comma.extras._null
        )
        result = comma.extras._detect_encoding_by_bom(
            bogus_bom,
            default=self.SOME_MADE_UP_ENCODING)

        # all BOM detection should have failed, and we should have gotten the
        # (made up) default encoding
        assert result == self.SOME_MADE_UP_ENCODING

    @pytest.mark.parametrize("original_string", [SOME_UTF8_STRING_FRENCH_NAME])
    @pytest.mark.parametrize("encoding", ENCODINGS_GUESSABLE_BY_CHARDET)
    def test_detect_by_chardet(self, original_string, encoding):
        """
        Checks that the heuristic provided by chardet is used when the BOM
        detection fails, and checks that strings (at least among the test
        pool of strings) are correctly decoded with the chosen encoding.
        """

        # first check if chardet is available, if not, tests succeeds by default
        try:
            import chardet
        except ImportError or ModuleNotFoundError:
            assert True
            return

        # checking that this works
        encoded_string = original_string.encode(encoding)
        decoded_string = encoded_string.decode(encoding)

        # check the result is what it should be
        assert original_string == decoded_string

        # now checking we would NOT detect this encoding properly with BOM
        guessed_encoding_by_bom = (
            comma.extras._detect_encoding_by_bom(
                sample=encoded_string,
                default=None))  # pylint: disable=protected-access
        assert guessed_encoding_by_bom is None

        # look at chardet's answer
        chardet_result = chardet.detect(encoded_string)
        assert chardet_result is not None
        chardet_encoding = chardet_result.get("encoding")
        assert chardet_encoding is not None

        chardet_decoded_string = encoded_string.decode(chardet_encoding)

        # succeed either if we guess the right encoding, or the encoding that
        # was guessed results in the right decoding of the encoded string
        # (e.g., latin-1 and ISO-8859-9 can be equivalent for some inputs)
        assert (
            (chardet_encoding == encoding) or
            (chardet_decoded_string == decoded_string))

        # now check that this is the same output produced by detect_encoding
        assert (chardet_encoding == comma.extras.detect_encoding(
            sample=encoded_string,
            default=None))

    def test_detect_by_default(self, mocker):
        """
        Checks that the `comma.extras.detect_encoding()` method returns
        the user-specified `default` (by default, `None`) if none of the
        heuristics provided a guess.
        """

        # check that _detect_encoding_by_bom is defined, and patch it
        assert "_detect_encoding_by_bom" in comma.extras.__dict__
        mocker.patch("comma.extras._detect_encoding_by_bom", return_value=None)

        # only patch the chardet module if it is available
        try:
            import chardet
            mocker.patch("chardet.detect", return_value=None)
        except ImportError or ModuleNotFoundError:
            pass

        # having had all the heuristics fail, check if the returned
        # default value is what we expect it will be
        assert comma.extras.detect_encoding(
            sample=self.SOME_UTF8_STRING_KANJI,
            default=self.SOME_MADE_UP_ENCODING) == self.SOME_MADE_UP_ENCODING


import os

from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import FileResponse, HttpResponse
from django.shortcuts import redirect, render

from .forms import AnalysisRequestForm
from .helpers import (
    api_get_report,
    client_get_all_reports_states,
    client_login,
    settings,
)
from .models import AnalysisRequest, IOTUser

@login_required
def index(request):
    try:
        if IOTUser.objects.get(user=request.user).activated:
            client = client_login(request.user.iotuser)
            reqs = AnalysisRequest.objects.filter(user=request.user.id)
            all_requests = client_get_all_reports_states(client, reqs)
            context = {"requests": all_requests}
            return render(request, "iot_index.html", context=context)
    except IOTUser.DoesNotExist:
        pass
    except Exception:
        pass
    return render(request, "iot_index.html")

@login_required
def analysis_request(request):
    if request.method == "POST":
        form = AnalysisRequestForm(request.POST, request.FILES)
        if "tos" not in request.POST:
            messages.error(
                request,
                "Please read and accept the terms and conditions of the service before proceeding.",
            )
            return render(request, "iot_request.html", {"form": form})
        if form.is_valid():
            data = form.cleaned_data
            a_request = AnalysisRequest(
                user=request.user,
                name=data["name"],
                vendor_name=data["vendor_name"],
                product_name=data["product_name"],
                file=data["file"],
            )
            a_request.save()
            messages.success(
                request,
                "Your analysis request was successfully saved, you will receive a pricing offer"
                " in the next few days.",
            )
            return redirect("iot_index")
    else:
        form = AnalysisRequestForm()
    return render(request, "iot_request.html", {"form": form})

@login_required
def download_report(request, firmware_uuid):
    a_req = AnalysisRequest.objects.get(firmware_uuid=firmware_uuid)
    req = api_get_report(request.user, str(a_req.report_uuid))
    file = req.content
    response = HttpResponse(
        file,
        headers={
            "Content-Type": "application/pdf",
            "Content-Disposition": f"attachment; "
            f'filename="'
            f'{request.user.company_name}_{firmware_uuid[-12:]}_{str(a_req.report_uuid)[-12:]}.pdf"',
        },
    )
    return response

@login_required
def read_tos(request):
    fp = os.path.join(settings.STATIC_ROOT, "pdf", "terms_and_conditions.pdf")
    response = FileResponse(open(fp, "rb"), content_type="application/pdf")
    return response


#!/usr/bin/env python

import logging
import os
import sys
import timeit
import traceback
import cProfile
from functools import wraps
from contextlib import contextmanager
from collections import Counter

logging.basicConfig(
    format='%(asctime)-15s  %(levelname)s  %(filename)s:%(lineno)d  %(message)s',
    level=logging.DEBUG
    # level=logging.INFO
)

# pylint: disable=protected-access
def findCaller(_):
    f = logging.currentframe()
    for _ in range(2 + logging._frame_delta):
        if f is not None:
            f = f.f_back
    rv = "(unknown file)", 0, "(unknown function)"
    while hasattr(f, "f_code"):
        co = f.f_code
        filename = os.path.normcase(co.co_filename)
        if filename == logging._srcfile:
            f = f.f_back
            continue
        rv = (co.co_filename, f.f_lineno, co.co_name)
        break
    return rv
logging.Logger.findCaller = findCaller
logging._frame_delta = 0

@contextmanager
def logdelta(n):
    d = logging._frame_delta
    logging._frame_delta = d + n
    yield
    logging._frame_delta = d
# pylint: enable=protected-access

_WIDTH = 50

class ProfilerHack(object):
    """
    An ill-designed performance measuring thing for Python, use at your own risk.
    I'd prefer line_profiler except I'm on Python 2.7 and cannot upgrade.
    """
    _profilers = {}

    @classmethod
    def get(cls, name=None):
        if name not in cls._profilers:
            cls._profilers[name] = cls()
        return cls._profilers[name]

    def __init__(self):
        self._profile_info = {}

    def pretty_name(self, file, line, msg):
        r = "{0}({1}) {2}".format(file, line, msg)
        if len(r) > _WIDTH:
            r = "..." + r[-(_WIDTH-3):]
        return r

    def profile(self, f):
        name = self.pretty_name(
            f.func_code.co_filename,
            f.func_code.co_firstlineno,
            f.func_code.co_name
        )

        @wraps(f)
        def wrapper_with_debug(*args, **kwargs):
            start = timeit.default_timer()
            r = f(*args, **kwargs)
            end = timeit.default_timer()
            self._profile_info[end] = (name, end - start)
            return r
        if logging.getLogger().isEnabledFor(logging.DEBUG):
            return wrapper_with_debug
        else:
            return f

    def get_profile(self):
        d = {}
        for (_, (name, t)) in self._profile_info.items():
            if name not in d:
                d[name] = 0.
            d[name] += t
        return d

    def show_profile(self):
        if logging.getLogger().isEnabledFor(logging.DEBUG):
            with logdelta(1):
                lst = [(-t, name) for name, t in self.get_profile().items()]
                lst.sort()
                for t, name in lst:
                    fmt = "{0:>" + str(_WIDTH) + "} {1}"
                    logging.debug(fmt.format(name, -t))

    @contextmanager
    def context(self, legend):
        if logging.getLogger().isEnabledFor(logging.DEBUG):
            filename, line, _, _ = traceback.extract_stack()[-3]
            name = self.pretty_name(filename, line, legend)
            start = timeit.default_timer()
            yield
            end = timeit.default_timer()
            self._profile_info[end] = (name, end - start)
        else:
            yield

if False:
    ## Let's test it

    p = ProfilerHack.get()
    c = Counter()

    @p.profile
    def inner():
        with p.context('inner update loop'):
            for _ in range(100):
                c.update('abcd')

    @p.profile
    def middle():
        for _ in range(100):
            for _ in range(100):
                c.update('efgh')
            inner()

    @p.profile
    def outer():
        for _ in range(100):
            with p.context('outer update loop'):
                for _ in range(100):
                    c.update('ijkl')
            middle()

    outer()

    p.show_profile()

########################

@contextmanager
def profile_to_log(log_level):
    class StreamToLogger(object):
        def __init__(self, logger):
            self.logger = logger
            self.linebuf = ''

        def write(self, buf):
            if buf.endswith("\n"):
                self.logger.log(log_level, self.linebuf + buf.rstrip())
                self.linebuf = ''
            else:
                self.linebuf += buf

        def flush(self):
            pass

    logger = logging.getLogger()
    pr = None
    enabled = logger.isEnabledFor(log_level)
    try:
        if enabled:
            pr = cProfile.Profile()
            pr.enable()
        yield
    finally:
        if enabled and pr is not None:
            pr.disable()
            orig_ss, sys.stdout = sys.stdout, StreamToLogger(logger)
            pr.print_stats(sort='tottime')
            sys.stdout = orig_ss

########################

c = Counter()
n = 50

def inner():
    for _ in range(n):
        c.update('abcd')

def middle():
    for _ in range(n):
        for _ in range(n):
            c.update('efgh')
        inner()

def outer():
    for _ in range(n):
        for _ in range(n):
            c.update('ijkl')
        middle()

with profile_to_log(logging.INFO):
    outer()