"""
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

"""

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

"""
s1 : AC  108 ms
     当遇到环时，转化为两个求两个链表交点。
     1. 求两个链表长度
     2. 让长的先走k个单位
     3. p q 同步走，当相遇即 交点

"""
class Solution1(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head :
            return None
        fast ,slow  = head, head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
            if fast == slow :   #有环时找第一个node
                p ,q = head,fast.next
                p_len , q_len = 0 ,0
                while p!=fast:
                    p_len +=1
                    p = p.next
                while q!=fast:
                    q_len +=1
                    q = q.next
                if q_len > p_len :   #让p 指向长的
                    p , q = fast.next , head
                    p_len , q_len = q_len,p_len
                else :
                    p ,q = head ,fast.next
                while p_len !=q_len:
                    p_len -=1
                    p = p.next
                while p != q:
                    p = p.next
                    q = q.next

                return p

        return None

"""
S2 :  优  96ms

"""
class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head :
            return None
        fast ,slow = head , head
        while fast.next and fast.next.next :   #slow必定在fast之后
            slow = slow.next
            fast = fast.next.next
            if fast == slow :   #设置p q 分别指向head 和slow next
                p ,q = head,fast  #q 应该是从fast 而不是 fast.next开始
                while p!=q:  #始终会相遇在环开始点
                    p = p.next
                    q = q.next
                return p

        return None

if __name__ == "__main__":
    l1 = ListNode(1)
    l1.next = ListNode(2)
    l1.next.next=ListNode(3)
    l1.next.next.next=ListNode(4)
    l1.next.next.next.next = l1.next
    s = Solution()
    r = s.detectCycle(l1)
    print(r.val)

"""
Q :
    判断有没有环，午返回null, 有则返回  环起始点；

    1.  使用141 判断有无环，当有环时，在此处seg 分别计算环和head 到此处长度， 转化为两个链表的交点问题

    2. 假设环的长度为r ,当相遇时 slow 走了 k, 则 fast 走了2k ;head 到环起始点为m,则环起始点到第一次相遇点为s = k-m

        2k = k +N*r   (slow 到达时，fast 已经走了N圈)
        m +s = N*r  =>  m = N*r -s =(N-1)*r  +(r-s)
        说明 如果设置两个指针p q 分别指向head 和第一次相遇点
        每次走一步，他们始终会相遇， 因为 m = (r-s)  +(N-1)r

            基于此 当fast==slow 时候 设置两个指针p q

    3. Note[wiz]

"""


import numpy as np
import cv2

img = cv2.imread("imagens/estrada.jpg")
vermelho = (0, 0, 255)
verde = (0, 255, 0)
azul = (255, 0, 0)
cv2.line(img, (0, 0), (100, 200), verde)
cv2.line(img, (300, 200), (150, 150), vermelho, 5)
cv2.rectangle(img, (20, 20), (120, 120), azul, 10)
cv2.rectangle(img, (200, 50), (225, 125), verde, -1)

(x, y) = (img.shape[0]//2, img.shape[0]//2)

for raio in range(0, 175, 15):
    cv2.circle(img, (x, y), raio, vermelho)

cv2.imshow("imagem alterada", img)
cv2.waitKey()

PDI(processamento digital de imagem)/estudos sobe PDI/desenhando_na_imagem.py


from __future__ import print_function
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Conv2D, Dense, Reshape, Conv2DTranspose, UpSampling2D, Input, Reshape, Concatenate, MaxPooling2D, ZeroPadding2D, BatchNormalization
import tensorflow as tf; tf.image # There's a bug in tensorflow that requires us to import tf.image like this
from tensorflow_addons.layers import InstanceNormalization
from StyleGAN_utils import fade_in, wasserstein_loss, pixel_norm, minibatch_std, EqualizedConv, EqualizedDense, AddNoise, AdaIN

# Need to make this output (51,51,3) for working with ANIMEFACES. Note that 51 = 17*3
def simple_generator(digit_dimension):
    inputs = Input(shape=(digit_dimension,))
    coarse_1 = Reshape((1, 1, digit_dimension,))(inputs)
    coarse_1 = ZeroPadding2D(padding=((8,8),(8,8)))(coarse_1)
    coarse_1 = Conv2D(digit_dimension, (7, 7), padding='same', activation='elu')(coarse_1)
    coarse_1 = BatchNormalization()(coarse_1)
    coarse_1 = Conv2D(128, (5, 5), padding='same', activation='elu')(coarse_1)
    coarse_1 = BatchNormalization()(coarse_1)
    coarse_3 = UpSampling2D(size=(3, 3), interpolation='bilinear')(coarse_1)
    mid_2 = Conv2D(128, (5, 5), padding='same', activation='elu')(coarse_1)
    mid_2 = BatchNormalization()(mid_2)
    mid_2 = Conv2D(128, (3, 3), padding='same', activation='elu')(mid_2)
    mid_2 = BatchNormalization()(mid_2)
    mid_3 = UpSampling2D(size=(3, 3), interpolation='bilinear')(mid_2)
    fine_3 = Conv2D(64, (5, 5), padding='same', activation='elu')(mid_3)
    fine_3 = BatchNormalization()(fine_3)
    fine_3 = Conv2D(64, (3, 3), padding='same', activation='elu')(fine_3)
    fine_3 = BatchNormalization()(fine_3)
    composition = Concatenate(axis=3)([coarse_3, mid_3, fine_3])
    outputs = Conv2D(3, (3, 3), padding='same', activation='sigmoid')(composition)
    model = Model(inputs=inputs, outputs=outputs)

    return model

def simple_discriminator():
    inputs = Input(shape=(51, 51, 3,))
    fine = Conv2D(64,(5,5), padding='same', activation='elu')(inputs)
    fine = Conv2D(64, (5, 5), padding='same', activation='elu')(fine)
    fine = Conv2D(64,(5,5), padding='same', activation='elu')(fine)
    mid = Conv2D(32,(5,5), padding='same', activation='elu', strides=(2,2))(fine)
    mid = Conv2D(32,(5,5), padding='same', activation='elu')(mid)
    mid = Conv2D(32,(5,5), padding='same', activation='elu')(mid)
    coarse = Conv2D(16,(3,3), padding='same', activation='elu', strides=(2,2))(mid)
    coarse = Conv2D(16,(3,3), padding='same', activation='elu')(coarse)
    coarse = Conv2D(16, (3, 3), padding='same', activation='elu')(coarse)
    fine_scores = MaxPooling2D(pool_size=(28,28))(fine)
    mid_scores = MaxPooling2D(pool_size=(14,14))(mid)
    coarse_scores= MaxPooling2D(pool_size=(7,7))(coarse)
    composition = Concatenate(axis=3)([fine_scores,mid_scores,coarse_scores])
    composition = Reshape((64+32+16,))(composition)
    outputs = Dense(1, activation='sigmoid')(composition)
    model = Model(inputs=inputs, outputs=outputs)
    return model

#Much of the below is for the StyleGAN. This is mostly ripped from https://keras.io/examples/generative/stylegan/

def Mapping(num_stages, input_shape=512):
    z = layers.Input(shape=(input_shape))
    w = pixel_norm(z)
    for i in range(8):
        w = EqualizedDense(512, learning_rate_multiplier=0.01)(w)
        w = layers.LeakyReLU(0.2)(w)
    w = tf.tile(tf.expand_dims(w, 1), (1, num_stages, 1))
    return keras.Model(z, w, name="mapping")

class Generator:
    def __init__(self, start_res_log2, target_res_log2):
        self.start_res_log2 = start_res_log2
        self.target_res_log2 = target_res_log2
        self.num_stages = target_res_log2 - start_res_log2 + 1
        # list of generator blocks at increasing resolution
        self.g_blocks = []
        # list of layers to convert g_block activation to RGB
        self.to_rgb = []
        # list of noise input of different resolutions into g_blocks
        self.noise_inputs = []
        # filter size to use at each stage, keys are log2(resolution)
        self.filter_nums = {
            0: 512,
            1: 512,
            2: 512,  # 4x4
            3: 512,  # 8x8
            4: 512,  # 16x16
            5: 512,  # 32x32
            6: 256,  # 64x64
            7: 128,  # 128x128
            8: 64,  # 256x256
            9: 32,  # 512x512
            10: 16,
        }  # 1024x1024

        start_res = 2 ** start_res_log2
        self.input_shape = (start_res, start_res, self.filter_nums[start_res_log2])
        self.g_input = layers.Input(self.input_shape, name="generator_input")

        for i in range(start_res_log2, target_res_log2 + 1):
            filter_num = self.filter_nums[i]
            res = 2 ** i
            self.noise_inputs.append(
                layers.Input(shape=(res, res, 1), name=f"noise_{res}x{res}")
            )
            to_rgb = Sequential(
                [
                    layers.InputLayer(input_shape=(res, res, filter_num)),
                    EqualizedConv(3, 1, gain=1),
                ],
                name=f"to_rgb_{res}x{res}",
            )
            self.to_rgb.append(to_rgb)
            is_base = i == self.start_res_log2
            if is_base:
                input_shape = (res, res, self.filter_nums[i - 1])
            else:
                input_shape = (2 ** (i - 1), 2 ** (i - 1), self.filter_nums[i - 1])
            g_block = self.build_block(
                filter_num, res=res, input_shape=input_shape, is_base=is_base
            )
            self.g_blocks.append(g_block)

    def build_block(self, filter_num, res, input_shape, is_base):
        input_tensor = layers.Input(shape=input_shape, name=f"g_{res}")
        noise = layers.Input(shape=(res, res, 1), name=f"noise_{res}")
        w = layers.Input(shape=512)
        x = input_tensor

        if not is_base:
            x = layers.UpSampling2D((2, 2))(x)
            x = EqualizedConv(filter_num, 3)(x)

        x = AddNoise()([x, noise])
        x = layers.LeakyReLU(0.2)(x)
        x = InstanceNormalization()(x)
        x = AdaIN()([x, w])

        x = EqualizedConv(filter_num, 3)(x)
        x = AddNoise()([x, noise])
        x = layers.LeakyReLU(0.2)(x)
        x = InstanceNormalization()(x)
        x = AdaIN()([x, w])
        return keras.Model([input_tensor, w, noise], x, name=f"genblock_{res}x{res}")

    def grow(self, res_log2):
        res = 2 ** res_log2

        num_stages = res_log2 - self.start_res_log2 + 1
        w = layers.Input(shape=(self.num_stages, 512), name="w")

        alpha = layers.Input(shape=(1), name="g_alpha")
        x = self.g_blocks[0]([self.g_input, w[:, 0], self.noise_inputs[0]])

        if num_stages == 1:
            rgb = self.to_rgb[0](x)
        else:
            for i in range(1, num_stages - 1):

                x = self.g_blocks[i]([x, w[:, i], self.noise_inputs[i]])

            old_rgb = self.to_rgb[num_stages - 2](x)
            old_rgb = layers.UpSampling2D((2, 2))(old_rgb)

            i = num_stages - 1
            x = self.g_blocks[i]([x, w[:, i], self.noise_inputs[i]])

            new_rgb = self.to_rgb[i](x)

            rgb = fade_in(alpha[0], new_rgb, old_rgb)

        return keras.Model(
            [self.g_input, w, self.noise_inputs, alpha],
            rgb,
            name=f"generator_{res}_x_{res}",
        )

class Discriminator:
    def __init__(self, start_res_log2, target_res_log2):
        self.start_res_log2 = start_res_log2
        self.target_res_log2 = target_res_log2
        self.num_stages = target_res_log2 - start_res_log2 + 1
        # filter size to use at each stage, keys are log2(resolution)
        self.filter_nums = {
            0: 512,
            1: 512,
            2: 512,  # 4x4
            3: 512,  # 8x8
            4: 512,  # 16x16
            5: 512,  # 32x32
            6: 256,  # 64x64
            7: 128,  # 128x128
            8: 64,  # 256x256
            9: 32,  # 512x512
            10: 16,
        }  # 1024x1024
        # list of discriminator blocks at increasing resolution
        self.d_blocks = []
        # list of layers to convert RGB into activation for d_blocks inputs
        self.from_rgb = []

        for res_log2 in range(self.start_res_log2, self.target_res_log2 + 1):
            res = 2 ** res_log2
            filter_num = self.filter_nums[res_log2]
            from_rgb = Sequential(
                [
                    layers.InputLayer(
                        input_shape=(res, res, 3), name=f"from_rgb_input_{res}"
                    ),
                    EqualizedConv(filter_num, 1),
                    layers.LeakyReLU(0.2),
                ],
                name=f"from_rgb_{res}",
            )

            self.from_rgb.append(from_rgb)

            input_shape = (res, res, filter_num)
            if len(self.d_blocks) == 0:
                d_block = self.build_base(filter_num, res)
            else:
                d_block = self.build_block(
                    filter_num, self.filter_nums[res_log2 - 1], res
                )

            self.d_blocks.append(d_block)

    def build_base(self, filter_num, res):
        input_tensor = layers.Input(shape=(res, res, filter_num), name=f"d_{res}")
        x = minibatch_std(input_tensor)
        x = EqualizedConv(filter_num, 3)(x)
        x = layers.LeakyReLU(0.2)(x)
        x = layers.Flatten()(x)
        x = EqualizedDense(filter_num)(x)
        x = layers.LeakyReLU(0.2)(x)
        x = EqualizedDense(1)(x)
        return keras.Model(input_tensor, x, name=f"d_{res}")

    def build_block(self, filter_num_1, filter_num_2, res):
        input_tensor = layers.Input(shape=(res, res, filter_num_1), name=f"d_{res}")
        x = EqualizedConv(filter_num_1, 3)(input_tensor)
        x = layers.LeakyReLU(0.2)(x)
        x = EqualizedConv(filter_num_2)(x)
        x = layers.LeakyReLU(0.2)(x)
        x = layers.AveragePooling2D((2, 2))(x)
        return keras.Model(input_tensor, x, name=f"d_{res}")

    def grow(self, res_log2):
        res = 2 ** res_log2
        idx = res_log2 - self.start_res_log2
        alpha = layers.Input(shape=(1), name="d_alpha")
        input_image = layers.Input(shape=(res, res, 3), name="input_image")
        x = self.from_rgb[idx](input_image)
        x = self.d_blocks[idx](x)
        if idx > 0:
            idx -= 1
            downsized_image = layers.AveragePooling2D((2, 2))(input_image)
            y = self.from_rgb[idx](downsized_image)
            x = fade_in(alpha[0], x, y)

            for i in range(idx, -1, -1):
                x = self.d_blocks[i](x)
        return keras.Model([input_image, alpha], x, name=f"discriminator_{res}_x_{res}")


from animals import *

def sample_mammal():
    dog = Mammal(name="Cannis familiaris", diet="Omnivorous",  schedule="Diurnal")
    return dog

def sample_amphibian():
    frog= Amphibian(name="Eleutherodactylus portoricensis",diet="Omnivorous", schedule="Nocturnal")
    return frog

def to_file(filename, data):
    try:
        with open(filename, 'wt') as f:
            f.write(data)
    except FileExistsError as e:
        print(e)

if __name__== "__main__":
    dog = str(sample_mammal())
    frog = str(sample_amphibian())
    to_file(filename="sample.txt", data=dog+frog)


import inspect

from django.contrib import admin
from django.contrib.admin import helpers
from django.http import HttpResponseRedirect
from django.http.response import HttpResponseBase

class AbstractBaseAdmin(admin.ModelAdmin):
    default_list_display = ('created_at',)
    list_display = ('id', '__str__') + default_list_display
    default_list_filter = ('created_at', 'updated_at')
    list_filter = default_list_filter
    default_search_fields = ('id',)
    search_fields = default_search_fields
    readonly_fields = ('created_at', 'updated_at')
    default_fieldset = (None, {'fields': (('created_at', 'updated_at'),)})

    def changelist_view(self, request, extra_context=None):
        actions = self.get_actions(request)
        if actions and request.method == 'POST' and 'index' in request.POST and '_save' not in request.POST:
            response = self.response_action(request, queryset=self.get_queryset(request))
            if response:
                return response
        return super().changelist_view(request, extra_context)

    def response_action(self, request, queryset):
        try:
            action_index = int(request.POST.get('index', 0))
        except ValueError:
            action_index = 0

        data = request.POST.copy()
        data.pop(helpers.ACTION_CHECKBOX_NAME, None)
        data.pop("index", None)

        try:
            data.update({'action': data.getlist('action')[action_index]})
        except IndexError:
            pass

        action_form = self.action_form(data, auto_id=None)
        action_form.fields['action'].choices = self.get_action_choices(request)

        if action_form.is_valid():
            action = action_form.cleaned_data['action']
            select_across = action_form.cleaned_data['select_across']
            func = self.get_actions(request)[action][0]
            has_queryset = 'queryset' in inspect.signature(func).parameters
            selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
            if not selected and not select_across and has_queryset:
                return None

            if not select_across:
                queryset = queryset.filter(pk__in=selected)

            if has_queryset:
                response = func(self, request, queryset)
            else:
                response = func(self, request)

            if isinstance(response, HttpResponseBase):
                return response
            else:
                return HttpResponseRedirect(request.get_full_path())
        else:
            return None


import pandas as pd
from collections import Counter
import time
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import os
import numpy as np

def binomial_distribution(data):
    numtails = pd.Series(data)
    hdata = pd.Series(Counter(numtails)).astype(int)
    plot = hdata.plot(kind='bar')
    plot.set_xlabel('')
    plot.set_ylabel('')
    plot.set_title('')
    fig = plot.get_figure()
    timestamp = int(time.time())
    output_file = str(timestamp) + ".png"
    fig.savefig( os.path.join(os.path.dirname(__file__), 'plots/' + output_file))
    plt.close()
    return output_file

def heat_capacity_of_solids(mcup, m1, T1, T2, Teq, m2):
    m = m1 - mcup
    M = m2 - m1
    c = 1.0
    delta_m = 2 * 0.05
    delta_T = 1
    C = ( M * c * ( T2 - Teq ) - m * c * ( Teq - T1 ) ) / ( Teq - T1 )
    p_1 = ( c * ( T2 - Teq ) + c * ( Teq - T1 ) ) * delta_m / ( Teq - T1 )
    p_2 = C
    p_3 = abs( ( T2 - Teq ) - ( Teq - T1) ) * 2 * M * c / (( Teq - T1 ) * ( Teq - T1 ))
    delta_C = p_1 + p_2 + p_3
    r_error = delta_C / C
    return {
        'M': round(M,2),
        'ccal': round(C,2),
        'abs_error': round(delta_C,2),
        'rel_error': '%'+str(round(r_error,2))
    }

def heat_capacity_of_multiple_materials(data, m, C):
    for key in data:
        heat_cap = calculate_heat_capacity_of_material(data[key], m, C)
        data[key]['c_material'] = heat_cap['c_material']
        data[key]['rel_error'] = heat_cap['rel_error']

    return data

def calculate_heat_capacity_of_material(material, m, C):
    c_material = ( ( float(material['Tf']) - float(material['T1']) ) * float(material['m_water']) ) + ( float(C) * ( float(material['Tf']) - float(material['T1']) ) ) / abs ( m * ( float(material['Tf']) - float(material['T1']) ) )
    rel_error = abs( float(material['c_real']) - c_material ) * 100.0 / float(material['c_real'])
    return {
        'c_material': round(c_material, 2),
        'rel_error': '%'+str(round(rel_error, 2))
    }

def latent_heat_of_water(m1, m2, T1, m3, T2):
    m1 = float(m1)
    m2 = float(m2)
    m3 = float(m3)
    T1 = float(T1)
    T2 = float(T2)
    m_water = m2 - m1
    m_ice = m3 - m2
    c_water = 1.0
    m_1c_c = 30.0
    Q_out = m_1c_c * ( T1 - T2 ) + m_water * c_water * ( T1 - T2 )
    # print "The heat (Qout) energy given off by the vessel+hot water equals to %f" %Q_out
    L = ( m_1c_c * ( T1 - T2 ) + m_water * c_water * ( T1 - T2 ) - m_ice * c_water * T2 ) / m_ice
    # print "The Latent heat for solid to liquid phase change of water is %f" %L
    L_literature = 80.0
    L_error = abs( L - L_literature ) * 100.0 / L_literature
    # print "The error percentage of L is  %  %f." %L_error
    return {
        'Q_out': round(Q_out, 2),
        'L': round(L, 2),
        'rel_error': '%'+str(round(L_error,2)),
        'm_water': round(m_water,2),
        'm_ice': round(m_ice,2)
    }

def thermal_expansion_coefficient(T1, L1, L2, L3, L4, L5, L6, L7, L8, a_real=0.000019):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    x = [T1,25,30,40,50.,60,70,80]
    y = [0, L2, L3, L4, L5, L6, L7, L8]
    ax.plot(x, y)
    ax.set_xlabel('T2 (C)')
    ax.set_ylabel('dL (mm))')
    ax.set_title('The grapH of L with respect to T2')
    timestamp = int(time.time())
    output_file = str(timestamp) + ".png"
    fig.savefig( os.path.join(os.path.dirname(__file__), 'plots/' + output_file))
    slope, b = np.polyfit(x, y, 1) # y = slope*x+b
    a = slope/(L1)
    a_error=(abs(a_real-a)*100.0)/a_real
    plt.close()
    return {
        'a': a,
        'rel_error': '%'+str(round(a_error,2)),
        'fig': output_file,
        'slope': round(slope,4)
    }

# ideal gas law
def ideal_gas_plots(data):
    f, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, sharex=True, sharey=True)
    ax1.plot( ideal_sub( **data['10'] )['x'], ideal_sub( **data['10'] )['y'], label="10 C" )
    ax1.set_title('The graph of P with respect to V')
    ax2.plot( ideal_sub( **data['20'])['x'], ideal_sub( **data['20'] )['y'], label="20 C" )
    ax3.plot( ideal_sub( **data['30'])['x'], ideal_sub( **data['30'] )['y'], label="30 C" )
    ax3.set_ylabel('P (cm-Hg)')
    ax4.plot( ideal_sub( **data['40'])['x'], ideal_sub( **data['40'] )['y'], label="40 C" )
    ax5.plot( ideal_sub( **data['50'])['x'], ideal_sub( **data['50'] )['y'], label="50 C" )
    ax6.plot( ideal_sub( **data['60'])['x'], ideal_sub( **data['60'] )['y'], label="60 C" )
    ax6.set_xlabel('V (cm3)')
    ax1.legend(loc='upper right', shadow=True)
    ax2.legend(loc='upper right', shadow=True)
    ax3.legend(loc='upper right', shadow=True)
    ax4.legend(loc='upper right', shadow=True)
    ax5.legend(loc='upper right', shadow=True)
    ax6.legend(loc='upper right', shadow=True)
    # Fine-tune figure; make subplots close to each other and hide x ticks for
    # all but bottom plot.
    f.subplots_adjust(hspace=0)
    plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
    timestamp = time.time()
    output_file = str(timestamp) + ".png"
    plt.savefig( os.path.join(os.path.dirname(__file__), 'plots/' + output_file))
    plt.close()
    return output_file

def ideal_sub(V_1,V_2,V_3,V_4,V_5,P_1,P_2,P_3,P_4,P_5):
    return {
        'x': [V_1,V_2,V_3,V_4,V_5],
        'y': [P_1,P_2,P_3,P_4,P_5]
        }

def numberOfMol(P,V,T):
    t=T+273.15
    R=8.3145
    n=(P*V)/(R*t)
    return n

# joule thomson
def joule_thomson(V_1,V_2,V_3,V_4,V_5,V_6,V_7,V_8,V_9,V_10,V_11, gas):
    x = [100,90,80,70.,60,50,40,30,20,10,0]
    y = [V_1,V_2,V_3,V_4,V_5,V_6,V_7,V_8,V_9,V_10,V_11]
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(x, y)
    ax.set_xlabel('P (kPa))')
    ax.set_ylabel('T (K)')
    ax.set_title('The graph of T with respect to P for ' + gas)
    timestamp = time.time()
    output_file = str(timestamp) + ".png"
    fig.savefig( os.path.join(os.path.dirname(__file__), 'plots/' + output_file))
    mu , b = np.polyfit(x, y, 1)
    mu_real=7.16*(10**-6) if gas == 'CO2' else 3.75*(10**-6)
    mu_error=abs(mu_real-mu)*100.0/mu_real
    plt.close()
    return {
        'mu': round(mu,2),
        'rel_error': '%'+str(round(mu_error,2)),
        'fig': output_file
    }

# thermal conductivity
def thermal_conductivity_part_one(mcal,mw_mcup,twater,teq):
    m_water=mw_mcup-mcal
    c=1.0
    T_room=22.0
    ccal=m_water*c*(twater-teq)/(teq-T_room)
    return {
        'mhot': round(m_water,2),
        'ccal': round(ccal,2)
    }

def thermal_conductivity_part_two(data):
    dq = [0]
    dt = [] # for average dt
    for i in range(9):
        dt.append( data['dt_'+str(i+1)] )
        dq.append(
            (data['dt_'+str(i+2)] - data['dt_1']) * (data['mcold'] + data['ccal'])
        )

    t = [0,180,360,540,720,900,1080,1260,1440,1620]
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(t, dq)
    ax.set_xlabel('t (sn)')
    ax.set_ylabel('dQ (cal)')
    ax.set_title('The graph of dQ with respect to t')
    slope , b = np.polyfit(t, dq, 1)
    dx=31.5
    A=4.91
    K_calculated=6*(-(slope*dx)/(A*np.mean(dt)))
    K_literature=0.5 # (cal/sec)/(cm2 C/cm)
    K_error=abs(K_calculated-K_literature)*100.0/K_literature
    timestamp = time.time()
    output_file = str(timestamp) + ".png"
    fig.savefig( os.path.join(os.path.dirname(__file__), 'plots/' + output_file))
    plt.close()
    return {
        'K_calculated': round(K_calculated,2),
        'K_error': '%'+str(round(K_error,2)),
        'fig': output_file,
        'slope': round(slope,2)
    }

# # maxwellian
# from pylab import *
# import math
# import numpy as np

# def plotMaxwell(M,R,T,Vin,Fin):
#     Vmin=V.min()
#     Vmax=V.max()
#     Vout=np.linspace(Vmin,Vmax,100);
#     fout=4*pi(M/(2*pi*R*T))**(3/2)*math.exp(-M*Vout/(2*R*T));
#     fig=figure()
#     ax=fig.gca()
#     ax.set_xlabel("V")
#     ax.set_ylabel("F(V)")
#     ax.plot(Vout,fout)
#     ax.plot(Vin,Fin,'x')
#     #return V1D,f

# #example for function call
# # V=np.array([1, 2, 3.0,4.1,5.])
# # F=np.array([1.1,2.,3.4,3.99,4.65])
# # plotMaxwell(1.,1.,1.,V,F)


"""Setup script"""

from setuptools import find_packages, setup

extras_require = { # pylint: disable=invalid-name
    'lint': [
        'pylint>=2.3.0,<3'
    ],
    'dev': [
        'rope>=0.14.0,<0.15'
    ]
}

extras_require['dev'] = (
    extras_require['lint'] +
    extras_require['dev']
)

setup(
    name='gasstation-express-oracle',
    version='0.1.0',
    license='MIT',
    description='Ethereum Gas Price Oracle',
    long_description_markdown_filename='README.md',
    author='Marcus R. Brown',
    author_email='contact@marcusrbrown.com',
    url='https://github.com/igetgames/gasstation-express-oracle',
    packages=find_packages(),
    scripts=['gasstation-express-oracle'],
    include_package_data=True,
    python_requires='>=3.6,<4',
    install_requires=[
        'numpy>=1.17.0,<2',
        'pandas>=0.25.0,<0.26',
        'web3>=5.1.0,<6',
    ],
    setup_requires=['setuptools-markdown'],
    extras_require=extras_require,
    zip_safe=True,
    classifiers=[
        'Development Status :: 4 - Beta',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
    ]
)


from math import log

def tf(t, d):
    return d.count(t) / len(d)

def df(t, docs):
    df = 0
    for doc in docs:
        df += 1 if t in doc else 0
    return df

def idf(t, docs):
    N = len(docs)
    return log(N/df(t, docs)) + 1

def vectorizer_transform(text):

    # 単語を生成
    words = []
    for s in text:
        words += s.split(' ')
    words = list(set(words))
    words.sort()

    tf_idf = []
    for txt in text:
        line_tf_idf = []
        for w in words:
            # tfを計算
            tf_v = tf(w, txt)

            # idfを計算
            idf_v = idf(w, text)

            # tfとidfを乗算
            line_tf_idf.append(tf_v * idf_v)
        tf_idf.append(line_tf_idf)
    return tf_idf

if __name__ == '__main__':
    # ベクトル化する文字列
    text = [
       'Apple computer of the apple mark',
       'linux computer is unix like',
       'windows computer'
    ]

    tf_idf = vectorizer_transform(text)

    for line in tf_idf:
        print(line)


import hashlib
from django.shortcuts import (
    get_list_or_404,
    get_object_or_404,
    redirect,
    render,
)
from django.db import IntegrityError
from django.http import Http404
from .models import Guest, Party

def index(request):
    if not request.user.is_authenticated:
        return redirect('login')

    if request.method == 'GET':

        # Load everything into RAM
        invitations = Party.objects.all()
        guests = Guest.objects.all()

        # calc stats
        total_invitations = invitations.count()
        sent_invitations = invitations.filter(sent=True).count()
        total_guests = guests.count() + sum([g.plus_ones for g in guests])
        guests_rsvp = guests.filter(rsvp=True).all()
        total_rsvp = guests_rsvp.count() + sum([g.plus_ones for g in guests_rsvp])

        context = dict(
            total_invitations=total_invitations,
            sent_invitations=sent_invitations,
            total_guests=total_guests,
            total_rsvp=total_rsvp,
            party_list=invitations,
        )
        return render(request, 'dashboard/index.html', context)

def details(request, party_id):
    # return guests associated with Party id
    if not request.user.is_authenticated:
        return redirect('login')

    if request.method == 'GET':
        print(party_id)
        party = get_object_or_404(Party, pk=party_id)
        party_guests = get_list_or_404(Guest, party=party_id)

        guests = list()
        for g in party_guests:
            name = g.first_name.title() + ' ' + g.last_name.title()
            guests.append(dict(
                id=g.id,
                name=name,
                plus_ones=g.plus_ones,
                rsvp=g.rsvp,
            ))

        context = dict(party=party, guests=guests)

        return render(request, 'dashboard/details.html', context)

def addnew(request):
    if not request.user.is_authenticated:
        return redirect('login')

    if request.method == 'GET':
        return render(request, 'dashboard/addnew.html')

def edit(request, party_id):

    if request.method == 'POST':
        print(party_id)
        p = request.POST
        print(p)

        Party.objects.filter(pk=party_id).update(
            description=p['description'],
            street=p['street'],
            city=p['city'],
            state=p['state'],
            zip_code=p['zip_code'],
            phone_number=p['phone_number'],
            # p['sent'] will only exist if rsvp button was clicked at form
            sent=True if 'sent' in p else False,
        )

        # p.getlist('guest_id') = ['1', '2', ...] corresponding to number of guests
        idx = 0
        for n in p.getlist('guest_id'):
            name = p.getlist('name')[idx].split()

            if len(name) == 1:
                last_name = ''
            else:
                last_name = name[1]

            Guest.objects.filter(pk=int(n)).update(
                first_name=name[0],
                last_name=last_name,
                plus_ones=p.getlist('plus_ones')[idx],
                # p['rsvp<n>'] will only exist if rsvp button was clicked at form
                rsvp=True if 'rsvp' + n in p else False,
            )
            idx += 1

        return redirect('dashboard:index')

def add(request):

    if request.method == 'POST':
        p = request.POST
        print(p)

        m = hashlib.sha1()
        hash_str = p['description'] + p['street'] + p['city'] + p['state'] + p['zip_code']
        m.update(hash_str.encode('utf-8'))

        try:
            party = Party(
                description=p['description'],
                street=p['street'],
                city=p['city'],
                state=p['state'],
                zip_code=p['zip_code'],
                phone_number=p['phone_number'],
                rsvp_id=m.hexdigest(),
            )
            party.save()

        except IntegrityError:
            raise Http404('That party already exists')

        for n in p.getlist('name'):
            name = n.split()

            if len(name) == 1:
                last_name = ''
            else:
                last_name = name[1]

            guest = Guest(
                party=party,
                first_name=name[0],
                last_name=last_name,
            )
            guest.save()

        return redirect('dashboard:index')


'''
This file implements a multi layer neural network for a multiclass classifier

Hemanth Venkateswara
hkdv1@asu.edu
Oct 2018
'''
import numpy as np
from mod_load_mnist import mnist, one_hot
import matplotlib.pyplot as plt
from cycler import cycler
import pdb
import sys, ast
import os

def tanh(Z):
    '''
    computes tanh activation of Z

    Inputs:
        Z is a numpy.ndarray (n, m)

    Returns:
        A is activation. numpy.ndarray (n, m)
        cache is a dictionary with {"Z", Z}
    '''
    A = np.tanh(Z)
    cache = {}
    cache["Z"] = Z
    return A, cache

def tanh_der(dA, cache):
    '''
    computes derivative of tanh activation

    Inputs:
        dA is the derivative from subsequent layer. numpy.ndarray (n, m)
        cache is a dictionary with {"Z", Z}, where Z was the input
        to the activation layer during forward propagation

    Returns:
        dZ is the derivative. numpy.ndarray (n,m)
    '''
    ### CODE HERE
    tan_h = tanh(cache["Z"])[0]
    dZ = dA * (1-tan_h)**2
    return dZ

def sigmoid(Z):
    '''
    computes sigmoid activation of Z

    Inputs:
        Z is a numpy.ndarray (n, m)

    Returns:
        A is activation. numpy.ndarray (n, m)
        cache is a dictionary with {"Z", Z}
    '''
    A = 1/(1+np.exp(-Z))
    cache = {}
    cache["Z"] = Z
    return A, cache

def sigmoid_der(dA, cache):
    '''
    computes derivative of sigmoid activation

    Inputs:
        dA is the derivative from subsequent layer. numpy.ndarray (n, m)
        cache is a dictionary with {"Z", Z}, where Z was the input
        to the activation layer during forward propagation

    Returns:
        dZ is the derivative. numpy.ndarray (n,m)
    '''
    ### CODE HERE
    sig = sigmoid(cache["Z"])[0]
    dZ = dA*sig*(1-sig)
    return dZ

def relu(Z):
    '''
    computes relu activation of Z

    Inputs:
        Z is a numpy.ndarray (n, m)

    Returns:
        A is activation. numpy.ndarray (n, m)
        cache is a dictionary with {"Z", Z}
    '''
    A = np.maximum(0,Z)
    cache = {}
    cache["Z"] = Z
    return A, cache

def relu_der(dA, cache):
    '''
    computes derivative of relu activation

    Inputs:
        dA is the derivative from subsequent layer. numpy.ndarray (n, m)
        cache is a dictionary with {"Z", Z}, where Z was the input
        to the activation layer during forward propagation

    Returns:
        dZ is the derivative. numpy.ndarray (n,m)
    '''
    dZ = np.array(dA, copy=True)
    Z = cache["Z"]
    dZ[Z<0] = 0
    return dZ

def linear(Z):
    '''
    computes linear activation of Z
    This function is implemented for completeness

    Inputs:
        Z is a numpy.ndarray (n, m)

    Returns:
        A is activation. numpy.ndarray (n, m)
        cache is a dictionary with {"Z", Z}
    '''
    A = Z
    cache = {}
    return A, cache

def linear_der(dA, cache):
    '''
    computes derivative of linear activation
    This function is implemented for completeness

    Inputs:
        dA is the derivative from subsequent layer. numpy.ndarray (n, m)
        cache is a dictionary with {"Z", Z}, where Z was the input
        to the activation layer during forward propagation

    Returns:
        dZ is the derivative. numpy.ndarray (n,m)
    '''
    dZ = np.array(dA, copy=True)
    return dZ

def softmax_cross_entropy_loss(Z, Y=np.array([])):
    '''
    Computes the softmax activation of the inputs Z
    Estimates the cross entropy loss

    Inputs:
        Z - numpy.ndarray (n, m)
        Y - numpy.ndarray (1, m) of labels
            when y=[] loss is set to []

    Returns:
        A - numpy.ndarray (n, m) of softmax activations
        cache -  a dictionary to store the activations later used to estimate derivatives
        loss - cost of prediction
    '''
    ### CODE HERE
    #softmax
    max_z = np.max(Z, axis=0, keepdims=True)

    # add e^-10 to prevent divide by zero error while taking log A?
    z_exp = np.exp(Z-max_z) #+ np.exp(-10)

    denominator = np.sum(z_exp, axis=0, keepdims=True)
    A = z_exp/denominator
    cache = {'A':A}

    #crossentropy
    if Y.size != 0:
        m = Y.shape[1]
        Y_ = one_hot(Y.astype(int),10).T
        # loss = -(1/Y.shape[1]) * np.sum( np.log( np.sum(A * Y_, axis = 0) ) )
        loss = -(1/Y.shape[1]) * np.sum( np.log( A[Y.astype(int),np.arange(m)] ) )

    else:
        loss = None

    return A, cache, loss

def softmax_cross_entropy_loss_der(Y, cache):
    '''
    Computes the derivative of softmax activation and cross entropy loss

    Inputs:
        Y - numpy.ndarray (1, m) of labels
        cache -  a dictionary with cached activations A of size (n,m)

    Returns:
        dZ - numpy.ndarray (n, m) derivative for the previous layer
    '''
    ### CODE HERE
    Y_ = one_hot(Y.astype(int),10).T
    dZ = (cache['A'] - Y_)/Y.shape[1]

    return dZ

def initialize_multilayer_weights(net_dims):
    '''
    Initializes the weights of the multilayer network

    Inputs:
        net_dims - tuple of network dimensions

    Returns:
        dictionary of parameters
    '''
    np.random.seed(0)
    numLayers = len(net_dims)
    parameters = {}
    for l in range(numLayers-1):
        parameters["W"+str(l+1)] = np.random.randn(net_dims[l+1], net_dims[l]) * 0.01
        parameters["b"+str(l+1)] = np.zeros((net_dims[l+1], 1)) #np.random.randn(net_dims[l+1], 1) * 0.01
    return parameters

def linear_forward(A, W, b):
    '''
    Input A propagates through the layer
    Z = WA + b is the output of this layer.

    Inputs:
        A - numpy.ndarray (n,m) the input to the layer
        W - numpy.ndarray (n_out, n) the weights of the layer
        b - numpy.ndarray (n_out, 1) the bias of the layer

    Returns:
        Z = WA + b, where Z is the numpy.ndarray (n_out, m) dimensions
        cache - a dictionary containing the inputs A
    '''
    ### CODE HERE
    Z = W.dot(A) + b
    cache = {}
    cache["A"] = A
    return Z, cache

def layer_forward(A_prev, W, b, activation):
    '''
    Input A_prev propagates through the layer and the activation

    Inputs:
        A_prev - numpy.ndarray (n,m) the input to the layer
        W - numpy.ndarray (n_out, n) the weights of the layer
        b - numpy.ndarray (n_out, 1) the bias of the layer
        activation - is the string that specifies the activation function

    Returns:
        A = g(Z), where Z = WA + b, where Z is the numpy.ndarray (n_out, m) dimensions
        g is the activation function
        cache - a dictionary containing the cache from the linear and the nonlinear propagation
        to be used for derivative
    '''
    Z, lin_cache = linear_forward(A_prev, W, b)
    if activation == "relu":
        A, act_cache = relu(Z)
    elif activation == "linear":
        A, act_cache = linear(Z)
    elif activation == "tanh":
        A, act_cache = tanh(Z)
    elif activation == "sigmoid":
        A, act_cache = sigmoid(Z)

    cache = {}
    cache["lin_cache"] = lin_cache
    cache["act_cache"] = act_cache
    return A, cache

def multi_layer_forward(X, parameters):
    '''
    Forward propgation through the layers of the network

    Inputs:
        X - numpy.ndarray (n,m) with n features and m samples
        parameters - dictionary of network parameters {"W1":[..],"b1":[..],"W2":[..],"b2":[..]...}
    Returns:
        AL - numpy.ndarray (c,m)  - outputs of the last fully connected layer before softmax
            where c is number of categories and m is number of samples in the batch
        caches - a dictionary of associated caches of parameters and network inputs
    '''
    L = len(parameters)//2
    A = X
    caches = []
    for l in range(1,L):  # since there is no W0 and b0
        A, cache = layer_forward(A, parameters["W"+str(l)], parameters["b"+str(l)], "relu")
        caches.append(cache)

    AL, cache = layer_forward(A, parameters["W"+str(L)], parameters["b"+str(L)], "linear")
    caches.append(cache)
    return AL, caches

def linear_backward(dZ, cache, W, b):
    '''
    Backward prpagation through the linear layer

    Inputs:
        dZ - numpy.ndarray (n,m) derivative dL/dz
        cache - a dictionary containing the inputs A, for the linear layer
            where Z = WA + b,
            Z is (n,m); W is (n,p); A is (p,m); b is (n,1)
        W - numpy.ndarray (n,p)
        b - numpy.ndarray (n, 1)

    Returns:
        dA_prev - numpy.ndarray (p,m) the derivative to the previous layer
        dW - numpy.ndarray (n,p) the gradient of W
        db - numpy.ndarray (n, 1) the gradient of b
    '''
    A_prev = cache["A"]
    ## CODE HERE
    dA_prev = W.T.dot(dZ)
    dW = np.dot(dZ, A_prev.T)
    db = np.sum(dZ, axis=1, keepdims=True)
    return dA_prev, dW, db

def layer_backward(dA, cache, W, b, activation):
    '''
    Backward propagation through the activation and linear layer

    Inputs:
        dA - numpy.ndarray (n,m) the derivative to the previous layer
        cache - dictionary containing the linear_cache and the activation_cache
        activation - activation of the layer
        W - numpy.ndarray (n,p)
        b - numpy.ndarray (n, 1)

    Returns:
        dA_prev - numpy.ndarray (p,m) the derivative to the previous layer
        dW - numpy.ndarray (n,p) the gradient of W
        db - numpy.ndarray (n, 1) the gradient of b
    '''
    lin_cache = cache["lin_cache"]
    act_cache = cache["act_cache"]

    if activation == "sigmoid":
        dZ = sigmoid_der(dA, act_cache)
    elif activation == "tanh":
        dZ = tanh_der(dA, act_cache)
    elif activation == "relu":
        dZ = relu_der(dA, act_cache)
    elif activation == "linear":
        dZ = linear_der(dA, act_cache)
    dA_prev, dW, db = linear_backward(dZ, lin_cache, W, b)
    return dA_prev, dW, db

def multi_layer_backward(dAL, caches, parameters):
    '''
    Back propgation through the layers of the network (except softmax cross entropy)
    softmax_cross_entropy can be handled separately

    Inputs:
        dAL - numpy.ndarray (n,m) derivatives from the softmax_cross_entropy layer
        caches - a dictionary of associated caches of parameters and network inputs
        parameters - dictionary of network parameters {"W1":[..],"b1":[..],"W2":[..],"b2":[..]...}

    Returns:
        gradients - dictionary of gradient of network parameters
            {"dW1":[..],"db1":[..],"dW2":[..],"db2":[..],...}
    '''
    L = len(caches)  # with one hidden layer, L = 2
    gradients = {}
    dA = dAL
    activation = "linear"
    for l in reversed(range(1,L+1)):
        dA, gradients["dW"+str(l)], gradients["db"+str(l)] = \
                    layer_backward(dA, caches[l-1], \
                    parameters["W"+str(l)],parameters["b"+str(l)],\
                    activation)
        activation = "relu"
    return gradients

def classify(X, parameters):
    '''
    Network prediction for inputs X

    Inputs:
        X - numpy.ndarray (n,m) with n features and m samples
        parameters - dictionary of network parameters
            {"W1":[..],"b1":[..],"W2":[..],"b2":[..],...}
    Returns:
        YPred - numpy.ndarray (1,m) of predictions
    '''
    ### CODE HERE
    # Forward propagate X using multi_layer_forward
    # Get predictions using softmax_cross_entropy_loss
    # Estimate the class labels using predictions
    AL, caches = multi_layer_forward(X, parameters)
    Af, cache, cost = softmax_cross_entropy_loss(AL)

    # maxp = np.max(Af, axis=0, keepdims=True)
    # Af = Af - maxp
    # Af[Af == 0] = 1
    # Af[Af < 0] = 0
    YPred = np.zeros(Af.shape)
    maxix = np.argmax(Af, axis=0)
    YPred[maxix, np.arange(len(maxix))] = 1

    return YPred

def update_parameters(parameters, gradients, epoch, learning_rate, decay_rate=0.0):
    '''
    Updates the network parameters with gradient descent

    Inputs:
        parameters - dictionary of network parameters
            {"W1":[..],"b1":[..],"W2":[..],"b2":[..],...}
        gradients - dictionary of gradient of network parameters
            {"dW1":[..],"db1":[..],"dW2":[..],"db2":[..],...}
        epoch - epoch number
        learning_rate - step size for learning
        decay_rate - rate of decay of step size - not necessary - in case you want to use
    '''
    alpha = learning_rate*(1/(1+decay_rate*epoch))
    L = len(parameters)//2
    for i in range(1,L+1):
        parameters['W'+str(i)] = parameters['W'+str(i)] - alpha*gradients['dW'+str(i)]
        parameters['b'+str(i)] = parameters['b'+str(i)] - alpha*gradients['db'+str(i)]
    return parameters, alpha

def multi_layer_network(X, Y, vX, vY, net_dims, num_iterations=500, learning_rate=0.2, decay_rate=0.00):
    '''
    Creates the multilayer network and trains the network

    Inputs:
        X - numpy.ndarray (n,m) of training data
        Y - numpy.ndarray (1,m) of training data labelsf
        net_dims - tuple of layer dimensions
        num_iterations - num of epochs to train
        learning_rate - step size for gradient descent

    Returns:
        costs - list of costs over training
        parameters - dictionary of trained network parameters
    '''
    parameters = initialize_multilayer_weights(net_dims)
    A0 = X
    costs = []
    val_costs = []
    for ii in range(num_iterations):
        ### CODE HERE
        # Forward Prop

        ## call to multi_layer_forward to get activations
        ## call to softmax cross entropy loss
        AL, caches = multi_layer_forward(A0, parameters)
        Af, cache, cost = softmax_cross_entropy_loss(AL, Y)

        vAL, vcaches = multi_layer_forward(vX, parameters)
        vAf, vcache, vcost = softmax_cross_entropy_loss(vAL, vY)

        # Backward Prop
        ## call to softmax cross entropy loss der
        ## call to multi_layer_backward to get gradients
        ## call to update the parameters
        dZ = softmax_cross_entropy_loss_der(Y, cache)
        grads = multi_layer_backward(dZ, caches, parameters)
        parameters, alpha = update_parameters(parameters, grads, ii, learning_rate, decay_rate)

        costs.append(cost)
        val_costs.append(vcost)
        if ii % 10 == 0:
            print("Cost at iteration %i is: %.05f, learning rate: %.05f" %(ii, cost, alpha))

    return costs, val_costs, parameters

def accuracy(YPred, Y):

    Y_ = one_hot(Y.astype(int),10).T
    x = np.abs(YPred-Y_)
    x = np.sum(x)/(2*Y.shape[1])
    return (1-x)

def train(train_data, train_label, val_data, val_label, test_data, test_label, net_dims, learning_rate=0.1, decay_rate=0.00, iters = 501):
    np.random.seed(1)
    # initialize learning rate and num_iterations
    num_iterations = iters

    costs, val_costs, parameters = multi_layer_network(train_data, train_label, val_data, val_label, net_dims, \
            num_iterations, learning_rate, decay_rate)

    # compute the accuracy for training set and testing set
    train_Pred = classify(train_data, parameters)
    val_Pred = classify(val_data, parameters)
    test_Pred = classify(test_data, parameters)

    #test loss
    # AL, caches = multi_layer_forward(test_data, parameters)
    # Af, cache, test_error = softmax_cross_entropy_loss(AL, test_label)

    trAcc = accuracy(train_Pred, train_label)
    valAcc = accuracy(val_Pred, val_label)
    teAcc = accuracy(test_Pred, test_label)
    print("\nAccuracy after",num_iterations,"decay_rate=",decay_rate)
    print("Training: {0:0.3f}%".format(trAcc*100), "Validation: {0:0.3f}%".format(valAcc*100), "Testing: {0:0.3f}%".format(teAcc*100))

    return costs, val_costs, 1-teAcc

def main():
    '''
    Trains a multilayer network for MNIST digit classification (all 10 digits)
    To create a network with 1 hidden layer of dimensions 800
    Run the progam as:
        python deepMultiClassNetwork_starter.py "[784,800]"
    The network will have the dimensions [784,800,10]
    784 is the input size of digit images (28pix x 28pix = 784)
    10 is the number of digits

    To create a network with 2 hidden layers of dimensions 800 and 500
    Run the progam as:
        python deepMultiClassNetwork_starter.py "[784,800,500]"
    The network will have the dimensions [784,800,500,10]
    784 is the input size of digit images (28pix x 28pix = 784)
    10 is the number of digits
    '''
    os.system("mkdir graphs_2")

    net_dims = ast.literal_eval( sys.argv[1] )
    net_dims.append(10) # Adding the digits layer with dimensionality = 10
    print("Network dimensions are:" + str(net_dims))

    # getting the subset dataset from MNIST
    train_data, train_label, val_data, val_label, test_data, test_label = \
            mnist(noTrSamples=5000, noValSamples=1000, noTsSamples=1000,\
            digit_range=[0,1,2,3,4,5,6,7,8,9],\
            noTrPerClass=500, noValPerClass=100, noTsPerClass=100)

    # initialize learning rate and num_iterations
    learning_rate = 0.2
    num_iterations = 1001
    decay_rate = 0.01

    costs, val_costs, test_error = train(train_data, train_label, val_data, val_label, test_data, test_label, net_dims, learning_rate, decay_rate, num_iterations)

    ### CODE HERE to plot costs
    #### Q2 1)
    x_points = [i for i in range(0,len(costs))]

    plt.clf()
    plt.title("Error v/s Iterations")
    cost_line, = plt.plot(x_points, costs, 'b-', label="Training")
    val_line, = plt.plot(x_points, val_costs, 'r-', label="Validation")
    plt.legend(handles=[cost_line, val_line])
    plt.ylabel('Error')
    plt.xlabel('Iterations')
    plt.savefig('graphs_2/Error_vs_Iterations.png')
    # plt.show()
    ####

    #### Q2 2)
    print("Test Error or Misclassification %: "+str(test_error*100))
    print("\n")
    ####

    #### Q2 3)
    c ,vc = [], []
    all_costs = []
    all_v_costs = []
    test_errors = []
    lrs = []
    for i in [0.1,0.5,1,10]:
        print("###")
        print("Learning Rate: ",i)

        tc, tvc, t_e = train(train_data, train_label, val_data, val_label, test_data, test_label, net_dims, i, 0.01, iters=1001)
        x_points = [i for i in range(0,len(tc))]

        plt.clf()
        plt.title('Learning Rate:'+str(i))
        plt.ylabel('Error')
        plt.xlabel('Iterations')
        cost_line, = plt.plot(x_points, tc, 'b-', label="Training")
        val_line, = plt.plot(x_points, tvc, 'r-', label="Validation")
        plt.legend(handles=[cost_line, val_line])
        plt.savefig('graphs_2/Error_Graph_Learning_Rate_'+str(i)+'.png')
        # plt.show()

        lrs.append(i)
        all_costs.append(tc)
        all_v_costs.append(tvc)
        test_errors.append(t_e)
        c.append(tc[-1])
        vc.append(tvc[-1])
        print("###")
        print("\n")

    #All lines together
    handles = []
    plt.clf()
    plt.title('All Learning Rates')
    plt.ylabel('Error')
    plt.xlabel('Iterations')
    plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b', 'y'])))
    for i in range(len(all_costs)):
        x_points = [i for i in range(0,len(all_costs[i]))]
        cost_line, = plt.plot(x_points, all_costs[i], label=str(lrs[i]))
        handles.append(cost_line)
    plt.legend(handles=handles)
    plt.savefig('graphs_2/Error for all Learning Rates'+str(i*0.01)+'.png')

    # Error (After x iterations) v/s Learning Rate graph
    # x_points = list(range(1, 21, 1))
    # x_points = [i*0.01 for i in x_points]
    # plt.clf()
    # plt.plot(x_points, c, 'b-', x_points, vc, 'r-')
    # plt.ylabel('Error')
    # plt.xlabel('Learning Rate')
    # plt.savefig('graphs_2/Error_vs_Learning_Rate.png')
    # plt.show()
    ####

    #### Q2 4)
    ix = np.argmin(vc)
    lr = lrs[ix]
    print("Minimum validation error found when learning_rate="+str(lr)+", Test accuracy for that run has been printed above")
    ####

if __name__ == "__main__":
    main()


from pymongo import MongoClient

uri = 'mongodb://127.0.0.1:27017'
client = MongoClient(uri)
db = client['services']
eventDatacollection = db.get_collection('serviceconfigdetails')
all_event_details = eventDatacollection.find({})
################################################################
authDatacollection = db.get_collection('authdetails')
all_auth_details = authDatacollection.find({})

########################## SERVICE #########################################
trigger_results =[]
action_results = []
for event in all_event_details:
    eventData = []
    eventData.append(event['service_idnetifier'])
    eventData.append(event['eventName'])
    if event['eventType'] == 'trigger':
        trigger_results.append(eventData)
    elif event['eventType'] == 'action':
        action_results.append(eventData)
############################ AUTHENTICATED #################################
all_auth_details_list  = []
for authService in all_auth_details:
    serviceID = authService['service_idnetifier']
    connected = authService['connected']
    if connected:
        all_auth_details_list.append(serviceID)

print(trigger_results)
for authService in all_auth_details_list:
    print(authService)
    ii = 0
    for item in trigger_results:
        if authService == item[0]:
            ii = ii + 1
            if ii == 1:
                print('is a trigger service !!')
            print(item[1])
    ii2 = 0
    for item2 in action_results:
        if authService == item2[0]:
            ii2 = ii2 + 1
            if ii2 == 1:
                print('is a action service !!')
            print(item2[1])

    print('###########################')


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

from FP import Maybe, List
from os_helpers import get_directories, get_files_from_root
from feature_helpers import extract_image_features, process_image, split_data, normalize_data, normalize_data_prediction, feature_reduction
from ml_helpers import save_data, load_data, experiment, train_model, save_model, load_model, predict_with_model
from lambdas import list_to_tuple, nothing_if_empty, is_not_none, split_to_tuple, add_reducer
from decorating import animated
import argparse
import time

#### Server

#from app import im2text_pb2, im2text_pb2_grpc

import im2text_pb2_grpc
import im2text_pb2

from concurrent import futures
import time
import grpc

_ONE_DAY_IN_SECONDS = 60 * 60 * 24

class Im2Text(im2text_pb2_grpc.Im2TxtServicer):

    def Run(self, request, context):
        fn = request.text

        res = 'unknown'
        try:
            res = predict([fn])[0]
        except Exception as e:
            print(e)

        return im2text_pb2.Im2TxtReply(text=str(res))

#### Emotion detection

# OPTIMIZATIONS TO BE DONE (hopefully)
# - Eliminate lambdas
# - Do more FP
# - Use keyword arguments

IMAGE_DIR = './images'
OLD_MODEL_PATH = './old_emotion_detector.pkl'
NEW_MODEL_PATH = './emotion_detector.pkl'
DATA_PATH = './data.pkl'
EMOTIONS = get_directories(IMAGE_DIR)

model = None

def accept_commands():
    data_arg, train_arg, predict_arg = parse_args()

    if data_arg is not None:
        generate_data(data_arg[0])

    elif train_arg is True:
        train()

    elif predict_arg is not None:
        print(predict(predict_arg))

def parse_args():
    parser = argparse.ArgumentParser(description='Emotion Detection Application')
    parser.add_argument('--train', action='store_true', help='start training the program to predict emotions')
    parser.add_argument('--data', nargs=1, help='process images from specified folder into usable data', metavar='path_to_training_folder')
    parser.add_argument('--predict', nargs='+', help='predict the emotion of face in image', metavar='path_to_input_image')
    args = parser.parse_args()
    unpacked_args = vars(args)
    data_arg = unpacked_args['data']
    train_arg = unpacked_args['train']
    predict_arg = unpacked_args['predict']

    return data_arg, train_arg, predict_arg

def generate_data(image_dir=IMAGE_DIR):
    return List.of(get_directories(image_dir)) \
        .chain(get_files_from_root(image_dir)) \
        .reduce(add_reducer) \
        .map(extract_image_features) \
        .reduce(split_data, ([], [])) \
        .map(normalize_data) \
        .map(feature_reduction(OLD_MODEL_PATH, True)) \
        .map(split_to_tuple) \
        .map(save_data) \
        .value

@animated
def train(data_dir=DATA_PATH):
    print("Training start...")

    Maybe.of(load_data()) \
        .map(experiment) \
        .map(train_model) \
        .map(save_model)

    print("Training complete.")

def predict(image_paths):
    print("Predicting...")
    print(image_paths)
    # get the time of a prediction

    t = time.process_time()
    preprocess = List(image_paths) \
        .map(process_image) \
        .filter(is_not_none) \
        .fold(nothing_if_empty) \
        .reduce(list_to_tuple, ())

    elapsed_time = time.process_time() - t
    print("Preprocessing time {}".format(elapsed_time))

    t = time.process_time()

    result = preprocess \
        .map(normalize_data_prediction) \
        .map(feature_reduction(OLD_MODEL_PATH)) \
        .map(predict_with_model(model)) \
        .map(get_emotions) \
        .value

    elapsed_time = time.process_time() - t
    print("Prediction time {}".format(elapsed_time))

    return result

# Remove DS Store from images: rm ./app/images/*/.DS_Store

def get_emotions(emotion_indices):
    return [EMOTIONS[index] for index in emotion_indices]

def init():
    """Sets up things we only need to do once"""
    print("Loaded model")
    global model
    model = load_model()

def serve():
    print("Serving started")
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    im2text_pb2_grpc.add_Im2TxtServicer_to_server(Im2Text(), server)
    server.add_insecure_port('[::]:50051')
    server.start()

    try:
        while True:
            time.sleep(_ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)

if __name__ == '__main__':
    init()
    accept_commands()
    print(model)
    serve()


#  Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#  SPDX-License-Identifier: Apache-2.0
import unittest
from copy import deepcopy
from unittest import skip

import constants

class TestManifest(unittest.TestCase):
    account_a = {
        "account_id": "012345678910",
        "default_region": "eu-west-1",
        "name": "accounta",
        "expanded_from": "ou-aaaa-aaaaaaaa",
        "organization": "o-aaaaaaaa",
        "regions_enabled": ["eu-west-2",],
        "tags": ["group:A"],
    }
    account_b = {
        "account_id": "009876543210",
        "default_region": "us-west-1",
        "expanded_from": "ou-bbbb-bbbbbbbb",
        "organization": "o-bbbbbbbb",
        "name": "accountb",
        "regions_enabled": ["us-west-2",],
        "tags": ["group:B"],
    }
    account_c = {
        "account_id": "432100098765",
        "default_region": "ap-west-1",
        "name": "accountc",
        "regions_enabled": ["ap-west-2",],
        "tags": ["group:C"],
    }
    accounts = {"accounts": [account_a, account_b, account_c,]}
    launch_a = {
        "portfolio": "portfolio_a",
        "product": "product_a",
        "execution": "hub",
        "version": "version_a",
        "deploy_to": {"tags": [{"regions": "default_region", "tag": "group:A"}]},
    }
    assertion_a = {
        "expected": {"foo": "bar"},
        "actual": {"bar": "foo"},
        "assert_for": {"tags": [{"regions": "default_region", "tag": "group:A"}]},
    }
    spoke_local_portfolio_a = {
        "portfolio": "portfolio_a",
        "deploy_to": {"tags": [{"regions": "default_region", "tag": "group:A"}]},
    }
    launch_b = {
        "portfolio": "portfolio_b",
        "product": "product_b",
        "version": "version_b",
        "execution": "hub",
        "deploy_to": {"tags": [{"regions": "default_region", "tag": "group:B"}]},
    }
    launch_c = {
        "portfolio": "portfolio_c",
        "product": "product_c",
        "version": "version_c",
        "execution": "hub",
        "deploy_to": {"tags": [{"regions": "enabled_regions", "tag": "group:B"}]},
    }
    launches = dict(
        launches=dict(launch_a=launch_a, launch_b=launch_b, launch_c=launch_c)
    )
    assertions = dict(assertions=dict(assertion_a=assertion_a))
    spoke_local_portfolios = {
        "spoke-local-portfolios": dict(spoke_local_portfolio_a=spoke_local_portfolio_a)
    }
    puppet_account_id = "0123456789010"

    def setUp(self):
        from servicecatalog_puppet.manifest_utils import Manifest

        self.sut = Manifest()

    def tearDown(self):
        self.sut = None

    def test_get_provisioning_tasks_for_launch_and_region_for_tags(self):
        # setup
        puppet_account_id = "pppppppppppp"
        section_name = "launches"
        item_name = "launch_a"
        region = "eu-west-1"
        self.sut.update(deepcopy(self.accounts))
        self.sut.update(deepcopy(self.launches))
        expected_result = [
            {
                "account_id": "012345678910",
                "account_parameters": {},
                "execution": "hub",
                "launch_name": item_name,
                "launch_parameters": {},
                "manifest_parameters": {},
                "portfolio": "portfolio_a",
                "product": "product_a",
                "puppet_account_id": puppet_account_id,
                "region": region,
                "ssm_param_outputs": [],
                "requested_priority": 0,
                "version": "version_a",
            }
        ]

        # exercise
        actual_results = self.sut.get_tasks_for_launch_and_region(
            puppet_account_id, section_name, item_name, region
        )

        # verify
        self.assertListEqual(expected_result, actual_results)

    def test_get_provisioning_tasks_for_spoke_local_portfolios_and_region_for_tags(
        self,
    ):
        # setup
        puppet_account_id = "pppppppppppp"
        section_name = "spoke-local-portfolios"
        item_name = "spoke_local_portfolio_a"
        region = "eu-west-1"
        self.sut.update(deepcopy(self.accounts))
        self.sut.update(deepcopy(self.launches))
        self.sut.update(deepcopy(self.spoke_local_portfolios))
        expected_result = [
            {
                "account_id": "012345678910",
                "spoke_local_portfolio_name": item_name,
                "portfolio": "portfolio_a",
                "puppet_account_id": puppet_account_id,
                "region": region,
                "associations": [],
                "launch_constraints": [],
                "organization": "",
                "product_generation_method": "copy",
                "sharing_mode": "ACCOUNT",
            }
        ]

        # exercise
        actual_results = self.sut.get_tasks_for_launch_and_region(
            puppet_account_id, section_name, item_name, region
        )

        # verify
        self.assertListEqual(expected_result, actual_results)

    def test_get_provisioning_tasks_for_launch_and_region_for_accounts(self):
        # setup
        puppet_account_id = "pppppppppppp"
        section_name = "launches"
        item_name = "launch_a"
        region = "eu-west-2"
        self.sut.update(deepcopy(self.accounts))
        self.sut.update(deepcopy(self.launches))
        self.sut[section_name][item_name]["deploy_to"] = dict(
            accounts=[dict(account_id="012345678910", regions="enabled_regions")]
        )
        expected_result = [
            {
                "account_id": "012345678910",
                "account_parameters": {},
                "execution": "hub",
                "launch_name": item_name,
                "launch_parameters": {},
                "manifest_parameters": {},
                "portfolio": "portfolio_a",
                "product": "product_a",
                "puppet_account_id": puppet_account_id,
                "region": region,
                "ssm_param_outputs": [],
                "requested_priority": 0,
                "version": "version_a",
            }
        ]

        # exercise
        actual_results = self.sut.get_tasks_for_launch_and_region(
            puppet_account_id, section_name, item_name, region
        )

        # verify
        self.assertListEqual(expected_result, actual_results)

    def test_get_assertion_tasks_for_launch_and_region_for_accounts(self):
        # setup
        puppet_account_id = "pppppppppppp"
        section_name = "assertions"
        item_name = "assertion_a"
        region = "eu-west-1"
        self.sut.update(deepcopy(self.accounts))
        self.sut.update(deepcopy(self.assertions))

        expected_result = [
            {
                "account_id": "012345678910",
                "assertion_name": item_name,
                "puppet_account_id": puppet_account_id,
                "region": region,
                "execution": constants.EXECUTION_MODE_DEFAULT,
                "requested_priority": 0,
                "expected": {"foo": "bar"},
                "actual": {"bar": "foo"},
            }
        ]

        # exercise
        actual_results = self.sut.get_tasks_for_launch_and_region(
            puppet_account_id, section_name, item_name, region
        )

        # verify
        self.assertListEqual(expected_result, actual_results)

    def test_get_regions_used_for_section_item_for_tags_and_default_region(self):
        # setup
        puppet_account_id = "01234567890"
        section_name = "launches"
        item_name = "launch_a"
        self.sut.update(deepcopy(self.accounts))
        self.sut.get("accounts").append(
            {
                "account_id": "9875983465794387",
                "default_region": "eu-west-3",
                "name": "accounta",
                "expanded_from": "ou-aaaa-aaaaaaaa",
                "organization": "o-aaaaaaaa",
                "regions_enabled": ["eu-west-2",],
                "tags": ["group:A"],
            }
        )
        self.sut.update(deepcopy(self.launches))
        expected_result = ["eu-west-1", "eu-west-3"]

        # exercise
        actual_results = self.sut.get_regions_used_for_section_item(
            puppet_account_id, section_name, item_name
        )
        actual_results.sort()

        # verify
        self.assertListEqual(expected_result, actual_results)

    def test_get_regions_used_for_section_item_for_accounts_and_default_region(self):
        # setup
        puppet_account_id = "01234567890"
        section_name = "launches"
        item_name = "launch_a"
        self.sut.update(deepcopy(self.accounts))
        self.sut.get("accounts").append(
            {
                "account_id": "9875983465794387",
                "default_region": "eu-west-99",
                "name": "accounta",
                "expanded_from": "ou-aaaa-aaaaaaaa",
                "organization": "o-aaaaaaaa",
                "regions_enabled": ["eu-west-2",],
                "tags": ["group:A"],
            }
        )
        self.sut.update(deepcopy(self.launches))
        self.sut["launches"][item_name]["deploy_to"] = dict(
            accounts=[dict(account_id="9875983465794387", regions="default_region")]
        )
        expected_result = ["eu-west-99"]

        # exercise
        actual_results = self.sut.get_regions_used_for_section_item(
            puppet_account_id, section_name, item_name
        )

        # verify
        self.assertListEqual(expected_result, actual_results)

    def test_get_regions_used_for_section_item_for_enabled_region(self):
        # setup
        puppet_account_id = "01234567890"
        section_name = "launches"
        item_name = "launch_c"
        self.sut.update(deepcopy(self.accounts))
        self.sut.get("accounts").append(
            {
                "account_id": "9875983465794387",
                "default_region": "eu-west-3",
                "name": "accounta",
                "expanded_from": "ou-aaaa-aaaaaaaa",
                "organization": "o-aaaaaaaa",
                "regions_enabled": ["eu-west-2",],
                "tags": ["group:A"],
            }
        )
        self.sut.update(deepcopy(self.launches))
        expected_result = ["us-west-2"]

        # exercise
        actual_results = self.sut.get_regions_used_for_section_item(
            puppet_account_id, section_name, item_name
        )

        # verify
        self.assertListEqual(expected_result, actual_results)

    def test_get_accounts_by_region(self):
        # setup
        self.sut.update(deepcopy(self.accounts))
        expected_regions = [
            "eu-west-1",
            "eu-west-2",
            "us-west-1",
            "us-west-2",
            "ap-west-1",
            "ap-west-2",
        ]

        # exercise
        actual_result = self.sut.get_accounts_by_region()
        actual_regions = list(actual_result.keys())

        # verify
        self.assertCountEqual(expected_regions, actual_regions)
        self.assertEqual(actual_result.get("eu-west-1"), [self.account_a])
        self.assertIsNone(actual_result.get("eu-west-999"))

    @skip
    def test_get_shares_by_region_portfolio_account(self):
        # setup
        self.sut.update(deepcopy(self.accounts))
        self.sut.update(deepcopy(self.launches))

        # exercise
        actual_result = self.sut.get_shares_by_region_portfolio_account(
            self.puppet_account_id, "launches"
        )

        # verify
        self.assertIsNotNone(actual_result.get("eu-west-1").get("portfolio_a"))
        self.assertEqual(
            actual_result.get("eu-west-1").get("portfolio_a").get("012345678910"),
            self.account_a,
        )
        self.assertIsNotNone(actual_result.get("us-west-1").get("portfolio_b"))
        self.assertEqual(
            actual_result.get("us-west-1").get("portfolio_b").get("009876543210"),
            self.account_b,
        )

    def test_get_sharing_policies_by_region(self):
        # setup
        self.sut.update(deepcopy(self.accounts))
        self.sut.update(deepcopy(self.launches))

        # exercise
        actual_result = self.sut.get_sharing_policies_by_region()

        # verify
        self.assertIsNotNone(actual_result.get("eu-west-1"))
        self.assertEqual(
            actual_result.get("eu-west-1"),
            dict(organizations=["o-aaaaaaaa"], accounts=[]),
        )
        self.assertEqual(
            actual_result.get("us-west-1"),
            dict(organizations=["o-bbbbbbbb"], accounts=[]),
        )
        self.assertEqual(
            actual_result.get("ap-west-1"),
            dict(organizations=[], accounts=["432100098765"]),
        )


from tkinter import *

root = Tk()
root.title("Scyan TTS")
#root.iconbitmap("./speaker.ico")
root.geometry("400x400")

# menu
menubar = Menu(root)

menu_1 = Menu(menubar, tearoff=0)
menu_1.add_command(label="새파일")
menu_1.add_command(label="열기")
menu_1.add_command(label="저장")
menu_1.add_separator()
menu_1.add_command(label="종료")
menubar.add_cascade(label="파일", menu=menu_1)

helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="파일목록")
helpmenu.add_command(label="정보")
menubar.add_cascade(label="도움말", menu=helpmenu)

