import os
import json
import time
from django.shortcuts import render
from django.http import JsonResponse

# Create your views here.
def main(request):
    context = {}
    return render(request, 'rml/main.html', context)

def about(request):
    context = {}
    return render(request, 'rml/about.html', context)

def jam(request, session_id=1):
    context = {
        'session_id': session_id,
        'jam': get_the_jam(session_id),
    }
    return render(request, 'rml/jam.html', context)

# API part
JUMP_TO_FUTURE = 6  # s
INTERVAL = 0.5
NUM_OF_FRAMES = 120
COLORS = ['#000000', '#FFFFFF']

def next_color(color):
    index = COLORS.index(color)
    if index + 1 == len(COLORS):
        return COLORS[0]
    return COLORS[index + 1]

def get_the_jam(session_id):
    d = os.path.dirname
    jam_path = os.path.join(d(d(__file__)), 'static', 'jams', str(session_id))
    if not os.path.exists(jam_path):
        return None
    intervals_path = os.path.join(jam_path, 'intervals.txt')
    jam = {}
    jam['intervals'] = [float(line.strip().strip(','))
                        for line in open(intervals_path)]
    logo_path = os.path.join(jam_path, 'logo.png')
    if os.path.exists(logo_path):
        jam['logo_path'] = logo_path
    song_path = os.path.join(jam_path, 'song.mp3')
    if os.path.exists(song_path):
        jam['song_path'] = song_path
    meta_path = os.path.join(jam_path, 'meta.json')
    if os.path.exists(meta_path):
        with open(meta_path) as json_file:
            jam['meta'] = json.load(json_file)
    return jam

def api_dj(request, session_id=1):
    data = {}
    # number of connected clients in the grid
    data['num_of_clients'] = 6
    data['frames'] = []
    start_time = int(time.time()) + JUMP_TO_FUTURE
    color = COLORS[0]
    # num_of_frames = NUM_OF_FRAMES
    # for frame_index in range(num_of_frames):jam
    jam = get_the_jam(session_id)
    if not jam:
        return JsonResponse(data)
    intervals = jam['intervals']
    the_time = start_time * 1000
    for interval in intervals:
        frame = {}
        # interval = frame_index * INTERVAL
        the_time += interval * 1000
        frame['timestamp'] = the_time
        frame['color'] = color
        color = next_color(color)
        data['frames'].append(frame)
    repsonse = JsonResponse(data)
    return repsonse


import requests
from bs4 import BeautifulSoup

if __name__ == '__main__':
    server = 'http://www.748219.com/meiwen/'
    target = 'http://www.748219.com/meiwen/13625.html'
    req = requests.get(url=target)
    req.encoding = req.apparent_encoding
    html = req.text
    bf = BeautifulSoup(html)
    # print(bf)
    # texts = bf.find_all('div', class_='article')  # 筛选出正文，class属性是article
    texts = bf.find_all('div', class_='box')
    a_bf = BeautifulSoup(str(texts))
    li = a_bf.find_all('li')
    lli = BeautifulSoup(str(li))
    a = lli.find_all('a')
    # print(a)
    # print(texts)
    # texts = bf.find_all('span', class_='next')
    # print(texts)
    # a_df = BeautifulSoup(str(texts[0]))
    # print(a_df)
    # a = bf.find_all('a')
    for each in a:
        # print(each)
        print(each.string, each.get('href'))


# coding=utf-8
"""
.. moduleauthor:: Torbjörn Klatt <t.klatt@fz-juelich.de>
"""
from pypint.communicators.i_communication_provider import ICommunicationProvider
from pypint.utilities import assert_condition, assert_named_argument
from pypint.utilities.logging import this_got_called

class ForwardSendingMessaging(ICommunicationProvider):
    """A linear forward-directed communication pattern
    """
    def __init__(self, *args, **kwargs):
        super(ForwardSendingMessaging, self).__init__(*args, **kwargs)
        self._previous = None
        self._next = None

    def send(self, *args, **kwargs):
        """Sends given message to the next communicator

        See Also
        --------
        :py:meth:`.ICommunicationProvider.write_buffer`
            for allowed arguments
        """
        super(ForwardSendingMessaging, self).send(*args, **kwargs)
        # this_got_called(self, *args, **kwargs)
        self._next.write_buffer(*args, **kwargs)

    def receive(self, *args, **kwargs):
        """Returns this communicator's buffer

        Returns
        -------
        message : :py:class:`.Message`
        """
        super(ForwardSendingMessaging, self).receive(*args, **kwargs)
        if 'tag' in kwargs:
            # this_got_called(self, *args, add_log_msg=str(self.tagged_buffer(tag=kwargs['tag'])), **kwargs)
            return self.tagged_buffer(tag=kwargs['tag'])
        else:
            # this_got_called(self, *args, add_log_msg=str(self.buffer), **kwargs)
            return self.buffer

    def link_solvers(self, *args, **kwargs):
        """Links the given communicators with this communicator

        Parameters
        ----------
        previous : :py:class:`.ForwardSendingMessaging`
            communicator of the previous solver
        next : :py:class:`.ForwardSendingMessaging`
            communicator of the next solver

        Raises
        ------
        ValueError
            if one of the two communicators of the specified type is not given
        """
        super(ForwardSendingMessaging, self).link_solvers(*args, **kwargs)
        assert_condition(len(kwargs) == 2,
                         ValueError, message="Exactly two communicators must be given: NOT %d" % len(kwargs),
                         checking_obj=self)

        assert_named_argument('previous', kwargs, types=ForwardSendingMessaging, descriptor="Previous Communicator",
                              checking_obj=self)
        self._previous = kwargs['previous']

        assert_named_argument('next', kwargs, types=ForwardSendingMessaging, descriptor="Next Communicator",
                              checking_obj=self)
        self._next = kwargs['next']


import discord
import asyncio
import CobraMusic

client = discord.Client()
BAN_WORDS= ["pokeball","carapuce","dresseurs","javascript","giratina","yeet"]

"""
Commandes possibles:
    - !hello
    - !carapuce
    - !embed
    - !play url_vidéo

    - Mot banni --> mp d'averissement
"""

@client.event
async def on_ready():
  print("Capitaine Salamèche à la rescousse !")

@client.event
async def on_message(message):
  print(message.content)

  if message.content=="!hello":
    member_name = message.author.name
    guild_name = message.guild.name
    new_msg = await message.channel.send("Salut "+member_name+". Tu te trouves sur "+guild_name)
    await new_msg.pin()

  if message.content=="!carapuce":
    await message.channel.send("OH NO")

  if message.content=="!embed":
    em = discord.Embed(title="titre", description="description (wow c'est fou)", colour=0xFF0000, timestamp=message.created_at)
    em.add_field(name="Un field", value="Youpi", inline=True)
    em.add_field(name="Un autre field", value="o/", inline=True)
    em.add_field(name="Un field pas sur la même ligne", value="grace au 'inline'", inline=False)
    em.set_author(name="Un gars super", icon_url=message.author.avatar_url)
    em.set_footer(text="Sur un super serveur", icon_url=message.guild.icon_url)
    em.set_image(url="https://cdn.discordapp.com/attachments/"+"567630033246617621/581496185424969749/1733852_0.jpg")
    await message.channel.send(embed=em)

  if message.content!="!carapuce":
    msgNO=False
    for word in BAN_WORDS:
      if word in message.content.lower():
          msgNO=True
          break
    if message.author != client.user and msgNO==True:
      print("ALERTE: MOT INTERDIT UTILISE")
      await message.delete()
      ID= message.author.id
      print(ID)
      await message.author.send("ATTENTION : Sur le serveur"+ message.guild.name +", vous avez envoyé le message : "+ message.content +". Ce message contient le mot interdit "+ word +". Veuillez ne pas renvoyer de message contenant de mot interdit sur ce serveur")

  if "!play " in message.content:
    split= message.content.split(" ")
    print(split)
    music_client = await CobraMusic.get_client(message, client)
    await music_client.play(split[1])

client.run ("TOKEN")


from django.shortcuts import render, redirect
from .models import TaskList, Task
from .forms import TaskForm
from django.contrib.auth.decorators import login_required

# Create your views here.

# def index(request):
#     # this data is comming from database
#     lists = TaskList.objects.all()
#     tasks = Task.objects.all()
#     return render(request, 'trello_app/index.html', {'lists': lists, 'tasks': tasks})

# decorator: decorating your view with some additional logic, magically
# if user is logged in then only show the add list page, otherwise redirect to login_url(redirection _url)
@login_required(login_url='login')
def create_list(request):
    if request.method == 'POST':
        # fetch the data and save it in he DB
        list_name = request.POST['list_name']
        # associat user
        list = TaskList(name = list_name, user=request.user)
        list.save()
        # return render(request, 'trello_app/new_list.html')
        # return redirect('index')
        return redirect('home')
    else:
        return render(request, 'trello_app/new_list.html')

@login_required(login_url='login')
def create_task(request):
    if request.method == 'POST':
        #fetch the data and save it in the DB
        form = TaskForm(data=request.POST)
        # associat user
        form.instance.user = request.user
        if form.is_valid():
            form.save()
            # return redirect('index')
            return redirect('home')
    else:
        form = TaskForm()

    # same form object will get rendered in case of error
    return render(request, 'trello_app/new_task.html', {'form' : form})


from CTL.causal_tree.ctl.binary_ctl import *
from sklearn.model_selection import train_test_split

class BaseCausalTreeLearnNode(CTLearnNode):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        # self.obj = obj

