#! /usr/bin/env python

# Get permutations
def get_permutations(ww):
    permutations = []
    if ww == None:
        return None

    n = len(ww)

    # Base case, n = 0
    if n == 0:
        permutations.append("")
        return permutations
    if n != 0:
        words = []
        # Get the first char
        first_char = ww[0]
        # Remove the first char
        remainder = ww.replace(first_char,'')

        words = get_permutations(remainder)

        for word in enumerate(words):
            for idx, val in enumerate(word):
                 print(idx, val, word, words)
#                ss = insert_char_at(word, first_char, idx)
#                permutations.append(ss)
#                print(permutations)

        return permutations

def insert_char_at(word, char, idx):
   start = word[0:idx]
   end   = word[idx:]
   return start + char + end;

print ('->hi')
word = 'abc'
# Testing insert_char_at
# word = insert_char_at(word,'z',1)
# print(word)
# permucat('1234')
pp = get_permutations(word)
print(pp)
#             before = words[0:idx]
#             curr_sent = words[idx]
#             after  = words[idx:l]


#create by useless_patato

#import lib.pm_g3 as pm_sensor
#import lib.th_htu21d as tmp_sensor
#import lib.light_tcs34725 as light_sensor
#import gas_tvoc_sgp30 as gas_sensor
#import lib.gas_co2_s8 as gas_sensor
#import pyupm_i2clcd as upmLCD

#import libs.serial_port as uno_sensor
#import libs.module_htu21d as  tmp_sensor

Version = "6.0.0" #for next generation PI version

#sencer configure
Sense_PM = 1
Sense_Tmp = 1
Sense_Light = 1
Sense_Co2 = 1
Sense_TVOC = 1
#Use_RTC_DS3231 = 1
Nbiot_Sim7000 = 1

#list every value
GPS_LAT = 25.1933
GPS_LON = 121.7870
APP_ID = "MAPS6"  #need to change for PI version
DEVICE = "Rsapberry_PI"
DEVICE_ID = "DEVICE_ID1234"
DEVICE_IP = ''
s_t0 = 0.0
s_h0 = 0.0
s_d2 = 0.0
s_d0 = 0
s_d1 = 0
s_l0 = 0
s_lr = 0
s_lg = 0
s_lb = 0
s_lc = 0
s_gh = 400
s_gg = 0
uptime = 0

#changeable interval
Interval_LCD = 5

Restful_URL = "https://data.lass-net.org/Upload/MAPS-secure.php?"
Restful_interval = 300			# 300 seconds

SecureKey = "NoKey"

FS_SD = "/mnt/mmcblk0p1"  #need to change

#========================#

import uuid
import re
import os
from multiprocessing import Queue

float_re_pattern = re.compile("^-?\d+\.\d+$")
num_re_pattern = re.compile("^-?\d+\.\d+$|^-?\d+$")

mac = open('/sys/class/net/eth0/address').readline().upper().strip()
DEVICE_ID = mac.replace(':','')

#do a '\' before space from "cut -d" to escape ' ' character
f = os.popen('ifconfig eth0 | grep "inet\ " | cut -d \  -f10')
DEVICE_IP=f.read()
if(DEVICE_IP == ''):
        f = os.popen('ifconfig wlan0 | grep "inet\ " | cut -d \  -f10')
        DEVICE_IP=f.read()

print("ID:"+DEVICE_ID)
print("wlan IP:"+DEVICE_IP)

#if Use_RTC_DS3231 == 1:
#	import mraa
#	import hmac
#	import hashlib
#	import base64
#	import urllib
#	import urllib.parse

#	DS3231_I2C_ADDR = 0x68
#need change
#	rtc = mraa.I2c(0)
#	rtc.address(DS3231_I2C_ADDR)
#	SecureKey = chr(rtc.readReg(0x07)) + chr(rtc.readReg(0x08)) + chr(rtc.readReg(0x09)) + chr(rtc.readReg(0x0A)) + chr(rtc.readReg(0x0B)) + chr(rtc.readReg(0x0C)) + chr(rtc.readReg(0x0D))
#	SecureKey = urllib.parse.quote_plus(SecureKey)
#	print("SecureKey = " , SecureKey)

#pm_q = Queue(maxsize=5)
#tmp_q = Queue(maxsize=5)
#light_q = Queue(maxsize=5)
#gas_q = Queue(maxsize=5)
#tvoc_q = Queue(maxsize=5)

#note: honeywell CO2 use "s_gh" instead of  SenseAir S8 "s_g8"

fields ={       "Tmp"   :       "s_t0",
                "RH"    :       "s_h0",
                "PM1.0" :       "s_d2",
                "PM2.5" :       "s_d0",
                "PM10"  :       "s_d1",
                "Lux"   :       "s_l0",
		"RGB_R"	:	"s_lr",
		"RGB_G"	:	"s_lg",
		"RGB_B"	:	"s_lb",
		"RGB_C"	:	"s_lc",
                "CO2"   :       "s_gh",
		"TVOC"	:	"s_gg",
        }
values = {      "app"           :       APP_ID,
                "device_id"     :       DEVICE_ID,
                "device"        :       DEVICE,
                "ver_format"    :       3,
                "fmt_opt"       :       0,
                "gps_lat"       :       GPS_LAT,
                "gps_lon"       :       GPS_LON,
                "FAKE_GPS"      :       1,
                "gps_fix"       :       1,
                "gps_num"       :       100,
                "date"          :       "1900-01-01",
                "time"          :       "00:00:00",
        }

#new version of value
'''
values = {      "app"           :       APP_ID,
                "app_ver"       :       Version,
                "device"        :       DEVICE,
                "device_id"     :       DEVICE_ID,
                "ver_format"    :       3,
                "fmt_opt"       :       0,
                "gps_lat"       :       GPS_LAT,
                "gps_lon"       :       GPS_LON,
                "FAKE_GPS"      :       1,
                "gps_fix"       :       1,
                "gps_num"       :       100,
                "date"          :       "1900-01-01",
                "time"          :       "00:00:00",
                "tick"          :       uptime,
                "Tmp"           :       s_t0,
                "RH"            :       s_h0,
                "PM1.0"         :       s_d2,
                "PM2.5"         :       s_d0,
                "PM10"          :       s_d1,
                "Lux"           :       s_l0,
                "RGB_R"         :       s_lr,
                "RGB_G"         :       s_lg,
                "RGB_B"         :       s_lb,
                "RGB_C"         :       s_lc,
                "CO2"           :       s_gh,
                "TVOC"          :       s_gg,
        }
'''


"""
ZADANIE:
Narysuj wykres funkcji kwadratowej, przedział <-100, 100> (najlepiej zadany)
Pobierz od użytkownika przedział, w którym ma zostać narysowana funkcja.
Stwórz funkcję, formatującą, zwracającą postać f(x): ax^2 + bx + c

Wyrysuj legendę na ekranie.

"""

from matplotlib import pyplot as plt

def create_function_string(coefficient_a: float, coefficient_b: float, coefficient_c: float) -> str:
    """
    Create the string for function
    :param coefficient_a:
    :param coefficient_b:
    :param coefficient_c:
    :return:
    """
    return "f(x): {}x^2 + {}x + {}".format(coefficient_a, coefficient_b, coefficient_c)

def input_params() -> float:
    """
    Return
    :return: valid float number
    """
    # set number - None
    number = None
    while number is None:
        try:
            number = float(input("Enter a number: \n"))
        except ValueError:
            print("Not an float value...")
    return number

def get_function_value(x_range: range, coefficient_a: float,
                       coefficient_b: float, coefficient_c: float) -> list:
    """
    Return list of values for function in given range"
    :param x_range:
    :param coefficient_a:
    :param coefficient_b:
    :param coefficient_c:
    :return:
    """
    return [coefficient_a * (x ** 2) + coefficient_b * x + coefficient_c for x in x_range]

def create_basic_curve(x_min: int, x_max: int) -> None:
    """
    Create curve, show x_min, and x_max
    :param x_min:
    :param x_max:
    :return:
    """
    # set coefficients for function, from user

    coefficient_a = input_params()
    coefficient_b = input_params()
    coefficient_c = input_params()

    x_range = range(x_min, x_max)
    y_range = get_function_value(x_range, coefficient_a, coefficient_b, coefficient_c)
    function_string = create_function_string(coefficient_a, coefficient_b, coefficient_c)

    plt.plot(x_range, y_range, label=function_string)
    plt.legend(loc='best')

    plt.show()

create_basic_curve(-100, 100)


def take_guess():
    print("숫자 3개를 하나씩 차례대로 입력하세요.")

    new_guess = []
    i = 1
    while len(new_guess) < 3:
        # temp_num 이 숫자를 받는다는 가정하에 작성
        temp_num = int(input(f"{i}번째 숫자를 입력하세요 : "))
        if temp_num > 9 or temp_num < 0:
            print("범위를 벗어나는 숫자입니다. 다시 입력하세요.")
            continue
        elif temp_num in new_guess:
            print("중복되는 숫자입니다. 다시 입력하세요.")
            continue

        new_guess.append(temp_num)
        i += 1

    return new_guess

'''
continue 할 필요 없이 그냥 if elif 안에 전부다 넣었어도 괜춘
i를 굳이 새로 정의할 필요 없이 len + 1로 몇번째 시도인지 했어도 좋았을 듯.
range 함수 안에 0, 10 을 범위로 정해서 했어도 굿!
'''

def get_score(guess, solution):
    strike_count = 0
    ball_count = 0

    for i in range(len(solution)):
        if guess[i] == solution[i]:
            strike_count += 1

        elif guess[i] in solution:
            ball_count += 1

    return strike_count, ball_count


import tensorflow as tf
import numpy as np
class wavernn(tf.keras.Model):
    def __init__(self,
                 quantization_channels=256,
                 gru_channels=896,
                 fc_channels=896,
                 lc_channels=80):
        super().__init__()
        self.quantization_channels = quantization_channels
        self.gru_channels = gru_channels
        self.split_size = gru_channels // 2
        self.fc_channels = fc_channels
        self.lc_channels = lc_channels

        #它的输入维度是lc_channels + 3？
        self.gru = tf.keras.layers.GRU(self.gru_channels)
        self.dense1 = tf.keras.layers.Dense(
            units=fc_channels, activation='relu', name="frame_projection")
        self.fc_coarse = tf.keras.layers.Dense(
            units=quantization_channels, activation=None, name="frame_projection")

        self.dense2 = tf.keras.layers.Dense(
            units=fc_channels, activation='relu', name="frame_projection")
        self.fc_fine = tf.keras.layers.Dense(
            units=quantization_channels, activation=None, name="frame_projection")

        #self.register_buffer('mask', self.create_mask())#还不知道怎么替换

    def create_mask(self):
        coarse_mask = tf.concat([tf.ones(self.split_size, self.lc_channels + 2),
                                 tf.zeros(self.split_size, 1)], 1)
        i2h_mask = tf.concat([coarse_mask,
                              tf.ones(self.split_size, self.lc_channels + 3)], 0)
        return tf.concat([i2h_mask, i2h_mask, i2h_mask], 0)

    def sparse_mask(self):
        pass

    def call(self, inputs, conditions):
        x = tf.concat([conditions, inputs], -1)
        h, h_n = self.gru(x)

        h_c, h_f = tf.split(h, self.split_size, axis=2)

        o_c = self.dense1(h_c)
        o_c = self.fc_coarse(o_c)
        p_c = tf.log_softmax(o_c, axis=2)

        o_f = self.dense1(h_c)
        o_f = self.fc_coarse(o_f)
        p_f = tf.log_softmax(o_f, axis=2)

        h_n = tf.squeeze(h_n, axis=0)

        return p_c, p_f, h_n