root.config(menu=menubar)

# widget
w = Label(root, text="TXT 파일 읽기")
w.grid(row=0, column=0)
e1 = Entry(root)
e1.grid(row=0, column=1)
w = Button(root, text="MP3 생성")
w.grid(row=0, column=2)
w = Button(root, text="▶")
w.grid(row=0, column=3)
w = Button(root, text="■")
w.grid(row=0, column=4)

w = Label(root, text="Phrase 읽기 ")
w.grid(row=1, column=0)
e2 = Entry(root)
e2.grid(row=1, column=1)
w = Button(root, text="구문 저장")
w.grid(row=1, column=2)
w = Button(root, text="구문 읽기")
w.grid(row=1, column=3, columnspan=2, sticky='e')

# frame with Text
frame = Frame(root)
frame.grid(row=2, column=0, columnspan=4, sticky='ew')
tb = Text(frame, width=50)
tb.pack(side='left', fill='both', expand=True)
scrollbar = Scrollbar(frame)
tb.config(yscrollcommand=scrollbar.set)
scrollbar.config(command= tb.yview)
scrollbar.focus_set()

scrollbar.pack(side='right', fill='y')

mainloop()


#!/usr/bin/python3
"""This script creates an unofficial sdist directory.
   It is useful when cmake can not be used (eg. on Windows)."""