# ----------------------------------------------------------------
# Base causal tree (ctl, base objective)
# ----------------------------------------------------------------
class CausalTreeLearnBase(CTLearn):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.root = BaseCausalTreeLearnNode()

    def fit(self, x, y, t):
        if x.shape[0] == 0:
            return 0

        # ----------------------------------------------------------------
        # Seed
        # ----------------------------------------------------------------
        np.random.seed(self.seed)

        # ----------------------------------------------------------------
        # Verbosity?
        # ----------------------------------------------------------------

        # ----------------------------------------------------------------
        # Split data
        # ----------------------------------------------------------------
        train_x, val_x, train_y, val_y, train_t, val_t = train_test_split(x, y, t, random_state=self.seed, shuffle=True,
                                                                          test_size=self.val_split)
        self.root.num_samples = train_y.shape[0]
        # ----------------------------------------------------------------
        # effect and pvals
        # ----------------------------------------------------------------
        effect = tau_squared(y, t)
        p_val = get_pval(y, t)
        self.root.effect = effect
        self.root.p_val = p_val

        # ----------------------------------------------------------------
        # Not sure if i should eval in root or not
        # ----------------------------------------------------------------
        node_eval, mse = self._eval(train_y, train_t, val_y, val_t)
        self.root.obj = node_eval

        # ----------------------------------------------------------------
        # Add control/treatment means
        # ----------------------------------------------------------------
        self.root.control_mean = np.mean(y[t == 0])
        self.root.treatment_mean = np.mean(y[t == 1])

        self.root.num_samples = x.shape[0]

        self._fit(self.root, train_x, train_y, train_t, val_x, val_y, val_t)

    def _fit(self, node: BaseCausalTreeLearnNode, train_x, train_y, train_t, val_x, val_y, val_t):

        if train_x.shape[0] == 0 or val_x.shape[0] == 0:
            return node

        if node.node_depth > self.tree_depth:
            self.tree_depth = node.node_depth

        if self.max_depth == self.tree_depth:
            if node.effect > self.max_effect:
                self.max_effect = node.effect
            if node.effect < self.min_effect:
                self.min_effect = node.effect
            self.num_leaves += 1
            node.leaf_num = self.num_leaves
            node.is_leaf = True
            return node

        best_gain = 0.0
        best_attributes = []
        best_tb_obj, best_fb_obj = (0.0, 0.0)

        column_count = train_x.shape[1]
        for col in range(0, column_count):
            unique_vals = np.unique(train_x[:, col])

            if self.max_values is not None:
                if self.max_values < 1:
                    idx = np.round(np.linspace(
                        0, len(unique_vals) - 1, self.max_values * len(unique_vals))).astype(int)
                    unique_vals = unique_vals[idx]
                else:
                    idx = np.round(np.linspace(
                        0, len(unique_vals) - 1, self.max_values)).astype(int)
                    unique_vals = unique_vals[idx]

            # using the faster evaluation with vector/matrix calculations
            try:
                if self.feature_batch_size is None:
                    split_obj, upper_obj, lower_obj, value = self._eval_fast(train_x, train_y, train_t, val_x, val_y,
                                                                             val_t,
                                                                             unique_vals, col)
                    gain = -node.obj + split_obj
                    if gain > best_gain:
                        best_gain = gain
                        best_attributes = [col, value]
                        best_tb_obj, best_fb_obj = (upper_obj, lower_obj)
                else:

                    for x in batch(unique_vals, self.feature_batch_size):
                        split_obj, upper_obj, lower_obj, value = self._eval_fast(train_x, train_y, train_t, val_x,
                                                                                val_y, val_t, x, col)

                        gain = -node.obj + split_obj
                        if gain > best_gain:
                            best_gain = gain
                            best_attributes = [col, value]
                            best_tb_obj, best_fb_obj = (upper_obj, lower_obj)
            # if that fails (due to memory maybe?) then use the old calculation
            except:
                for value in unique_vals:

                    (val_x1, val_x2, val_y1, val_y2, val_t1, val_t2) \
                        = divide_set(val_x, val_y, val_t, col, value)

                    # check validation set size
                    val_size = self.val_split * self.min_size if self.val_split * self.min_size > 2 else 2
                    if check_min_size(val_size, val_t1) or check_min_size(val_size, val_t2):
                        continue

                    # check training data size
                    (train_x1, train_x2, train_y1, train_y2, train_t1, train_t2) \
                        = divide_set(train_x, train_y, train_t, col, value)
                    check1 = check_min_size(self.min_size, train_t1)
                    check2 = check_min_size(self.min_size, train_t2)
                    if check1 or check2:
                        continue

                    tb_eval, tb_mse = self._eval(train_y1, train_t1, val_y1, val_t1)
                    fb_eval, fb_mse = self._eval(train_y2, train_t2, val_y2, val_t2)

                    split_eval = (tb_eval + fb_eval)
                    gain = -node.obj + split_eval

                    if gain > best_gain:
                        best_gain = gain
                        best_attributes = [col, value]
                        best_tb_obj, best_fb_obj = (tb_eval, fb_eval)

        if best_gain > 0:
            node.col = best_attributes[0]
            node.value = best_attributes[1]

            # print(node.col)

            (train_x1, train_x2, train_y1, train_y2, train_t1, train_t2) \
                = divide_set(train_x, train_y, train_t, node.col, node.value)

            (val_x1, val_x2, val_y1, val_y2, val_t1, val_t2) \
                = divide_set(val_x, val_y, val_t, node.col, node.value)

            y1 = np.concatenate((train_y1, val_y1))
            y2 = np.concatenate((train_y2, val_y2))
            t1 = np.concatenate((train_t1, val_t1))
            t2 = np.concatenate((train_t2, val_t2))

            best_tb_effect = ace(y1, t1)
            best_fb_effect = ace(y2, t2)
            tb_p_val = get_pval(y1, t1)
            fb_p_val = get_pval(y2, t2)

            self.obj = self.obj - node.obj + best_tb_obj + best_fb_obj

            # ----------------------------------------------------------------
            # Ignore "mse" here, come back to it later?
            # ----------------------------------------------------------------

            tb = BaseCausalTreeLearnNode(obj=best_tb_obj, effect=best_tb_effect, p_val=tb_p_val,
                                         node_depth=node.node_depth + 1,
                                         num_samples=y1.shape[0])
            fb = BaseCausalTreeLearnNode(obj=best_fb_obj, effect=best_fb_effect, p_val=fb_p_val,
                                         node_depth=node.node_depth + 1,
                                         num_samples=y2.shape[0])

            node.true_branch = self._fit(tb, train_x1, train_y1, train_t1, val_x1, val_y1, val_t1)
            node.false_branch = self._fit(fb, train_x2, train_y2, train_t2, val_x2, val_y2, val_t2)

            if node.effect > self.max_effect:
                self.max_effect = node.effect
            if node.effect < self.min_effect:
                self.min_effect = node.effect

            return node

        else:
            if node.effect > self.max_effect:
                self.max_effect = node.effect
            if node.effect < self.min_effect:
                self.min_effect = node.effect

            self.num_leaves += 1
            node.leaf_num = self.num_leaves
            node.is_leaf = True
            return node


from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404
from django.views.generic.base import View
from stickable.models import User, Task
from utils.response import json_response
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt

class ApiView(View):

    request = None

    class Meta:
        abstract = True

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        self.request = request
        return super(ApiView, self).dispatch(request, *args, **kwargs)

    def _error(self, message):
        data = {
            'error': True,
            'message': message
        }
        return json_response(data)

    def _success(self):
        data = {
            'error': False,
            'success': True
        }
        return json_response(data)

    def _get_user(self, username, require_auth=True):
        user = get_object_or_404(User, username=username)
        if require_auth:
            if not self.request.user.is_authenticated:
                raise PermissionDenied
            if self.request.user.id != user.id:
                raise PermissionDenied

        return user

    def _get_task(self, id):
        task = get_object_or_404(Task, id=id)
        return task


from sklearn.linear_model import Ridge
from sklearn.model_selection import KFold
from sklearn.model_selection import GridSearchCV
from sklearn import metrics
import numpy as np
from . import learning_methods
tunned_alpha = [0.1,0.3,0.5,1,1.2,1.5,2]

class ridge_CV(learning_methods.learning_methods):
    def __init__(self,x,y,metric,metric_proba = False,scoring = 'neg_mean_squared_error',n_jobs=2,save_model=False,processed_data_version_dir='./'):
        """
        初始化相关参数

        args:
            x: numpy array
            y: numpy array
            metric: sklearn 中的函数，用来在交叉验证中评估验证集上的效果，不过auc 不行，因为auc的参数 不是 (y_true,y_pred) 的形式
                 optional: http://scikit-learn.org/stable/modules/classes.html#sklearn-metrics-metrics
            metric_proba: False, 表示 metric 函数是否接受模型输出0-1之间的概率值
            labels: 默认为[0,1]， 在分类任务中，进行预测时可能所有预测数据集都是正类或都是负类，这个参数是用来告诉metric 应该是又两个类
            scoring: 用sklearn自带的 GridSearchCV 时需要的评估函数, 一般是越大越好。默认为 neg_mean_squared_error
                    可选项: 'neg_log_loss' 'roc_auc' ,'neg_mean_squared_error' 等
            n_jobs: 多少个线程,默认为2
            save_model: True or False, 表示是否保存模型,保存路径为 processed_data_version_dir/modules/
            processed_data_version_dir: 存放log 或者保存模型的目录,默认为 ./
        """
        super(ridge_CV,self).__init__(x,y,metric,metric_proba=metric_proba,scoring=scoring,save_model=save_model,processed_data_version_dir=processed_data_version_dir)
        #normalize
        self.model = Ridge(alpha=1,normalize=True)
        self.n_jobs=n_jobs

    #scoring : neg_mean_squared_error
    def cross_validation(self):
        scoring = self.scoring
        self.train_score()
        self.cv_score()
        params = {'alpha':tunned_alpha}
        gsearch = GridSearchCV(estimator=self.model,param_grid=params,scoring=scoring,n_jobs=self.n_jobs,iid=False,cv=3)
        gsearch.fit(self.x,self.y)
        self.model.set_params(alpha = gsearch.best_params_['alpha'])
        print('best alpha for ridge:{}'.format(gsearch.best_params_['alpha']))
        self.cv_score()
        self.train_score()
        self.plot_save(name='ridge')
        return self.model

if __name__ == '__main__':
    x= None
    y = None
    metrics = None
    obj = ridge_cv(x,y,metrics)


# Stack implementation

# Amila Ferron
# CS300
# April 14, 2020

# Implements a flexible array for a stack -- a linked list of arrays

import random

# The size of each array
SIZE = 3

# The maximum value for the numbers added to the stack for testing
MAX_VALUE = 37

# The maximum number of entries that will be added to the stack for testing
MAX_ENTRIES = 23

# Array class has a list and a pointer to the next array.
class Array:

    # Creates a list, sets top to 0, and the next pointer to none
    def __init__(self):
        self.data = []
        self.top = 0
        self.next = None

    # Appends to the list if the list has not reached maximum size
    # returns 1 if successfully added, None if not
    def push(self, value):
        if self.top >= SIZE:
            return None
        self.data.append(value)
        self.top += 1
        return 1

    # Removes the last data item added, and returns the value of that item
    def pop(self):
        if self.top == 0:
            return None
        if self.top > SIZE:
            return None
        self.top -= 1
        popped = self.data.pop()
        return popped

    # Returns the value of the last item added
    def peek(self):
        if self.top == 0:
            return None
        if self.top > SIZE:
            return None
        return self.data[self.top - 1]

    # Removes all values in the list
    # Returns 1
    def remove_all(self):
        for i in self.data:
            self.data.pop()
        self.top = 0
        return 1

    # Displays all values in the list
    def display(self):
        for i in range(0, self.top):
            print(self.data[i], " ")