class ResBlock(tf.keras.layers.Layer):
    def __init__(self, dims):
        super().__init__()
        self.conv1 = tf.keras.layers.Conv1D(
            filters=dims,
            kernel_size=1,
            padding="same",
        )
        self.conv2 = tf.keras.layers.Conv1D(
            filters=dims,
            kernel_size=1,
            padding="same",
        )
        self.batch_norm1 = tf.keras.layers.BatchNormalization()
        self.batch_norm2 = tf.keras.layers.BatchNormalization()

    def forward(self, x):
        residual = x
        x = self.conv1(x)
        x = self.batch_norm1(x)
        x = tf.nn.relu(x)
        x = self.conv2(x)
        x = self.batch_norm2(x)
        return x + residual

class MelResNet(tf.keras.layers.Layer):
    def __init__(self, res_blocks, in_dims, compute_dims, res_out_dims, pad):
        super().__init__()
        k_size = pad * 2 + 1
        self.conv_in = tf.keras.layers.Conv1D(compute_dims, kernel_size=k_size, padding="same")
        self.batch_norm = tf.keras.layers.BatchNormalization()
        self.layers = []
        for i in range(res_blocks):
            self.layers.append(ResBlock(compute_dims))
        self.conv_out = tf.keras.layers.Conv1D(res_out_dims, kernel_size=1, padding="same")

    def forward(self, x):
        x = self.conv_in(x)
        x = self.batch_norm(x)
        x = tf.nn.relu(x)
        for f in self.layers:
            x = f(x)
        x = self.conv_out(x)
        return x

class Stretch2d(tf.keras.layers.Layer):
    def __init__(self, x_scale, y_scale):
        super().__init__()
        self.x_scale = x_scale
        self.y_scale = y_scale

    def forward(self, x):
        b, c, h, w = x.size()
        x = tf.expand_dims(x, axis=-1)
        x = tf.expand_dims(x, axis=3)
        x = np.repeat(x, self.y_scale, axis=3)
        x = np.repeat(x, self.x_scale, axis=5)
        return tf.reshape(x, (b, c, h * self.y_scale, w * self.x_scale))

#
# class UpsampleNetwork(tf.keras.layers.Layer):
#     def __init__(self, feat_dims, upsample_scales, compute_dims,
#                  res_blocks, res_out_dims, pad):
#         super().__init__()
#         total_scale = np.cumproduct(upsample_scales)[-1]
#         self.indent = pad * total_scale
#         self.resnet = MelResNet(res_blocks, feat_dims, compute_dims, res_out_dims, pad)
#         self.resnet_stretch = Stretch2d(total_scale, 1)
#         self.up_layers = []
#         for scale in upsample_scales:
#             k_size = (1, scale * 2 + 1)
#             padding = (0, scale)
#             stretch = Stretch2d(scale, 1)
#             conv = nn.Conv2d(1, 1, kernel_size=k_size, padding=padding, bias=False)
#             conv.weight.data.fill_(1. / k_size[1])
#             self.up_layers.append(stretch)
#             self.up_layers.append(conv)
#
#     def forward(self, m):
#         aux = self.resnet(m).unsqueeze(1)
#         aux = self.resnet_stretch(aux)
#         aux = aux.squeeze(1)
#         m = m.unsqueeze(1)
#         for f in self.up_layers: m = f(m)
#         m = m.squeeze(1)[:, :, self.indent:-self.indent]
#         return m.transpose(1, 2), aux.transpose(1, 2)


#!/usr/bin/python3
"""Routes for Place"""
from flask import jsonify, request, abort, make_response
from api.v1.views import app_views
from models import storage
from models.base_model import BaseModel
from models.state import State
from models.city import City
from models.amenity import Amenity
from models.place import Place
from flasgger import swag_from

@app_views.route('/cities/<city_id>/places', strict_slashes=False,
                 methods=['GET'])
def showPlace(city_id):
    """ Shows all places in the file storage """
    count_l = []
    city = storage.get("City", city_id)
    if city is None:
        abort(404)
    eachPlace = storage.all("Place")
    for value in eachPlace.values():
        if value.city_id == city_id:
            count_l.append(value.to_dict())
    return(jsonify(count_l))

@app_views.route('/places/<place_id>',
                 strict_slashes=False,
                 methods=['GET'])
@swag_from("places.yml")
def a_place_id(place_id):
    """ Gets the place and its id if any """
    i = storage.get("Place", place_id)
    if i:
        return jsonify(i.to_dict())
    else:
        abort(404)

@app_views.route('/places/<place_id>', strict_slashes=False,
                 methods=["DELETE"])
def del_place_id(place_id):
    """ deletes an place if given the id """
    thing = storage.all('Place')
    place = "Place." + place_id
    p = thing.get(place)
    if p is None:
        abort(404)
    else:
        p.delete()
        storage.save()
        return (jsonify({}), 200)

@app_views.route('/cities/<city_id>/places', strict_slashes=False,
                 methods=['POST'])
def postPlace(city_id):
    """ creates a new placee """
    if storage.get("City", city_id) is None:
        abort(404)
    thing = request.get_json()
    if not thing:
        return (jsonify({"error": "Not a JSON"}), 400)
    user = thing.get("user_id")
    if user is None:
        return (jsonify({"error": "Missing user_id"}), 400)
    useConfirm = storage.get("User", user)
    if useConfirm is None:
        abort(404)
    place = thing.get("name")
    if place is None:
        return (jsonify({"error": "Missing name"}), 400)
    p = Place()
    p.name = place
    p.city_id = city_id
    p.user_id = user
    p.save()
    return (jsonify(p.to_dict()), 201)

@app_views.route('/places/<place_id>',
                 strict_slashes=False,
                 methods=["PUT"])
def updatePlace(place_id):
    """ updates the place info, specifically name """
    # garbage = {"id", "created_at", "updated_at"}
    place = storage.get("Place", place_id)
    if place is None:
        abort(404)
    thing = request.get_json()
    if not thing:
        return (jsonify({"error": "Not a JSON"}), 400)

    for key, value in thing.items():
        if key == 'name':
            setattr(place, key, value)
        if key == 'description':
            setattr(place, key, value)
        if key == 'number_rooms':
            setattr(place, key, value)
        if key == 'number_bathrooms':
            setattr(place, key, value)
        if key == 'max_guest':
            setattr(place, key, value)
        if key == 'price_by_night':
            setattr(place, key, value)
        if key == 'lattitude':
            setattr(place, key, value)
        if key == 'longitude':
            setattr(place, key, value)

    place.save()
    return (jsonify(place.to_dict()), 200)


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

UDP_IP = "192.168.137.1"
UDP_PORT = 1234
MESSAGE = "Hello, World!"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

for num in range(10,20):
	MESSAGE = "Hello, World! %d" % num
	sock.sendto( MESSAGE , ( UDP_IP, UDP_PORT))


##fig2.7的第四幅图
##
##Date:2020/06/26
import numpy as np
import matplotlib.pyplot as plt
dimension=range(1,11)
trainsize=100#训练样本集大小
trainnum=100#训练样本集数量
varian=np.zeros(shape=(len(dimension),1))#方差
sqbias=np.zeros(shape=(len(dimension),1))#偏差的平方
ytrain=np.zeros(shape=(trainsize,1))
ytest=np.zeros(shape=(trainnum,1))
for i in range(len(dimension)):
    tdim=dimension[i]
    xtest=np.zeros(shape=(1,tdim))
    for j in range(trainnum):#生成单个训练样本集
        xtrain=np.random.random(size=(trainsize,tdim))*2-1#生成训练样本
        ytrain=np.exp(-8*sum((xtrain**2).T))#使用的函数
        dist=np.zeros(shape=(trainsize,1))
        for k in range(trainsize):
            dist[k]=sum((xtrain[k,:]**2).T)
        onennx=dist.argmin()#最近邻的坐标
        ytest[j]=ytrain[onennx]
    varian[i]=np.mean((ytest-np.mean(ytest))**2)
    sqbias[i]=(np.mean(ytest)-1)**2#f(0)=1
fig=plt.figure()
ax2=fig.add_subplot(1,1,1)
ax2.plot(dimension,varian,'bo-',label='variance')
ax2.plot(dimension,sqbias,'ro-',label='square bias')
ax2.plot(dimension,varian+sqbias,'ko-',label='mse')
plt.legend(loc='upper right')
plt.show()


import os
import csv # read CrunchBase CSV files, for cleaning
import _io # file opening and writing
import pandas
import numpy
import json
import time
import random
import copy
import urllib # send URL request - API interaction

dataset_I_sample_rand = False
dataset_nSample_rand = 1

dataset_I_sample = True
dataset_nSample = 100

# Get current directory of where this code file is
# Get project root directory by going to the parent directory
folderPath_root = "/export/home/dor/pjonak/Projects/RKoning_CB/"
# folderPath_root = os.path.dirname( os.path.realpath(__file__) )
# folderPath_root = folderPath_root[::-1].split("\\",1)[1][::-1] + "\\"

# Identify where data is held
folderPath_data = "dataset/"
folderPath_response = "BW_responses/"
folderPath_keys = "keys/"

# Which file are we looking to load?
fileName = "organizations"
fileName = fileName + "_trim.csv"

def cleanWebsiteURL(website:str) -> str:
    # SimilarWeb does not accept company URLs with "/" nor "www."

    # Clean up website URL
    #   Remove "/"
    website = website.lower()
    if len(website) > 5 and website[0:4] == "http":
        website = website.split("/")
        if len(website[1]) == 0:
            website = website[2]
        else:
            website = website[1]
    else:
        website = website.split("/")
        for w in website:
            if len(w) != 0:
                website = w
                break
    #   Remove "www."
    if len(website) > 4 and website[0:4] == "www.":
        website = website[4::]
    return website

def bw_getKey() -> str:
    # Loads API key for SimilarWeb
    #   File must be named "sw.cnf"
    #   File must reside in the root of the project folder
    hFile = open(folderPath_root + folderPath_keys + "bw.cnf")
    hReader = csv.reader(hFile,delimiter=',')
    apiKey_bw = None
    for rowData in hReader:
        if rowData[0]=="api_key":
            apiKey_bw = rowData[1]
    hFile.close()
    return apiKey_bw