from os import makedirs, walk, chdir
from os.path import dirname, join
from shutil import copy2
from sys import argv

def copyfile(src, dst ,reverse):
    if reverse:
        src, dst = dst, src
    makedirs(dirname(dst), exist_ok=True)
    copy2(src, dst)

def copydir(src, dst, fileend, reverse):
    for dirpath, dirnames, filenames in walk(src):
        for afile in filenames:
            if afile.endswith(fileend):
                fsrc = join(dirpath, afile)
                fdst = join(dirpath, afile).replace(src, dst)
                copyfile(fsrc, fdst ,reverse)

def main():
    chdir(dirname(__file__))
    reverse = "-r" in argv

    copydir("../cpp/cpp_odbc/Library/cpp_odbc", "sdist/include/cpp_odbc", ".h", reverse)
    copydir("../cpp/turbodbc/Library/turbodbc", "sdist/include/turbodbc", ".h", reverse)
    copydir("../cpp/turbodbc_numpy/Library/turbodbc_numpy", "sdist/include/turbodbc_numpy", ".h", reverse)
    copydir("../cpp/turbodbc_python/Library/turbodbc_python", "sdist/include/turbodbc_python", ".h", reverse)

    copydir("../cpp/cpp_odbc/Library/src", "sdist/src/cpp_odbc", ".cpp", reverse)
    copydir("../cpp/turbodbc/Library/src", "sdist/src/turbodbc", ".cpp", reverse)
    copydir("../cpp/turbodbc_numpy/Library/src", "sdist/src/turbodbc_numpy", ".cpp", reverse)
    copydir("../cpp/turbodbc_python/Library/src", "sdist/src/turbodbc_python", ".cpp", reverse)

    copydir("../python/turbodbc", "sdist/turbodbc", ".py", reverse)

    for afile in ["setup.cfg",
                  "setup.py",
                  "README.md",
                  "CHANGELOG.rst",
                  "MANIFEST.in",
                  "LICENSE",
                  ]:
        fsrc = join("..", afile)
        fdst = join("sdist", afile)
        copyfile(fsrc, fdst ,reverse)