# Stack class is a linked list of arrays.
# When an array is at maximum size, a new array is added to the list.
class Stack:

    # Sets head to none
    def __init__(self):
        self.head = None

    # Adds data to the stack, calling a recursive function to add
    # to the end of the stack. It would be more efficient to add
    # at head instead of at the end of the linked list
    # Returns 1 if successful, 0 if not
    def push(self, value):
        if self.head is None:
            self.head = Array()
        if self.head.push(value) is None:
            add = Array()
            add.next = self.head
            self.head = add
            return self.head.push(value)
        return 1

    # Removes the last value added to the stack, returning the value
    def pop(self):
        if self.head is None:
            return None
        popped = self.head.pop()
        if self.head.peek() is None:
            remove = self.head
            self.head = self.head.next
        return popped
        #popped = list()
        #self.head = self._pop(self.head, popped)
        #return popped[0]

    # Recursively traverses to the end of the list to remove the last
    # value added. Appends the value to popped (a list).
    # Returns head.
    def _pop(self, head, popped):
        if head is None:
            return None
        if head.next is None:
            popped.append(head.pop())
            if head.top == 0:
                return None
            return head
        head.next = self._pop(head.next, popped)
        return head

    # Gets the last value added
    def peek(self):
        if self.head is None:
            return None
        return self.head.peek()
        #return self._peek(self.head)

    # Recursively traverses to get the last value added
    def _peek(self, head):
        if head is None:
            return None
        if head.next is None:
            return head.peek()
        return self._peek(head.next)

    # Removes all values in the stack by setting head to None
    def remove_all(self):
        if self.head is not None:
            self.head = None

    # Displays all values in the stack, returning nothing
    def display(self):
        if self.head is not None:
            self._display(self.head)
        print()

    # Recursively traverses the list to display all values in the stack
    # Returns nothing.
    def _display(self, head):
        if head is None:
            return
        self._display(head.next)
        head.display()

    # Randomly get the size of the stack and push random values onto it
    def random_create(self):
        size = random.randint(1, MAX_ENTRIES)
        for i in range(0, size):
            value = random.randint(1, MAX_VALUE)
            self.push(value)

    def test(self):

        # Seed the random number generator
        random.seed()

        # Create a class instance
        info = Stack()

        # Test peek with no data in stack:
        print("Peeking: ", info.peek())

        # Test random create and display
        info.random_create()
        print("The stack: ")
        info.display()

        # Test peek
        print("Peeking: ", info.peek())

        # Test pop
        print("Popping:")
        pop_times = random.randint(1, 5)
        for i in range(0, pop_times):
            print(info.pop())
        print("The stack: ")
        info.display()

        # Test peek
        print("Peeking: ", info.peek())

        # Let the user experience push, peek, and pop:
        push_value = int(input("Enter a number to push onto the stack: "))
        info.push(push_value)
        print("The stack is now: ")
        info.display()
        print("Peeking: ", info.peek())
        print("Popping, the value returned is: ", info.pop())

        # Test remove all
        info.remove_all()
        print("The stack after remove all: ")
        info.display()


import datetime
import os

from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render

from adaptation.conflicts.classes import SeleniumPhantomJSDriver
from adaptation.core.adapters import Adapter
from adaptation.core.classes import Getter
from adaptation.core.functions import handle_adapt_request
from adaptation.core.themes import UploadedTheme
from .forms import WpAdaptForm, JoomlaAdaptForm, ConflictsForm

def wordpress_adaptation(request):
    return handle_adapt_request(request, WpAdaptForm, 'WordPress')

def joomla_adaptation(request):
    return handle_adapt_request(request, JoomlaAdaptForm, 'Joomla')

def wp_test(request):
    get_dict = request.GET.dict()

    file_name = get_dict.get('file', 'snowboarding')
    file = file_name + '.zip'
    example = os.path.join(settings.BASE_DIR, 'examples', 'wp', file)

    form_data = {
        'name': file_name,
        'file': example,
        'form': 'WordPress',
        'version': 461,
        'author': '',
        'description': '',
        'license': '',
        'tags': '',
        'comments': '',
    }

    adapter = Adapter()
    result_href = adapter.adapt(form_data)

    return HttpResponse('Скачать')

def joomla_test(request):
    get_dict = request.GET.dict()

    file_name = get_dict.get('file', 'snowboarding')
    file = file_name + '.zip'
    example = os.path.join(settings.BASE_DIR, 'examples', 'wp', file)

    form_data = {
        'name': file_name,
        'file': example,
        'form': 'Joomla',
        'version': 362,
        'language': 'en-GB',
        'creationDate': datetime.datetime.now().strftime("%d-%m-%Y"),
        'author': '',
        'authorEmail': '',
        'copyright': '',
        'license': '',
        'authorUrl': '',
    }

    adapter = Adapter()
    result_href = adapter.adapt(form_data)

    return HttpResponse('Скачать')

def conflicts(request):
    if request.method == 'POST':
        form = ConflictsForm(request.POST, request.FILES)
        file = form.save_file()
        cfg = Getter.get_user_cfg()["CONFLICTS"]

        if request.POST.get('use_defaults', '') != 'on':
            cfg['urls']['wordpress_url'] = request.POST['wordpress_url']
            cfg['urls']['joomla_url'] = request.POST['joomla_url']

        driver = SeleniumPhantomJSDriver()
        theme = UploadedTheme(file, 'conflicts')
        theme.unpack()
        theme.read_files()
        index_file = theme.get_file('index.html')
        result = {
            'engines': {},
            'intersection': {},
            'theme': driver.execute_script(index_file.path, cfg["script"])
        }

        for key, url in cfg['urls'].items():
            script_result = driver.execute_script(url, cfg["script"])
            result['engines'][key] = script_result
            result['intersection'][key] = list(set(script_result) & set(result['theme']))

        # return JsonResponse(result)
        return render(request, 'base/conflicts_result.html', {
            'result': result,
            'title': "Поиск конфликтов",
            'page_header': "Результаты проверки"
        })

    else:
        return render(request, 'base/conflicts.html', {
            'title': "Поиск конфликтов",
            "page_header": "Поиск конфликтов",
            'panel_heading': 'Проверьте данные проверки конфликтов',
            'panel_type': 'panel-info',
            'submit_btn_type': 'btn-outline btn-warning',
            'submit_value': 'Проверить',
            'form_action': '#',
            'hidden': 'conflict',
            'form': ConflictsForm
        })


# Node 클래스 정의
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

# LinkedList 클래스 (자료구조 정의)
class LinkedList:
    # 초기화 메소드
    def __init__(self):
        dummy = Node("dummy")
        self.head = dummy
        self.tail = dummy

        self.current = None
        self.before = None

        self.num_of_data = 0

    # append 메소드 (insert - 맨 뒤에 노드 추가, tail과 node의 next, 데이터 개수 변경)
    def append(self, data):
        new_node = Node(data)
        self.tail.next = new_node
        self.tail = new_node

        self.num_of_data += 1

    # delete 메소드 (delete - current 노드 삭제, 인접 노드의 current, next 변경, 데이터 개수 변경)
    def delete(self):
        pop_data = self.current.data

        if self.current is self.tail:
            self.tail = self.before

        self.before.next = self.current.next
        self.current = self.before  # 중요 : current가 next가 아닌 before로 변경된다.

        self.num_of_data -= 1

        return pop_data

    # first 메소드 (search1 - 맨 앞의 노드 검색, before, current 변경)
    def first(self):
        if self.num_of_data == 0:
            return None

        self.before = self.head
        self.current = self.head.next

        return self.current.data

    # next 메소드 (search2 - current 노드의 다음 노드 검색, 이전에 first 메소드가 한번은 실행되어야 함)
    def next(self):
        if self.current.next == None:
            return None

        self.before = self.current
        self.current = self.current.next

        return self.current.data

    def size(self):
        return self.num_of_data

# LList = LinkedList()
# LList.append(1)
# LList.append(2)
# LList.append(3)
# LList.append(4)
# # LList = ["dummy", 1, 2, 3, 4] 와 같은 모습을 상상하면 된다.
#
# print('first :', LList.first())         # first : 1
# print('second :', LList.next())         # second : 2
# print('third :', LList.next())          # third : 3
# print('tail :', LList.next())           # tail : 4
# print('size :', LList.size())           # size : 4
# LList.first()
# LList.next()
# print('current:', LList.current.data)   # current: 2 (first로 간 다음 next로 한 번 이동하였으므로 두 번째 값)
# print('pop_data :', LList.delete())     # pop_data : 2
# print('current:', LList.current.data)   # current: 1 (delete 메소드 사용 후 탐색 위치는 삭제한 노드 바로 앞)
# print('size :', LList.size())           # size : 3 (노드 하나를 삭제했으므로 size는 3)


import re
from .cmd import _CMD

r"""
NVIDIA Interface
================
- **NVIDIA** : NVIDIA Interface
"""

class NVIDIA(_CMD):
    r"""NIVIDA Interface"""
    def __init__(self, *args, **kargs):
        r"""Initialize the class"""
        # super call
        _CMD.__init__(self, *args, **kargs)

        # set pid2user call
        self.pid2user = getattr(self, "pid2user_{}".format(self.sys))

    def pid2user_win(self, pid):
        r"""Get Username of Given PID (Windows)

        Args
        ----
        pid : int
            PID.

        Returns
        -------
        user : str
            Username.

        """
        # command line call
        out, err = self.term("tasklist /fi \"PID eq {}\" /v".format(pid), fmtout='str')

        # only the last line matters
        line = re.split(r'[\n\r]+', out)[-1]
        user = re.split(r'\s+', line)[7]
        return user

    def pid2user_unix(self, pid):
        r"""Get Username of Given PID (Unix)

        Args
        ----
        pid : int
            PID.

        Returns
        -------
        user : str
            Username.

        """
        # command line call
        out, err = self.term("ps -u -p {}".format(pid), fmtout='str')

        # only the last line matters
        line = re.split(r'[\n\r]+', out)[-1]
        user = re.split(r'\s+', line)[0]
        return user

    @property
    def stat(self):
        r"""Update Monitor Info

        Returns
        -------
        stat : {str: object, ...}
            Lastest NVIDIA state dictionary.

        """
        # get new info
        stat, err = self.term('nvidia-smi -q', fmtout='nsd')

        # get username for each process
        for device in stat['devices']:
            for proc in device['procs']:
                user = self.pid2user(proc['pid'])
                proc['user'] = user
        return stat

    @property
    def afree(self):
        r"""A Free Device

        Returns
        -------
        id : int or None
            A free device ID.

        """
        # get status first
        stat = self.stat

        # find a free device
        for device in stat['devices']:
            if len(device['procs']) == 0:
                return device['id']
            else:
                pass
        return None


##
## Imprima la cantidad de registros por letra para la
## primera columna, ordenados alfabeticamente.
##
## A,8
## B,7
## C,5
## D,6
## E,14
##

# Guarda cada linea del archivo como elemento de una lista
file = open('data.csv', 'r').readlines()

# Quitamos el ultimo caracter de cada elemento
file = [row[0:-1] for row in file]

# Separa los caracteres por tabulacion
file = [row.split('\t') for row in file]
data = file
# print data

result = {}

for element in data:
	result[element[0]] = 0

for element in data:
	result[element[0]] = result[element[0]] + 1

for key in sorted(result.keys()):
     print(key + ',' + str(result[key]))


import matplotlib.pyplot as plt
import numpy as np

# Read the stim data
stim_dat = np.genfromtxt('stim_space.txt', skip_header=1)
# Read the trial data
trial_dat = np.genfromtxt('trial_space.txt', skip_header=1)

# Create an array of zeros to store mw scores in stim space
stim_mw_score = np.zeros(len(stim_dat))

for visit in range(1, 3):

    vix = trial_dat[:, 0]==visit

    participants = np.unique(trial_dat[vix, 1])

    for pid in participants:

        # Get the indices for this participant
        pix = np.logical_and(trial_dat[:, 0]==visit, trial_dat[:, 1]==pid)

        # Get the blocks for this participant
        blocks = np.unique(trial_dat[pix, 3])

        # Loop through the blocks
        for b in blocks:

            # Get the stim and trial indices
            stim_ix = np.logical_and(stim_dat[:, 0]==visit, stim_dat[:, 1]==pid, stim_dat[:, 3]==b)
            trial_ix = np.logical_and(trial_dat[:, 0]==visit, trial_dat[:, 1]==pid, trial_dat[:, 3]==b)

            # Get the trials
            trial_numbers = np.unique(trial_dat[trial_ix, 5])

            # Loop through the trials
            for trial_number in trial_numbers:

                # Get the stim and trial indices
                stim_ix = np.mean((stim_dat[:, 0]==visit, stim_dat[:, 1]==pid,
                                   stim_dat[:, 3]==b, stim_dat[:, 5]==trial_number), 0)==1
                trial_ix = np.mean((trial_dat[:, 0]==visit, trial_dat[:, 1]==pid,
                                    trial_dat[:, 3]==b, trial_dat[:, 5]==trial_number), 0)==1

                # Get the mw score for this trial
                mw_score = trial_dat[trial_ix, 6][0]

                # Fill the stim array
                stim_mw_score[stim_ix] = mw_score