def CB_buildURL_BW(website: str, company: str, apiKey_bw: str) -> (str, str):
    # The URL is composed of the following parts:
    #   base / domain = api.builtwith.com/
    urlBase = "https://api.builtwith.com/"

    # Technology Categories index = True
    # All else = False
    bw_category = False

    # All potential vertical values?
    bw_verticals = False

    # Last database update dates?
    bw_update = False

    if bw_category:
        urlCategory = "categoriesV4"
    else:
        urlCategory = "v11/api"

    if bw_verticals:
        urlVert = "VERTICALS=1"
    else:
        urlVert = None

    if bw_update:
        urlUpdate = "UPDATE=1"
    else:
        urlUpdate = None

    urlRequest = urlBase + urlCategory + ".json" + "?KEY=" + apiKey_bw + "&LOOKUP=" + website

    if urlVert is not None:
        urlRequest = urlRequest + "&" + urlVert
    if urlUpdate is not None:
        urlRequest = urlRequest + "&" + urlUpdate

    if isinstance(company, float):
        # Empty
        company = website

    # filenameResponse = "bw__" + company.replace(" ", "_") + urlCategory.replace("/","_")
    filenameResponse = "bw__" + company.replace(" ", "_").replace(",", "_").replace(".", "_").replace("/","_").replace("\\","_")
    if urlVert is not None:
        filenameResponse = filenameResponse + "__VERTICALS"
    if urlUpdate is not None:
        filenameResponse = filenameResponse + "__UPDATE"
    filenameResponse = filenameResponse + ".json"

    return urlRequest, filenameResponse

def main():
    # Verify file exists
    fullPath = folderPath_root + folderPath_data + fileName
    if os.path.exists(fullPath):
        print("File found")
        I_flag = True
    else:
        print("File not found\n\tSearch path: " + fullPath)
        I_flag = False

    if I_flag:
        # Load data
        print("Loading data: " + fileName)
        dat = pandas.read_csv(fullPath, sep=',', encoding='utf-8', index_col=0)
        print("\tDone")

        # Take a sample?
        if dataset_I_sample_rand:
            print("Taking a random sample of " + str(dataset_nSample_rand) + " companies")
            print("\tSampling check\n\t\tOriginal # rows = " + str(len(dat)))
            dat = dat.iloc[sorted(random.sample(range(0, len(dat)), dataset_nSample_rand)), :]
            print("\t\tSample # rows = " + str(len(dat)))

        # Make sure we're organized by date
        #   Sorting by date
        #       column = 'founded_on'
        dat = dat.ix[dat['founded_on'].sort_values(ascending=False).index]

        if not dataset_I_sample_rand and dataset_I_sample:
            print("Taking a sample of first " + str(dataset_nSample) + " companies")
            print("\tSampling check\n\t\tOriginal # rows = " + str(len(dat)))
            dat = dat.iloc[numpy.arange(dataset_nSample)]
            print("\t\tSample # rows = " + str(len(dat)))

        # Add 3 columns
        #   bw_url - what is the request we will send?
        #   bw_filename - where will we store the response?
        #   bw_I_request - a flag to determine if we sent the request
        #   bw_I_response - a flag to determine if we received a response
        dat['bw_url'] = [None]*dat.shape[0]
        dat['bw_filename'] = [None]*dat.shape[0]
        dat['bw_I_request'] = [0] * dat.shape[0]
        dat['bw_I_response'] = [0] * dat.shape[0]

        # Ready to build up queries
        #   Get API key
        bw_apiKey = bw_getKey()
        #   Then store the query
        #   Finally add the API key before sending request
        pandas.options.mode.chained_assignment = None  # default='warn'
        print("Building API requests: BuiltWith")
        for iRow in range(0, dat.shape[0]):
            urlReq, filenameResponse = CB_buildURL_BW( cleanWebsiteURL(dat['homepage_url'].iloc[iRow]),
                                                      dat['company_name'].iloc[iRow],
                                                      bw_apiKey)

            if urlReq is not None:
                dat['bw_url'].iloc[iRow] = urlReq
                dat['bw_filename'].iloc[iRow] = filenameResponse
        pandas.options.mode.chained_assignment = 'warn'

        # Check to see if we already have a response for any of these
        pandas.options.mode.chained_assignment = None  # default='warn'
        for iRow in range(0, dat.shape[0]):
            if os.path.exists(folderPath_root + folderPath_response + dat['bw_filename'].iloc[iRow]):
                # File exists!
                # dat['bw_I_request'].iloc[iRow] = 1
                dat['bw_I_response'].iloc[iRow] = 1
        pandas.options.mode.chained_assignment = 'warn'

        # Ready
        print("Sending BW requests:")
        pandas.options.mode.chained_assignment = None  # default='warn'
        for iRow in range(0, dat.shape[0]):
            if dat['bw_I_response'].iloc[iRow] == 0:
                print("\t" + dat['bw_url'].iloc[iRow])
                try:
                    dat['bw_I_request'].iloc[iRow] = 1
                    hJSON = json.loads(urllib.request.urlopen( dat['bw_url'].iloc[iRow] ).read().decode('utf-8'))
                    dat['bw_I_response'].iloc[iRow] = 1
                    I_json = True
                except:
                    print("\t\tError")
                    I_json = False

                # Save BW data to file
                #   Leave empty if no response received
                hFile = _io.open(folderPath_root + folderPath_response + dat['bw_filename'].iloc[iRow], "w")
                if I_json:
                    print("\t\tSaving BW data to file")
                    json.dump(hJSON, hFile)
                hFile.close()

                # Add time delay
                time.sleep(0.5)

        print("\tEnd of requests")
        pandas.options.mode.chained_assignment = 'warn'

        print("Saving status matrix to file")
        dat.to_csv(folderPath_root + folderPath_response + "dat_" + time.strftime("%Y_%m_%d") + ".csv", sep=',', encoding='utf-8')
        print("Done")

    return

main()
exit()


from decimal import Decimal as D
from django.contrib import messages
from duxdekes.exceptions import ChargeAdjustmentException, ChargeCaptureException
from oscar.apps.dashboard.orders.views import OrderDetailView as OscarOrderDetailView
from oscar.apps.order.exceptions import InvalidShippingEvent, InvalidPaymentEvent
from oscar.core.loading import get_class, get_model
from .forms import FinalizeOrderForm

EventHandler = get_class('order.processing', 'EventHandler')
PaymentEventType = get_model('order', 'PaymentEventType')
ShippingEventType = get_model('order', 'ShippingEventType')

class OrderDetailView(OscarOrderDetailView):
    """
    Add a finalize order method to the OrderDetailView
    """
    order_actions = OscarOrderDetailView.order_actions + ('finalize_order',)

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)

        # Forms
        ctx['finalize_order_form'] = self.get_finalize_order_form()

        return ctx

    def get_finalize_order_form(self):
        """
        Get an instance of the "finalize order" form
        """
        kwargs = {}

        if self.object and self.object.final_shipping:
            kwargs['initial'] = {
                'final_shipping': self.object.final_shipping,
                }

        if self.request.method == 'POST':
            kwargs['data'] = self.request.POST

        return FinalizeOrderForm(**kwargs)

    def finalize_order(self, request, order):
        """
        Take a previously authorized order, and finalize the charge
        """
        handler = EventHandler()
        finalize_form = self.get_finalize_order_form()

        if finalize_form.is_valid():

            try:
                # Save the final shipping value, just in case something gets
                # ruined
                order.final_shipping = finalize_form.cleaned_data['final_shipping']
                order.save()

                # Calculate the new final amount
                amount = D(order.final_shipping) + order.basket_total_incl_tax

                # Capture the payment, with the NEW and IMPROVED amount
                if order.status == 'Pending':
                    capture_event_type, _ = PaymentEventType.objects.get_or_create(
                            code='capture', defaults={'name': 'Captured'})
                    handler.handle_payment_event(order, capture_event_type, order.total_incl_tax)
                    handler.handle_order_status_change(order, 'Needs Adjustment',
                            note_msg='Customer successfully charged')
                    # Maybe this will allow us to see the capture event?
                    order.save()

                # Adjust the total with a refund to the customer to reflect
                # differences in the shipping costs
                if order.status == 'Needs Adjustment' and amount != order.total_incl_tax:
                    adjust_event_type, _ = PaymentEventType.objects.get_or_create(
                            code='adjust', defaults={'name': 'Adjusted'})
                    handler.handle_payment_event(order, adjust_event_type, amount)

                    # Do we really need this order status change?
                    #handler.handle_order_status_change(order, 'Adjusted',
                    #        note_msg='Customer refunded difference in shipping')

                # Set everything as shipped, and calculate the lines if needed
                lines = [ line for line in order.lines.all() ]
                line_quantities = [ line.quantity for line in order.lines.all() ]
                shipping_event_type, _ = ShippingEventType.objects.get_or_create(
                        code='shipped', defaults={'name': 'Shipped'})

                handler.handle_shipping_event(order, shipping_event_type,
                        lines, line_quantities)
                handler.handle_order_status_change(order, 'Processed',
                        note_msg='Customer successfully charged')

            except ChargeAdjustmentException as e:
                msg = """
                There was a problem adjusting the final charge to
                reflect the real shipping charge.
                """

                messages.error(request, msg + str(e))
                handler.handle_order_status_change(order, 'Needs Adjustment',
                        note_msg=msg)
            except ChargeCaptureException as e:
                msg = """
                There was a problem finalizing the payment: the payment gateway
                may be experiencing problems.

                Please try again in a few minutes.
                """
                messages.error(request, msg)
            except InvalidPaymentEvent as e:
                messages.error(request, '[Payment] '+str(e))
            except InvalidShippingEvent as e:
                msg = """
                [Shipping] There was a problem registering the shipping event. This was
                unexpected, but shouldn't actually affect anything.
                """
                messages.error(request, msg)

        else:
            messages.error(request, "[Form] The final amount you've typed in is not valid")

        return self.reload_page()


from PIL import Image

im = Image.open('boat_850.jpg')
gray = im.convert('L')
width, height = im.size
# gray = Image.new('L', (width, height))
a=50
b=150
beta =2
alfa = 0.2
gama = 1
ya = 30
yb = 200

for w in range(width):
    for h in range(height):
        color = gray.getpixel((w, h))
        if 0<=color<a:
            color = alfa*color
        elif a<=color<b:
            color = beta*(color-a)+ya
        elif b<=color<256:
            color = gama*(color-b)+yb
        gray.putpixel((w,h),int(color))

gray.show()
gray.save('contras.jpg')


import os
import subprocess

# artifact name needs to match entries in the pom
# https://central.sonatype.org/pages/requirements.html
groupId = 'com.mux'
archiveName = 'com.mux.stats.sdk'

def findFiles(path, ext):
    return [f for f in os.listdir(path) if f.endswith('.' + ext)]