if __name__ == "__main__":
    main()


from kivy.clock import Clock
from kivy.logger import Logger
from kivy.uix.button import Button

def opposite(x, y):
    return x < 0 and y > 0 or x > 0 and y < 0

class IntroLabel(Button):
    def __init__(self, *a, **kw):
        super().__init__(*a, **kw)

    def on_size(self, label, size):
        Clock.schedule_once(self.adjust_size, 0)

    def adjust_size(self, dt):

        step = 3

        while True:
            w, h = self.size
            tw, th = self.texture_size

            Logger.debug("tw=%s w=%s th=%s h=%s step=%s", tw, w, th, h, step)

            dir_dfs = -1 if (tw > w or th > h) else 1

            if opposite(dir_dfs, step):
                step *= -0.5
                Logger.debug("step set to %s", step)

            if abs(step) < 0.1:
                Logger.debug("reached finish")
                break

            self.font_size += step
            Logger.debug("font_size=%s", self.font_size)
            self.texture_update()


'''
Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string ""
'''

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if len(strs) == 0:
            return ""
        res = ""
        i = 0
        lengths = []
        for l in range(len(strs)):
            lengths.append(len(strs[l]))
        while i < min(lengths):
            first = strs[0][i]
            for j in range(len(strs)):
                if strs[j][i] == first:
                    flag = 1
                else:
                    return res
            if flag:
                res += first
                i += 1

        return res