stim_dat_mw = np.zeros((stim_dat.shape[0], stim_dat.shape[1]+1))
stim_dat_mw[:, :-1] = stim_dat
stim_dat_mw[:, -1] = stim_mw_score

np.savetxt('stim_space_mw.txt', stim_dat_mw, delimiter=' ')


import os
import torch
import numpy as np
import torch.nn as nn
from tensorboardX import SummaryWriter

import lib.parser as parser
import lib.baseline_models as model
import lib.baseline_data as data
from lib.baseline_trainer import Trainer

if __name__ == '__main__':

    args = parser.arg_parse()

    if not os.path.exists(args.save_dir):
        os.makedirs(args.save_dir)

    use_cuda = torch.cuda.is_available()

    np.random.seed(args.random_seed)
    torch.manual_seed(args.random_seed)
    torch.cuda.manual_seed(args.random_seed)

    print('===> Preparing data...')

    train_loader = torch.utils.data.DataLoader(data.DATA(args, mode='train'),
                                               batch_size=args.batch_size,
                                               num_workers=args.workers,
                                               shuffle=True)
    val_query_loader = torch.utils.data.DataLoader(data.DATA(args, mode='valid', type='query'),
                                                   batch_size=args.batch_size,
                                                   num_workers=args.workers,
                                                   shuffle=True)
    val_gallery_loader = torch.utils.data.DataLoader(data.DATA(args, mode='valid', type='gallery'),
                                                     batch_size=args.batch_size,
                                                     num_workers=args.workers,
                                                     shuffle=True)

    writer = SummaryWriter(os.path.join(args.save_dir, 'log'))
    print('===> Preparing model...')
    my_model = model.Model()
    if use_cuda:
        my_model.cuda()

    optim = torch.optim.Adam([
        {'params': my_model.parameters()},
    ], lr=args.lr, betas=(0.5, 0.999), weight_decay=args.weight_decay)

    my_trainer = Trainer(model=my_model,
                         train_loader=train_loader,
                         val_query_loader=val_query_loader,
                         val_gallery_loader=val_gallery_loader,
                         optim=optim,
                         args=args,
                         writer=writer,
                         use_cuda=use_cuda
                         )

    print("===> Initializing training...")
    my_trainer.train()


# tf_unet is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# tf_unet is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with tf_unet.  If not, see <http://www.gnu.org/licenses/>.

'''
Created on Jul 28, 2016

author: jakeret
'''
from __future__ import print_function, division, absolute_import, unicode_literals
import tensorflow.contrib as tf_contrib
from tensorflow.contrib.layers.python.layers import layers

import os
import shutil
import numpy as np
import logging
from collections import OrderedDict
from sklearn.metrics import precision_score, recall_score, accuracy_score, f1_score
import tensorflow as tf
from ops import *
from nets.tf_unet.layers import *

logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
weight_init = tf.random_normal_initializer(mean=0.0, stddev=0.1)