def writePOMfile(path, product, ext):
    x0 = product.find('.' + ext)
    x1 = product.find('-')
    filename = path + '/' + product[:x0] + '.pom'
    with open(filename, 'w') as file:
        file.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        file.write('<project xmlns="http://maven.apache.org/POM/4.0.0"\n')
        file.write('   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" \n')
        file.write('   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">\n')
        file.write('   <modelVersion>4.0.0</modelVersion>\n')
        file.write('\n')

        x0 = product.find('.aar')
        product = product[: x0]
        x0 = product.rfind('-')
        version = product[x0 + 1:]
        product = product[: x0]
        x0 = product.rfind('-')
        exoVersion = product[x0 + 1:]
        file.write('   <groupId>' + groupId + '</groupId>\n')
        file.write('   <artifactId>' + archiveName + '-' + exoVersion + '</artifactId>\n')
        file.write('   <version>' + version + '</version>\n')
        file.write('   <packaging>' + ext + '</packaging>\n')
        file.write('\n')

        file.write('   <name>' + archiveName + '</name>\n')
        file.write('   <description>This is the Mux wrapper around ExoPlayer ' + exoVersion + '</description>\n')
        file.write('   <url>https://github.com/muxinc/mux-stats-sdk-exoplayer</url>\n')
        file.write('\n')

        file.write('   <scm>\n')
        file.write('       <connection>scm:git:git@github.com:muxinc/mux-stats-sdk-exoplayer.git</connection>\n')
        file.write('       <developerConnection>scm:git:git@github.com:muxinc/mux-stats-sdk-exoplayer.git</developerConnection>\n')
        file.write('       <url>https://github.com/muxinc/mux-stats-sdk-exoplayer</url>\n')
        file.write('   </scm>\n')
        file.write('\n')

        file.write('   <developers>\n')
        file.write('       <developer>\n')
        file.write('           <name>mux</name>\n')
        file.write('           <email>info@mux.com</email>\n')
        file.write('           <organization>Mux Inc</organization>\n')
        file.write('           <organizationUrl>www.mux.com</organizationUrl>\n')
        file.write('       </developer>\n')
        file.write('   </developers>\n')
        file.write('\n')

        file.write('   <licenses>\n')
        file.write('       <license>\n')
        file.write('           <name>The Apache License, Version 2.0</name>\n')
        file.write('           <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>\n')
        file.write('       </license>\n')
        file.write('   </licenses>\n')
        file.write('\n')

        file.write('</project>')

def gpgSignProduct(path, product):
    x0 = product.find('.aar')
    product = product[: x0]
    subprocess.check_output(['gpg','-ab', '--yes', product + '.aar'])
    subprocess.check_output(['gpg','-ab', '--yes', product + '.pom'])
    subprocess.check_output(['gpg','-ab', '--yes', product + '-javadoc.jar'])
    subprocess.check_output(['gpg','-ab', '--yes', product + '-sources.jar'])
    subprocess.check_output(['jar','-cvf', product + '.bundle.jar', \
        product + '.aar', product + '.aar.asc', \
        product + '.pom', product + '.pom.asc', \
        product + '-javadoc.jar', product + '-javadoc.jar.asc', \
        product + '-sources.jar', product + '-sources.jar.asc' \
        ])

dir_path = os.path.dirname(os.path.realpath(__file__)) + '/MuxExoPlayer/buildout/outputs/publish'
products = findFiles(dir_path, 'aar')
for product in products:
    writePOMfile(dir_path, product, 'aar')

os.chdir(dir_path)
for product in products:
    gpgSignProduct(dir_path, product)


"""
Module contains the catering model.
"""
from .. import db
from . base_model import BaseModel

class Catering(BaseModel):
    """
    Catering class represents caterings table
    """
    __tablename__ = 'caterings'
    name = db.Column(db.String(100), nullable=False)
    address = db.Column(db.String(100))
    menus = db.relationship('Menu', backref='catering', lazy='dynamic')
    meals = db.relationship('Meal', backref='catering', lazy='dynamic')
    orders = db.relationship('Order', backref='catering', lazy='dynamic')
    admin_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    admin = db.relationship(
        "User", backref=db.backref('catering', uselist=False))

    def to_dict(self):
        """
        to_dict. turns object to dict
        """
        return {
            'id': self.id,
            'name': self.name,
            'address': self.address
        }


import logging

from arteria.web.handlers import BaseRestHandler

log = logging.getLogger(__name__)

class StagingRunfolderHandler(BaseRestHandler):
    """
    Handler class for handling how to start staging of a runfolder. Polling for status, canceling, etc can then be
    handled by the more general `StagingHandler`
    """

    def initialize(self, staging_service, **kwargs):
        self.staging_service = staging_service

    def post(self, runfolder_id):
        """
        Attempt to stage projects from the the specified runfolder, so that they can then be delivered.
        Will return a set of status links, one for each project that can be queried for the status of
        that staging attempt. A list of project names can be specified in the request body to limit which projects
        should be staged. E.g:

            import requests

            url = "http://localhost:8080/api/1.0/stage/runfolder/160930_ST-E00216_0111_BH37CWALXX"

            payload = "{'projects': ['ABC_123', 'DEF_456']}"
            headers = {
                'content-type': "application/json",
            }

            response = requests.request("POST", url, data=payload, headers=headers)

            print(response.text)

        The return format looks like:

            {
               "staging_order_links": [
                    "http://localhost:8080/api/1.0/stage/1"
                ]
            }
        """

        log.debug("Trying to stage runfolder with id: {}".format(runfolder_id))

        try:
            request_data = self.body_as_object()
        except ValueError:
            request_data = {}

        projects_to_stage = request_data.get("projects", [])

        staging_order_ids = self.staging_service.stage_runfolder(runfolder_id, projects_to_stage)
        status_end_points = map(lambda order_id: "{0}://{1}{2}".format(self.request.protocol,
                                                                       self.request.host,
                                                                       self.reverse_url("stage_status", order_id)),
                                staging_order_ids)

        self.set_status(202)
        self.write_json({'staging_order_links': status_end_points})

class StagingHandler(BaseRestHandler):

    def initialize(self, staging_service, **kwargs):
        self.staging_service = staging_service

    def get(self, stage_id):
        """
        Returns the current status as json of the of the staging order, or 404 if the order is unknown.
        Possible values for status are: pending, staging_in_progress, staging_successful, staging_failed
        Return format looks like:
        {
           "status": "staging_successful"
        }
        """
        status = self.staging_service.get_status_of_stage_order(stage_id)
        if status:
            self.write_json({'status': status.name})
        else:
            self.set_status(404, reason='No stage order with id: {} found.'.format(stage_id))

    def delete(self, stage_id):
        """
        Kill a stage order with the give id. Will return status 204 if the staging process was successfully cancelled,
        otherwise it will return status 500.
        """
        was_killed = self.staging_service.kill_process_of_stage_order(stage_id)
        if was_killed:
            self.set_status(204)
        else:
            self.set_status(500, reason="Could not kill stage order with id: {}, either it wasn't in a state "
                                        "which allows it to be killed, or the pid associated with the stage order "
                                        "did not allow itself to be killed. Consult the server logs for an exact "
                                        "reason.")


from tkinter import *
from tkinter import messagebox

inicio = Tk()
inicio.title("Alco - Sáenz Peña")

#mensaje de aviso que funciona
def funciona():
    funcionamiento = messagebox.askokcancel("Mensaje de aviso", "Esto está funcionando")
    if funcionamiento == True:
        inicio.destroy()

#configurar menus
barraMenu = Menu(inicio)
inicio.config(menu = barraMenu,width = 300,height = 300)
MenuPrincipal=Menu(barraMenu,tearoff = 0)
barraMenu.add_cascade(label = "Alquista", menu = MenuPrincipal)
MenuInformes = Menu(barraMenu,tearoff = 0)

MenuAyuda = Menu(barraMenu,tearoff = 0)
MenuLicencia = Menu(barraMenu,tearoff = 0)

barraMenu.add_cascade(label = "Informes y estadísticas", menu = MenuInformes)
barraMenu.add_cascade(label = "Ayuda", menu = MenuAyuda)
barraMenu.add_cascade(label = "Licencia", menu = MenuLicencia)
MenuPrincipal.add_command(label = "Control del peso",command = funciona)

inicio.mainloop()