#! /usr/bin/env python
"""
Write TurbSim input files
"""
import sys,os
libpath = 'C:\\Users\\jrinker\\Documents\\GitHub\\dissertation'
if (libpath not in sys.path): sys.path.append(libpath)

import JR_Library.main as jr
import random

# define turbine name
TurbNames = ['WP0.75A08V00','WP1.5A08V03','WP3.0A02V02','WP5.0A04V00']
BaseWindDir = '\\\\monsoon-data\\Public\\JRinker\\fast_simulations\\WindDir'

# wind parameters
#URefs  = [5.0, 7.0, 9.0, 10.0, 10.5, 11.0, 11.5, \
#        12.0, 13.0, 16.0, 19.0, 22.0]
#Is     = [0.1, 0.2, 0.3, 0.4, 0.5]
#logLs  = [1.5, 2.0, 2.5, 3.0]
#rhos   = [0.0, 0.1, 0.2, 0.3, 0.4]
#n_dups = 5
URefs  = [9.0, 10.0, 10.5, 11.0, 11.5, 12.0]
Is     = [0.1, 0.2, 0.3, 0.4, 0.5]
logLs  = [2.0]
rhos   = [0.4]
n_dups = 10

# loop through turbines
for TurbName in TurbNames:

    print('Creating TurbSim input files for turbine \"{:s}\"'.format(TurbName))

    # define output directory for TurbSim files
    out_dir = os.path.join(BaseWindDir,TurbName)

    # create output directory if it doesn't exist
    if not os.path.isdir(out_dir):
        os.makedirs(out_dir)

    # write TurbSim file
    TSDict = jr.MakeTSDict(TurbName,URef,sig_u,L_u,rho_u,R1,R2)