def Unet(x, labels, keep_prob=1.0, channels=3, n_class=2, num_layers=5, features_root=64, filter_size=3, pool_size=2,summaries=True, trainable=True, reuse=False, scope='dis'):
    with tf.variable_scope(scope, reuse=reuse):
        print(scope)

        end_points = {}
        logging.info(
        "Layers {layers}, features {features}, filter size {filter_size}x{filter_size}, pool size: {pool_size}x{pool_size}".format(
            layers=layers,
            features=features_root,
            filter_size=filter_size,
            pool_size=pool_size))

    # Placeholder for the input image
        with tf.name_scope("preprocessing"):
            batch_size = tf.shape(x)[0]
            nx = tf.shape(x)[1]
            ny = tf.shape(x)[2]
            in_node = x

        weights = []
        biases = []
        convs = []
        pools = OrderedDict()
        deconv = OrderedDict()
        dw_h_convs = OrderedDict()
        up_h_convs = OrderedDict()

        in_size = 1000
        size = in_size
        # down layers
        for layer in range(0, num_layers):
            with tf.variable_scope("down_conv_{}".format(str(layer)), reuse=reuse):
                features = 2 ** layer * features_root
                stddev = np.sqrt(2 / (filter_size ** 2 * features))
                if layer == 0:
                    w1 = weight_variable([filter_size, filter_size, channels, features], stddev, weight_init, name="w1")
                else:
                    w1 = weight_variable([filter_size, filter_size, features // 2, features], stddev, weight_init, name="w1")

                w2 = weight_variable([filter_size, filter_size, features, features], stddev, weight_init, name="w2")
                b1 = bias_variable([features], weight_init, name="b1")
                b2 = bias_variable([features], weight_init, name="b2")

                in_node = tf.nn.max_pool(in_node,ksize=[1,3,3,1],strides=[1,1,1,1], padding='SAME')
                conv1 = conv2d(in_node, w1, b1, keep_prob,reuse=reuse)
                conv1 = -tf.nn.max_pool(-conv1,ksize=[1,3,3,1],strides=[1,1,1,1], padding='SAME')

                conv1 = tf_contrib.layers.batch_norm(conv1,decay=0.9, epsilon=1e-05,center=True, scale=True, updates_collections=None,is_training=True)
                tmp_h_conv = tf.nn.relu(conv1)

                tmp_h_conv = tf.nn.max_pool(tmp_h_conv,ksize=[1,3,3,1],strides=[1,1,1,1], padding='SAME')
                conv2 = conv2d(tmp_h_conv, w2, b2, keep_prob,reuse=reuse)
                conv2 = -tf.nn.max_pool(-conv2,ksize=[1,3,3,1],strides=[1,1,1,1], padding='SAME')

                conv2 = tf_contrib.layers.batch_norm(conv2,decay=0.9, epsilon=1e-05,center=True, scale=True, updates_collections=None,is_training=True)
                dw_h_convs[layer] = tf.nn.relu(conv2)
                print(dw_h_convs[layer])

                weights.append((w1, w2))
                biases.append((b1, b2))
                convs.append((conv1, conv2))

                size -= 4
                if layer < num_layers - 1:
                    pools[layer] = max_pool(dw_h_convs[layer], pool_size)
                    in_node = pools[layer]
                    size /= 2

        in_node = dw_h_convs[num_layers - 1]

        # up layers
        for layer in range(num_layers - 2, -1, -1):
            with tf.variable_scope("up_conv_{}".format(str(layer)), reuse=reuse):
                features = 2 ** (layer + 1) * features_root
                stddev = np.sqrt(2 / (filter_size ** 2 * features))

                wd = weight_variable_devonc([pool_size, pool_size, features // 2, features], stddev, weight_init, name="wd")
                bd = bias_variable([features // 2], weight_init, name="bd")
                h_deconv = tf.nn.relu(deconv2d(in_node, wd, pool_size,reuse=reuse) + bd)
                h_deconv_concat = tf.concat([dw_h_convs[layer], h_deconv],axis=-1)
                deconv[layer] = h_deconv_concat

                w1 = weight_variable([filter_size, filter_size, features, features // 2], stddev, weight_init, name="w1")
                w2 = weight_variable([filter_size, filter_size, features // 2, features // 2], stddev, weight_init, name="w2")
                b1 = bias_variable([features // 2], weight_init, name="b1")
                b2 = bias_variable([features // 2], weight_init, name="b2")

                h_deconv_concat = tf.nn.max_pool(h_deconv_concat,ksize=[1,3,3,1],strides=[1,1,1,1], padding='SAME')
                conv1 = conv2d(h_deconv_concat, w1, b1, keep_prob,reuse=reuse)
                conv1 = -tf.nn.max_pool(-conv1,ksize=[1,3,3,1],strides=[1,1,1,1], padding='SAME')

                conv1 = tf_contrib.layers.batch_norm(conv1,decay=0.9, epsilon=1e-05,center=True, scale=True, updates_collections=None,is_training=True)
                h_conv = tf.nn.relu(conv1)

                h_conv = tf.nn.max_pool(h_conv,ksize=[1,3,3,1],strides=[1,1,1,1], padding='SAME')
                conv2 = conv2d(h_conv, w2, b2, keep_prob,reuse=reuse)
                conv2 = -tf.nn.max_pool(-conv2,ksize=[1,3,3,1],strides=[1,1,1,1], padding='SAME')

                conv2 = tf_contrib.layers.batch_norm(conv2,decay=0.9, epsilon=1e-05,center=True, scale=True, updates_collections=None,is_training=True)
                in_node = tf.nn.relu(conv2)
                up_h_convs[layer] = in_node
                print(up_h_convs[layer])

                weights.append((w1, w2))
                biases.append((b1, b2))
                convs.append((conv1, conv2))

                size *= 2
                size -= 4

        # Output Map
        with tf.name_scope("output_map"):
            weight = weight_variable([1, 1, features_root, n_class], stddev, weight_init)
            bias = bias_variable([n_class], weight_init, name="bias")
            conv = conv2d(in_node, weight, bias, tf.constant(1.0),reuse=reuse)
            #output_map = tf.nn.relu(conv)
            output_map = conv
            up_h_convs["out"] = output_map
        '''if summaries:
            with tf.name_scope("summaries"):
                for i, (c1, c2) in enumerate(convs):
                    tf.summary.image('summary_conv_%02d_01' % i, get_image_summary(c1))
                    tf.summary.image('summary_conv_%02d_02' % i, get_image_summary(c2))

                for k in pools.keys():
                    tf.summary.image('summary_pool_%02d' % k, get_image_summary(pools[k]))

                for k in deconv.keys():
                    tf.summary.image('summary_deconv_concat_%02d' % k, get_image_summary(deconv[k]))

                ''''''for k in dw_h_convs.keys():
                    #tf.summary.histogram("dw_convolution_%02d" % k + '/activations', dw_h_convs[k])
                    tf.summary.scalar("down_conv_%d" % k + '/gamma1', gamma1)
                    tf.summary.scalar("down_conv_%d" % k + '/gamma2', gamma2)
                    tf.summary.scalar("down_conv_%d" % k + '/gamma3', gamma3)

                for k in up_h_convs.keys():
                    #tf.summary.histogram("up_convolution_%s" % k + '/activations', up_h_convs[k])
                    tf.summary.scalar("up_conv_%d" % k + '/alphabeta1', beta1)
                    tf.summary.scalar("up_conv_%d" % k + '/alphabeta2', beta2)
                    tf.summary.scalar("up_conv_%d" % k + '/alphabeta3', beta3)''''''
                tf.summary.image("out" , get_image_summary(tf.expand_dims(tf.argmax(output_map,-1),-1)))
                tf.summary.image("label" , get_image_summary(tf.expand_dims(tf.argmax(labels,-1),-1)))
                tf.summary.image("offset" , get_image_summary(offset1))
                tf.summary.image("input" , tf.expand_dims(x[0,:,:,:],0))'''

        variables = []
        for w1, w2 in weights:
            variables.append(w1)
            variables.append(w2)

        for b1, b2 in biases:
            variables.append(b1)
            variables.append(b2)

        end_points['Logits'] = output_map
        end_points['Predictions'] = layers.softmax(output_map, scope='predictions')
        end_points['offset'] = layers.softmax(output_map, scope='predictions')

        return output_map,end_points

def get_image_summary(img, idx=0):
    """
    Make an image summary for 4d tensor image with index idx
    """

    V = tf.slice(img, (0, 0, 0, idx), (1, -1, -1, 1))
    V -= tf.reduce_min(V)
    V /= tf.reduce_max(V)
    V *= 255

    img_w = tf.shape(img)[1]
    img_h = tf.shape(img)[2]
    V = tf.reshape(V, tf.stack((img_w, img_h, 1)))
    V = tf.transpose(V, (2, 0, 1))
    V = tf.reshape(V, tf.stack((-1, img_w, img_h, 1)))
    return V


"""CIS 211 Winter 2015
   Haomin He
   Project 4: Building GUIs with Tk

   2. Write a program that computes the monthly payment on a loan. The payment
   is a function of the loan amount, the annual rate, and the number of years
   to pay off the loan.

   I also tried Extra Credit Ideas, in the file called paymentEC.py.

   You should be able to find formulas that will compute any one of the loan
   attributes given values for the other three. For example, given the interest
   rate, loan amount, and payment amount you should be able to calculate the
   number of years before the loan is paid off. Modify your program so it fills
   in any one of the boxes if the other three have been filled in.

"""
import tkinter as tk
from math import log, pow

def calculate():
    readamount = amount.get()
    readrate = rate.get()
    readyears = years.get()
    readmonpay = payment.get()
    if (len(readamount) > 0 and len(readrate) > 0
        and len(readyears) > 0 and len(readmonpay) == 0):
        #To calculate the payment, first compute a value r: as r = rate/100/12
        r = float(readrate) / 100 / 12
        amount_ = float(readamount)
        years_ = float(readyears)

        #value p as: p = 12 * years.
        p = 12 * years_

        #Then the payment is:
        monthly_payment = (r * amount_) / (1 - (1 + r)**(-p))

        payment.delete(0, tk.END)
        payment.insert(0, "{:.2f}".format(monthly_payment))

    elif (len(readamount) > 0 and len(readrate) > 0
        and len(readmonpay) > 0 and len(readyears) == 0):
        r = float(readrate) / 100 / 12
        amount_ = float(readamount)
        monpay = float(readmonpay)

        negp = log(1-(r*amount_)/monpay, 1 + r)

        p = -negp

        years_ = p / 12

        years.delete(0, tk.END)
        years.insert(0, "{:.2f}".format(years_))

    elif (len(readamount) > 0 and len(readmonpay) > 0
        and len(readyears) > 0) and len(readrate) == 0:
        amount_ = float(readamount)
        years_ = float(readyears)
        monpay = float(readmonpay)

        N = 12 * years_

        q = (log(1 + (1/N)) / log(2))

        amt1 = pow((1 + (monpay/amount_)),1/q)
        amt2 = pow(amt1-1,q)

        rate_ = 1200 * (amt2 - 1)

        rate.delete(0, tk.END)
        rate.insert(0, "{:.2f}".format(rate_))

    elif (len(readmonpay) > 0 and len(readrate) > 0
        and len(readyears) > 0) and len(readamount) == 0:
        r = float(readrate) / 100 / 12
        years_ = float(readyears)
        monpay = float(readmonpay)

        p = 12 * years_

        amount_ = (monpay * (1 - (1 + r)**(-p))) / r

        amount.delete(0, tk.END)
        amount.insert(0, "{:.2f}".format(amount_))

root = tk.Tk()

#Entry 1
amountLabel = tk.Label(root, text = "Loan Amount:")
amountLabel.grid(row = 0, column=0, sticky=tk.W, padx = 20, pady = 30)
amount = tk.Entry(root, bd = 5)
amount.grid(row = 0, column = 1, padx = 20)

#Entry 2
rateLabel = tk.Label(root, text = "Interest Rate:")
rateLabel.grid(row = 1, column=0, sticky=tk.W, padx = 20, pady = 30)
rate = tk.Entry(root, bd = 5)
rate.grid(row = 1, column = 1, padx = 20)

#Entry 3
yearsLabel = tk.Label(root, text = "Number of Years:")
yearsLabel.grid(row = 2, column=0, sticky=tk.W, padx = 20, pady = 30)
years = tk.Entry(root, bd = 5)
years.grid(row = 2, column = 1, padx = 20)

#Entry 4
paymentLabel = tk.Label(root, text = "Monthly Payment:")
paymentLabel.grid(row = 3, column=0, sticky=tk.W, padx = 20, pady = 30)
payment = tk.Entry(root, bd = 5)
payment.grid(row = 3, column = 1, padx = 20)

paymentButton = tk.Button(root, text = "Payment", width = 25, command = calculate)
paymentButton.grid(row = 4, column = 0, columnspan = 2, pady = 30)

if __name__ == "__main__":
    root.mainloop()

CIS211 Computer Science II/Projects/p4/paymentEC.py


from django.db import models
from django.core.validators import MinValueValidator
from django.core.validators import MaxValueValidator
from datetime import date
from django.utils.translation import ugettext_lazy as _

class Quote(models.Model):
    """Model for a quote"""
    # TODO Add a carrier code reference to each quote
    # TODO Add a carrier code reference to each quote
    US_STATE = [
        ('AL', 'Alabama'),
        ('AK', 'Alaska'),
        ('AZ', 'Arizona'),
        ('AR', 'Arkansas'),
        ('CA', 'California'),
        ('CO', 'Colorado'),
        ('CT', 'Connecticut'),
        ('DE', 'Delaware'),
        ('DC', 'District of Columbia'),
        ('FL', 'Florida'),
        ('GA', 'Georgia'),
        # Hawaii not available
        # ('HI', 'Hawaii'),
        ('ID', 'Idaho'),
        ('IL', 'Illinois'),
        ('IN', 'Indiana'),
        ('IA', 'Iowa'),
        ('KS', 'Kansas'),
        ('KY', 'Kentucky'),
        ('LA', 'Louisiana'),
        ('ME', 'Maine'),
        ('MD', 'Maryland'),
        ('MA', 'Massachusetts'),
        ('MI', 'Michigan'),
        ('MN', 'Minnesota'),
        ('MS', 'Mississippi'),
        ('MO', 'Missouri'),
        ('MT', 'Montana'),
        ('NE', 'Nebraska'),
        ('NV', 'Nevada'),
        ('NH', 'New Hampshire'),
        ('NJ', 'New Jersey'),
        ('NM', 'New Mexico'),
        ('NY', 'New York'),
        ('NC', 'North Carolina'),
        ('ND', 'North Dakota'),
        ('OH', 'Ohio'),
        ('OK', 'Oklahoma'),
        ('OR', 'Oregon'),
        ('PA', 'Pennsylvania'),
        ('RI', 'Rhode Island'),
        ('SC', 'South Carolina'),
        ('SD', 'South Dakota'),
        ('TN', 'Tennessee'),
        ('TX', 'Texas'),
        ('UT', 'Utah'),
        ('VT', 'Vermont'),
        ('VA', 'Virginia'),
        ('WA', 'Washington'),
        ('WV', 'West Virginia'),
        ('WI', 'Wisconsin'),
        ('WY', 'Wyoming'),
    ]
    LOCATION_TYPE = [
        ('H','House'),
        ('A','Apt/Condo'),
        ('D','Dorm'),
        ('O','Office'),
        ('S','Storage'),
        ('M','Military'),
    ]
    MOVE_TYPE = [
        ('B', 'Individual boxes'),
        ('P', 'Fill a pod'),
    ]
    STATUS = [
        ('U', 'Unpaid'),
        ('P', 'Paid'),
    ]
    # reference_number begins as an empty value
    reference_number = models.CharField(max_length=22, blank=True, default=None)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='Created')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='Last updated')
    quote_status = models.CharField(max_length=1, choices=STATUS, default='U')
    # Origin
    moving_from_address = models.CharField(max_length=50, blank=False, verbose_name='Where are you moving FROM?')
    moving_from_city = models.CharField(max_length=30, blank=False, verbose_name='City')
    moving_from_state = models.CharField(max_length=2, choices=US_STATE, blank=False, verbose_name='State')
    moving_from_zip = models.CharField(max_length=5, blank=False, verbose_name='Zip Code')
    moving_from_country = models.CharField(max_length=2, verbose_name='Country', default='US', editable=False)
    moving_from_location = models.CharField(max_length=1, choices=LOCATION_TYPE, blank=False, verbose_name='What type of location is this?')
    # Destination
    moving_to_address = models.CharField(max_length=50, blank=False, verbose_name='Where are you moving TO?')
    moving_to_city = models.CharField(max_length=30, blank=False, verbose_name='City')
    moving_to_state = models.CharField(max_length=2, choices=US_STATE, blank=False, verbose_name='State')
    moving_to_zip = models.CharField(max_length=5, blank=False, verbose_name='Zip Code')
    moving_to_country = models.CharField(max_length=2, verbose_name='Country', default='US', editable=False)
    moving_to_location = models.CharField(max_length=1, choices=LOCATION_TYPE, blank=False, verbose_name='What type of location is this?')
    # Other information
    saturday_pick_up = models.BooleanField(default=False)
    saturday_delivery = models.BooleanField(default=False)
    appointment_pick_up = models.BooleanField(default=False)
    appointment_delivery = models.BooleanField(default=False)
    inside_pick_up = models.BooleanField(default=False)
    inside_delivery = models.BooleanField(default=False)
    extended_loading_pick_up = models.BooleanField(default=True)
    extended_loading_delivery = models.BooleanField(default=False)
    carrier_insurance = models.BooleanField(default=True, editable=False)
    extended_insurance = models.BooleanField(default=False, editable=False)
    expiration_date = models.DateTimeField(auto_now_add=True)
    total_pieces = models.IntegerField(blank=True, default=0)
    total_gross_weight = models.IntegerField(validators=[MaxValueValidator(10000)], blank=True, default=0)
    total_cubic_feet = models.IntegerField(blank=True, default=0)
    total_shipment_value = models.IntegerField(validators=[MaxValueValidator(10000)], blank=True, default=0)
    density = models.FloatField(blank=True, default=0)
    freight_class = models.FloatField(blank=True, default=0)
    # Empty until API response from carrier is received
    origin_station = models.CharField(max_length=3, blank=True, default='N/A')
    destitation_station = models.CharField(max_length=3, blank=True, default='N/A')

    class Meta:
        verbose_name = _("Quote")
        verbose_name_plural = _("Quotes")

    # Add custom values to quote by adjusting the save method
    def save(self, *args, **kwargs):
        if self.pk is None:
            def increment_reference_number():
                # Generate the 2nd and 3rd part of the quote reference
                today = date.today()
                date_ref = today.strftime('%y%m%d')
                last_quote = Quote.objects.all().order_by('id').last()
                if not last_quote:
                    new_quote_ref = str(date_ref) + '-' + '00000000'
                else:
                    quote_ref = last_quote.reference_number
                    quote_ref_int = int(quote_ref.split('-')[-1])
                    new_quote_int = quote_ref_int + 1
                    new_quote_ref = date_ref + '-' + str(new_quote_int).zfill(8)
                    return new_quote_ref
            new_quote_ref = increment_reference_number()
            self.reference_number = new_quote_ref

        else:
            pass

        super().save(*args, **kwargs)

    def update_total_pieces(self, *args, **kwargs):
        if self.total_pieces == 0:
            quote_id = self.id
            this_quote = Quote.objects.get(quote_id=quote_id)
            pieces = this_quote.piece_quote_set.all()
            counted_pieces = 0
            for piece in pieces.all():
                counted_pieces += 1
            self.total_pieces = counted_pieces

        else:
            pass

        super().save(*args, **kwargs)

    def __str__(self):
        return self.reference_number

class Carrier(models.Model):
    """Model for a carrier"""
    # TODO Decide on max_weight_per_piece/shipment, max_cubic_feet_per_piece/shipment
    # TODO Check if insurance_rate/insurance_min comes through the API
    #quote = models.ForeignKey(Quote)#, on_delete=models.CASCADE)
    name = models.CharField(max_length=30, blank=False, unique=True, verbose_name='Carrier Name')
    code = models.CharField(max_length=3, blank=False, unique=True, verbose_name='Carrier Code')
    contact_name = models.CharField(max_length=30, blank=False, verbose_name='Contact Name')
    contact_email = models.EmailField(max_length=30, blank=False, unique=False, verbose_name='Contact Email')
    insurance_doc = models.FileField(upload_to='carrier_docs/', verbose_name='Carrier Insurance Document')

class Piece(models.Model):
    """Model for a piece"""
    quote = models.ForeignKey('Quote', related_name='piece_quote_set', on_delete=models.CASCADE)
    length = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(125)], blank=False, default=0)
    width = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(88)], blank=False, default=0)
    height = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(96)], blank=False, default=0)
    weight = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(500)], blank=False, default=0)
    value = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(2500)], blank=False, default=0)

    class Meta:
        verbose_name = _("Piece")
        verbose_name_plural = _("Pieces")


class Column():
    """
    Database Column의 속성을 담고 있는 클래스입니다.

    **Parameters**

    * **name** (*string*) --

        컬럼명

    * **column_type** (*string*) --

        컬럼 타입(BIGINT, VARCHAR(100), etc.)

    * **attr** (*string*) --

        컬럼 속성(DEFAULT CURRENT_TIMESTAMP, etc.)

    * **comment** (*string*) --

        코멘트
    """
    def __init__(self, name, column_type, attr="", comment=""):
        self.name = name
        self.column_type = column_type
        self.attr = attr
        self.comment = comment

def update_df_type_through_redshift_columns(df, columns):
    """
    Pandas DataFrame과 Columns를 이용해 Pandas DataFrame의 타입을 업데이트합니다.

    **Example**

    ```python
    import simple_utils
    from simple_utils.simple_redshift import Column

    members = [
        {
            "id": 1,
            "name": "park",
            "phone": "01020203030",
            "created_at": "2020-01-01"
        },
        {
            "id": 2,
            "name": "kim",
            "phone": "01020203031",
            "created_at": "2020-01-02"
        },
        {
            "id": 3,
            "name": "han",
            "phone": "01020203032",
            "created_at": "2020-01-03"
        }]

    df = pd.DataFrame(members)
    columns = [Column('id', 'BIGINT'), Column('name', 'VARCHAR(100)'), Column(
        'phone', 'VARCHAR(100)'), Column('created_at', 'TIMESTAMP')]
    dtypes = simple_utils.redshift.update_df_type_through_redshift_columns(df, columns).dtypes

    assert dtypes['id'] == np.int64
    assert dtypes['name'] == np.object
    assert dtypes['phone'] == np.object
    assert dtypes['created_at'] == np.object
    ```

    **Parameters**

    * **df** (*pandas.DataFrame*) --

        변환 할 padnas dataframe 입니다.

    * **columns** (*list*) --

        simple_utils.redshift.Column을 포함하고 있는 list입니다.

    **Returns**

    * **변환된 데이터프레임** (*pandas.DataFrame*) --
    """

    wdf = df.copy()
    case_insensitive_check = lambda x, word: word.lower() in [s.lower() for s in x]
    for column in columns:
        if case_insensitive_check(["BIGINT", "INT", "SMALLINT"], column.column_type):
            wdf[column.name] = wdf[column.name].astype(int)
        elif case_insensitive_check(["FLOAT"], column.column_type):
            wdf[column.name] = wdf[column.name].astype(float)
        elif column.column_type.upper().startswith("VARCHAR"):
            wdf[column.name] = wdf[column.name].astype(str)
        elif case_insensitive_check(["BOOLEAN"], column.column_type):
            wdf[column.name] = wdf[column.name].astype(bool)
        elif column.column_type in ["DATE", "TIMESTAMP"]:
            pass
        else:
            raise ValueError(f"Unknown type {column.column_type}")

    return wdf


from .page import *

time.sleep(1)
def case_6_5(self, full_screen):

    self.page.loger('\n Запуск Тест кейс № 6_5 tvweb_new-6_5: Проверка добавления и удаления комментария \n')

    emailt = 'ttvzavr126@mail.ru'
    passw = '111111'

    self.page.click_f('Клик_Вход', 1)
    time.sleep(1)
    #self.page.send_f('Ввод_логина_вход', emailt, 2)
    self.driver.find_element_by_xpath('.//input[@class="authorization__login textbox"]').send_keys(emailt)
    time.sleep(2)

    #self.page.send_f('Ввод_пароля_вход', passw, 3)
    self.driver.find_element_by_xpath('.//input[@class="authorization__password textbox"]').send_keys(passw)
    time.sleep(2)

    self.page.click_f('Клик_Войти_auth', 2)
    time.sleep(5)

    self.page.waitForElementVisible('.//div[@class="selection__heading heading-2"][contains(., "Рекомендуем")]', 10)
    target = self.driver.find_element_by_xpath('.//div[@class="selection__heading heading-2"][contains(., "Рекомендуем")]') # скролл до заголовка с названием фильма
    target.location_once_scrolled_into_view # скролл
    time.sleep(2)

    self.driver.find_element_by_xpath('.//a[@href="/catalog/besplatnye-filmy/"][contains(., "Смотреть все")]').click() # Клик
    time.sleep(3)

    self.driver.find_element_by_xpath('.//a[@class="card card_clip"]').click()
    time.sleep(4)

    target = self.driver.find_element_by_xpath('.//button[@data-modal="feedback"]') # скролл до заголовка с названием фильма
    target.location_once_scrolled_into_view # скролл
    time.sleep(2)

    self.card.click_f('Клик_на_вкладку_Отзывы ', 3)
    time.sleep(2)

    self.driver.find_element_by_xpath('.//textarea[@class="clip-comments__field textbox"]').send_keys('Суперр!')
    time.sleep(3)

    time.sleep(1)
    self.driver.find_element_by_xpath('.//button[@id="clip-comments-send"]').click()
    time.sleep(2)

    self.page.waitForElementVisible('.//div[@class="clip-comments__list"]', 10) # Поиск блока с комментариями
    res_txt = str(self.result.find_all_link("div", "clip-comments__list"))
    assert('Алексей') in res_txt
    assert('Суперр!') in res_txt
    self.page.loger('Комментарий добавлен')
    time.sleep(2)

    self.page.delete_comments('ttvzavr126@mail.ru') # Удаление комментариев
    self.page.loger('Комментарии пользователя "ttvzavr126@mail.ru" удалены в админке')
    time.sleep(3)

    self.driver.close() # Закрыть вкладку
    self.driver.switch_to.window(self.driver.window_handles[-1]) # Переключиться на предыдущую вкладку
    time.sleep(3)

    self.driver.refresh()
    time.sleep(5)

    self.page.waitForElementVisible('.//div[@class="clip-comments__list"]', 10) # Поиск блока с комментариями
    res_txt = str(self.result.find_all_link("div", "clip-comments__list"))
    assert('Fktrctq') not in res_txt
    assert('Суперр!') not in res_txt
    self.page.loger('Комментарий удален из отзывов')
    time.sleep(2)

    self.driver.quit()


#!/usr/bin/env python
from threading import Lock
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit, join_room, leave_room, \
    close_room, rooms, disconnect

import zmq.green as zmq

# Set this variable to "threading", "eventlet" or "gevent" to test the
# different async modes, or leave it set to None for the application to choose
# the best option based on installed packages.
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
thread = None
thread_lock = Lock()

def background_thread():
    """Example of how to send server generated events to clients."""
    count = 0
    context = zmq.Context()
    socket = context.socket(zmq.REP)
    socket.bind("tcp://*:5556")
    while True:
        data = socket.recv_string()
        socket.send_string("ok")
        count += 1
        socketio.emit('my_response',
                      {'data': data, 'count': count},
                      namespace='/test')

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(background_thread)
    emit('my_response', {'data': 'Connected', 'count': 0})

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected', request.sid)

if __name__ == '__main__':
    socketio.run(app)


__author__ = 'zoli'
from decimal import *

def tminFor(C, F, X):
    tmin = X/Decimal(2.0)
    n = Decimal(0)
    tCn = Decimal(0.0)
    while True:
        n += Decimal(1)
        tCn += C/(Decimal(2.0)+(n- Decimal(1))*F)
        tX = tCn + X/(Decimal(2)+n*F)
        if tX < tmin:
            tmin = tX
        else:
            return tmin

def solve(filnIn, filnOut):
    f = open(filnIn)
    fOut = open(filnOut, "w")
    T = int(f.readline())

    for i in range(T):
        rgparams = [Decimal(st) for st in f.readline().split()]
        C = rgparams[0]
        F = rgparams[1]
        X = rgparams[2]
        tmin = tminFor(C, F, X)
        stMsg = "Case #{0}: {1:.7f}".format(i + 1, tmin)
        print(stMsg)
        fOut.write(stMsg)
        fOut.write("\n")

if __name__ == "__main__":
    solve("B-large.in", "B-large.out")
#    solve("sample.in", "sample.out")
#    solve("B-small-attempt0.in", "B-small-attempt0.out")


"""The CubeEditorToolBar class module."""

from PyQt5 import QtGui, QtWidgets

################################################################################
class CubeEditorToolBar(QtWidgets.QToolBar):
    """Toolbar for the mainWindow."""

#-------------------------------------------------------------------------------
    def __init__(self, parent, mainFrameParent):
        """"""

        super(CubeEditorToolBar, self).__init__(parent)
        self._mainFrameParent = mainFrameParent

        openAction = QtWidgets.QAction(QtGui.QIcon('Icons\open.ico'), 'Open cube', self)
        openAction.setStatusTip('Open a cube')
        openAction.triggered.connect(self._open)

        saveAction = QtWidgets.QAction(QtGui.QIcon('Icons\save.ico'), 'Save cube', self)
        saveAction.setShortcut('Ctrl+S')
        saveAction.setStatusTip('Save cube as')
        saveAction.triggered.connect(self._save)

        statsAction = QtWidgets.QAction(QtGui.QIcon('Icons\statistics.ico'), 'Deep analysis', self)
        statsAction.setShortcut('Ctrl+A')
        statsAction.setStatusTip('Deep analysis')
        statsAction.triggered.connect(self._stats)

        self._colorAction = QtWidgets.QAction(QtGui.QIcon('Icons\color.ico'), 'Color the cards which are already in the cube', self)
        self._colorAction.setShortcut('Ctrl+D')
        self._colorAction.setStatusTip('Color the cards which are already in the cube')
        self._colorAction.triggered.connect(self._colorCards)

        resizeAction = QtWidgets.QAction(QtGui.QIcon('Icons\resize.ico'), 'Resize columns to contents', self)
        resizeAction.setShortcut('Ctrl+R')
        resizeAction.setStatusTip('Resize columns to contents')
        resizeAction.triggered.connect(self._resize)

        self.addActions([openAction, saveAction, statsAction, self._colorAction, resizeAction])

#==========================================================================#
#                              Actions                                     #
#==========================================================================#

#-------------------------------------------------------------------------------
    def _stats(self):
        """Stats action handler. Shows deeper analysis of the cube."""

#-------------------------------------------------------------------------------
    def _open(self):
        """Open action handler. Opens and loads a cube."""

        self._mainFrameParent.openCube()

#-------------------------------------------------------------------------------
    def _resize(self):
        """
        Resize action handler. Resizes the columns of the deck and sideboard
        to contents
        """

        self._mainFrameParent.cubeList.resizeColumns()
        self._mainFrameParent.masterBaseList.resizeColumns()

#-------------------------------------------------------------------------------
    def _colorCards(self):
        """
        Color cards handler. Colors the cards in the master list which are
        already in the cube
        """

        self._mainFrameParent.colorMasterListCards()

#-------------------------------------------------------------------------------
    def _save(self):
        """Save action handler. Saves the deck as mwsdeck format."""

        self._mainFrameParent.saveCubeAs()


'''
ImageSegmentationProject
Mask R-CNN model image segmentation modeling and tuning
'''
import os
import neptune
# Use case for image segmentation
# Connect your script to Neptune
project = neptune.init(api_token=os.getenv('NEPTUNE_API_TOKEN'),
                       project_qualified_name='katyl/ImageSegmentationProject') ## 'YourUserName/YourProjectName'

## How to track the weights and predictions in Neptune
npt_exp = project.create_experiment('implement-MaskRCNN-Neptune',
                                    tags=['image segmentation', 'mask rcnn', 'keras', 'neptune'])

import sys
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt
# Root directory of the project
ROOT_DIR = os.path.abspath(r"..\entty\Desktop\0.Article_Pitching\Image_Segmentation\aktwelve_mask_rcnn")

# Import Mask RCNN
sys.path.append(ROOT_DIR)  # To find local version of the library
from mrcnn import utils
import mrcnn.model as modellib
from mrcnn import visualize
from mrcnn.config import Config
from mrcnn.model import MaskRCNN
from mrcnn.visualize import display_instances
from mrcnn.model import log

from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array

# Import COCO config
sys.path.append(os.path.join(ROOT_DIR, "samples/coco/"))  # To find local version
import coco

# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")

# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")

# Directory of images to run detection on
IMAGE_DIR = os.path.join(ROOT_DIR, "images")

class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
               'bus', 'train', 'truck', 'boat', 'traffic light',
               'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
               'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
               'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
               'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
               'kite', 'baseball bat', 'baseball glove', 'skateboard',
               'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
               'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
               'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
               'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
               'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
               'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
               'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
               'teddy bear', 'hair drier', 'toothbrush']

class InferenceConfig(coco.CocoConfig):
    GPU_COUNT = 1
    IMAGES_PER_GPU = 1

config = InferenceConfig()
npt_exp.send_text('Model Config Pars', str(config.to_dict()))

# Create model object in inference mode.
def runMaskRCNN(modelConfig, imagePath, MODEL_DIR=MODEL_DIR, COCO_MODEL_PATH=COCO_MODEL_PATH):
    model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=modelConfig)
    # Load weights trained on MS-COCO
    ## Exclude the last layers because they require a matching number of classes
    # exclude=["mrcnn_class_logits", "mrcnn_bbox_fc",
    #          "mrcnn_bbox", "mrcnn_mask"]
    model.load_weights(COCO_MODEL_PATH, by_name=True)

    ## img = load_img(r'C:\Users\entty\Desktop\0.Article_Pitching\Image_Segmentation\teddybear.jpg')
    image_path = imagePath
    img = load_img(image_path)
    img = img_to_array(img)

    # make prediction
    results = model.detect([img], verbose=1)
    # get dictionary for first prediction
    modelOutput = results[0]

    return modelOutput, img