l1 = input()
l = [int(x) for x in l1.split(" ")]
d,r = {}, []
flag=0
for num in l:
	if 20%num == 0 and 20//num in d:
		if not flag: flag = 1
		t1 = (20//num,num)
		r.append(t1)

	else:
		d[num] = 1
if len(r) == 0:
	print('No match possible')
else:
	for t in r:
		print(t, end = " ")


#!/usr/bin/env python
"""
Query the CMIP6 data request database to return CMIP6 experiments options.
--------------------------
Created October, 2016

Author: CSEG <cseg@cgd.ucar.edu>
"""

from __future__ import print_function

import sys

# check the system python version and require 2.7.x or greater
if sys.hexversion < 0x02070000:
    print(70 * "*")
    print("ERROR: {0} requires python >= 2.7.x. ".format(sys.argv[0]))
    print("It appears that you are running python {0}".format(
            ".".join(str(x) for x in sys.version_info[0:3])))
    print(70 * "*")
    sys.exit(1)

try:
    from dreqPy import dreq
except ImportError:
    print('ERROR cmip6_lookup in listCMIP6 - unable to import dreqPy package.')
    print('Please install or update to the latest dreqPy version in your local user directory as follows:')
    print('pip install -i https://testpypi.python.org/pypi --user  dreqPy==[01.beta.#]')
    print('The latest version can be found at https://www.earthsystemcog.org/projects/wip/CMIP6DataRequest')
    sys.exit(1)
#
# built-in modules
#
import argparse
import errno
import json
import pprint
import traceback

# define global variables
_pp = pprint.PrettyPrinter(indent=4)

# -------------------------------------------------------------------------------
# commandline_options - parse any command line options
# -------------------------------------------------------------------------------
def commandline_options():
    """Process the command line arguments.

    """
    parser = argparse.ArgumentParser(
        description='Query and display information from the CMIP6 data request database.')

    parser.add_argument('--backtrace', action='store_true',
                        help='Show exception backtraces as extra debugging output')

    parser.add_argument('--debug', required=False, action='store_true',
                        help='Display debugging messages')

    parser.add_argument('--expNames', action='store_true',
                        help='Display a list of valid CMIP6 experiment names.')

    parser.add_argument('--MIPS', action='store_true',
                        help='Display a list of valid MIPS.')

    parser.add_argument('--expMips', action='store_true',
                        help='Display a list of requesting and designing MIPs for each experiment name.')

    parser.add_argument('--vars', action='store_true',
                        help='Display a list of variables for each experiment name.')

    options = parser.parse_args()

    return options

# ---------------------------------------------------------------------
# get_mip_list
# ---------------------------------------------------------------------
def get_mip_list(dq=None):

    """
    Get a list of all MIPs within the CMIP6 data request
    Return:

    mips(dictionary): a dictionary containing the mip name as the key and
          its values being the description of that mip
    """

    mips = {}
    if dq is None:
        dq = dreq.loadDreq()
    for m in dq.coll['mip'].items:
        mips[m.label] = m.title

    return mips

# ---------------------------------------------------------------------
# get_exp_list
# ---------------------------------------------------------------------
def get_exp_list(dq=None):

    """
    Get a list of all experiments within the CMIP6 data request

    Return:
    exp(ditctionary): a dictionary containing the experiment name as the key and
         its values being the description of that experiment
    """

    exp = {}
    if dq is None:
        dq = dreq.loadDreq()
    for e in dq.coll['experiment'].items:
        exp[e.label] = [e.description, e.uid]

    return exp

# ---------------------------------------------------------------------
# map_exp_to_design_mip
# ---------------------------------------------------------------------
def map_exp_to_design_mip(exp_name, dq=None):

    """
    Takes an experiment name and returns the designing mip name

    Args:
    exp_name: name of the experiment to look up

    Return:
    mip(string):  name of the designing mip
    """

    if dq is None:
        dq = dreq.loadDreq()
    e_id = dq.inx.experiment.label[exp_name][0]
    mip = dq.inx.uid[e_id].mip

    return mip

# ---------------------------------------------------------------------
# map_exp_to_request_mip
# ---------------------------------------------------------------------
def map_exp_to_request_mip(exp_name, dq=None):

    """
    Takes an experiment name and returns the mips requesting data from it

    Args:
    exp_name: name of the experiment to look up

    Return:
    mip (list):  name of the requesting mips
    """

    if dq is None:
        dq = dreq.loadDreq()

    mips = []
    e_id = dq.inx.experiment.label[exp_name][0]
    mips.append(dq.inx.uid[e_id].mip)
    e_vars = dq.inx.iref_by_sect[e_id].a
    for ri in e_vars['requestItem']:
        dr = dq.inx.uid[ri]
        if dr.mip not in mips:
            mips.append(dr.mip)

    return mips

# ---------------------------------------------------------------------
# main
# ---------------------------------------------------------------------

def main(options):
    """ main

    Arguments:
        options (list) - input options from command line
    """
    case_dict = dict()
    debug = options.debug

    dq = dreq.loadDreq()

    if options.MIPS:
        print('\n\n##################################################################')
        mips = get_mip_list(dq=dq)
        print('MIPS: ')
        _pp.pprint(mips)

    if options.expNames:
        print('\n\n##################################################################')
        exps = get_exp_list(dq=dq)
        print('Experiments:  ')
        _pp.pprint(exps)

    if options.expMips:
        print('\n\n##################################################################')
        for e in dq.coll['experiment'].items:
            print('Requesting: ',e.label, map_exp_to_request_mip(e.label, dq=dq))
            print('Designing: ',e.label, map_exp_to_design_mip(e.label, dq=dq),'\n')

#===================================
if __name__ == "__main__":
    options = commandline_options()
    try:
        status = main(options)
        sys.exit(status)
    except Exception as error:
        print(str(error))
        if options.backtrace:
            traceback.print_exc()
        sys.exit(1)


"""abp_padel URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/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.conf import settings
from django.conf.urls.static import static
from django.urls import path, include

from users.views import signup_view, profile_view, LoginView, LogoutView, inscripcion_view, desinscripcion_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
    path('signup/', signup_view, name='users-signup'),
    path('login/', LoginView.as_view(template_name='users/login.html'), name='users-login'),
    path('logout/', LogoutView.as_view(template_name='users/logout.html'), name='users-logout'),
    path('profile/', profile_view, name='users-profile'),
    path('inscripcion/', inscripcion_view, name='users-inscripcion'),
    path('desinscripcion/', desinscripcion_view, name='users-desinscripcion'),
    path('pista/', include('pistas.urls')),
    path('reserva/', include('reservas.urls')),
    path('campeonato/', include('campeonatos.urls')),
    path('partidos-promocionados/', include('promociones_partidos.urls'))

]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

admin.site.index_title = "iPadl Admin"
admin.site.site_header = "iPadl Admin"


from flask import Flask
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import folium
from folium import plugins

app = Flask(__name__)

@app.route('/')
def index():
	fire_nrt_m6 = pd.read_csv("./data/fire_archive_M6_101673.csv")
	fire_archive_m6 = pd.read_csv("./data/fire_archive_M6_101673.csv")
	fire_nrt_v1 = pd.read_csv("./data/fire_nrt_V1_101674.csv")
	fire_archive_v1 = pd.read_csv("./data/fire_archive_V1_101674.csv")

	df_merged = pd.concat([fire_archive_v1,fire_nrt_v1],sort=True)
	data = df_merged
	df_filter = data.filter(["latitude","longitude","acq_date","frp"])

	df = df_filter[(df_filter['acq_date']>='2019-12-01')&(df_filter['acq_date']<='2020-01-02')]

	from folium.plugins import HeatMapWithTime
	# A small function to get heat map with time given the data

	def getmap(ip_data,location,zoom,radius):

    	#get day list
		dfmap = ip_data[['acq_date','latitude','longitude','frp']]
		df_day_list = []
		for day in dfmap.acq_date.sort_values().unique():
			df_day_list.append(dfmap.loc[dfmap.acq_date == day, ['acq_date','latitude', 'longitude', 'frp']].groupby(['latitude', 'longitude']).sum().reset_index().values.tolist())

		# Create a map using folium
		m = folium.Map(location, zoom_start=zoom,tiles='Stamen Terrain',height=500)
		#creating heatmap with time
		HeatMapWithTime(df_day_list,index =list(dfmap.acq_date.sort_values().unique()), auto_play=False,radius=radius, gradient={0.2: 'blue', 0.4: 'lime', 0.6: 'orange', 1: 'red'}, min_opacity=0.5, max_opacity=0.8, use_local_extrema=True).add_to(m)

		return m

	m = getmap(df,[-28,132],3.5,3)
	#m.save('./html/australia_bushfire.html')
	#m

	return m._repr_html_()

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


# test the pre-trained model on a single video
# (working on it)
# Bolei Zhou and Alex Andonian

import os
import re
import cv2
import argparse
import functools
import subprocess
import numpy as np
from PIL import Image
#import moviepy.editor as mpy
import torch
import torchvision
import torch.nn.parallel
import torch.optim
from models import TSN
import transforms
from torch.nn import functional as F

def extract_frames(video_file, num_frames=8):
    try:
        os.makedirs(os.path.join(os.getcwd(), 'frames'))
    except OSError:
        pass

    output = subprocess.Popen(['ffmpeg', '-i', video_file],
                              stderr=subprocess.PIPE).communicate()
    # Search and parse 'Duration: 00:05:24.13,' from ffmpeg stderr.
    re_duration = re.compile('Duration: (.*?)\.')
    duration = re_duration.search(str(output[1])).groups()[0]

    seconds = functools.reduce(lambda x, y: x * 60 + y,
                               map(int, duration.split(':')))
    rate = num_frames / float(seconds)

    output = subprocess.Popen(['ffmpeg', '-i', video_file,
                               '-vf', 'fps={}'.format(rate),
                               '-vframes', str(num_frames),
                               '-loglevel', 'panic',
                               'frames/%d.jpg']).communicate()
    frame_paths = sorted([os.path.join('frames', frame)
                          for frame in os.listdir('frames')])

    frames = load_frames(frame_paths)
    subprocess.call(['rm', '-rf', 'frames'])
    return frames

def load_frames(frame_paths, num_frames=8):
    frames = [Image.open(frame).convert('RGB') for frame in frame_paths]
    if len(frames) >= num_frames:
        return frames[::int(np.ceil(len(frames) / float(num_frames)))]
    else:
        raise ValueError('Video must have at least {} frames'.format(num_frames))

def render_frames(frames, prediction):
    rendered_frames = []
    for frame in frames:
        img = np.array(frame)
        height, width, _ = img.shape
        cv2.putText(img, prediction,
                    (1, int(height / 8)),
                    cv2.FONT_HERSHEY_SIMPLEX,
                    1, (255, 255, 255), 2)
        rendered_frames.append(img)
    return rendered_frames

# options
parser = argparse.ArgumentParser(description="test TRN on a single video")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--video_file', type=str, default=None)
group.add_argument('--frame_folder', type=str, default=None)
parser.add_argument('--modality', type=str, default='RGB',
                    choices=['RGB', 'Flow', 'RGBDiff'], )
parser.add_argument('--dataset', type=str, default='moments',
                    choices=['something', 'jester', 'moments', 'somethingv2'])
parser.add_argument('--rendered_output', type=str, default=None)
parser.add_argument('--arch', type=str, default="InceptionV3")
parser.add_argument('--input_size', type=int, default=224)
parser.add_argument('--test_segments', type=int, default=8)
parser.add_argument('--img_feature_dim', type=int, default=256)
parser.add_argument('--consensus_type', type=str, default='TRNmultiscale')
parser.add_argument('--weights', type=str)

args = parser.parse_args()

# Get dataset categories.
categories_file = 'pretrain/{}_categories.txt'.format(args.dataset)
categories = [line.rstrip() for line in open(categories_file, 'r').readlines()]
num_class = len(categories)

args.arch = 'InceptionV3' if args.dataset == 'moments' else 'BNInception'

# Load model.
net = TSN(2,
          args.test_segments,
          args.modality,
          base_model=args.arch,
          consensus_type=args.consensus_type,
          img_feature_dim=args.img_feature_dim, print_spec=False)

net = torch.nn.DataParallel(net)
import glob

checkpoint_names = glob.glob('checkpoint_*.pth')
save_acc_dict = {}
best_acc = 0.0
best_cp = None
torch.manual_seed(1111)
import pickle
from tqdm import tqdm
for checkpoint_name in tqdm(checkpoint_names):
    checkpoint = torch.load(checkpoint_name)
    print(checkpoint_name)
    """
    base_dict = {'.'.join(k.split('.')[1:]): v for k, v in list(checkpoint['state_dict'].items())}
    for key in ['consensus.fc_fusion_scales.6.3.bias', 'consensus.fc_fusion_scales.5.3.bias', 'consensus.fc_fusion_scales.4.3.bias',
    'consensus.fc_fusion_scales.3.3.bias', 'consensus.fc_fusion_scales.2.3.bias', 'consensus.fc_fusion_scales.1.3.bias',
    'consensus.fc_fusion_scales.0.3.bias', 'consensus.fc_fusion_scales.6.3.weight', 'consensus.fc_fusion_scales.5.3.weight',
    'consensus.fc_fusion_scales.4.3.weight', 'consensus.fc_fusion_scales.3.3.weight', 'consensus.fc_fusion_scales.2.3.weight',
    'consensus.fc_fusion_scales.1.3.weight', 'consensus.fc_fusion_scales.0.3.weight']:
    del base_dict[key]
    #print(base_dict)
    """
    #net.load_state_dict(base_dict, strict=False)
    net.load_state_dict(checkpoint, strict=True)
    #print(net)
    #exit(0)
    net.eval()
    net.cuda()

    # Initialize frame transforms.
    transform = torchvision.transforms.Compose([
        transforms.GroupOverSample(net.module.input_size, net.module.scale_size),
        transforms.Stack(roll=(args.arch in ['BNInception', 'InceptionV3'])),
        transforms.ToTorchFormatTensor(div=(args.arch not in ['BNInception', 'InceptionV3'])),
        transforms.GroupNormalize(net.module.input_mean, net.module.input_std),
    ])

    segments_gt = [0, 0, 1, 1, 0, 0, 0,
                   0, 0, 1, 1, 1, 1, 0,
                   1, 0, 0, 0, 0, 0, 0,
                   1, 1, 1, 0, 0, 0, 0,
                   1, 1, 1, 0, 0, 1, 1,
                   2, 2, 0, 0, 1, 1, 1,
                   0, 0, 0, 0, 2]

    pred = [2]* len(segments_gt)
    video_dir = 'segments_2_slow/*.mp4'
    for video_file_name in sorted(glob.glob(video_dir)):
        print('best acc : {}, best cp : {}'.format(best_acc, best_cp))
        video_file = video_file_name
        index = int(video_file_name.split('/')[-1].split('_')[-1].split('.')[0])
        print(video_file_name, index)
        # Obtain video frames
        if args.frame_folder is not None:
            print('Loading frames in {}'.format(args.frame_folder))
            # Here, make sure after sorting the frame paths have the correct temporal order
            frame_paths = sorted(glob.glob(os.path.join(args.frame_folder, '*.jpg')))
            frames = load_frames(frame_paths)
        else:
            try:
                print('Extracting frames using ffmpeg...')
                frames = extract_frames(video_file, args.test_segments)
            except:
                continue
        # Make video prediction.
        data = transform(frames)
        input = data.view(-1, 3, data.size(1), data.size(2)).unsqueeze(0)
        pred_index = 2
        with torch.no_grad():
            logits = net(input.cuda())
            h_x = torch.mean(F.sigmoid(logits), dim=0).data
            probs, idx = h_x.sort(0, True)
        print(h_x)
        if h_x[0] >= 0.5 and h_x[0] > h_x[1]:
            pred_index = 0
        elif h_x[1] >= 0.5 and h_x[1] > h_x[0]:
            pred_index = 1
        pred[index // 6] = pred_index
        continue
    """
    # Output the prediction.
    video_name = args.frame_folder if args.frame_folder is not None else video_file
    print('RESULT ON ' + video_name)
    top5 = []
    exit(0)
    for i in range(0, 5):
        print('{:.3f} -> {}'.format(probs[i], categories[idx[i]]))
        top5.append((probs[i].item(), categories[idx[i]]))
    outputs[index] = top5
    print('---------')
    # print(outputs)
    exit(0)
    """
    acc = np.sum(np.array(segments_gt) == np.array(pred)) / len(segments_gt)
    save_acc_dict[checkpoint_name] = acc
    print(acc)
    if acc > best_acc:
        best_acc = acc
        best_cp = checkpoint_name

    pickle.dump(save_acc_dict, open('saved_acc_dict.pkl', 'wb'))
# Render output frames with prediction text.
#if args.rendered_output is not None:
#    prediction = categories[idx[0]]
#    rendered_frames = render_frames(frames, prediction)
#    clip = mpy.ImageSequenceClip(rendered_frames, fps=4)
#    clip.write_videofile(args.rendered_output)


from admin_views.admin import AdminViews
from conferences.models.conference import Conference
from django.contrib import admin, messages
from django.shortcuts import redirect
from newsletters.exporter import Endpoint
from notifications.aws import send_endpoints_to_pinpoint
from pretix import get_all_order_positions, get_items
from users.models import User

from .exporter import convert_user_to_endpoint
from .models import Subscription

def get_positions_with_missing_user(users, conference):
    admission_items = get_items(conference, {"admission": True})
    admission_items_ids = list(admission_items.keys())

    order_positions = [
        position
        for position in get_all_order_positions(
            conference,
            {"order__status": "p", "item__in": ",".join(admission_items_ids)},
        )
        if position["attendee_email"]
    ]

    position_by_email = {
        position["attendee_email"]: position for position in order_positions
    }

    order_emails = set(position_by_email)
    user_emails = set([user.email for user in users])

    missing_emails = order_emails - user_emails

    for email in missing_emails:
        yield position_by_email[email]

def get_missing_users_endpoints(users):
    conference = Conference.objects.last()
    positions = get_positions_with_missing_user(users, conference)

    return [
        Endpoint(
            id=f"pretix_{position['attendee_email']}",
            name=position["attendee_name"],
            full_name=position["attendee_name"],
            email=position["attendee_email"],
            is_staff=False,
            has_sent_submission_to=[],
            has_item_in_schedule=[],
            has_cancelled_talks=[],
            has_ticket=[conference.code],
            talks_by_conference={},
        )
        for position in positions
    ]

@admin.register(Subscription)
class SubscriptionAdmin(AdminViews):
    list_display = ("email", "date_subscribed")
    admin_views = (("Export all users to Pinpoint", "export_all_users_to_pinpoint"),)

    def export_all_users_to_pinpoint(self, request, **kwargs):
        users = User.objects.all()

        endpoints = [
            convert_user_to_endpoint(user) for user in users
        ] + get_missing_users_endpoints(users)

        send_endpoints_to_pinpoint(endpoints)

        self.message_user(
            request, "Exported all the users to Pinpoint", level=messages.SUCCESS
        )

        return redirect("admin:index")


import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split

def getDataClassification(path):
    data = pd.read_csv(path)
    x_data = np.array(data.drop('class_price', 1))
    y_data = np.array(data['class_price'])
    n_class = data.drop_duplicates(subset='class_price')['class_price']
    x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.33, random_state=42)
    return x_train, x_test, y_train, y_test, n_class

def getDataPrediction(path):
    data = pd.read_csv(path)
    data = data.drop('class_price', 1)
    x_data = np.array(data.drop('SalePrice', 1))
    y_data = np.array(data['SalePrice'])
    n_class = data.drop_duplicates(subset='SalePrice')['SalePrice']
    x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.33, random_state=42)
    return x_train, x_test, y_train, y_test, n_class


'''Questão Número: 1'''
def mult(matriz, multiplo):
    '''essa função recebe uma matriz e retorna ela multiplicada pelo numero que foi inserido'''
    '''list, int -> list'''
    resultado = list()
    qtd_linhas = len(matriz)
    qtd_colunas = len(matriz[0])

    for i in range(qtd_linhas):
        resultado.append([])
        for j in range(qtd_colunas):
            mult = multiplo * matriz[i][j]
            list.append(resultado[i], mult)
    return resultado

'''Questão Número: 2'''
def ligou(lista,telefone):
    '''essa função recebe uma lista e pesquisa por um determinado telefone de pessoa, e retorna uma lista com as informações encontradas'''
    '''list, str -> list'''
    contatos_encontrados = list()

    for i in range(len(lista)):
        if (telefone in lista[i][1]):
            contatos_encontrados.append(lista[i])
    return contatos_encontrados


#!/usr/bin/python3
# -*- coding:utf-8 -*-
import sys
import getopt
import traceback
import yaml

from . import logger
from .task import Task
from .version import __version__

class Executor:
    @staticmethod
    def autoremove(config):
        # Set default logging path to current working directory
        log_path = "./"

        # Decide whether to output debug log
        debug_mode = config["debug"]

        # Init logger
        logger.Logger.init(
            log_path, file_debug_log=debug_mode, output_debug_log=debug_mode
        )
        lg = logger.Logger.register(__name__)

        # Run autoremove
        try:
            # Show version
            lg.debug("Auto Remove Torrents %s" % __version__)

            # Run task
            try:
                Task(config["name"], config, not config["view"]).execute()
            except Exception:
                lg.error(traceback.format_exc().splitlines()[-1])
                lg.error("Task %s fails. " % config["name"])
                lg.debug("Exception Logged", exc_info=True)
        except Exception:
            lg.error(traceback.format_exc().splitlines()[-1])
            lg.debug("Exception Logged", exc_info=True)
            lg.critical(
                "An error occured. If you think this is a bug or need help, you can submit an issue."
            )


# -*- coding: utf-8 -*-
"""
Created on Mon Sep 20 09:33:19 2021

@author: alexa
"""

import pandas as pd
import h5py

filename = '20210825.h5'

with h5py.File(filename, "r") as f:
    # List all groups
    print("Keys: %s" % f.keys())
    a_group_key = list(f.keys())[0]

    # Get the data
    data = list(f[a_group_key])

# pd.read_hdf('20210825.h5','key')


# -*- coding: utf-8 -*-
"""
Created on Mon Apr 23 14:25:54 2018

@author: Hongtao Liu
"""

# -*- coding: utf-8 -*-
"""
Created on Mon Apr 23 10:04:19 2018

@author: Hongtao Liu
"""

# -*- coding: utf-8 -*-
"""
Created on Sun Apr 22 13:45:44 2018

@author: Hongtao Liu
"""
import warnings
warnings.filterwarnings("ignore")
import datetime
start = datetime.datetime.now()

import numpy as np
import pandas as pd

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from scipy.sparse import hstack

class_names = ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']

train = pd.read_csv('train.csv',nrows=30000).fillna(' ')
#test = pd.read_csv('test.csv').fillna(' ')

train_text = train['comment_text']
#test_text = test['comment_text']
#all_text = pd.concat([train_text, test_text])
all_text=train_text

word_vectorizer = CountVectorizer(
 #   sublinear_tf=True,
    strip_accents='unicode',
    analyzer='word',
    token_pattern=r'\w{1,}',
    stop_words='english',
    ngram_range=(1, 2),
    max_features=10000,binary=False)
word_vectorizer.fit(all_text)
train_word_features = word_vectorizer.transform(train_text)
#test_word_features = word_vectorizer.transform(test_text)

#char_vectorizer = CountVectorizer(

#    strip_accents='unicode',
#    analyzer='char',
 #   stop_words='english',
#    ngram_range=(2, 6),
#    max_features=50000)
#char_vectorizer.fit(all_text)
#train_char_features = char_vectorizer.transform(train_text)
#test_char_features = char_vectorizer.transform(test_text)

#train_features = hstack([train_word_features, train_char_features])
#train_features=hstack([train_char_features])
train_features=hstack([train_word_features])
#test_features = hstack([test_char_features, test_word_features])

#submission = pd.DataFrame.from_dict({'id': test['id']})
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils.validation import check_X_y, check_is_fitted
from scipy import sparse
class NbSvmClassifier(BaseEstimator, ClassifierMixin):
    def __init__(self, C=1.0, dual=False, n_jobs=1):
        self.C = C
        self.dual = dual
        self.n_jobs = n_jobs

    def predict(self, x):
        # Verify that model has been fit
        check_is_fitted(self, ['_r', '_clf'])
        return self._clf.predict(x.multiply(self._r))

    def predict_proba(self, x):
        # Verify that model has been fit
        check_is_fitted(self, ['_r', '_clf'])
        return self._clf.predict_proba(x.multiply(self._r))

    def fit(self, x, y):
        # Check that X and y have correct shape
        y = y.values
        x, y = check_X_y(x, y, accept_sparse=True)

        def pr(x, y_i, y):
            p =  x[y==y_i].sum(0)
            return (p+1) / ((y==y_i).sum()+1)

        self._r = sparse.csr_matrix(np.log(pr(x,1,y) / pr(x,0,y)))
        x_nb = x.multiply(self._r)
        self._clf = LogisticRegression(C=self.C, dual=self.dual, n_jobs=self.n_jobs).fit(x_nb, y)
        return self

scores = []
#submission = pd.DataFrame.from_dict({'id': test['id']})
for class_name in class_names:
    train_target = train[class_name]
    classifier = NbSvmClassifier(C=4, dual=True, n_jobs=-1)
    cv_score = np.mean(cross_val_score(classifier,train_features, train_target, cv=5, scoring='roc_auc'))
    scores.append(cv_score)
    print('CV score for class {} is {}'.format(class_name, cv_score))

 #   classifier.fit(train_features, train_target)
 #   submission[class_name] = classifier.predict_proba(test_features)[:, 1]

print('Total CV score is {}'.format(np.mean(scores)))
end = datetime.datetime.now()
print (end-start)
#submission.to_csv('submission.csv', index=False)


import django

if django.VERSION < (1, 11):
    def get_constraints(self, cursor, table_name):
        """
        Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns.
        """
        constraints = {}
        # Loop over the key table, collecting things as constraints
        # This will get PKs, FKs, and uniques, but not CHECK
        cursor.execute("""
            SELECT
                kc.constraint_name,
                kc.column_name,
                c.constraint_type,
                array(SELECT table_name::text || '.' || column_name::text
                      FROM information_schema.constraint_column_usage
                      WHERE constraint_name = kc.constraint_name
                      AND table_schema = kc.table_schema)
            FROM information_schema.key_column_usage AS kc
            JOIN information_schema.table_constraints AS c ON
                kc.table_schema = c.table_schema AND
                kc.table_name = c.table_name AND
                kc.constraint_name = c.constraint_name
            WHERE
                kc.table_schema = %s AND
                kc.table_name = %s
            ORDER BY kc.ordinal_position ASC
        """, [self.connection.schema_name, table_name])
        for constraint, column, kind, used_cols in cursor.fetchall():
            # If we're the first column, make the record
            if constraint not in constraints:
                if len(used_cols) == 0:
                    continue  # added as if the public schema hasn't got the field any more it errors
                constraints[constraint] = {
                    "columns": [],
                    "primary_key": kind.lower() == "primary key",
                    "unique": kind.lower() in ["primary key", "unique"],
                    "foreign_key": tuple(used_cols[0].split(".", 1)) if kind.lower() == "foreign key" else None,
                    "check": False,
                    "index": False,
                }
            # Record the details
            constraints[constraint]['columns'].append(column)
        # Now get CHECK constraint columns
        cursor.execute("""
            SELECT kc.constraint_name, kc.column_name
            FROM information_schema.constraint_column_usage AS kc
            JOIN information_schema.table_constraints AS c ON
                kc.table_schema = c.table_schema AND
                kc.table_name = c.table_name AND
                kc.constraint_name = c.constraint_name
            WHERE
                c.constraint_type = 'CHECK' AND
                kc.table_schema = %s AND
                kc.table_name = %s
        """, [self.connection.schema_name, table_name])
        for constraint, column in cursor.fetchall():
            # If we're the first column, make the record
            if constraint not in constraints:
                constraints[constraint] = {
                    "columns": [],
                    "primary_key": False,
                    "unique": False,
                    "foreign_key": None,
                    "check": True,
                    "index": False,
                }
            # Record the details
            constraints[constraint]['columns'].append(column)
        # Now get indexes
        cursor.execute("""
            SELECT
                c2.relname,
                ARRAY(
                    SELECT (SELECT attname FROM pg_catalog.pg_attribute WHERE attnum = i AND attrelid = c.oid)
                    FROM unnest(idx.indkey) i
                ),
                idx.indisunique,
                idx.indisprimary
            FROM pg_catalog.pg_class c
                 INNER JOIN pg_catalog.pg_index idx ON c.oid = idx.indrelid
                 INNER JOIN pg_catalog.pg_class c2 ON idx.indexrelid = c2.oid
                 LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
            WHERE c.relname = %s and n.nspname = %s
        """, [table_name, self.connection.schema_name])
        for index, columns, unique, primary in cursor.fetchall():
            if index not in constraints:
                constraints[index] = {
                    "columns": list(columns),
                    "primary_key": primary,
                    "unique": unique,
                    "foreign_key": None,
                    "check": False,
                    "index": True,
                }
        return constraints

elif django.VERSION < (2, 0):
    from django.db.models.indexes import Index

    def get_constraints(self, cursor, table_name):
        """
        Retrieve any constraints or keys (unique, pk, fk, check, index) across
        one or more columns. Also retrieve the definition of expression-based
        indexes.
        """
        constraints = {}
        # Loop over the key table, collecting things as constraints. The column
        # array must return column names in the same order in which they were
        # created.
        # The subquery containing generate_series can be replaced with
        # "WITH ORDINALITY" when support for PostgreSQL 9.3 is dropped.
        cursor.execute("""
            SELECT
                c.conname,
                array(
                    SELECT attname
                    FROM (
                        SELECT unnest(c.conkey) AS colid,
                               generate_series(1, array_length(c.conkey, 1)) AS arridx
                    ) AS cols
                    JOIN pg_attribute AS ca ON cols.colid = ca.attnum
                    WHERE ca.attrelid = c.conrelid
                    ORDER BY cols.arridx
                ),
                c.contype,
                (SELECT fkc.relname || '.' || fka.attname
                FROM pg_attribute AS fka
                JOIN pg_class AS fkc ON fka.attrelid = fkc.oid
                WHERE fka.attrelid = c.confrelid AND fka.attnum = c.confkey[1]),
                cl.reloptions
            FROM pg_constraint AS c
            JOIN pg_class AS cl ON c.conrelid = cl.oid
            JOIN pg_namespace AS ns ON cl.relnamespace = ns.oid
            WHERE ns.nspname = %s AND cl.relname = %s
        """, [self.connection.schema_name, table_name])
        for constraint, columns, kind, used_cols, options in cursor.fetchall():
            constraints[constraint] = {
                "columns": columns,
                "primary_key": kind == "p",
                "unique": kind in ["p", "u"],
                "foreign_key": tuple(used_cols.split(".", 1)) if kind == "f" else None,
                "check": kind == "c",
                "index": False,
                "definition": None,
                "options": options,
            }
        # Now get indexes
        # The row_number() function for ordering the index fields can be
        # replaced by WITH ORDINALITY in the unnest() functions when support
        # for PostgreSQL 9.3 is dropped.
        cursor.execute("""
            SELECT
                indexname, array_agg(attname ORDER BY rnum), indisunique, indisprimary,
                array_agg(ordering ORDER BY rnum), amname, exprdef, s2.attoptions
            FROM (
                SELECT
                    row_number() OVER () as rnum, c2.relname as indexname,
                    idx.*, attr.attname, am.amname,
                    CASE
                        WHEN idx.indexprs IS NOT NULL THEN
                            pg_get_indexdef(idx.indexrelid)
                    END AS exprdef,
                    CASE am.amname
                        WHEN 'btree' THEN
                            CASE (option & 1)
                                WHEN 1 THEN 'DESC' ELSE 'ASC'
                            END
                    END as ordering,
                    c2.reloptions as attoptions
                FROM (
                    SELECT
                        *, unnest(i.indkey) as key, unnest(i.indoption) as option
                    FROM pg_index i
                ) idx
                LEFT JOIN pg_class c ON idx.indrelid = c.oid
                LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
                LEFT JOIN pg_class c2 ON idx.indexrelid = c2.oid
                LEFT JOIN pg_am am ON c2.relam = am.oid
                LEFT JOIN pg_attribute attr ON attr.attrelid = c.oid AND attr.attnum = idx.key
                WHERE c.relname = %s and n.nspname = %s
            ) s2
            GROUP BY indexname, indisunique, indisprimary, amname, exprdef, attoptions;
        """, [table_name, self.connection.schema_name])
        for index, columns, unique, primary, orders, type_, definition, options in cursor.fetchall():
            if index not in constraints:
                constraints[index] = {
                    "columns": columns if columns != [None] else [],
                    "orders": orders if orders != [None] else [],
                    "primary_key": primary,
                    "unique": unique,
                    "foreign_key": None,
                    "check": False,
                    "index": True,
                    "type": Index.suffix if type_ == 'btree' else type_,
                    "definition": definition,
                    "options": options,
                }
        return constraints


"""Syncronizes cell Zookeeper with LDAP data."""
from __future__ import absolute_import

import logging
import os
import time
import itertools
import collections

import click
import ldap3
import yaml

from treadmill import context
from treadmill import exc
from treadmill import sysinfo
from treadmill import authz
from treadmill import zknamespace as z
from treadmill.api import instance

_LOGGER = logging.getLogger(__name__)

def reevaluate(instance_api, state):
    """Evaluate state and adjust app count."""

    grouped = dict(state['scheduled'])
    monitors = dict(state['monitors'])

    for name, count in monitors.iteritems():

        current_count = len(grouped.get(name, []))
        _LOGGER.debug('App: %s current: %s, target %s',
                      name, current_count, count)

        if count == current_count:
            continue

        if count > current_count:
            # need to start more.
            needed = count - current_count
            try:
                _scheduled = instance_api.create(name, {}, count=needed)
                # TODO: may need to rationalize this and not expose low
                #       level ldap exception from admin.py, and rather
                #       return None for non-existing entities.
            except ldap3.LDAPNoSuchObjectResult:
                _LOGGER.warn('Application not configured: %s',
                             name)
            except Exception:  # pylint: disable=W0703
                _LOGGER.exception('Unable to create instances: %s: %s',
                                  name, needed)

        if count < current_count:
            for extra in grouped[name][:current_count - count]:
                try:
                    instance_api.delete(extra)
                except Exception:  # pylint: disable=W0703
                    _LOGGER.exception('Unable to delete instance: %s',
                                      extra)

def _run_sync():
    """Sync app monitor count with instance count."""

    instance_api = instance.init(authz.NullAuthorizer())
    zkclient = context.GLOBAL.zk.conn

    state = {
        'scheduled': {},
        'monitors': {}
    }

    @zkclient.ChildrenWatch(z.path.scheduled())
    @exc.exit_on_unhandled
    def _scheduled_watch(children):
        """Watch scheduled instances."""
        scheduled = sorted(children)
        appname_f = lambda n: n[:n.find('#')]
        grouped = collections.defaultdict(
            list,
            {k: list(v) for k, v in itertools.groupby(scheduled, appname_f)}
        )
        state['scheduled'] = grouped
        reevaluate(instance_api, state)
        return True

    def _watch_monitor(name):
        """Watch monitor."""

        # Establish data watch on each monitor.
        @zkclient.DataWatch(z.path.appmonitor(name))
        @exc.exit_on_unhandled
        def _monitor_data_watch(data, _stat, event):
            """Monitor individual monitor."""
            if (event and event.type == 'DELETED') or (data is None):
                try:
                    del state['monitors'][name]
                except KeyError:
                    pass

                _LOGGER.info('Removing watch on deleted monitor: %s', name)
                return False

            try:
                count = yaml.load(data)['count']
            except Exception:  # pylint: disable=W0703
                _LOGGER.exception('Invalid monitor: %s', name)
                return False

            _LOGGER.info('Reconfigure monitor: %s, count: %s', name, count)
            state['monitors'][name] = count
            reevaluate(instance_api, state)
            return True

    @zkclient.ChildrenWatch(z.path.appmonitor())
    @exc.exit_on_unhandled
    def _appmonitors_watch(children):
        """Watch app monitors."""

        monitors = set(children)
        extra = set(state['monitors'].keys()) - monitors
        for name in extra:
            _LOGGER.info('Removing extra monitor: %s', name)
            del state['monitors'][name]

        missing = monitors - set(state['monitors'].keys())

        for name in missing:
            _LOGGER.info('Adding missing monitor: %s', name)
            _watch_monitor(name)

    _LOGGER.info('Ready')

    while True:
        time.sleep(6000)

def init():
    """Return top level command handler."""

    @click.command()
    @click.option('--no-lock', is_flag=True, default=False,
                  help='Run without lock.')
    def top(no_lock):
        """Sync LDAP data with Zookeeper data."""
        context.GLOBAL.zk.conn.ensure_path('/appmonitor-election')
        me = '%s.%d' % (sysinfo.hostname(), os.getpid())
        lock = context.GLOBAL.zk.conn.Lock('/appmonitor-election', me)
        if not no_lock:
            _LOGGER.info('Waiting for leader lock.')
            with lock:
                _run_sync()
        else:
            _LOGGER.info('Running without lock.')
            _run_sync()

    return top


from app import app
import os

def createFolder(directory):
    print('******** Upload directory creating ...')
    try:
        if not os.path.exists(directory):
            os.makedirs(directory)
            print('******** ' + directory + ' Directory created successfully ...')
    except OSError:
        print ('********** Error: Creating directory' +  directory)

# Example
createFolder('./uploads/')
createFolder('./audio_sources/')
createFolder('./Speakers_models/')
createFolder('./test_samples/')
if __name__ == "__main__":
    #app.run(debug=app.config['DEBUG'], port=app.config['PORT'])
    app.run(debug=True)


import torch
from torch import optim
import yaml
from models.mobilenet_v2 import mobilenet
from torch.utils.tensorboard import SummaryWriter

def read_cfg(config_path):
    """ Read config from yaml file
    Args:
        config_path (str): path to yaml file
    Return:
        data (dict): dict of configurations
    """
    with open(config_path, 'r') as rf:
        data = yaml.safe_load(rf)
        return data

def build_optimizer(cfg, network):
    """ Build optimizer based on config
    Args:
        - cfg (dict): dict of configurations
    Return:
        - optimizer
    """
    if cfg['train']['optimizer'] == 'adam':
        return optim.Adam(network.parameters(), lr=cfg['train']['lr'])
    else:
        raise NotImplementedError

def build_network(cfg):
    """ Build network based on config
    Args:
        - cfg (dict): dict of configurations
    Returns:
        - network (nn.Module)
    """
    if cfg['model']['base'] == 'mobilenet_v2':
        network = mobilenet(cfg=cfg)
        return network
    else:
        raise NotImplementedError

def build_writer(cfg):
    """ Build tensorboard writer
    Args:
        - cfg (dict): dict of configuration
    Returns:
        - writer
    """
    writer = SummaryWriter(log_dir=cfg['log_dir'])
    return writer

def get_device(cfg):
    """ Get device based on config
    Args:
        - cfg (dict): dict of configuration
    Returns:
        - device
    """
    device = None
    if cfg['device'] == 'cpu':
        device = torch.device('cpu')
    elif cfg['device'] == 'cuda':
        device = torch.device('cuda')
    else:
        raise NotImplementedError
    return device


import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import os

# from stgcn import STGCN
from stgcn_test import STGCN
# from stgcn_origin import STGCN
# from gcn import STGCN
# from TGCN import STGCN
# from GRU import STGCN
# from ASTGCN import STGCN
# from STDN import STGCN
# from LSTM import STGCN

from utils import get_normalized_adj, CalConfusionMatrix
from data_load import Data_load
from logs.logger import Logger

# os.environ['CUDA_VISIBLE_DEVICES'] = '1'
num_timesteps_input = 12
num_timesteps_output = 3

epochs = 1000
batch_size = 16
N = 249

parser = argparse.ArgumentParser(description='STGCN')
parser.add_argument('--enable-cuda', action='store_true', help='Enable CUDA')
parser.add_argument('--log_file', type=str, default='run_log')
args = parser.parse_args()

logger = Logger(args.log_file)

def train_epoch(training_input, training_target, nodes, batch_size, means, stds):
    """
    Trains one epoch with the given data.
    :param training_input: Training inputs of shape (num_samples, num_nodes,
    num_timesteps_train, num_features).
    :param training_target: Training targets of shape (num_samples, num_nodes,
    num_timesteps_predict).
    :param batch_size: Batch size to use during training.
    :return: Average loss for this epoch.
    """
    permutation = torch.randperm(training_input.shape[0])

    epoch_training_losses = []
    loss_mean = 0.0
    for i in range(0, training_input.shape[0] - 64, batch_size):
        net.train()
        optimizer0.zero_grad()
        optimizer1.zero_grad()
        optimizer_lc.zero_grad()

        indices = permutation[i:i + batch_size]
        X_batch, y_batch = training_input[indices], training_target[indices]
        if torch.cuda.is_available():
            X_batch = X_batch.cuda()
            y_batch = y_batch.cuda()

            stds = torch.tensor(stds).cuda()
            means = torch.tensor(means).cuda()
            # max_value = torch.tensor(max_value).cuda()

        out = net(A_wave, X_batch, 'train')

        '''
        loss0 是整个网络最终的输出与labels的损失
        loss1 是局部网络的输出与labels的损失
        loss 是loss0与loss1之间的损失
        应该用loss更新局部网络，用loss1 更新前半部分网络，用loss0更新后半部分网络。
        '''

        # nodes = torch.LongTensor(nodes)
        loss0 = F.nll_loss(out[0], nodes)
        loss1 = F.nll_loss(out[1], nodes)
        loss = F.l1_loss(loss0, loss1)
        loss0.requires_grad_(True)

        # 更新后半部分网络 ( block2, last_temporal, fully_train)
        # 设置 requires_grad ,不更新block1的参数
        for name, param in net.named_parameters():
            if "block1" in name:
                param.requires_grad = False
            else:
                param.requires_grad = True
        loss0.backward(retain_graph=True)
        # optimizer1.step()

        # 更新前半部分网络 ( block1 )
        # 设置 requires_grad, 只更新block1的参数
        for name, param in net.named_parameters():
            if "block1" in name:
                param.requires_grad = True
            else:
                param.requires_grad = False
        loss1.backward(retain_graph=True)
        # optimizer0.step()

        # 更新局部网络，已经在optimizer中设置了只更新LC_block，但也会计算其余部分的梯度
        for name, param in net.named_parameters():
            if "LC_block" in name:
                param.requires_grad = True
            else:
                param.requires_grad = False
        loss.backward()
        # optimizer_lc.step()

        optimizer0.step()
        optimizer1.step()
        optimizer_lc.step()

        epoch_training_losses.append(loss0.detach().cpu().numpy())
        loss_mean = sum(epoch_training_losses)/len(epoch_training_losses)
    return loss_mean

if __name__ == '__main__':
    torch.manual_seed(7)

    A, means, stds, training_input, training_target, val_input, val_target, test_input, test_target, nodes = Data_load(num_timesteps_input, num_timesteps_output)

    torch.cuda.empty_cache()    # free cuda memory
    #
    # nodes = torch.Tensor(np.tile(nodes, batch_size).reshape(batch_size, N))

    A_wave = get_normalized_adj(A)
    A_wave = torch.from_numpy(A_wave)
    if torch.cuda.is_available():
        A_wave = A_wave.cuda()
        # nodes = torch.Tensor(nodes).type(torch.LongTensor).cuda()
        nodes = torch.LongTensor(nodes).cuda()

    net = STGCN(A_wave.shape[0],
                training_input.shape[3],
                num_timesteps_input,
                num_timesteps_output)
    if torch.cuda.is_available():
        net.cuda()

    # 更新后半部分网络 ( block2, last_temporal, fully_train)
    # 设置 requires_grad ,不更新block1的参数
    for name, param in net.named_parameters():
        if "block1" in name:
            param.requires_grad = False
        else:
            param.requires_grad = True
    optimizer0 = torch.optim.Adam(filter(lambda p: p.requires_grad, net.parameters()), lr=1e-3)

    # 更新前半部分网络 ( block1 )
    # 设置 requires_grad, 只更新block1的参数
    for name, param in net.named_parameters():
        if "block1" in name:
            param.requires_grad = True
        else:
            param.requires_grad = False
    optimizer1 = torch.optim.Adam(filter(lambda p: p.requires_grad, net.block1.parameters()), lr=1e-3)  # 只更新block1

    # 更新局部网络，已经在optimizer中设置了只更新LC_block，但也会计算其余部分的梯度
    for name, param in net.named_parameters():
        if "LC_block" in name:
            param.requires_grad = True
        else:
            param.requires_grad = False
    optimizer_lc = torch.optim.Adam(filter(lambda p: p.requires_grad, net.LC_block.parameters()), lr=1e-4)  # 用于更新局部网络

    # optimizer1 = torch.optim.Adam(net.block1.parameters(), lr=1e-3)     # 只更新block1
    # optimizer_lc = torch.optim.Adam(net.LC_block.parameters(), lr=1e-4)  # 用于更新局部网络

    training_losses = []
    validation_losses = []
    validation_MAE = []
    validation_RMSE = []
    validation_MAPE = []
    arr = [3, 6, 9]
    confusion_matrix = torch.zeros(4, 4)
    accuracy = 0
    eval_loss = 0
    max_accuracy, max_precise, max_recall, max_f1_score = 0, 0, 0, 0
    for epoch in range(epochs):
        print("epoch: {}/{}".format(epoch + 1, epochs))
        loss = train_epoch(training_input, training_target, nodes, batch_size=batch_size, means=means, stds=stds)
        training_losses.append(loss)
        torch.cuda.empty_cache()  # free cuda memory
        # Run validation
        with torch.no_grad():
            net.eval()
            if torch.cuda.is_available():
                val_input = val_input.cuda()
                val_target = val_target.cuda()
            out = net(A_wave, val_input, 'eval')

            eval_loss = F.nll_loss(out[0], nodes, size_average=False).to(device="cpu")
            pred = out[0].data.max(1, keepdim=True)[1]
            pred = torch.squeeze(pred)
            for i in range(len(pred)):
                confusion_matrix[nodes[i]][pred[i]] += 1

            accuracy = pred.eq(nodes.data.view_as(pred)).cpu().sum()
            precise, recall, f1_score = CalConfusionMatrix(confusion_matrix)

            accuracy_value = accuracy.item() / len(nodes)
            if accuracy_value > max_accuracy:
                max_accuracy = accuracy_value
            if precise > max_precise:
                max_precise = precise
            if recall > max_recall:
                max_recall = recall
            if f1_score > max_f1_score:
                max_f1_score = f1_score

            print('Evalution: Average loss: {:.4f}'.format(eval_loss))
            print(
                'Current Evalution: Accuracy: {}/{} ({:.4f}), Precise: {:.4f}, ReCall: {:.4f}, F1 Score: {:.4f}'.format(
                    accuracy, len(nodes), accuracy_value, precise, recall, f1_score))
            print(
                'Max Evalution: Accuracy: {:.4f}, Precise: {:.4f}, ReCall: {:.4f}, F1 Score: {:.4f}'.format(
                    max_accuracy, max_precise, max_recall, max_f1_score))

            out = None
            val_input = val_input.to(device="cpu")
            val_target = val_target.to(device="cpu")