import sys

from part3.http_server_multi_connection import HttpServerMultiConnection

def main(argv: list):
    if argv is None or len(argv) != 2:
        wrong_format()

    # try:
    port = int(argv[1])

    if port <= 1024:
        print("Port number needs to be higher than or equal to 1024.")
        sys.exit(2)
    else:
        http_server = HttpServerMultiConnection()
        http_server.open_connection(port)
    # except:
    #     wrong_format()

def wrong_format():
    print('http_server2.py <port>')
    sys.exit(2)

if __name__ == "__main__":
    main(sys.argv)


import time, sys, os.path, json
from subprocess import check_output

class OpenPCR:
    def __init__(self,devicepath=''):
        self.platform = sys.platform[:3]
        # Linux 	'lin'
        # Windows	'win'
        # Cygwin 	'cyg'
        # Mac OS X	'dar'
        # OS/2 (/EMX)	'os2'

        if not devicepath: #i.e. if none was passed at object initiation..
            self.devicepath = self.DefaultPlatformPath()
        else:
            self.devicepath = devicepath # Just assume user knows what s/he is doing..

        if not os.path.exists(self.devicepath):
            print("Directory specified (default /media/OPENPCR) does not exist. Is OpenPCR turned on?")
            self.devicepath = ''
        assert(self.devicepath)

    def DefaultPlatformPath(self):
        'Checks "usual" mount locations on supported platforms and returns directory if successful.'
        if self.platform == 'lin':
            return '/media/OPENPCR/' # Ubuntu mountpoint, at least.
            # TODO: Cascade through potential mountpoints on other linuxes, using os.path.exists()?
        elif self.platform == 'win':
            print("Windows not yet supported. You can try manually invoking the OpenPCR() object with a "+\
                  "'devicepath' argument consisting of the openpcr mountpoint, if you like; be sure to "+\
                  "share your results if it works!")
            return ''
        elif self.platform == 'dar':
            print("Mac/Darwin not yet supported. You can try manually invoking the OpenPCR() object with a "+\
                  "'devicepath' argument consisting of the openpcr mountpoint, if you like; be sure to "+\
                  "share your results if it works!")
            return ''
        elif self.platform == 'os2':
            print("OS/2 not yet supported. You can try manually invoking the OpenPCR() object with a "+\
                  "'devicepath' argument consisting of the openpcr mountpoint, if you like; be sure to "+\
                  "share your results if it works!\n"+\
                  "Please note, there is no 'ncc' binary for OS2, so reading OpenPCR status is not possible.")
            return ''
        elif self.platform == 'cyg':
            print("Cygwin not yet supported. You can try manually invoking the OpenPCR() object with a "+\
                  "'devicepath' argument consisting of the openpcr mountpoint, if you like; be sure to "+\
                  "share your results if it works!")
            return ''

    def sendprogram(self,program):
        'Sends a program to the OpenPCR and prints a verification if successful.'
        assert(self.devicepath)
        Status = self.readstatus()
        CurrentNonce = Status['nonce']