#### CUSTOMIZE MODEL CONFIG ####
class CustomConfig(coco.CocoConfig):
    """Configuration for inference on the teddybear image.
    Derives from the base Config class and overrides values specific
    to the teddybear image.
    """
    # configuration name
    NAME = "customized"
    # number of classes: +1 for background
    NUM_CLASSES = 1 + 80

    # batch size = 1 for one image
    GPU_COUNT = 1
    IMAGES_PER_GPU = 1

    # how many steps in one epoch
    STEPS_PER_EPOCH = 500
    # min. probability for segmentation
    DETECTION_MIN_CONFIDENCE = 0.71

    # learning rate, momentum and weight decay for regularization
    LEARNING_RATE = 0.06
    LEARNING_MOMENTUM = 0.7
    WEIGHT_DECAY = 0.0002

    VALIDATION_STEPS = 30

config = CustomConfig()
## Log current config to Neptune
npt_exp.send_text('Model Config Pars', str(config.to_dict()))

###### Model inference:
# cur_image_path = r'C:\Users\entty\Desktop\0.Article_Pitching\Image_Segmentation\monks_and_dogs.jpg'
cur_image_path = r'C:\Users\entty\Desktop\0.Article_Pitching\Image_Segmentation\teddybear.jpg'
image_results, img = runMaskRCNN(modelConfig=config, imagePath=cur_image_path)