#        CurrentNonce = 65534 # For debugging purposes only, replace with the above..
        if CurrentNonce < 65535: # Max int size on arduino; wrap around to avoid bugs.
            NewNonce = CurrentNonce + 1
        else:
            NewNonce = 1
        NonceCMD = 'd=' + str(NewNonce)

        # Chop up program string, insert nonce, and reassemble for sending.
        dissectedprogram = program.split("&")
        for item in dissectedprogram:
            if item[0]=='d': # If there's already a nonce in this program for some reason..
                print("Found existing nonce value ('d=xxx') in program. Removing..")
                noncelistindex = dissectedprogram.index(item) # Find index to delete first..
                del(dissectedprogram[noncelistindex]) # Then kill it with fire.

        dissectedprogram.insert(1,NonceCMD) # Add new nonce to program.
        assembledprogram = "&".join(dissectedprogram) # Reassembles YAML-formatted program.
        self._sendprogram(assembledprogram)

        time.sleep(2) # If no waiting time is given, readstatus fails.
        recurse = 0
        def checkNonce():
            try:
                Status = self.readstatus()
                if Status['nonce'] == NewNonce:
                    print("Program sent successfully!")
                else:
                    print("Nonce values unchanged; program may not have sent correctly.")
            except ValueError:
                if recurse < 6: # Max 5 seconds wait after initial second.
                    print("Waiting for OpenPCR to respond..")
                    time.sleep(1)
                    recurse += 1
                    checkNonce() # Recursive function calls, yay! (Puppies may die.)
                else:
                    print("OpenPCR not responding to checkstatus calls. Giving up.")
        checkNonce() # Start checking.

    def _sendprogram(self,program):
        assert(self.devicepath)
        with open(self.devicepath+'CONTROL.TXT', encoding='utf-8', mode='w') as ProgramPipe:
            ProgramPipe.write(program)

    def test(self):
        assert(self.devicepath)
        self.sendprogram('s=ACGTC&c=start&n=OpenPyCR Test Program&p=(20[10|45|TestStep1][20|25|TestStep2])')

    def stop(self):
        assert(self.devicepath)
        self.sendprogram('s=ACGTC&c=stop')

    def ncc(self):
        'Low-level. Calls ncc binary for appropriate platform, returns raw output as string.'
        if (self.platform == 'lin') or (self.platform == 'dar'): # Assuming that mac uses same binary here..
            try:
                ByteStatus = check_output(["./ncc", self.devicepath+"STATUS.TXT"])
            except:
                print("'ncc' binary exited with an error. Platform may be incompatible.")
        elif (self.platform == 'win') or (self.platform == 'cyg'): # Assuming cygwin calls windows binary.
            try:
                ByteStatus = check_output(["./ncc.exe", self.devicepath+"STATUS.TXT"]) # Totally untested.
            except:
                print("'ncc.exe' binary exited with an error. Platform may be incompatible.")
        else:
            print("System not supported.")
            return None
        StrStatus = str(ByteStatus, encoding='utf-8')
        return StrStatus

    def readstatus(self):
        'Calls ncc and translates output into a dictionary of values.'
        assert(self.devicepath)
        statustxt = self.ncc()
        statusdict = {}
        for entry in statustxt.split("&"):
            key, val = entry.split("=")
            if key == 's': # State: running, idle, etc.
                statusdict['state'] = val
            elif key == 't': # Job: Heating/Cooling/Holding
                statusdict['job'] = val
            elif key == 'b': # Temperature of the block; Celsius.
                statusdict['blocktemp'] = float(val)
            elif key == 'l': # Temperature of the lid; Celsius.
                statusdict['lidtemp'] = float(val)
            elif key == 'e': # Elapsed seconds.
                statusdict['elapsedsecs'] = int(val)
            elif key == 'r': # Remaining seconds (accuracy?).
                secs = int(val) # Converts from string to int.
                mins = int(secs/60) # int() omits decimals.
                hours = int(mins/60)
                statusdict['secsleft'] = secs
                statusdict['minsleft'] = mins
                statusdict['hoursleft']= hours
                 # Remainders, for hours:mins:seconds
                extramins = mins - (hours*60)
                extrasecs = secs - (mins*60)
                formattedtime = '{0}:{1}:{2}'.format(hours,extramins,extrasecs)
                statusdict['timeleft'] = formattedtime
            elif key == 'p': # Name of current step, if given.
                statusdict['currentstep'] = val
            elif key == 'c': # Cycle number.
                statusdict['cycle'] = int(val)
            elif key == 'n': # Program name, if given.
                statusdict['program'] = val
            elif key == 'd':
                # The "number-used-once" that helps verify program sending.
                # No other function, generally safe to ignore except when
                # testing program delivery.
                statusdict['nonce'] = int(val)
        return statusdict

    def csvstatus(self,keyorder = ['elapsedsecs','cycle','blocktemp']):
        '''Calls readstatus and formats output for logging to csv.

        keyorder is a list of dictionary keys to use, in desired order, when
        formatting output. The default provides the elapsed time in seconds,
        current cycle number, and temperature of the block.'''
        assert(self.devicepath)
        S = self.readstatus()
        if (S['state'] == 'stopped') or (S['job'] == 'idle'):
            return 'Inactive' # OpenPCR not running, will probably raise keyerrors below if we proceed.
        if (S['state'] == 'complete'):
            return 'Complete'
        thisline = []
        try:
            for key in keyorder:
                thisline.append(str(S[key]))
            return ','.join(thisline)
        except KeyError:
            print("Provided keys invalid. Available keys are: state, job, blocktemp, lidtemp, elapsedsecs, secsleft, minsleft, hoursleft, timeleft, currentstep, cycle, program, nonce.")

    def printstatus(self):
        'Calls readstatus and prints useful information to stdout.'
        assert(self.devicepath)
        S = self.readstatus()
        if S['state'] == 'complete':
            print("Program complete.")
            return None
        if S['state'] == 'stopped':
            print("System idle. No program running.")
            return None
        PrettyStatus = '''Current Program: {0}
 Step '{1}' of cycle {2}
 Currently: {3}
 Block: {4}°C, Lid: {5}°C
 Remaining Time: {6}'''.format(S['program'],S['currentstep'],str(S['cycle']),S['job'],str(S['blocktemp']),str(S['lidtemp']),S['timeleft'])
        print(PrettyStatus)


import os
import tweepy as tw
import pandas as pd

consumer_key= ''
consumer_secret= ''
access_token= ''
access_token_secret= ''

auth = tw.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tw.API(auth, wait_on_rate_limit=True)

# Define the search term and the data_since date
search_words = "basketball -filter:retweets" # keyword to search for
# date format as 2018-11-16
date_since = "2020-02-13"
# Collect tweets
tweets = tw.Cursor(api.search,
                   q=search_words,
                   lang="en",
                   since=date_since).items(100) # amt of tweets to return

users_locs = [[tweet.user.screen_name, tweet.user.location] for tweet in tweets]
print(users_locs)

tweet_text = pd.DataFrame(data=users_locs,   # creates table
                          columns=['user', "location"])
print(tweet_text)


from math import sqrt
def modi(ls,k):
    '''Per ogni elemento della lista, controlla se i suoi divisori propri siano quanti richiesti,
    altrimenti l'elemento viene eliminato dalla lista. In seguito ritorna una lista formata dai soli elementi primi della lista iniziale'''
    num_primi=[]
    lista_sottraendo=[]
    for elemento in ls:
        div_propri=0
        primo=True
        analizza_lista(elemento,k,div_propri,primo,num_primi,lista_sottraendo)
    for elemento in lista_sottraendo:ls.remove(elemento)
    return num_primi

def analizza_lista(elemento,k,div_propri,primo,num_primi,lista_sottraendo):
    for divisore in range(2,int(sqrt(elemento))+2):
        if elemento%divisore == 0:
            div_propri+=1
            primo=False
            if not divisore == elemento/divisore: div_propri+=1
            if div_propri>k: break
    genera_liste(elemento,k,div_propri,primo,num_primi,lista_sottraendo)

def genera_liste(elemento,k,div_propri,primo,num_primi,lista_sottraendo):
    if not div_propri == k:lista_sottraendo.append(elemento)
    if primo ==True:num_primi.append(elemento)


class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        output = list()
        if not matrix:
            return output
        self.append(matrix, output, 0)
        return output

    def append(self, matrix: List[List[int]], output: List[int], cur: int) -> None:

        m, n = len(matrix), len(matrix[0])

        if cur > (min(m, n) - 1) // 2:
            return

        output.extend(matrix[cur][cur: n - cur])
        for i in range(cur + 1, m - cur):
            output.append(matrix[i][n - cur - 1])

        if cur == m // 2 or cur == n // 2:
            return

        output.extend(matrix[m - cur - 1][cur: n - cur - 1][::-1])
        for i in range(m - cur - 2, cur, -1):
            output.append(matrix[i][cur])

        self.append(matrix, output, cur + 1)


try:
    from egovScDoc.spiders.docSpider.base_spider import *
except ImportError:
    from egovResearch.egovScDoc.spiders.docSpider.base_spider import *

class XiningSpider(BaseSpider):
    __city_abbreviation__ = "xining"

    # ---/---更新页码信息
    def _update_page_count(self):
        """
        更新页码信息
        :return:
        """
        base_url = "http://www.xining.gov.cn/webaspx/view_list.aspx?portalid=1&lmid={class_id}&pages={page_index}"

        for config in self.config_list:
            request_url = base_url.format(class_id=config.class_id, page_index=config.loop_start)
            res = requests.get(request_url, headers=requests_header)
            soup = BeautifulSoup(res.text, "lxml")
            td = soup.find("td",attrs={
                "class":"heiyh15",
                "align":"center",
                "valign":"middle"
            })
            pages = re.findall("共(\d+)页", td.text)

            page_count = int(pages[0]) + 1
            print(" --page_num--:", page_count)
            config.loop_stop = page_count
            config.update()

    def resolve_detail_page(self, item, html):
        soup = BeautifulSoup(html, 'lxml')
        origin_content = soup.find("font", id="Zoom")
        item.update_content(origin_content)
        item.update()

    def save_all_files(self):
        base_url = "http://www.xining.gov.cn/webaspx/view_list.aspx?portalid=1&lmid={class_id}&pages={page_index}"
        config_list = self.config_list
        for config in config_list:
            for i in range(config.loop_start, config.loop_stop):
                page_dir = "{}{}\{}".format(self.base_dir, config.class_id, i + config.page_start)
                request_url = base_url.format(class_id=config.class_id,page_index=i)
                res = requests.get(request_url, headers=requests_header)
                soup = BeautifulSoup(res.text, "lxml")
                trs = soup.find_all("tr", attrs={
                    "bgcolor": "#ffffff"
                })
                time.sleep(3)
                if not os.path.exists(page_dir):
                    os.makedirs(page_dir)
                for tr in trs:
                    tds = tr.find_all("td")
                    a = tds[0].find("a")
                    url = a.get("href")
                    title = a.get("title").strip().replace("", "").strip()
                    release_time = tds[-1].text

                    item = EGOVSCPolicyPaper()
                    item.release_time = release_time
                    item.title = title
                    item.url = url
                    item.origin_page_index = i
                    item.remarks = config.remarks
                    item.save(self)

                    sub_res = requests.get(url, headers=requests_header)
                    sub_res.encoding = "utf-8"
                    with open("{}\{}.html".format(page_dir, item.id), "w",
                              encoding=self.html_encoding) as f:
                        f.write(sub_res.text)
                    self.resolve_detail_page(item, sub_res.text)
                    time.sleep(3)

if __name__ == '__main__':
    with app.app_context():
        XiningSpider(True).update()


from django.conf.urls import url

from .views import blog_list, create_blog, blog_detail, blog_delete

urlpatterns = [

    url(r'^list/', blog_list, name='list'),
    url(r'^create/', create_blog, name='create'),
    url(r'^detail/(?P<pk>\d+)$', blog_detail, name='detail'),
   # url(r'^update/(?P<pk>\d+)$', TweetUpdateView.as_view(), name='update'),
    url(r'^delete/(?P<pk>\d+)$',blog_delete, name='delete'),

]


from boto3.session import Session

import json
import urllib.parse
import boto3
import tempfile
import traceback
import botocore
import zipfile
import os

ECS_REGION = os.environ.get("ECS_REGION")
ECR_REGION = os.environ.get("ECR_REGION")
ECS_CLUSTER = os.environ.get("ECS_CLUSTER")
SERVICE_NAME = os.environ.get("SERVICE_NAME")
FAMILY_NAME = os.environ.get("FAMILY_NAME")
#ECS_TASK_CPU = int(os.environ.get("ECS_TASK_CPU"))
#ECS_TASK_MEMORY = int(os.environ.get("ECS_TASK_MEMORY"))
#ECS_TASK_PORT = int(os.environ.get("ECS_TASK_PORT"))
DESIRED_COUNT = int(os.environ.get("DESIRED_COUNT"))
MAX_HEALTHY_PERCENT = int(os.environ.get("MAX_HEALTHY_PERCENT"))
MIN_HEALTH_PERCENT = int(os.environ.get("MIN_HEALTH_PERCENT"))

ecs_client = boto3.client('ecs',region_name=ECS_REGION)
code_pipeline = boto3.client('codepipeline')

def setup_s3_client(job_data):
    """Creates an S3 client

    Uses the credentials passed in the event by CodePipeline. These
    credentials can be used to access the artifact bucket.

    Args:
        job_data: The job data structure

    Returns:
        An S3 client with the appropriate credentials

    """
    key_id = job_data['artifactCredentials']['accessKeyId']
    key_secret = job_data['artifactCredentials']['secretAccessKey']
    session_token = job_data['artifactCredentials']['sessionToken']

    session = Session(aws_access_key_id=key_id,
        aws_secret_access_key=key_secret,
        aws_session_token=session_token)
    return session.client('s3', config=botocore.client.Config(signature_version='s3v4'))

def updateECService(imageTag):
    # Get the latest task definition
    response = ecs_client.describe_task_definition(
        taskDefinition=FAMILY_NAME
    )
    familyName = response['taskDefinition']['family']
    revision = response['taskDefinition']['revision']
    task_def = response['taskDefinition']['containerDefinitions'][0]
    preImage = task_def['image']
    tagStart = preImage.find(':')+1
    tagEnd = len(preImage)
    tag = preImage[tagStart:tagEnd]
    imageRepo = preImage[:tagStart]
    print("Image Old Tag:"+tag+",Image New Tag:"+imageTag)
    print("imageRepo:"+imageRepo)
    task_def['image']=imageRepo+imageTag

    response = ecs_client.register_task_definition(
       family=familyName,
       containerDefinitions=[
          task_def
       ]
    )
    print("Register Task Response: " + json.dumps(response, indent=2))
    revision = response['taskDefinition']['revision']
    srvUpdatResponse = ecs_client.update_service(
        cluster=ECS_CLUSTER,
        service=SERVICE_NAME,
        desiredCount=DESIRED_COUNT,
        taskDefinition=FAMILY_NAME+':'+str(revision),
        deploymentConfiguration={
          'maximumPercent': MAX_HEALTHY_PERCENT,
          'minimumHealthyPercent': MIN_HEALTH_PERCENT
        }
    )

def put_job_success(job, message):
    """Notify CodePipeline of a successful job

    Args:
        job: The CodePipeline job ID
        message: A message to be logged relating to the job status

    Raises:
        Exception: Any exception thrown by .put_job_success_result()

    """
    print('Putting job success')
    print(message)
    code_pipeline.put_job_success_result(jobId=job)

def put_job_failure(job, message):
    """Notify CodePipeline of a failed job

    Args:
        job: The CodePipeline job ID
        message: A message to be logged relating to the job status

    Raises:
        Exception: Any exception thrown by .put_job_failure_result()

    """
    print('Putting job failure')
    print(message)
    code_pipeline.put_job_failure_result(jobId=job, failureDetails={'message': message, 'type': 'JobFailed'})

def lambda_handler(event, context):
    """
     Args:
        event: The event passed from code pipeline
    """
    print("Received event: " + json.dumps(event, indent=2))
    ACCOUNT_ID = context.invoked_function_arn.split(":")[4]

    try:
        # Extract the Job ID
        job_id = event['CodePipeline.job']['id']
        # Extract the Job Data
        job_data = event['CodePipeline.job']['data']
         # Get the list of artifacts passed to the function
        artifacts = job_data['inputArtifacts']
        imageTabArtifact = artifacts[0]
        imageTagData = {}

        if 'continuationToken' in job_data:
            # If we're continuing then the update ecs service has already been triggered
            # we will do nothing.
            put_job_success(job_id, 'There were ongoing ecs service updates')
        else:
            s3 = setup_s3_client(job_data)
            tmp_file = tempfile.NamedTemporaryFile()
            bucket = imageTabArtifact['location']['s3Location']['bucketName']
            key = imageTabArtifact['location']['s3Location']['objectKey']
            with tempfile.NamedTemporaryFile() as tmp_file:
                s3.download_file(bucket, key, tmp_file.name)
                with zipfile.ZipFile(tmp_file.name, 'r') as zip:
                    imageTagData = json.loads(zip.read('build.json').decode())

            print("Downloaded Image Tab  : " + json.dumps(imageTagData, indent=2))
            imageTag = imageTagData['tag']
            updateECService(imageTag)
            put_job_success(job_id, 'Update ecs serivce using the new docker image tag'+imageTag)

    except Exception as e:
        # If any other exceptions which we didn't expect are raised
        # then fail the job and log the exception message.
        print('Function failed due to exception.')
        print(e)
        traceback.print_exc()
        put_job_failure(job_id, 'Function exception: ' + str(e))

    print('Function complete.')
    return "Complete."