# Create model object in inference mode.
# show image with bounding boxes, masks, class labels and scores
fig_images, cur_ax = plt.subplots(figsize=(15, 15))
display_instances(img, image_results['rois'], image_results['masks'],
                  image_results['class_ids'], class_names, image_results['scores'], ax=cur_ax)

# Log Predicted images to Neptune
npt_exp.log_image('Predicted Image', fig_images)

##########===========Review model stats ================================#######
# Show stats of trainable model weights
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)

LAYER_TYPES = ['Conv2D']
# Get layers
layers = model.get_trainable_layers()
layers = list(filter(lambda l: l.__class__.__name__ in LAYER_TYPES, layers))
print(f'Total layers = {len(layers)}')

## select a subset of layers
layers = layers[:5]

# Display Histograms
fig, ax = plt.subplots(len(layers), 2, figsize=(10, 3*len(layers)+10),
                       gridspec_kw={"hspace":1})

for l, layer in enumerate(layers):
    weights = layer.get_weights()
    for w, weight in enumerate(weights):
        tensor = layer.weights[w]
        ax[l, w].set_title(tensor.name)
        _ = ax[l, w].hist(weight[w].flatten(), 50)

npt_exp.log_image('Model_Weights', fig)


# encoding: utf-8
# Author: LW

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        result = ''
        tt = zip(*[x for x in strs])
        for x in tt:
            if len(set(x)) ==1:
                result += set(x).pop()
            else :
                break
        return result

a = ["flower","flow","flight"]
print(Solution().longestCommonPrefix(a))


"""
python test_keypoints_images.py --shape-predictor kplum.dat
python test_keypoints_images.py --shape-predictor kplum_gen.dat
python test_keypoints_images.py --shape-predictor kplum_gen_500.dat
python test_keypoints_images.py --shape-predictor kplum_gen_fix2.dat

python test_keypoints_images.py --shape-predictor kplum_gen_third_comb_test.dat
"""

# import the necessary packages
#from imutils.video import VideoStream
from imutils import face_utils
import argparse
import imutils
import time
import dlib
import cv2
import os

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--shape-predictor", required=True,
	help="path to facial landmark predictor")
args = vars(ap.parse_args())

# trained shape predictor
print("[INFO] loading facial landmark predictor...")
predictor = dlib.shape_predictor(args["shape_predictor"])

# initialize the video stream and allow the cammera sensor to warmup
n = 0
img_path = 'Validation_photos_KP_cropped/'

fls = os.listdir(img_path)
font = cv2.FONT_HERSHEY_SIMPLEX
# loop over the frames from the video stream
while True:
	if not (img_path + '/' +fls[n]).endswith('.jpg'):
		n += 1
	else:
		frame = cv2.imread(img_path + '/' +fls[n])
		frame = imutils.resize(frame, width=200)
		gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

		# detect faces in the grayscale frame
		rect = dlib.rectangle(0, 0, frame.shape[1], frame.shape[0])

		shape = predictor(gray, rect)
		shape = face_utils.shape_to_np(shape)
		i = -1
		for (sX, sY) in shape:
			cv2.circle(frame, (sX, sY), 1, (0, 0, 255), -1)
			cv2.putText(frame, str(i + 1), (sX, sY), font,0.8, (0, 0, 0), 2, cv2.LINE_AA)
			cv2.putText(frame, str(i + 1), (sX, sY), font,0.8, (255, 255, 255), 1, cv2.LINE_AA)
			i += 1

		# show the frame
		cv2.imshow("Frame", frame)
		key = cv2.waitKey(1) & 0xFF
		# if the `q` key was pressed, break from the loop

		if key == ord('q') or key == 27:
			break
		elif key == ord('a'):
			if n > 0:
				n -= 1
		elif key == ord('d'):
			n += 1
		elif key == ord("q"):
			break

	# do a bit of cleanup
cv2.destroyAllWindows()


#! /usr/bin/env python3
from api.nuttshell_device import *

def parse_running_time(lines, expected_key, user_key, msg):
    line = next(lines)
    if expected_key in line:
        msg.set_value(user_key, line.split()[3].strip() + ' s')
    else:
        raise ParsingException()

def parse_volume(lines, expected_key, user_key, msg):
    line = next(lines)
    if expected_key in line:
        msg.set_value(user_key, line.split()[3].strip())
    else:
        raise ParsingException()

def parse_beep(lines, expected_key, user_key, msg):
    line = next(lines)
    if expected_key in line:
        msg.set_value(user_key, line.split()[2].strip() + 'dB, ' + line.split()[2].strip() + 'Hz')
    else:
        raise ParsingException()

class PlayerDevice(NuttshellDevice):

    PLAYER_START = 'PLAYER_START'
    PLAYER_MUTE_ON = 'PLAYER_MUTE_ON'
    PLAYER_MUTE_OFF = 'PLAYER_MUTE_OFF'
    PLAYER_CHANGE_VOLUME = 'PLAYER_CHANGE_VOLUME'
    PLAYER_CHANGE_VOLUME_INPUT = 'PLAYER_CHANGE_VOLUME_INPUT'
    PLAYER_BEEP = 'PLAYER_BEEP'
    PLAYER_EXIT = 'PLAYER_EXIT'
    ACAPULCO = 'ACAPULCO'
    RUNNING_TIME = 'RUNNING_TIME'

    KEY_DURATION = 'Duration'
    KEY_VOLUME = 'Volume'
    KEY_BEEP = 'BEEP'

    def __init__(self, device, name):
        super(PlayerDevice, self).__init__(device, name)

    msg_templates = [
        MessageTemplate(PLAYER_START,
                        ('Start Player Test', None, MessageTemplate.validate_line),
                        ),
        MessageTemplate(PLAYER_MUTE_ON,
                        ('Player Mute On', None, MessageTemplate.validate_line),
                        ),
        MessageTemplate(PLAYER_MUTE_OFF,
                        ('Player Mute Off', None, MessageTemplate.validate_line),
                        ),
        MessageTemplate(PLAYER_CHANGE_VOLUME,
                        ('Player Change Volume', KEY_VOLUME, parse_volume),
                        ),
        MessageTemplate(PLAYER_CHANGE_VOLUME_INPUT,
                        ('Player Change Input', None, MessageTemplate.validate_line),
                        ),
        MessageTemplate(PLAYER_BEEP,
                        ('Player Beep', KEY_BEEP, parse_beep),
                        ),
        MessageTemplate(PLAYER_EXIT,
                        ('Exit Player Test', None, MessageTemplate.validate_line),
                        ),
        MessageTemplate(ACAPULCO,
                        ('AcaPulco ES4(4Ch)', None, MessageTemplate.validate_line),
                        ),
        MessageTemplate(RUNNING_TIME,
                        ('Running time', KEY_DURATION, parse_running_time),
                        ),
    ] + NuttshellDevice.msg_templates


#!/usr/bin/python3
class shop:
	_console=True
	drinks={"item": [], "cost":[], "count":0}
	food={"item": [], "cost": [], "count":0 }
	other={"item": [], "cost": [], "count":0}
	def add_item(key,i,c):
		key["item"].append(i)
		key["cost"].append(c)
		key["count"] += 1
	def list_out(key):
		for each in range(key["count"]):
			print("Item: %s | Cost: %f"%(key["item"][each],key["cost"][each]))
shop.add_item(shop.drinks,"Monster Energy Drink",1.55)
shop.add_item(shop.drinks,"Beer",5.00)
shop.add_item(shop.drinks,"Fruit-juice",2.00)
shop.add_item(shop.food,"Pizza",5.00)
shop.add_item(shop.food,"Cake",5.00)
shop.add_item(shop.food,"Bacon",2.00)
def str_info(arg):
	print("%s"%(arg))
	return str(input("> "))
def int_info(arg):
	print("%s"%(arg))
	return int(input("> "))
def float_info(arg):
	print("%s"%(arg))
	return float(input("> "))
def console(arg):
	cmdlist=["help: This help menu.", "add_food: Tells the console to add a food item and a price for it.",
	"add_drink: Tells the console to add a drink item and a price for it.",
	"add_other: Tells the console to add another type of item with a price."
	"list_out: Tells the console to list out a spesific list."]
	if arg == "add_drink":
		drink_item=str_info("Drink item please: "); drink_cost = float_info("The price of this drink item please.")
		shop.add_item(shop.drinks,drink_item,drink_cost)
	elif arg == "add_food":
		food_item=str_info("Food item please."); food_cost = float_info("The price of this food item please.")
		shop.add_item(shop.food,food_item,food_cost)
	elif arg == "add_other":
		other_item=str_info("Any type of item please: "); other_cost = float_info("The price of this 'other' please.")
	elif arg == "list_out":
		list_out=str_info("Please give me a list name of 'food','drink' or 'other'.")
		if list_out == "food":
			shop.list_out(shop.food)
		elif list_out == "drink":
			shop.list_out(shop.drinks)
		elif list_out == "other":
			shop.list_out(shop.other)
		else:
			print("No idea, sorry!")
	elif arg == "help":
		for each in cmdlist:
			print("%s"%(each))
	elif arg == "exit":
		print("See you, then!")
		shop._console = False
while 1 and shop._console:
	console(str_info("A command please(not sure?'help' may help.)."))


# Write a program to read in words from the keyboard one at a time until the word "quit" is typed.
# Store them in a list then print them alphabetically

running = 1
wordlist = []

while running == 1:
    x = input('Word: ')
    if x.lower() == 'quit':
        running = 0
    if x.lower() != 'quit':
        wordlist.append(x)

wordlist.sort()

for i in range(len(wordlist)):
    print(wordlist[i])


from . import api_map
from . import resolvers

default_api_map = api_map._API_MAP['current']['api']

class Mkm:

    def __init__(self, api_map=None, **kwargs):
        """
        Initializes the api_map and eventual sandbox mode

        Params:
            `api_map`: Dict with urls and methods for the request
            `kwargs`: Custom arguments that may specify if sandbox should be used

        """
        self.api_map = api_map
        self.sandbox_mode = kwargs.get('sandbox_mode')

    def __getattr__(self, name):
        """
        Used to get inside the api_map

        Params:
            `name`: api_map entry to get

        Returns:
            `instance`: Return an instance of Mkm with updated api_map
        """

        instance = Mkm(api_map=self.api_map[name], sandbox_mode=self.sandbox_mode)
        setattr(self, name, instance)
        return instance

    def __call__(self, *args, **kwargs):
        """
        Here is where the request happens

        Params:
            `kwargs`: May contain eventual parameters for the request

        Returns:
            `response`: Returns the response from the server
        """

        resolver = resolvers.SimpleResolver(self.sandbox_mode)
        return resolver.resolve(api_map=self.api_map, **kwargs)

mkm = Mkm(api_map=default_api_map)
mkm_sandbox = Mkm(api_map=default_api_map, sandbox_mode=True)


from rest_framework import routers
from django.urls import re_path
from tasks import views

router = routers.DefaultRouter()

router.register(r'tasks/completed', views.CompletedTaskViewSet, basename='task-completed')
router.register(r'tasks/uncompleted', views.UncompletedTaskViewSet, basename='task-uncompleted')
router.register(r'tasks', views.TaskViewSet, basename='task')

urlpatterns = [
    re_path('^tasks/complete/(?P<id>\d+)/$', views.task_complete_view, name='task_complete_view'),
    re_path('^tasks/uncomplete/(?P<id>\d+)/$', views.task_uncomplete_view, name='task_uncomplete_view'),

]
urlpatterns += router.urls


def input_number(message):
    while True:
        try:
            user_input = int(input(message))
        except ValueError:
            print("Entrada incorrecta; recuerda poner un NUMERO entero (1, 2, 5000,..)")
            print("-"*20)
            continue
        else:
            return user_input
            break

N = input_number("Ingrese N:\n")
C = 2
while N % C != 0:
    C += 1
    print("C: ", C)

if N == C:
    print("El número es Primo")
else:
    print("El número NO es Primo")


from uuid import uuid1
from copy import deepcopy

class txntable:

	class __txntable:
		def __init__(self):
			self.table = dict()

	__instance = None

	def __init__(self):
		if not self.__instance:
			self.__instance = self.__txntable()
		else:
			pass

	def __str__(self):
		s = "transaction table\ntxnid:   \titemset\n"
		for k, v in self.__instance.table.items():
			s += k[:5] + "...\t" + str(v) + "\n"
		return s

	def insert(self, itemset):
		try:
			self.__instance.table[uuid1().hex] = itemset
			print("successfully insert into txntable")
		except e:
			print("failed to insert into txntable")
			print(e)

	def clear(self):
		self.__instance.table.clear()

	def getitems(self):
		items = set()
		for key in self.__instance.table.keys():
			items.update(self.__instance.table[key])
		return items

	def getsupcnt(self, itemset):
		supcnt = 0
		if itemset and len(itemset) > 0:
			for key in self.__instance.table.keys():
				if self.__instance.table[key].issuperset(itemset):
					supcnt += 1
		return supcnt

	def get_item_supcnt(self, minsup=0):
		item_supcnt = dict()
		for key in self.__instance.table.keys():
			for item in self.__instance.table[key]:
				if item in item_supcnt.keys():
					item_supcnt[item] += 1
				else:
					item_supcnt[item] = 1
		for item in item_supcnt.keys():
			if item_supcnt[item] < minsup:
				del(item_supcnt[item])
		return item_supcnt

	def get_table_copy(self):
		return deepcopy(self.__instance.table)

	def example(self):
		transactions = txntable()
		transactions.insert(set(["A", "C", "D"]))
		transactions.insert(set(["B", "C", "E"]))
		transactions.insert(set(["A", "B", "C", "E"]))
		transactions.insert(set(["B", "E"]))
		return transactions


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """

        return p == q and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

if __name__ == "__main__":
    sol = Solution()
    print(sol.isSameTree([1, 2], [1, 2]))


from tkinter import *
import pygame
import time
import random

path = "Encounter\\"
main = "Random Encounter"
txt = ".txt"
width =30
tk = Tk()
tk.geometry("350x150")
tk.title('Random Entcounter')
tk.iconbitmap('random encounter.ico')

def role():
    u = {}
    x = str(w.get())
    fullpath = path+x+txt
    #print(fullpath)
    f = open(fullpath,"r")
    z = 0
    for y in f:
        #print(y)
        u[z] = y
        z = z+1
    #print(u)
    f.close()
    r=random.randint(0,z)
    #print(str(u[r]))
    try:
        rand.config(text=str(u[r]))
    except:
        pass

menuf = Frame(tk,relief=RIDGE, bd=2)
Label(menuf,text="Path: ").grid(row=0,column=0)
w = Entry(menuf)
w.insert(0, main)
w.grid(row=0,column=1)
Label(menuf,text=txt).grid(row=0,column=2)
menuf.pack()
f = Frame(tk,relief=RIDGE, bd=2)
rand = Label(f,text=txt)
rand.grid(row=0,column=0)
f.pack(fill=X)

role()
rol = Button(tk, text='rol',width=5,command=role).pack(side=BOTTOM)

tk.mainloop()


"""
This code includes Gumbel sofmax classes.
"""

import numpy as np
import theano
import theano.tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams as MRG
from lemontree.layers.layer import BaseLayer

class GumbelSoftmax(BaseLayer):
    """
    This class implements gumbel softmax activation.
    See "Categorical Reparameterization with Gumbel-softmax".
    (Eric Jang, Shixiang Gu, Ben Poole, 2016.)
    """
    def __init__(self, temperature_init=1.0, name=None):
        """
        This function initializes the class.

        Parameters
        ----------
        temperature_init: float, default: 1
            a positive float value.
            if T > 1, become more soften, and T < 1, become more sharpen.
            if temperature is 1, same as normal softmax.
        name: string
            a string name of this class.

        Returns
        -------
        None.
        """
        super(GumbelSoftmax, self).__init__(name)
        # check asserts
        assert temperature_init > 0, '"temperature_init" should be a positive float.'

        # set members
        temperature = np.array(temperature_init).astype('float32')
        self.temperature = theano.shared(temperature, 'temperature')
        self.temperature.tags = ['temperature']
        self.rng = MRG(np.random.randint(1, 2147462569))

    def change_temperature(self, new_temperature):
        """
        This function changes the temperature for softmax.

        Parameters
        ----------
        new_temperature: float
            a positive float value which will be a new temperature.

        Returns
        -------
        None.
        """
        # check asserts
        assert new_temperature > 0, '"new_temperature" should be a positive float.'

        self.temperature.set_value(float(new_temperature))

    def get_output(self, input_):
        """
        This function overrides the parents' one.
        Softmax converts output energy to probability distributuion.

        Math Expression
        -------------------
        g_k ~ Gumbel(0, 1)
        y_k = exp((x_k + g_k) / T) / \sum(exp((x_i + g_k) / T))

        Parameters
        ----------
        input_: TensorVariable

        Returns
        -------
        TensorVariable
        """
        # generate random gumbel distribution
        gumbel_random = self.rng.uniform(input_.shape, 0, 1)
        gumbel_noise= -T.log(-T.log(gumbel_random + 1e-8) + 1e-8)
        return T.nnet.softmax((input_ + gumbel_noise) / self.temperature)  # divide by temperature