from typing import Any, Dict, List, Union

from langchain_core.messages import BaseMessage, get_buffer_string

from langchain.memory.chat_memory import BaseChatMemory

class ConversationBufferWindowMemory(BaseChatMemory):
    """Buffer for storing conversation memory inside a limited size window."""

    human_prefix: str = "Human"
    ai_prefix: str = "AI"
    memory_key: str = "history"  #: :meta private:
    k: int = 5
    """Number of messages to store in buffer."""

    @property
    def buffer(self) -> Union[str, List[BaseMessage]]:
        """String buffer of memory."""
        return self.buffer_as_messages if self.return_messages else self.buffer_as_str

    @property
    def buffer_as_str(self) -> str:
        """Exposes the buffer as a string in case return_messages is True."""
        messages = self.chat_memory.messages[-self.k * 2 :] if self.k > 0 else []
        return get_buffer_string(
            messages,
            human_prefix=self.human_prefix,
            ai_prefix=self.ai_prefix,
        )

    @property
    def buffer_as_messages(self) -> List[BaseMessage]:
        """Exposes the buffer as a list of messages in case return_messages is False."""
        return self.chat_memory.messages[-self.k * 2 :] if self.k > 0 else []

    @property
    def memory_variables(self) -> List[str]:
        """Will always return list of memory variables.

        :meta private:
        """
        return [self.memory_key]

    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, Any]:
        """Return history buffer."""
        return {self.memory_key: self.buffer}


import json
import numpy as np

def create_minutely(time, hours):
	minutely = [{"key": time + 60*x, "value": np.random.normal(25, 1) + (x/60)%300} for x in range(60*hours)]
	return minutely

def create_hourly(time):
	hourly = [{"key": time + 3600*x, "value": np.random.normal(20, 1) + x%5} for x in range(24)]
	return hourly

##Dump to text file
hour = create_minutely(1436920200 - 1770, 1)
hour_json = json.dumps(hour,separators=(',', ': '), sort_keys=True, indent=4)
print (hour[1]['value'])

text_file = open("hour.txt", 'w')
text_file.write(hour_json)
text_file.flush()
text_file.close()

min_day = create_minutely(1436920200 - 1770, 24)
min_day_json = json.dumps(min_day,separators=(',', ': '), sort_keys=True, indent=4)

text_file = open("min_day.txt", 'w')
text_file.write(min_day_json)
text_file.flush()
text_file.close()

day = create_hourly(1436920200)
day_json = json.dumps(day,separators=(',', ': '), sort_keys=True, indent=4)

text_file = open("day.txt", 'w')
text_file.write(day_json)
text_file.flush()
text_file.close()

##Test importing
text_file = open("hour.txt", 'r')
hour2 = json.loads(text_file.read())
if hour2 == hour:
	print ("Worked!")
	print (hour2[1]['value'])


# -*- coding: utf-8 -*-
"""
Created on Fri Apr 19 07:23:58 2019

@author: roma
"""

# Importing the libraries
import os
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier
from sklearn.preprocessing import LabelEncoder

# Importing the dataset
train_X1 = pd.read_csv('X_train.csv')
test_X1 = pd.read_csv('X_test.csv' )
cols=["row_id","series_id","measurement_number"]

train_X=train_X1.drop(cols,axis=1).iloc[:,3:].values.reshape(-1,128,10)

test_X=test_X1.drop(cols,axis=1).values.reshape(-1,128,10)

df_train_y =pd.read_csv('y_train.csv')

train_y=df_train_y['surface']

surface_names = df_train_y['surface'].unique()
num_surfaces = len(surface_names)
surface_to_numeric = dict(zip(surface_names, range(num_surfaces)))

#titanic train part
cols=["row_id","measurement_number"]
train_y = df_train_y['surface'].replace(surface_to_numeric).values
train_X=train_X1.drop(cols,axis=1)

test_X=test_X1.drop(cols,axis=1)

def FE(data):
    df = pd.DataFrame()
    #craetion of another variables(total angular velocity) using relationship
    data['total_anglr_vel'] = (data['angular_velocity_X']**2 + data['angular_velocity_Y']**2 +
                             data['angular_velocity_Z']**2)** 0.5
    data['total_linr_acc'] = (data['linear_acceleration_X']**2 + data['linear_acceleration_Y']**2 +
                             data['linear_acceleration_Z']**2)**0.5
    data['total_xyzW'] = (abs(data['orientation_X']) + abs(data['orientation_Y']) +
                              abs(data['orientation_Z'])+abs(data['orientation_W']))/4

    data['acc_vs_vel'] = data['total_linr_acc'] / data['total_anglr_vel']
    data['acc_vs_vel'] = data['total_linr_acc'] * data['total_anglr_vel']
    data['quaternion1'] = 2*np.arccos(data['orientation_W'])

    #using python basics function and some gymnastics(obtained on internet)
    for col in data.columns:
        if col in ['row_id','series_id','measurement_number', 'orientation_X', 'orientation_Y', 'orientation_Z', 'orientation_W']:
            continue
        df[col + '_mean'] = data.groupby(['series_id'])[col].mean()
        df[col + '_median'] = data.groupby(['series_id'])[col].median()
        df[col + '_max'] = data.groupby(['series_id'])[col].max()
        df[col + '_min'] = data.groupby(['series_id'])[col].min()
        df[col + '_std'] = data.groupby(['series_id'])[col].std()
        df[col + '_range'] = df[col + '_max'] - df[col + '_min']
        df[col + '_maxtoMin'] = df[col + '_max']/ df[col + '_min']
        df[col + '_mean_abs_chg'] = data.groupby(['series_id'])[col].apply(lambda x: np.mean(np.abs(np.diff(x))))
        df[col + '_abs_max'] = data.groupby(['series_id'])[col].apply(lambda x: np.max(np.abs(x)))
        df[col + '_abs_min'] = data.groupby(['series_id'])[col].apply(lambda x: np.min(np.abs(x)))
        df[col + '_abs_avg'] = (df[col + '_abs_min'] + df[col + '_abs_max'])/2
    return df
new_train = FE(train_X)

test = FE(test_X)
""" is an cross validation technique (randomly dividing datasets into k groups)"""

def k_folds(clf, X, t, X_test, k):
    folds = StratifiedKFold(n_splits = k, shuffle=True, random_state=13)
    y_test = np.zeros((X_test.shape[0], 9))
    y_oof = np.zeros((X.shape[0]))
    score = 0
    for i, (train_idx, val_idx) in  enumerate(folds.split(X, t)):
        clf.fit(X[train_idx], t[train_idx])
        y_oof[val_idx] = clf.predict(X[val_idx])
        y_test += clf.predict_proba(X_test) / folds.n_splits
        score += clf.score(X[val_idx], t[val_idx])
    return y_oof, y_test

label1 = pd.read_csv("y_train.csv")
surface_names = label1['surface'].unique()
num_surfaces = len(surface_names)
surface_to_numeric = dict(zip(surface_names, range(num_surfaces)))

label = label1['surface'].replace(surface_to_numeric).values
ntv=new_train.values
tst=test.values

#Feature Scaling
le = LabelEncoder()

label = le.fit_transform(label)
label = le.transform(label)

rand = RandomForestClassifier(n_estimators=1000, random_state=13)
y_oof, y_test_rand = k_folds(rand,ntv, label, tst, k=10)

ext = ExtraTreesClassifier(n_estimators=1000, random_state=13)
y_oof, y_test_ext = k_folds(ext, ntv, label, tst, k=10)

y_test = (y_test_ext + y_test_rand)/2#mean of the test giving by the two algo
y_test = np.argmax(y_test, axis=1)
career = pd.read_csv(os.path.join("sample_submission.csv"))
career['surface'] = le.inverse_transform(y_test)
career['surface'].replace({0:"fine_concrete",1:"concrete",
                2:"soft_tiles",3:"tiled",4:"soft_pvc",
                5:"hard_tiles_large_space",6:"carpet",7:"hard_tiles",8:"wood"},inplace=True)
career.to_csv('careercon.csv', index=False)


##########################################################################
#                                                                        #
#      May you do good and not evil                                      #
#      May you find forgiveness for yourself and forgive others          #
#      May you share freely, never taking more than you give.            #
#                                                                        #
##########################################################################

# My libraries
from my_plots import SimpleScatter
from my_analysis import RandomDataAnalysis

# Other general python libraries
import sys

# Libraries for the PyQt5 interface
#from PyQt5 import QtGui as qtg
#from PyQt5.QtCore import Qt as qt
from PyQt5 import QtWidgets as qtw
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg

class MyInterface_Qt:
    def __init__(self,
                 geometry = None # Unused
                 ):

        # The engine is for the math/analysis
        self.engine = RandomDataAnalysis()

        # The display is for the plot
        self.display = SimpleScatter()

        # A separate method to initialize the plot
        # This was removed from the SimpleScatter contstructor
        # due to an issue with tk
        self.display.init_scatter()

        # Layout the figure and the buttons
        self.configure_main_window(geometry)

        # Show the window and run the app
        self.main_window.show()
        sys.exit(self.app.exec_())
        return

    def configure_main_window(self,
                              geometry
                              ):

        # Application
        self.app = qtw.QApplication([])

        # Main window
        self.main_window = qtw.QWidget()
        self.main_window.setWindowTitle('Example interface using PyQt5')

        # The main layout is a vertical container
        #   The top part will be the figure, the bottom will be the buttons
        self.main_layout = qtw.QVBoxLayout()
        self.main_window.setLayout(self.main_layout)

        # For the figure, we first create a canvas
        self.canvas = FigureCanvasQTAgg(self.display.fig)
        # Then we add it to the main_layout
        self.main_layout.addWidget(self.canvas)

        # Two rows of buttons, each is a horizontal container
        self.button_row1 = qtw.QHBoxLayout()
        self.button_row2 = qtw.QHBoxLayout()

        # Put those two button rows in their own vertical container
        self.button_rows = qtw.QVBoxLayout()
        self.button_rows.addLayout(self.button_row1)
        self.button_rows.addLayout(self.button_row2)
        # Put the button row container in the main_layout
        self.main_layout.addLayout(self.button_rows)

        ### Creating the actual buttons
        # Create a button
        self.button_generate_random_data = qtw.QPushButton("Generate Random Data")
        # Tell the button what function to call when clicked
        self.button_generate_random_data.clicked.connect(self.make_random_data)
        # Add it to its row
        self.button_row1.addWidget(self.button_generate_random_data)

        # Repeat for the rest of the buttons
        self.button_load_data = qtw.QPushButton("Load a File")
        self.button_load_data.clicked.connect(self.load_data)
        self.button_row1.addWidget(self.button_load_data)

        self.button_save_data = qtw.QPushButton("Save data to file")
        self.button_save_data.clicked.connect(self.engine.output_data)
        self.button_row2.addWidget(self.button_save_data)

        # Save Figure
        self.button_save_figure = qtw.QPushButton("Save Figure")
        self.button_save_figure.clicked.connect(lambda: self.display.save_plot())
        self.button_row2.addWidget(self.button_save_figure)
        return

    def make_random_data(self):
        self.engine.make_random_data()
        self.update_plot()
        return

    def update_plot(self):
        self.display.update_scatter(self.engine.data)
        self.canvas.draw()
        return

    def load_data(self):
        filename,_ = qtw.QFileDialog.getOpenFileName(self.main_window,
                                                     "Select file",
                                                     "./data/")
        try:
            self.engine.load_data(filename)
            self.update_plot()
        except Exception as e:
            print('Problem loading data. File name was: ' + str(filename))
        return

if __name__ == '__main__':
    MyInterface_Qt()


import pytest
import sys
import pandas as pd
from pandas.testing import assert_series_equal
from modular_parts.ranking import calculate_promethee_ii_ranking

sys.path.append('../..')

@pytest.fixture
def net_outranking_flows():
    alternatives = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6']
    return pd.DataFrame({
        'positive': [0.14151, 0.62188, -0.16870, 0.70934, 0.36058, -0.63652],
        'negative': [0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
        'net': [0.04151, 0.52188, -0.26870, 0.60934, 0.26058, -0.73652]
    }, index=alternatives)

def test_prometheeII_ranking(net_outranking_flows):
    expected = pd.Series(data=['a4', 'a2', 'a5', 'a1', 'a3', 'a6'],
                         index=[1, 2, 3, 4, 5, 6], name='ranking')
    actual = calculate_promethee_ii_ranking(net_outranking_flows)
    assert_series_equal(expected, actual, atol=0.006)

if __name__ == '__main__':
    test_prometheeII_ranking(net_outranking_flows)


from collections import OrderedDict

import numpy as np
import tensorflow as tf

from gym import spaces

from imitation.helpers.tf_util import clip, flatgrad, TheanoFunction
from imitation.helpers.distributions import BernoulliPd
from imitation.helpers.networks import RewardNN
from imitation.helpers.mpi_adam import MpiAdamOptimizer
from imitation.helpers.mpi_running_mean_std import MpiRunningMeanStd
from imitation.helpers.math_util import rmsify
from imitation.helpers.console_util import log_module_info
from imitation.helpers import logger

class Discriminator(object):

    def __init__(self, name, env, hps, comm):
        self.name = name
        # Define everything in a specific scope
        with tf.variable_scope(self.name):
            self.scope = tf.get_variable_scope().name
            self._init(env=env, hps=hps, comm=comm)

    def _init(self, env, hps, comm):
        self.env = env
        self.ob_shape = self.env.observation_space.shape
        self.ac_space = self.env.action_space
        self.ac_shape = self.ac_space.shape
        if "NoFrameskip" in env.spec.id:
            # Expand the dimension for Atari
            self.ac_shape = (1,) + self.ac_shape
        self.hps = hps
        assert self.hps.ent_reg_scale >= 0, "'ent_reg_scale' must be non-negative"
        self.comm = comm

        # Assemble clipping functions
        unlimited_range = (-np.infty, np.infty)
        if isinstance(self.ac_space, spaces.Box):
            self.clip_obs = clip((-5., 5.))
        elif isinstance(self.ac_space, spaces.Discrete):
            self.clip_obs = clip(unlimited_range)
        else:
            raise RuntimeError("ac space is neither Box nor Discrete")

        # Define the synthetic reward network
        self.reward_nn = RewardNN(scope=self.scope, name='sr', hps=self.hps)

        # Create inputs
        self.p_obs = tf.placeholder(name='p_obs', dtype=tf.float32,
                                    shape=(None,) + self.ob_shape)
        self.p_acs = tf.placeholder(name='p_acs', dtype=tf.float32,
                                    shape=(None,) + self.ac_shape)
        self.e_obs = tf.placeholder(name='e_obs', dtype=tf.float32,
                                    shape=(None,) + self.ob_shape)
        self.e_acs = tf.placeholder(name='e_acs', dtype=tf.float32,
                                    shape=(None,) + self.ac_shape)

        # Rescale observations
        if self.hps.from_raw_pixels:
            # Scale de pixel values
            p_obz = self.p_obs / 255.0
            e_obz = self.e_obs / 255.0
        else:
            if self.hps.rmsify_obs:
                # Smooth out observations using running statistics and clip
                with tf.variable_scope("apply_obs_rms"):
                    self.obs_rms = MpiRunningMeanStd(shape=self.ob_shape)
                p_obz = self.clip_obs(rmsify(self.p_obs, self.obs_rms))
                e_obz = self.clip_obs(rmsify(self.e_obs, self.obs_rms))
            else:
                p_obz = self.p_obs
                e_obz = self.e_obs

        # Build graph
        p_scores = self.reward_nn(p_obz, self.p_acs)
        e_scores = self.reward_nn(e_obz, self.e_acs)
        scores = tf.concat([p_scores, e_scores], axis=0)
        # `scores` define the conditional distribution D(s,a) := p(label|(state,action))

        # Create entropy loss
        bernouilli_pd = BernoulliPd(logits=scores)
        ent_mean = tf.reduce_mean(bernouilli_pd.entropy())
        ent_loss = -self.hps.ent_reg_scale * ent_mean

        # Create labels
        fake_labels = tf.zeros_like(p_scores)
        real_labels = tf.ones_like(e_scores)
        if self.hps.label_smoothing:
            # Label smoothing, suggested in 'Improved Techniques for Training GANs',
            # Salimans 2016, https://arxiv.org/abs/1606.03498
            # The paper advises on the use of one-sided label smoothing (positive targets side)
            # Extra comment explanation: https://github.com/openai/improved-gan/blob/
            # 9ff96a7e9e5ac4346796985ddbb9af3239c6eed1/imagenet/build_model.py#L88-L121
            if not self.hps.one_sided_label_smoothing:
                # Fake labels (negative targets)
                soft_fake_u_b = 0.0  # standard, hyperparameterization not needed
                soft_fake_l_b = 0.3  # standard, hyperparameterization not needed
                fake_labels = tf.random_uniform(shape=tf.shape(fake_labels),
                                                name="fake_labels_smoothing",
                                                minval=soft_fake_l_b, maxval=soft_fake_u_b)
            # Real labels (positive targets)
            soft_real_u_b = 0.7  # standard, hyperparameterization not needed
            soft_real_l_b = 1.2  # standard, hyperparameterization not needed
            real_labels = tf.random_uniform(shape=tf.shape(real_labels),
                                            name="real_labels_smoothing",
                                            minval=soft_real_l_b, maxval=soft_real_u_b)

        # # Build accuracies
        p_acc = tf.reduce_mean(tf.sigmoid(p_scores))
        e_acc = tf.reduce_mean(tf.sigmoid(e_scores))

        # Build binary classification (cross-entropy) losses, equal to the negative log likelihood
        # for random variables following a Bernoulli law, divided by the batch size
        p_bernoulli_pd = BernoulliPd(logits=p_scores)
        p_loss_mean = tf.reduce_mean(p_bernoulli_pd.neglogp(fake_labels))
        e_bernoulli_pd = BernoulliPd(logits=e_scores)
        e_loss_mean = tf.reduce_mean(e_bernoulli_pd.neglogp(real_labels))

        # Add a gradient penalty (motivation from WGANs (Gulrajani),
        # but empirically useful in JS-GANs (Lucic et al. 2017))

        def batch_size(x):
            """Returns an int corresponding to the batch size of the input tensor"""
            return tf.to_float(tf.shape(x)[0], name='get_batch_size_in_fl32')

        shape_obz = (tf.to_int64(batch_size(p_obz)),) + self.ob_shape
        eps_obz = tf.random_uniform(shape=shape_obz, minval=0.0, maxval=1.0)
        obz_interp = eps_obz * p_obz + (1. - eps_obz) * e_obz
        shape_acs = (tf.to_int64(batch_size(self.p_acs)),) + self.ac_shape
        eps_acs = tf.random_uniform(shape=shape_acs, minval=0.0, maxval=1.0)
        acs_interp = eps_acs * self.p_acs + (1. - eps_acs) * self.e_acs
        interp_scores = self.reward_nn(obz_interp, acs_interp)
        grads = tf.gradients(interp_scores, [obz_interp, acs_interp], name="interp_grads")
        assert len(grads) == 2, "length must be exacty 2"
        grad_squared_norms = [tf.reduce_mean(tf.square(grad)) for grad in grads]
        grad_norm = tf.sqrt(tf.reduce_sum(grad_squared_norms))
        grad_pen = tf.reduce_mean(tf.square(grad_norm - 1.0))

        losses = OrderedDict()

        # Add losses
        losses.update({'d_policy_loss': p_loss_mean,
                       'd_expert_loss': e_loss_mean,
                       'd_ent_mean': ent_mean,
                       'd_ent_loss': ent_loss,
                       'd_policy_acc': p_acc,
                       'd_expert_acc': e_acc,
                       'd_grad_pen': grad_pen})

        # Assemble discriminator loss
        loss = p_loss_mean + e_loss_mean + ent_loss + 10 * grad_pen
        # gradient penalty coefficient aligned with the value used in Gulrajani et al.

        # Add assembled disciminator loss
        losses.update({'d_total_loss': loss})

        # Compute gradients
        grads = flatgrad(loss, self.trainable_vars, self.hps.clip_norm)

        # Create mpi adam optimizer
        self.optimizer = MpiAdamOptimizer(comm=self.comm,
                                          clip_norm=self.hps.clip_norm,
                                          learning_rate=self.hps.d_lr,
                                          name='d_adam')
        optimize_ = self.optimizer.minimize(loss=loss, var_list=self.trainable_vars)

        # Create callable objects
        phs = [self.p_obs, self.p_acs, self.e_obs, self.e_acs]
        self.get_losses = TheanoFunction(inputs=phs, outputs=list(losses.values()))
        self.get_grads = TheanoFunction(inputs=phs, outputs=grads)
        self.optimize = TheanoFunction(inputs=phs, outputs=optimize_)

        # Make loss names graspable from outside
        self.names = list(losses.keys())

        # Define synthetic reward
        if self.hps.non_satur_grad:
            # Recommended in the original GAN paper and later in Fedus et al. 2017 (Many Paths...)
            # 0 for expert-like states, goes to -inf for non-expert-like states
            # compatible with envs with traj cutoffs for good (expert-like) behavior
            # e.g. mountain car, which gets cut off when the car reaches the destination
            reward = tf.log_sigmoid(p_scores)
        else:
            # 0 for non-expert-like states, goes to +inf for expert-like states
            # compatible with envs with traj cutoffs for bad (non-expert-like) behavior
            # e.g. walking simulations that get cut off when the robot falls over
            reward = -tf.log(1. - tf.sigmoid(p_scores) + 1e-8)  # HAXX: avoids log(0)

        # Create Theano-like op that compute the synthetic reward
        self.compute_reward = TheanoFunction(inputs=[self.p_obs, self.p_acs],
                                             outputs=reward)

        # Summarize module information in logs
        log_module_info(logger, self.name, self.reward_nn)

    def get_reward(self, ob, ac):
        """Compute synthetic reward from a single observation
        The network is able to process observations and actions in minibatches, but the RL
        paradigm enforces the agent to see observations and perform actions in sequences,
        therefore seeing only one at a time.
        `ob` and `ac` are structured as np.array([a, b, c, ...]). Since the network work with
        minibatches, we have to construct a minibatch of size 1, e.g. by using `ob[None]`
        (do not use `[ob]`!) and `ac[None]` which are structured as np.array([[a, b, c, ...]]).
        The network outputs a single synthetic_reward per single observation-action pair in the
        joined input minibatch: np.array([[d]])
        Since a minibatch will later be sequentially construted out of the outputs, we extract
        the output from the returned minibatch of size 1. The extraction can be done by taking
        the first element (one or several times) with `.[0]` or by collapsing the returned array
        into one dimension with numpy's `flatten()` function:
            `synthetic_reward`: np.array([[d]]) -> np.array([d])
        Note that we only manipulate numpy arrays and not lists. We therefore do not need to
        extract the scalar `d` from `np.array([d])`, as for arithmetic operations a numpy array
        of size 1 is equivalent to a scalar (`np.array([1]) + np.array([2]) = np.array([3])` but
        `[1] + [2] = [1, 2]`).
        For safety reason, the scalar is still extracted from the singleton numpy array with
        `np.asscalar`.
        """
        synthetic_reward = self.compute_reward({self.p_obs: ob[None],
                                                self.p_acs: ac[None]})

        return np.asscalar(synthetic_reward.flatten())

    def sync_from_root(self):
        """Synchronize the optimizer across all mpi workers"""
        self.optimizer.sync_from_root(self.trainable_vars)

    @property
    def vars(self):
        return tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.scope)

    @property
    def trainable_vars(self):
        return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=self.scope)


import cv2
from matplotlib import pyplot as plt
imgL = cv2.imread('left_img.jpg',0)
imgR = cv2.imread('right_img.jpg',0)

cv2.imshow('Image', imgL)
#cv2.waitKey(0)
#v2.destroyAllWindows()
stereo = cv2.StereoBM_create(numDisparities=48, blockSize=5)
disparity = stereo.compute(imgL,imgR)
plt.imshow(disparity,'gray')
plt.show()


import pygame
class Switch:
    def __init__(self, x, y, surface, default_color=(0, 204, 204), hover_color=(0, 255, 255), outline_color=(0, 0, 0), enable_color=(47, 194, 0), disable_color=(207, 0, 0)):
        '''A switch that acts like a button, based on the button class'''
        self.x = x
        self.y = y
        self.width = 86
        self.height = 36
        self.surface = surface

        self.theme = [None] * 16
        self.outline_color = outline_color
        self.hover_color = hover_color
        self.default_color = default_color
        self.enable_color = enable_color
        self.disable_color = disable_color

        self.was_pressed = False

    def draw(self, active, bkp_pos=None, is_over=False):
        '''Simply draw the switch'''
        if bkp_pos == None:
            self.pos = pygame.mouse.get_pos()
        else:
            self.pos = bkp_pos
        if is_over:
            pygame.draw.rect(self.surface, self.hover_color, (self.x, self.y, self.width, self.height), 0, int(self.height / 2))
        else:
            pygame.draw.rect(self.surface, self.default_color, (self.x, self.y, self.width, self.height), 0, int(self.height / 2))
        pygame.draw.rect(self.surface, self.outline_color, (self.x-2, self.y-2, self.width+4, self.height+4), 4, int(self.height / 2))
        if active:
            pygame.draw.circle(self.surface, self.enable_color, (self.x + 70, self.y + 18), 18)
            pygame.draw.circle(self.surface, self.outline_color, (self.x + 70, self.y + 18), 18, 4)
        else:
            pygame.draw.circle(self.surface, self.disable_color, (self.x + 16, self.y + 18), 18)
            pygame.draw.circle(self.surface, self.outline_color, (self.x + 16, self.y + 18), 18, 4)

    def is_over(self, bkp_pos=None) -> bool:
        '''Returns true if mouse is over'''
        if bkp_pos == None:
            self.pos = pygame.mouse.get_pos()
        else:
            self.pos = bkp_pos
        if self.pos[0] > self.x and self.pos[0] < self.x + self.width and self.pos[1] > self.y and self.pos[1] < self.y + self.height:
            return True
        else:
            return False

    def smart_draw(self, active, bkp_pos=None) -> bool:
        '''Draws the switch and returns if it's been clicked at recently'''
        self.draw(active, bkp_pos, self.is_over(bkp_pos))
        if not self.was_pressed and pygame.mouse.get_pressed()[0]:
            self.was_pressed = True
            is_clicked = True
        elif self.was_pressed and pygame.mouse.get_pressed()[0]:
            self.was_pressed = True
            is_clicked = False
        else:
            self.was_pressed = False
            is_clicked = False
        return self.is_over(bkp_pos) and is_clicked


import qgis, qgis.utils, os, datetime, PIL, platform
if platform.system() == 'Windows':
    from PIL import ImageGrab
from PIL.ImageQt import ImageQt

from qgis.PyQt import uic, QtCore, QtGui
from qgis.PyQt.QtWidgets import (QWidget,QMainWindow, QSpinBox, QAction, QDialog, QFrame)

from ...lamia_abstractformtool import AbstractLamiaFormTool
from .lamiabase_photoviewer import PhotoViewer

class BaseCroquisTool(AbstractLamiaFormTool):

    PREPROTOOLNAME = 'Croquis'
    DBASETABLENAME = 'Photo'
    LOADFIRST = False

    tooltreewidgetCAT = 'Ressources'
    tooltreewidgetSUBCAT = 'Croquis'
    tooltreewidgetICONPATH = os.path.join(os.path.dirname(__file__), 'lamiabase_croquis_tool_icon.png')

    tempparentjoin = {}
    linkdict = {'colparent': 'id_objet',
                'colthistable': 'id_ressource',
                    'tctable': 'Tcobjetressource',
                    'tctablecolparent':'lid_objet',
                    'tctablecolthistable':'lid_ressource'}
    for tablename in ['Observation', 'Noeud', 'Infralineaire', 'Equipement']:
        tempparentjoin[tablename] = linkdict
    PARENTJOIN = tempparentjoin

    TABLEFILTERFIELD = {'typephoto': 'CRO' }
    GEOMETRYSKIP = True

    def __init__(self, **kwargs):
        super(BaseCroquisTool, self).__init__(**kwargs)
    """
    def initTool(self):
        # ****************************************************************************************
        # Main spec
        self.CAT = 'Ressources'
        self.NAME = 'Croquis'
        self.dbasetablename = 'Photo'
        self.visualmode = [ 1, 2]
        # self.PointENABLED = True
        # self.LineENABLED = True
        # self.PolygonEnabled = True
        # self.magicfunctionENABLED = True
        self.linkagespec = {'Tcobjetressource' : {'tabletc' : 'Tcobjetressource',
                                              'idsource' : 'id_ressource',
                                            'idtcsource' : 'lid_ressource',
                                           'iddest' : 'id_objet',
                                           'idtcdest' : 'lid_objet',
                                           'desttable' : ['Profil','Infralineaire','Observation','Equipement','Noeud']} }
        # self.pickTable = None
        self.iconpath = os.path.join(os.path.dirname(__file__), 'lamiabase_croquis_tool_icon.png')

        # ****************************************************************************************
        #properties ui
        pass
    """

    def initMainToolWidget(self):
        # ****************************************************************************************
        # userui
        self.toolwidgetmain = UserUI()
        self.formtoolwidgetconfdictmain = {'Photo' : {'linkfield' : 'id_photo',
                                            'widgets' : {}},
                                            'Objet' : {'linkfield' : 'id_objet',
                                                        'widgets' : {}},
                                            'Ressource' : {'linkfield' : 'id_ressource',
                                                        'widgets' : {}}}

        # self.groupBox_geom.setParent(None)
        # self.frame_editing.setVisible(False)
        self.toolwidgetmain.stackedWidget.setCurrentIndex(1)

        self.toolwidgetmain.pushButton_open.clicked.connect(self.openPhoto)
        self.toolwidgetmain.pushButton_edit.clicked.connect(self.editPhoto)
        self.toolwidgetmain.pushButton_getfromclipboard.clicked.connect(self.pasteImage)
        self.editorwindow = ScribbleMainWindow(parentwdg=self)
        self.photowdg = PhotoViewer()
        self.toolwidgetmain.frame_cr.layout().addWidget(self.photowdg)

    """
    def postOnActivation(self):
        pass

    def postOnDesactivation(self):
        pass

    def postloadIds(self,sqlin):
        sqlin += " AND typephoto = 'CRO'"
        return sqlin
    """
    #def postInitFeatureProperties(self, feat):
    def postSelectFeature(self):

        if self.currentFeaturePK is None:   #first time
            datecreation = str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            self.formutils.applyResultDict({'Ressource':{'datetimeressource' : datecreation}})
            self.editorwindow.reinitSize()
            self.editorwindow.clear()
            self.photowdg.clear()

        else:
            sql = "SELECT file FROM photo_qgis  WHERE pk_photo = " + str(self.currentFeaturePK)
            file = self.dbase.query(sql)[0][0]
            if file is not None and file != '' and os.path.isfile(self.dbase.completePathOfFile(file)) :
                self.editorwindow.openImage(self.dbase.completePathOfFile(file))
                self.formutils.showImageinLabelWidget(self.photowdg, self.dbase.completePathOfFile(file))
            else:
                self.editorwindow.clear()
                self.photowdg.clear()

    def pasteImage(self):
        if platform.system() == 'Windows':
            pilimage = PIL.ImageGrab.grabclipboard()
            if pilimage is not None:
                im = ImageQt(pilimage )
                # self.editorwindow.scribbleArea
                #self.image = loadedImage
                #self.modified = False
                #self.update()
                self.editorwindow.setImage(im)
                #self.editorwindow.scribbleArea.image = im
                #self.editorwindow.scribbleArea.update()
                self.photowdg.clear()
                self.photowdg.setPixmap(im)

                self.editPhoto()

    def editPhoto(self):
        if qgis.utils.iface is not None :
            self.editorwindow.show()
        else:
            self.editorwindow.setWindowModality(QtCore.Qt.ApplicationModal)
            self.editorwindow.show()

    def openPhoto(self):
        if False:
            if os.path.isfile(self.dbase.completePathOfFile(self.currentFeature['File'] )):
                filepath = self.dbase.completePathOfFile(self.currentFeature['File'])
                os.startfile(filepath)

        if True:
            #sql = "SELECT file FROM Ressource  WHERE id_ressource = " + str(self.currentFeature['id_ressource']) + ";"
            sql = "SELECT file FROM photo_qgis  WHERE pk_photo = " + str(self.currentFeaturePK)
            query = self.dbase.query(sql)
            #result = [row[0] for row in query]
            resultfile = query[0][0]
            if os.path.isfile(self.dbase.completePathOfFile(resultfile)):
                filepath = self.dbase.completePathOfFile(resultfile)
                os.startfile(filepath)

    """
    def createParentFeature(self):
        pkobjet = self.dbase.createNewObjet()

        if False:
            # lastrevision = self.dbase.maxrevision
            datetimecreation =  str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            lastobjetid = self.dbase.getLastId('Objet') + 1
            sql = "INSERT INTO Objet (id_objet, lpk_revision_begin, datetimecreation ) "
            sql += "VALUES(" + str(lastobjetid ) + "," + str(self.dbase.maxrevision) +  ",'" + datetimecreation + "');"
            query = self.dbase.query(sql)
            self.dbase.commit()
            pkobjet = self.dbase.getLastRowId('Objet')

        lastressourceid = self.dbase.getLastId('Ressource') + 1
        sql = "INSERT INTO Ressource (id_ressource, lpk_objet) "
        sql += "VALUES(" + str(lastressourceid) +   "," + str(pkobjet) + ");"
        query = self.dbase.query(sql)
        self.dbase.commit()
        pkres = self.dbase.getLastRowId('Ressource')

        pkphoto = self.currentFeaturePK
        lastidphoto = self.dbase.getLastId('Photo') + 1
        datecreation = datetime.datetime.now().strftime("%Y-%m-%d")
        datetimecreation = str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

        fileimage = os.path.join('.', self.dbasetablename, ''.join(datecreation.split('-')),
                                 str(lastidphoto) + '_croquis.png')
        if not os.path.exists(os.path.dirname(self.dbase.completePathOfFile(fileimage))):
            os.makedirs(os.path.dirname(self.dbase.completePathOfFile(fileimage)))
        self.editorwindow.saveImage(self.dbase.completePathOfFile(fileimage))

        sql = "UPDATE Photo SET id_photo = " + str(lastidphoto)  + ","
        sql += "lpk_ressource = " + str(pkres)
        sql += ", typephoto = 'CRO' "
        sql += " WHERE pk_photo = " + str(pkphoto) + ";"
        query = self.dbase.query(sql)
        self.dbase.commit()

        sql = "UPDATE Ressource SET  file = '" + fileimage + "', datetimeressource = '" + datetimecreation + "'"
        sql += " WHERE pk_ressource = " + str(pkres) + ";"
        query = self.dbase.query(sql)
        self.dbase.commit()

        if self.parentWidget is not None and self.parentWidget.currentFeature is not None:
            # self.linkagespec = {'Tcobjetressource'
            if 'Tcobjetressource' in self.linkagespec.keys():
                #get parent id_objet
                sql = " SELECT id_objet FROM " + self.parentWidget.dbasetablename.lower() + "_qgis"
                sql += " WHERE pk_" + self.parentWidget.dbasetablename.lower() + " = " + str(self.parentWidget.currentFeaturePK)
                currentparentlinkfield = self.dbase.query(sql)[0][0]

                #currentparentlinkfield = self.parentWidget.currentFeature['id_objet']
                sql = "INSERT INTO Tcobjetressource(lpk_revision_begin, lid_objet, lid_ressource) "
                sql += " VALUES(" + str(self.dbase.maxrevision) + "," + str(currentparentlinkfield) + ',' + str(lastressourceid) + ")"
                query = self.dbase.query(sql)
                self.dbase.commit()

        if False:
            #lastrevision = self.dbase.getLastPk('Revision')
            lastrevision = self.dbase.maxrevision
            datecreation = QtCore.QDate.fromString(str(datetime.date.today()), 'yyyy-MM-dd').toString('yyyy-MM-dd')
            lastobjetid = self.dbase.getLastId('Objet') + 1
            sql = "INSERT INTO Objet (id_objet, id_revisionbegin, datecreation ) "
            sql += "VALUES(" + str(lastobjetid ) + "," + str(lastrevision) +  ",'" + datecreation + "');"
            query = self.dbase.query(sql)
            self.dbase.commit()
            #idobjet = self.dbase.getLastRowId('Objet')

            lastressourceid = self.dbase.getLastId('Ressource') + 1
            sql = "INSERT INTO Ressource (id_ressource, id_revisionbegin, id_objet) "
            sql += "VALUES(" + str(lastressourceid) + "," + str(lastrevision) +  "," + str(lastobjetid) + ");"
            query = self.dbase.query(sql)
            self.dbase.commit()
            lastressourcepk = self.dbase.getLastRowId('Ressource')

            pkcroquis = self.currentFeature.id()
            lastidcroquis = self.dbase.getLastId('Photo') + 1

            fileimage = os.path.join('.', self.dbasetablename, ''.join(datecreation.split('-')),
                                     str(lastidcroquis) + '_croquis.png')
            if not os.path.exists(os.path.dirname(self.dbase.completePathOfFile(fileimage))):
                os.makedirs(os.path.dirname(self.dbase.completePathOfFile(fileimage)))
            self.editorwindow.saveImage(self.dbase.completePathOfFile(fileimage))

            sql = "UPDATE Photo SET id_objet = " + str(lastobjetid)  + ","
            sql += "id_ressource = " + str(lastressourceid)   + ","
            sql += "id_photo = " + str(lastidcroquis)  + ","
            sql += "id_revisionbegin = " + str(lastrevision) + ","
            sql += "typephoto = 'CRO' "
            sql += " WHERE pk_photo = " + str(pkcroquis) + ";"
            query = self.dbase.query(sql)
            self.dbase.commit()

            sql = "UPDATE Ressource SET  file = '" + fileimage + "', dateressource = '" + datecreation + "'"
            sql += " WHERE pk_ressource = " + str( lastressourcepk) + ";"
            query = self.dbase.query(sql)
            self.dbase.commit()

            if self.parentWidget is not None and self.parentWidget.currentFeature is not None:
                currentparentlinkfield = self.parentWidget.currentFeature['id_objet']
                sql = "INSERT INTO Tcobjetressource(id_tcobjet, id_tcressource,id_revisionbegin) "
                sql += " VALUES(" + str(currentparentlinkfield) + ", " + str(lastressourceid) + "," + str(lastrevision) + ");"
                query = self.dbase.query(sql)
                self.dbase.commit()
    """

    def postSaveFeature(self, savedfeaturepk=None):

        if self.currentFeaturePK is None:   #first creation
            idphoto, pkres = self.dbase.getValuesFromPk(self.DBASETABLENAME.lower() + '_qgis',
                                                 ['id_' + self.DBASETABLENAME.lower(),'pk_ressource'],
                                                 savedfeaturepk)
            datecreation = datetime.datetime.now().strftime("%Y-%m-%d")
            datetimecreation = str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

            sql = "UPDATE Photo SET  typephoto = 'CRO' WHERE pk_photo = {}".format(str(savedfeaturepk))
            query = self.dbase.query(sql)

            fileimage = os.path.join('.', self.DBASETABLENAME, ''.join(datecreation.split('-')),
                                    str(idphoto) + '_croquis.png')
            if not os.path.exists(os.path.dirname(self.dbase.completePathOfFile(fileimage))):
                os.makedirs(os.path.dirname(self.dbase.completePathOfFile(fileimage)))
            #self.editorwindow.saveImage(self.dbase.completePathOfFile(fileimage))

            sql = "UPDATE Ressource SET  file = '" + fileimage + "', datetimeressource = '" + datetimecreation + "'"
            sql += " WHERE pk_ressource = " + str(pkres)
            query = self.dbase.query(sql)

        else:
            """
            sql = "SELECT file FROM Photo_qgis WHERE pk_photo = " + str(self.currentFeaturePK)
            query = self.dbase.query(sql)
            fileimage = [row[0] for row in query][0]
            """
            fileimage = self.dbase.getValuesFromPk(self.DBASETABLENAME + '_qgis',
                                                 'file',
                                                 self.currentFeaturePK )
        self.editorwindow.saveImage(self.dbase.completePathOfFile(fileimage))

    """
    def deleteParentFeature(self):
        sql = "SELECT pk_objet, pk_ressource, id_ressource FROM Photo_qgis WHERE pk_photo = " + str(self.currentFeaturePK)
        pkobjet, pkressource, idressource = self.dbase.query(sql)[0]
        #idobjet = self.currentFeature['id_objet']
        #idressource = self.currentFeature['id_ressource']

        sql = "DELETE FROM Objet WHERE pk_objet = " + str(pkobjet)
        query = self.dbase.query(sql)
        self.dbase.commit()

        sql = "DELETE FROM Ressource WHERE pk_ressource = " + str(pkressource)
        query = self.dbase.query(sql)
        self.dbase.commit()

        sql = "DELETE FROM Tcobjetressource WHERE id_tcressource = " + str(idressource)
        sql += " AND lpk_revision_begin <= " + str(self.dbase.maxrevision)
        sql += " AND lpk_revision_end IS  NULL "

        return True
    """

class UserUI(QWidget):
    def __init__(self, parent=None):
        super(UserUI, self).__init__(parent=parent)
        uipath = os.path.join(os.path.dirname(__file__), 'lamiabase_photo_tool_ui.ui')
        uic.loadUi(uipath, self)

class ScribbleMainWindow(QMainWindow):
    def __init__(self, parentwdg=None, parent=None):
        super(ScribbleMainWindow, self).__init__(parent=parent)
        uipath = os.path.join(os.path.dirname(__file__), 'lamiabase_croquis_tool_drawingwidg_ui.ui')
        uic.loadUi(uipath, self)
        self.parentwdg = parentwdg
        self.scribbleArea = ScribbleArea(parent=self)
        self.scribbleArea.clearImage()
        self.scribbleArea.mainWindow = self  # maybe not using this?

        self.scrollArea.setWidget(self.scribbleArea)

        self.toolbar = self.addToolBar('Color')
        self.colorwdg = qgis.gui.QgsColorButton()
        self.colorwdg.setColor(QtCore.Qt.black)
        self.toolbar.addWidget(self.colorwdg)
        self.spinb = QSpinBox()
        self.spinb.setValue(3)
        self.toolbar.addWidget(self.spinb)

        self.spinb.valueChanged.connect(self.scribbleArea.setPenWidth)
        self.colorwdg.colorChanged.connect(self.scribbleArea.setPenColor)

        self.clearAction = QAction('Clear', self)
        self.clearAction.triggered.connect(self.scribbleArea.clearImage)
        self.toolbar.addAction(self.clearAction)

        self.reinitAction = QAction('reinit', self)
        self.reinitAction.triggered.connect(self.scribbleArea.reinit)
        self.toolbar.addAction(self.reinitAction)

    def reinitSize(self):
        self.scribbleArea.reinitSize()

    def saveImage(self,file):
        self.scribbleArea.saveImage(file,"png")

    def clear(self):
        self.scribbleArea.clearImage()

    def openImage(self,file):
        self.scribbleArea.openImage(file)

    def setImage(self, qimage):
        self.scribbleArea.setImage(qimage)

    def closeEvent(self, event):
        self.parentwdg.photowdg.clear()
        self.parentwdg.photowdg.setPixmap(self.scribbleArea.image)
        event.accept()

class ScribbleArea(QWidget):
    """
      this scales the image but it's not good, too many refreshes really mess it up!!!
    """
    def __init__(self, larg=500,haut=500, parent=None):
        super(ScribbleArea, self).__init__(parent)

        #self.setAttribute(QtCore.Qt.WA_StaticContents)
        self.setFixedSize(larg, haut)
        self.modified = False
        self.scribbling = False
        self.myPenWidth = 3
        self.myPenColor = QtCore.Qt.black
        imageSize = QtCore.QSize(larg, haut)
#       self.image = QtGui.QImage()
        self.image = QtGui.QImage(imageSize, QtGui.QImage.Format_RGB32)
        self.lastPoint = QtCore.QPoint()

        self.currentfilename=None

    def openImage(self, fileName=None):
        loadedImage = QtGui.QImage()
        if not loadedImage.load(fileName):
            return False
        self.currentfilename = fileName
        return self.setImage(loadedImage)

    def reinit(self):
        if self.currentfilename is not None:
            self.openImage(self.currentfilename)

    def reinitSize(self):
        self.setFixedSize(500, 500)
        self.mainWindow.resize(500, 500)
        imageSize = QtCore.QSize(500, 500)
        self.image = QtGui.QImage(imageSize, QtGui.QImage.Format_RGB32)

    def setImage(self, loadedImage):
        w = loadedImage.width()
        h = loadedImage.height()
        self.setFixedSize(w, h)
        self.mainWindow.resize(w, h)

        #       newSize = loadedImage.size().expandedTo(self.size())
        #       self.resizeImage(loadedImage, newSize)
        self.image = loadedImage
        self.modified = False
        self.update()
        return True

    def saveImage(self, fileName, fileFormat):
        if self.image.save(fileName, fileFormat):
            self.modified = False
            return True
        else:
            return False

    def setPenColor(self, newColor):
        self.myPenColor = newColor

    def setPenWidth(self, newWidth):
        self.myPenWidth = newWidth

    def clearImage(self):
        #print('celar')
        self.image.fill(QtGui.qRgb(255, 255, 255))
        self.modified = True
        self.update()

    def mousePressEvent(self, event):
#       print "self.image.width() = %d" % self.image.width()
#       print "self.image.height() = %d" % self.image.height()
#       print "self.image.size() = %s" % self.image.size()
#       print "self.size() = %s" % self.size()
#       print "event.pos() = %s" % event.pos()
        if event.button() == QtCore.Qt.LeftButton:
            self.lastPoint = event.pos()
            self.scribbling = True

    def mouseMoveEvent(self, event):
        if (event.buttons() & QtCore.Qt.LeftButton) and self.scribbling:
            self.drawLineTo(event.pos())

    def mouseReleaseEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton and self.scribbling:
            self.drawLineTo(event.pos())
            self.scribbling = False

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.drawImage(event.rect(), self.image,event.rect())

    if False:
        def resizeEvent(self, event):
            #       print "resize event"
            #       print "event = %s" % event
            #       print "event.oldSize() = %s" % event.oldSize()
            #       print "event.size() = %s" % event.size()

            self.resizeImage(self.image, event.size())

            #       if self.width() > self.image.width() or self.height() > self.image.height():
            #           newWidth = max(self.width() + 128, self.image.width())
            #           newHeight = max(self.height() + 128, self.image.height())
            #           print "newWidth = %d, newHeight = %d" % (newWidth, newHeight)
            #           self.resizeImage(self.image, QtCore.QSize(newWidth, newHeight))
            #           self.update()

            super(ScribbleArea, self).resizeEvent(event)

    def drawLineTo(self, endPoint):
        painter = QtGui.QPainter(self.image)
        painter.setPen(QtGui.QPen(self.myPenColor, self.myPenWidth,
            QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin))
        painter.drawLine(self.lastPoint, endPoint)
        self.modified = True

        # rad = self.myPenWidth / 2 + 2
        # self.update(QtCore.QRect(self.lastPoint, endPoint).normalized().adjusted(-rad, -rad, +rad, +rad))
        self.update()
        self.lastPoint = QtCore.QPoint(endPoint)

    if False:
        def resizeImage(self, image, newSize):
            if image.size() == newSize:
                return

            #       print "image.size() = %s" % repr(image.size())
            #       print "newSize = %s" % newSize

            # this resizes the canvas without resampling the image
            newImage = QtGui.QImage(newSize, QtGui.QImage.Format_RGB32)
            newImage.fill(QtGui.qRgb(255, 255, 255))
            painter = QtGui.QPainter(newImage)
            painter.drawImage(QtCore.QPoint(0, 0), image)

            ##  this resampled the image but it gets messed up with so many events...
            ##      painter.setRenderHint(QtGui.QPainter.SmoothPixmapTransform, True)
            ##      painter.setRenderHint(QtGui.QPainter.HighQualityAntialiasing, True)
            #
            #       newImage = QtGui.QImage(newSize, QtGui.QImage.Format_RGB32)
            #       newImage.fill(QtGui.qRgb(255, 255, 255))
            #       painter = QtGui.QPainter(newImage)
            #       srcRect = QtCore.QRect(QtCore.QPoint(0,0), image.size())
            #       dstRect = QtCore.QRect(QtCore.QPoint(0,0), newSize)
            ##      print "srcRect = %s" % srcRect
            ##      print "dstRect = %s" % dstRect
            #       painter.drawImage(dstRect, image, srcRect)

            self.image = newImage

    def print_(self):
        printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution)

        printDialog = QtGui.QPrintDialog(printer, self)
        if printDialog.exec_() == QDialog.Accepted:
            painter = QtGui.QPainter(printer)
            rect = painter.viewport()
            size = self.image.size()
            size.scale(rect.size(), QtCore.Qt.KeepAspectRatio)
            painter.setViewport(rect.x(), rect.y(), size.width(), size.height())
            painter.setWindow(self.image.rect())
            painter.drawImage(0, 0, self.image)
            painter.end()

    def isModified(self):
        return self.modified

    def penColor(self):
        return self.myPenColor

    def penWidth(self):
        return self.myPenWidth


from rest_framework import serializers

from app.models import Book

class BookModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ("book_name", "price", "publish", "authors", "pic")
        extra_kwargs = {
            'book_name': {
                'required': True,
                'min_length': 2,
                'error_message': {
                    'required': '图书名必须提供',
                    'min_length': '图书名不能少于两个字',
                }
            },
            'pic': {
                'read_only': True
            },
            'publish': {
                'write_only': True
            },
            'authors': {
                'write_only': True
            },
        }

    def validate(self, attrs):
        return attrs

    def validate_book_name(self, value):
        return value


#!/usr/bin/env python
# coding: utf-8

# In[1]:

# Importing all libraries required in this notebook
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')

# In[2]:

link= "http://bit.ly/w-data"
data=pd.read_csv(link)

# In[3]:

print("Data imported successfully")
data.head(10)

# In[5]:

# Plotting the distribution of scores
data.plot(x='Hours', y='Scores', style='o')
plt.title('Hours vs Percentage')
plt.xlabel('Hours Studied')
plt.ylabel('Percentage Score')
plt.show()

# In[6]:

x=data.iloc[:,:-1].values
y=data.iloc[:,1].values

# In[7]:

x

# In[8]:

from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)

# In[9]:

x_test

# In[10]:

from sklearn.linear_model import LinearRegression

# In[11]:

LR=LinearRegression()
LR.fit(x_train,y_train)
print("We have successfully train the algo")

# In[12]:

# Plotting the regression line
line = LR.coef_*x+LR.intercept_

# Plotting for the test data
plt.scatter(x, y)
plt.plot(x, line);
plt.show()

# In[13]:

# Predicting the scores
y_pred = LR.predict(x_test)

# In[14]:

y_pred

# In[15]:

# Comparing Actual vs Predicted
df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
df

# In[17]:

from sklearn import metrics
print('Mean Absolute Error:',
      metrics.mean_absolute_error(y_test, y_pred))

# In[ ]:


import json

# ASCII symbol to sokoban entity
# I've assumed that the sokoban robot starts from his docking station
conversion_dict = {
	'#': 'U',
	'@': 'RD',
	'$': 'B',
	'.': 'G',
	' ': ' '
}

def convert_line(line, line_counter):
	"""Converts an ASCIIart sokoban instance to a JSON request that can be passed to the server thru curl"""
	cells = []
	# cell = collections.OrderedDict({})
	cell = {}

	for x in range(len(line)):
		cell = {'y': line_counter, 'x': x, 'entities': conversion_dict[line[x]]}
		cells.append(cell)
	return cells

def parse_ASCII(file_in):
	"""Parses a file to extract the ASCII art"""
	sokoban_instance = {'version': 1.0}
	cell_list = []

	with open(file_in, 'r') as f:
		lines = [line.rstrip('\n') for line in f]

	rows = len(lines)
	columns = len(lines[0])

	line_counter = 0

	# check walls presence at the beginning & at the end of the file
	if ''.join(lines[0]) != '#' * columns or ''.join(lines[-1]) != '#' * columns:
		raise ValueError("Unexpected file format @ line {}".format(line_counter))

	for l in lines:
		if line_counter == 0 or line_counter == len(lines) - 1:
			pass
		else:
			if len(l) > 0:
				if l[0] != '#' or l[-1] != '#':  # expecting a starting (and ending) wall for each line
					raise ValueError("Unexpected file format @ line {}".format(line_counter))
				else:
					formatted_line = l[1:len(l) - 1]  # remove walls in the line
					line2cells = convert_line(line=formatted_line, line_counter=line_counter)
					for cell in line2cells:
						cell_list.append(cell)
		line_counter += 1

	world_instance = {'rows': rows, 'columns': columns, 'cells': cell_list}
	sokoban_instance['world'] = world_instance

	return sokoban_instance

def dict_2_json(d, file_out):
	"""Write a dictionary to a file"""
	with open(file_out, 'w') as f:
		json.dump(d, f, indent=4)

# main for quick testing
# if __name__ == '__main__':
# 	instance = parse_ASCII(file_in=r'C:\Users\Nicola\Desktop\ZUMOrobot\Robotieee\Server\planner_wrapper\tests\sokoban_example2.txt')
# 	dict_2_json(d=instance, file_out=r'C:\Users\Nicola\Desktop\ZUMOrobot\Robotieee\Server\planner_wrapper\tests\sokoban_out.json')


from typing import Any, Optional, Tuple, Union

import torch
import torch.nn as nn
from torch.autograd import Function

from ..utils import ext_loader, is_tuple_of

ext_module = ext_loader.load_ext(
    '_ext', ['riroi_align_rotated_forward', 'riroi_align_rotated_backward'])

class RiRoIAlignRotatedFunction(Function):

    @staticmethod
    def forward(ctx: Any,
                features: torch.Tensor,
                rois: torch.Tensor,
                out_size: Union[int, tuple],
                spatial_scale: float,
                num_samples: int = 0,
                num_orientations: int = 8,
                clockwise: bool = False) -> torch.Tensor:
        if isinstance(out_size, int):
            out_h = out_size
            out_w = out_size
        elif is_tuple_of(out_size, int):
            assert len(out_size) == 2
            out_h, out_w = out_size
        else:
            raise TypeError(
                f'"out_size" should be an integer or tuple of integers,'
                f' but got {out_size}')
        ctx.spatial_scale = spatial_scale
        ctx.num_samples = num_samples
        ctx.num_orientations = num_orientations
        ctx.clockwise = clockwise
        ctx.save_for_backward(rois)
        ctx.feature_size = features.size()

        batch_size, num_channels, _, _ = features.size()
        num_rois = rois.size(0)

        output = features.new_zeros(num_rois, num_channels, out_h, out_w)

        ext_module.riroi_align_rotated_forward(
            features,
            rois,
            output,
            pooled_height=out_h,
            pooled_width=out_w,
            spatial_scale=spatial_scale,
            num_samples=num_samples,
            num_orientations=num_orientations,
            clockwise=clockwise)
        return output

    @staticmethod
    def backward(
        ctx: Any, grad_output: torch.Tensor
    ) -> Optional[Tuple[torch.Tensor, None, None, None, None, None, None]]:
        feature_size = ctx.feature_size
        spatial_scale = ctx.spatial_scale
        num_orientations = ctx.num_orientations
        clockwise = ctx.clockwise
        num_samples = ctx.num_samples
        rois = ctx.saved_tensors[0]
        assert feature_size is not None
        batch_size, num_channels, feature_h, feature_w = feature_size

        out_w = grad_output.size(3)
        out_h = grad_output.size(2)

        grad_input = None

        if ctx.needs_input_grad[0]:
            grad_input = rois.new_zeros(batch_size, num_channels, feature_h,
                                        feature_w)
            ext_module.riroi_align_rotated_backward(
                grad_output.contiguous(),
                rois,
                grad_input,
                pooled_height=out_h,
                pooled_width=out_w,
                spatial_scale=spatial_scale,
                num_samples=num_samples,
                num_orientations=num_orientations,
                clockwise=clockwise)

            return grad_input, None, None, None, None, None, None
        return None

riroi_align_rotated = RiRoIAlignRotatedFunction.apply

class RiRoIAlignRotated(nn.Module):
    """Rotation-invariant RoI align pooling layer for rotated proposals.

    It accepts a feature map of shape (N, C, H, W) and rois with shape
    (n, 6) with each roi decoded as (batch_index, center_x, center_y,
    w, h, angle). The angle is in radian.

    The details are described in the paper `ReDet: A Rotation-equivariant
    Detector for Aerial Object Detection  <https://arxiv.org/abs/2103.07733>`_.

    Args:
        out_size (tuple): fixed dimensional RoI output with shape (h, w).
        spatial_scale (float): scale the input boxes by this number
        num_samples (int): number of inputs samples to take for each
            output sample. 0 to take samples densely for current models.
        num_orientations (int): number of oriented channels.
        clockwise (bool): If True, the angle in each proposal follows a
            clockwise fashion in image space, otherwise, the angle is
            counterclockwise. Default: False.
    """

    def __init__(self,
                 out_size: tuple,
                 spatial_scale: float,
                 num_samples: int = 0,
                 num_orientations: int = 8,
                 clockwise: bool = False):
        super().__init__()

        self.out_size = out_size
        self.spatial_scale = float(spatial_scale)
        self.num_samples = int(num_samples)
        self.num_orientations = int(num_orientations)
        self.clockwise = clockwise

    def forward(self, features: torch.Tensor,
                rois: torch.Tensor) -> torch.Tensor:
        return RiRoIAlignRotatedFunction.apply(features, rois, self.out_size,
                                               self.spatial_scale,
                                               self.num_samples,
                                               self.num_orientations,
                                               self.clockwise)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import torch.nn as nn

# Do not change these imports; your module names should be
#   `CNN` in the file `cnn.py`
#   `Highway` in the file `highway.py`
# Uncomment the following two imports once you're ready to run part 1(f)

from cnn import CNN
from highway import Highway

# End "do not change"

class ModelEmbeddings(nn.Module):
    """
    Class that converts input words to their CNN-based embeddings.
    """

    def __init__(self, embed_size, vocab, char_embed_size=50):
        """
        Init the Embedding layer for one language
        @param embed_size (int): Embedding size (dimensionality) for the output
        @param vocab (VocabEntry): VocabEntry object. See vocab.py for documentation.
        """
        super(ModelEmbeddings, self).__init__()

        ## A4 code
        # pad_token_idx = vocab.src['<pad>']
        # self.embeddings = nn.Embedding(len(vocab.src), embed_size, padding_idx=pad_token_idx)
        ## End A4 code

        ### YOUR CODE HERE for part 1f
        self.embed_size = embed_size
        self.char_embed_size = char_embed_size
        self.pad_token_idx = vocab.char2id['<pad>']
        self.char_embeddings = nn.Embedding(len(vocab.char2id), self.char_embed_size, padding_idx = self.pad_token_idx)
        self.cnn = CNN(self.char_embed_size, self.embed_size)
        self.highway = Highway(self.embed_size)
        self.dropout = nn.Dropout(p=0.3)
        ### END YOUR CODE

    def forward(self, input_tensor):
        """
        Looks up character-based CNN embeddings for the words in a batch of sentences.
        @param input_tensor: Tensor of integers of shape (sentence_length, batch_size, max_word_length) where
            each integer is an index into the character vocabulary

        @param output: Tensor of shape (sentence_length, batch_size, embed_size), containing the
            CNN-based embeddings for each word of the sentences in the batch
        """
        ## A4 code
        # output = self.embeddings(input)
        # return output
        ## End A4 code
        ### YOUR CODE HERE for part 1f
        sentence_length, batch_size, max_word_length = input_tensor.shape[0], input_tensor.shape[1], input_tensor.shape[2]
        x = self.char_embeddings(input_tensor) # (sentence_length, batch_size, max_word_len, char_embed_size)
        x = x.permute(0,1,3,2) # change it to sentence_length, batch_size, char_embed_size, max_word_length

        x = x.reshape(-1, self.char_embed_size, max_word_length) # sentence_len* batch_size, char_embed_size, max_word_length
        # Test x.shape == (char_embed_size, m_word)
        x_conv = self.cnn(x)
        x_highway = self.highway(x_conv)
        x_highway = x_highway.reshape(sentence_length, batch_size, -1) # undo the shape unwrapping the same way you did. x_highway is supposed to be sentence first, batch second.
        x_word_embed = self.dropout(x_highway)
        return x_word_embed
        ### END YOUR CODE


'''
This could be improved by using networkx during part 1 instead of walking back and forth repeatedly
- may be a task for a later date.
'''
class Node():
    def __init__(self, x,y, path, closed, result, goal=False):
        self.x = x
        self.y = y
        self.path = path
        self.closed = closed
        self.result = result
        self.distance = len(path)
        self.goal = goal
        self.oxygenated = False

    def __repr__(self):
        return "({},{})N".format(self.x,self.y)

def update_location(x,y,dr):
    '''Converts intcomputer-readable movement to x,y coordinates'''
    if dr==1:
        return x,y+1
    elif dr==2:
        return x,y-1
    elif dr==3:
        return x-1,y
    elif dr==4:
        return x+1,y

def wiggle(x,y,nodes,movement_options,reverse_movement,path,brain):
    '''Uses the intcode computer brain to visit nearby locations (adjacent to x,y), and check if they are open.
    Logs their information.'''
    # wiggle (based on x,y)
    for i in range(4):
        movement = movement_options[i]
        reverse = reverse_movement[i]

        new_x,new_y = update_location(x,y,movement)

        # skip node if it's been calculated before
        # might need to change to check for shorter path later
        if (new_x,new_y) in [(node.x,node.y) for node in nodes]:
            #print('skipping {},{}'.format(new_x,new_y))
            continue

        if new_x==0 and new_y==0:
            print('wow ok')
        current_path = path+[movement]
        # try move and find out what's there
        brain.add_input(movement)
        brain.process_code()
        result = brain.outputs[-1]

        # store result (if wall, empty, or goal)
        nodes.append(Node(new_x,new_y, path=current_path, closed=(result==0),
                                                    result=result, goal=(result==2)))

        if result>0:
            # move back to starting location
            brain.add_input(reverse)
            brain.process_code()
            assert brain.outputs[-1]!=0

    return nodes

def part_1(brain):
    '''Fills out the list nodes by traveling to each node individually, then "wiggling" to visit each neighbor,
    while keeping track of position. Will continue until all locations have been tested.'''

    nodes = []
    movement_options = np.arange(1,5)
    reverse_movement = movement_options[[1,0,3,2]]

    # start at 0,0
    x,y = 0,0

    # store location
    nodes.append(Node(x,y,path=[], result=1, closed=False))

    max_distance = -1
    while max_distance!=max([node.distance for node in nodes]):
        max_distance = max([node.distance for node in nodes])

        # pick next x,y to wiggle around
        for node in nodes:
            if node.distance==max_distance and ~node.closed:
                # move to node
                for dr in node.path:
                    brain.add_input(dr)
                    result = brain.process_code()
                    assert result!=0

                # wiggle
                nodes = wiggle(node.x,node.y,nodes,movement_options,reverse_movement,node.path,brain)

                # return to start
                for dr in node.path[::-1]:
                    brain.add_input(reverse_movement[dr-1])
                    assert brain.process_code()!=0

    return nodes

def part_2(nodes, goal_node):
    '''Uses input list of nodes to create a graph in using networkx, then finds the furthest distance
    from any node in the graph to the goal node'''
    import networkx as nx

    # convert nodes to dictionary
    node_guide = {(node.x,node.y):node.result for node in nodes}

    g = nx.Graph()

    # add all edges to graph
    for x,y in node_guide.keys():
        result = node_guide[(x,y)]

        if result==0:
            continue

        if node_guide[(x-1,y)] == 1:
            g.add_edge((x,y), (x-1,y))
        if node_guide[(x+1,y)] == 1:
            g.add_edge((x,y), (x+1,y))
        if node_guide[(x,y-1)] == 1:
            g.add_edge((x,y), (x,y-1))
        if node_guide[(x,y+1)] == 1:
            g.add_edge((x,y), (x,y+1))

    # iterate through every location, finding the maximum number of steps from the oxygenated node
    # this is the number of minutes it will take for oxygen to fill the entire map
    num_minutes = 0
    for x, y in node_guide.keys():
        if node_guide[(x,y)]==0:
            continue
        path_length =  len(nx.dijkstra_path(g,(goal_node.x,goal_node.y),(x,y)))
        if path_length > num_minutes:
            num_minutes = path_length

    return num_minutes-1

def main():
    with open('day15.txt', 'r') as f:
        data = np.array(f.read().strip().split(","), dtype=np.int64)
    f.close()

    # initialize computer
    from intComputer import IntcodeComputer

    brain = IntcodeComputer(dt=data)

    # part 1
    nodes = part_1(brain)
    goal_node = [node for node in nodes if node.goal][0]
    print(goal_node.distance)

    # part 2
    print(part_2(nodes, goal_node))

if __name__=='__main__':
    import numpy as np
    main()


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

import chainer
from chainer import cuda

import csv
import sys
import time
import random
import copy
import math
import os
import numpy as np
import argparse
import configparser

sys.path.append(os.getcwd())
from src.lib.trainer import NSNTrainer, NDNTrainer
from src.lib.utils import createOpbase
from src.lib.utils import create_dataset_parser, create_model_parser, create_runtime_parser
from src.lib.utils import print_args
from src.lib.utils import get_dataset, get_model

def main():

    """ Implementation of Quantitative Criteria Acquisition Network based on Chainer """
    start_time = time.time()

    ''' ConfigParser '''
    conf_parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter,
        add_help=False
    )
    conf_parser.add_argument("-c", "--conf_file",
                             help="Specify config file", metavar="FILE_PATH")
    args, remaining_argv = conf_parser.parse_known_args()

    dataset_conf_dict, model_conf_dict, runtime_conf_dict = {}, {}, {}

    if args.conf_file is not None:
        config = configparser.ConfigParser()
        config.read([args.conf_file])
        dataset_conf_dict = dict(config.items("Dataset"))
        model_conf_dict = dict(config.items("Model"))
        runtime_conf_dict = dict(config.items("Runtime"))

    ''' Parameters '''
    dataset_parser, dataset_args, remaining_argv = \
        create_dataset_parser(remaining_argv, **dataset_conf_dict)
    model_parser, model_args, remaining_argv = \
        create_model_parser(remaining_argv, **model_conf_dict)
    runtime_parser, runtime_args, remaining_argv = \
        create_runtime_parser(remaining_argv, **runtime_conf_dict)

    ap = argparse.ArgumentParser(
        description='Learning Nuclear Segmentation Network',
        parents=[conf_parser, dataset_parser, model_parser, runtime_parser])
    ap.add_argument('--gpu_id', type=int, help='GPU option')
    args = ap.parse_args()

    patchsize = args.patch_size
    opbase = createOpbase(args.save_dir)
    psep = '/'
    print_args(dataset_args, model_args, runtime_args)
    #with open(opbase + psep + 'result.txt', 'w') as f:
    #    f.write(print_args(dataset_args, model_args, runtime_args))

    ''' Dataset '''
    print('Loading datasets...')
    train_dataset, validation_dataset = get_dataset(args)
    print('-- train_dataset.size = {}\n-- validation_dataset.size = {}'.format(
        len(train_dataset), len(validation_dataset)))

    ''' Iterator '''
    train_iterator = chainer.iterators.SerialIterator(
        train_dataset, int(args.batchsize), repeat=True, shuffle=True
    )
    validation_iterator = chainer.iterators.SerialIterator(
        validation_dataset, int(args.batchsize), repeat=True, shuffle=False
    )

    ''' Model '''
    print('Initializing models...')
    model = get_model(args)
    if args.init_model is not None:
        print('Load model from', args.init_model)
        try:
            chainer.serializers.load_npz(args.init_model, model)
        except:
            chainer.serializers.load_hdf5(args.init_model, model)
    if args.gpu >= 0:
        cuda.get_device(args.gpu).use()  # Make a specified GPU current
        model.to_gpu()  # Copy the SegmentNucleus model to the GPU

    ''' Training Phase '''
    with open(opbase + psep + 'TestResult.csv', 'w') as f:
        c = csv.writer(f)
        c.writerow(['Epoch', 'Accuracy', 'Recall', 'Precision', 'Specificity', 'F-measure', 'IoU'])
    with open(opbase + psep + 'TrainResult.csv', 'w') as f:
        c = csv.writer(f)
        c.writerow(['Epoch', 'Accuracy', 'Recall', 'Precision', 'Specificity', 'F-measure', 'IoU'])

    mean_image = None
    if args.model == 'NSN' or args.model == '3DUNet':
        trainer = NSNTrainer(
            model=model,
            epoch=args.epoch,
            patchsize=eval(args.patch_size),
            batchsize=args.batchsize,
            gpu=args.gpu,
            opbase=opbase,
            mean_image=mean_image,
            opt_method=args.optimizer,
            ndim=args.ndim
        )
    elif args.model == 'NDN':
        trainer = NDNTrainer(
            model=model,
            epoch=args.epoch,
            patchsize=eval(args.patch_size),
            batchsize=args.batchsize,
            gpu=args.gpu,
            opbase=opbase,
            mean_image=mean_image,
            opt_method=args.optimizer,
            delv=3,
            r_thr=10,
            ndim=args.ndim
        )
    train_eval, test_eval, best_score = trainer.training((train_iterator, validation_iterator))

    end_time = time.time()
    process_time = end_time - start_time
    print('Elapsed time is (sec) {}'.format(process_time))
    with open(opbase + psep + 'result.txt', 'a') as f:
        f.write('======================================\n')
        f.write('Elapsed time is (sec) {} \n'.format(process_time))

if __name__ == '__main__':
    main()


import numpy as np
import matplotlib.pyplot as plt

from mpl_toolkits import mplot3d

class Model:

    def __init__(self, converter, policies, mutator, crossover, scaler=None):
        self._converter = converter
        self._policies = policies
        self._scaler = scaler
        self._mutator = mutator
        self._crossover = crossover

        self._func = None
        self._population = None
        self._arg_num = None
        self._axes = None
        self._digits = None

        self._cache = {}

    @property
    def converter(self):
        return self._converter.__name__

    @property
    def policies(self):
        include = self._policies['include'].__name__
        exclude = self._policies['exclude'].__name__
        parents = self._policies['parents'].__name__

        return 'include: {}\nexclude{}\nparents:{}'.format(include, exclude, parents)

    @property
    def scaler(self):
        return self._scaler.__name__

    @property
    def mutator(self):
        return self._mutator.__name__

    @property
    def crossover(self):
        return self._crossover.__name__

    @property
    def population(self):
        return self._population

    def run(self, func, *intervals, n=20, eps=0.01):
        """
            Run algorithm.

            func:function - function to optimize.
            intervals:[(float)] - intervals for each variable where we optimize our function.
            n:int - population volume.
            eps:float - accuracy of the algorithm.
        """

        assert self._converter is not None, 'Converter is not found.'
        assert self._policies is not None, 'Policies is not found.'
        assert self._mutator is not None, 'Mutator operator is not found.'
        assert self._crossover is not None, 'Crossover operator is not found.'

        self._func = func
        self._arg_num = func.__code__.co_argcount

        assert self._arg_num == len(intervals)

        self._axes = [list(np.arange(a, b, eps)) for a, b in intervals]

        max_len = max([len(ax) for ax in self._axes])

        self._digits = int(np.ceil(np.log2(max_len)))

        self._population = [list(np.random.choice(ax, size=n)) for ax in self._axes]

        self._population = list(zip(*self._population))

    def _to_genes(self, x, scope):
        """
        Converts x value to gene representation.

        :param x:float - value.
        :param scope:[float] - scope where x could be.
        :return:[bool] - gene representation/
        """

        x = scope.index(x)
        x = self._converter.convert(x, self._digits)

        return x

    def _to_float(self, x, scope):
        """
        Converts x gene representation to its value.

        :param x:[bool] - gene representation.
        :param scope:[float] - scope where x could be
        :return:float - value.
        """

        x = self._converter.to_int(x)
        x = min(x, len(scope) - 1)
        x = scope[x]

        return x

    def _caching(self, t):
        """
        Cache data for future ploting and other activities.

        :param t:int - time-step when we use caching.
        :return:None
        """

        self._cache[t] = self._population[:]

    def plot(self):
        """
        Plot evolution.

        :return: None
        """

        for key, value in self._cache.items():
            eps = 0.0001
            x = [key] * len(value)
            y = [self._func(*i) for i in value]
            #size = [np.sqrt(abs(i)) + eps for i in y]

            plt.scatter(x, y, label='Epoch: {}'.format(key))

        plt.xlabel('epoch')
        plt.ylabel('function value')
        plt.legend()
        plt.savefig('result.png')
        plt.show()

    def plot_graph(self):
        """
        Plot function graph depending on the number of values.

        :return: None
        """

        assert self._arg_num in (1, 2)

        if self._arg_num == 1:
            self.plot1D()
        elif self._arg_num == 2:
            self.plot2D()

    def plot1D(self):
        """
        Plot function graph.

        :return: None
        """

        assert self._arg_num == 1, 'Function must be 1-dimensional'

        x = self._axes[0]
        y = [self._func(i) for i in x]
        plt.plot(x, y)

        max_key = max(self._cache.keys())
        min_key = min(self._cache.keys())
        for key, value in self._cache.items():
            color = 1 - (key - min_key) / (max_key - min_key)
            x = [i[0] for i in value]
            y = [self._func(i) for i in x]
            plt.scatter(x, y, c=str(color), label='Epoch: {}'.format(key))

        plt.xlabel('x')
        plt.ylabel('f(x)')
        plt.legend()
        plt.show()

    def plot2D(self):
        """
        Plot function graph.

        :return: None
        """

        assert self._arg_num == 2, 'Function must 2-dimensional.'

        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')

        x, y = self._axes
        X, Y = np.meshgrid(x, y)
        Z = self._func(X, Y)
        ax.plot_surface(X, Y, Z)

        max_key = max(self._cache.keys())
        min_key = min(self._cache.keys())
        for key, value in self._cache.items():
            X, Y, Z = [], [], []
            for x, y in value:
                X.append(x)
                Y.append(y)
                Z.append(self._func(x, y))

            color = 1 - (key - min_key) / (max_key - min_key)

            ax.scatter(X, Y, Z, c=str(color), label='Epoch: {}'.format(key))

        ax.set_xlabel('x')
        ax.set_ylabel('y')
        ax.set_zlabel('f(x, y)')
        ax.legend()

        plt.show()


# coding=utf-8
__author__ = 'pengchong.lee'

import re
import os

from passlib import hash

ALGORITHM_MAPPER = {
    1: hash.md5_crypt,
    5: hash.sha256_crypt,
    6: hash.sha512_crypt
}

def crypt(word, salt):
    standard_salt = re.compile('\s*\$(\d+)\$([\w\./]*)\$')
    match = standard_salt.match(salt)
    if not match:
        raise ValueError("salt format is not correct, "
                         "in D:\Python27\Lib\site-packages\crypt.py")
    algorithm_num = match.group(1)
    extra_str = match.group(2)
    entryptor = ALGORITHM_MAPPER.get(int(algorithm_num))
    if int(algorithm_num) == 1:
        result = entryptor.encrypt(word, salt=extra_str)
    else:
        result = entryptor.encrypt(word, salt=extra_str, rounds=5000)
    return result


from django.shortcuts import render,redirect
from .models import Image,Category,Location
from django.http import Http404

# Create your views here.
def gallery(request):
    images = Image.objects.all()
    locations = Location.objects.all()
    return render(request,'all-gallery/gallery.html',{'images':images,'locations':locations})

def display_location(request):
    try:
        location = Location.objects.get(id = location_id)
        photos = Image.objects.filter(image_location = location.id)
    except:
        raise Http404()
    return render(request,'all-gallery/location-gallery.html',{'location':location,'images':images})

def search_results(request):
    if 'image' in request.GET and request.GET['image']:
        search_input = request.GET.get('image')
        searched_images = Image.search_by_category(search_input)
        message = f"{search_input}"

        return render(request, 'all-gallery/search.html', {"message":message, "images":searched_images})

    else:
        message = "Please input something in the search field"
        return render(request, 'all-gallery/search.html', {'message':message})
def display_images_categories(request):
    images = Image.image_categories()

    return render(request, 'category.html', {"images":images})

def display_images_locations(request):
    images = Image.image_locations()

    return render(request, 'location.html', {"images":images})


from torch import nn as nn
from torch.nn import functional as F

class MLP(nn.Module):
    def __init__(self, d_in: int, d_out: int, arch_spec: list, f_act=None):
        """
        A standard multi-layer perceptron.
        :param d_in: number of input features.
        :param d_out: number of output features.
        :param arch_spec: list containing the number of units in each hidden layer. If arch_spec == [], this is a
                          linear model.
        :param f_act: nonlinear activation function (if arch_spec != [])
        """
        super(MLP, self).__init__()

        self.arch_spec = arch_spec
        self.f_act = f_act
        self.is_linear = (arch_spec == [])  # no hidden layers --> linear model
        if not self.is_linear:
            assert f_act is not None

        # define the network
        if self.is_linear:
            self.fc = nn.ModuleList([nn.Linear(in_features=d_in, out_features=d_out)])
        else:
            self.fc = nn.ModuleList([nn.Linear(in_features=d_in, out_features=arch_spec[0])])
            for i in range(1, len(arch_spec)):
                self.fc.append(nn.Linear(in_features=self.fc[-1].out_features, out_features=arch_spec[i]))
            self.fc.append(nn.Linear(in_features=self.fc[-1].out_features, out_features=d_out))

    def forward(self, X):
        Y = X
        if self.is_linear:
            Y = self.fc[0](Y)
        else:
            for layer in self.fc[:-1]:
                Y = self.f_act(layer(Y))
            Y = self.fc[-1](Y)

        return Y


from typing import List
a = [[1, 2, 3],
     [4, 5, 1]]

def min_val(arr):
    path = []
    bottom = len(a)-1
    right = len(a[0])-1

    x, y = 0, 0

    while x != bottom or y != right:
        value = arr[x][y]
        path.append(value)

        if x+1 <= bottom:
            value_below = arr[x+1][y]

        if y+1 <= right:
            value_right = arr[x][y+1]

        larger = max(value_below, value_right)
        if larger == arr[x+1][y]:
            x += 1
        else:
            y += 1

    path.append(arr[x][y])

    print(path)
    return min(path)

class Solution:
    def fill_zeroes(self, matrix, row, col):
        # right
        for i in range(len(matrix[0])):
            print("first", matrix, (row, i))
            matrix[row][i] = 0

        # # left
        # for i in range(0, col):
        #     print("sec", matrix, (row, i))
        #     matrix[row][i] = 0

        # # up
        # for i in range(0, row):
        #     print("t", matrix, (i, col))
        #     matrix[i][col] = 0

        # down
        for i in range(len(matrix)):
            print("f", matrix, (i, col))
            matrix[i][col] = 0

        print(matrix)

    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        zeros = []
        height, width = len(matrix), len(matrix[0])

        for row in range(height):
            for col in range(width):
                if matrix[row][col] == 0:
                    zeros.append((row, col))

        for row, col in zeros:
            self.fill_zeroes(matrix, row, col)

    def setZeroes2(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        MODIFIED = -1000000
        R = len(matrix)
        C = len(matrix[0])
        for r in range(R):
            for c in range(C):
                if matrix[r][c] == 0:
                    # We modify the elements in place. Note, we only change the non zeros to MODIFIED
                    for k in range(C):
                        matrix[r][k] = MODIFIED if matrix[r][k] != 0 else 0
                    for k in range(R):
                        matrix[k][c] = MODIFIED if matrix[k][c] != 0 else 0
        for r in range(R):
            for c in range(C):
                # Make a second pass and change all MODIFIED elements to 0 """
                if matrix[r][c] == MODIFIED:
                    matrix[r][c] = 0

# print(min_val(a))
aa = [
    [1, 1, 1],
    [1, 0, 1],
    [1, 1, 1]
]
b = [[1, 3, 0]]
# print(Solution().setZeroes(aa))

c = ['Waltz', 'walt', 'Tango', 'Viennese Waltz', 'Foxtrot',
     'Cha Cha', 'Samba', 'Rumba', 'Paso Doble', 'Jive']

c.sort(key=lambda elem: elem[len(elem) // 2], reverse=True)

for word in c:
    print(word)

# 'Cha Cha'
# 'Paso Doble'
# 'Viennese Waltz'
# 'Waltz'
# 'Samba'
# 'Rumba'
# 'Tango'
# 'Foxtrot'
# 'Jive'


import os
import jinja2
import webapp2
from stream import Stream

JINJA_ENV=jinja2.Environment(loader=jinja2.FileSystemLoader(
os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)

class viewAllStreamsPage(webapp2.RequestHandler):
	def get(self):
		template=JINJA_ENV.get_template('viewAllStream.html')
		streams=Stream.query().order(-Stream.createDate).fetch()
		template_values={
		"streams": streams,
		}
		self.response.write(template.render(template_values))

app=webapp2.WSGIApplication([('/viewAll',viewAllStreamsPage),],debug=True)


#!/usr/bin/env python

import sys
from scapy.all import *
from prettytable import PrettyTable
from mac_vendor_lookup import MacLookup
from argparse import ArgumentParser
from scapy.layers.l2 import Ether
from scapy.layers.l2 import ARP
from sys import exit,stderr,argv

class NetworkScanner():
    def __init__(self,host):
        #for host in hosts:
        self.host = host
        self.alive = {}
        self.create_packet()
        self.send_packet()
        self.get_alive()
        self.print_alive()

    def create_packet(self):
        layer1 = Ether(dst="ff:ff:ff:ff:ff:ff")
        layer2 = ARP(pdst=self.host)
        packet = layer1 / layer2
        self.packet = packet

    def send_packet(self):
        answered, unanswered = srp(self.packet,timeout=1,verbose=False)
        if answered:
            self.answered=answered

        else:
            print("No host is up")
            sys.exit(1)

    def get_alive(self):
        for sent,received in self.answered:
            self.alive[received.psrc] = received.psrc

    def print_alive(self):
        table = PrettyTable(["IP","MAC","VENDOR"])
        for ip,mac in self.alive.items():
            try:
                table.add_row([ip,mac,MacLookup().lookup(mac)])
            except:
                table.add_row([ip,mac,"Unknown"])
        print(table)

def get_args():
    parser = ArgumentParser(description="Network Scanner")
    parser.add_argument("--h",dest="hosts",nargs="+",help="Hosts to scan")
    arg = parser.parse_args()
    if len(sys.argv) == 1:
        parser.print_help(sys.stderr)
        sys.exit(1)
    return arg.hosts

hosts = get_args()
for host in hosts:
    NetworkScanner(host)


#!/usr/bin/env python
import sympy
import mpmath
import numpy as np

max_order        = 6
max_angular      = 10
expansion_points = np.arange(-50, 50, dtype=np.float64)
offset           = - int(expansion_points[0])
num_points       = len(expansion_points)

z,z0 = sympy.symbols('z z0', assume='real')
a    = sympy.symbols('a', assume='integer')
f = sympy.Function('fun')

hyp = sympy.hyper([a],[a+1], z)
gen = sympy.series(hyp, z, x0=z0, n=None)
exp = 0
for i in range(max_order):
    nextgen = next(gen).subs(sympy.hyper((a+i,), (a+i+1,), z0), 'table[ai+{},{}]'.format(i,'zi'))
    print(nextgen)
    exp += nextgen

with open("taylor.py", "w") as f:
    f.write("import numpy as np\n")
    f.write("from numba import jit\n")
    f.write("\n\n")
    f.write("table = np.array([\n")
    for i in range(max_angular+max_order):
        print(i)
        f.write("{},\n".format([float(mpmath.hyp1f1(i+0.5, i+1.5, x)) for x in expansion_points]))
    f.write("])\n")
    f.write("\n\n")
    f.write("@jit(nopython=True, cache=True)\n")
    f.write("def taylor(a,z):\n")
    f.write("    z0 = int(np.round(z))\n")
    f.write("    zi = z0 + {}\n".format(offset))
    f.write("    ai = a\n")
    f.write("    return {}\n".format(exp.subs(a,a+0.5).evalf()))


import decimal
import math

from rest_framework import generics
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.status import HTTP_201_CREATED, HTTP_400_BAD_REQUEST, HTTP_200_OK

from products.models import Product
from products.serializers import ProductSerializer

class ProductListView(generics.ListAPIView, generics.CreateAPIView):
    queryset = Product.objects.filter(is_deleted=False)
    serializer_class = ProductSerializer

    def get_queryset(self):
        queryset = self.queryset.all()
        name = self.request.query_params.get('name')
        min_price = self.request.query_params.get('min_price')
        max_price = self.request.query_params.get('max_price')
        if name:
            queryset = queryset.filter(name__icontains=name)
        if min_price:
            queryset = queryset.filter(price__gte=min_price)
        if max_price:
            queryset = queryset.filter(price__lte=max_price)
        return queryset

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=HTTP_201_CREATED)
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

class ProductDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

@api_view(['GET'])
def get_order_total_price(request):
    total_price = 0
    product_codes = request.query_params.get('product_codes')
    if not product_codes:
        return Response({"message": "Product codes weren't provided."}, status=HTTP_400_BAD_REQUEST)
    product_codes = product_codes.split()
    required_products = Product.objects.filter(code__in=product_codes).values('code', 'price')
    # getting product prices to reduce queries to db
    product_prices = {}
    for product in required_products:
        product_prices[product['code']] = product['price']
    # getting product quantities
    products_count = {}
    for code in product_codes:
        if code in products_count:
            products_count[code] += 1
        else:
            products_count[code] = 1
    # getting total price with some rules
    for product_code, product_count in products_count.items():
        if product_code not in product_prices:
            return Response({"message": f"Invalid product code ({product_code})."}, status=HTTP_400_BAD_REQUEST)
        if product_code == 'PC' and product_count >= 3:
            discount = decimal.Decimal('0.2')
            total_price += (1 - discount) * product_prices[product_code] * product_count
        elif product_code == 'CC':
            total_price += product_prices[product_code] * math.ceil(product_count / 2)
        else:
            total_price += product_prices[product_code] * product_count
    return Response(f'${round(total_price, 2)}', status=HTTP_200_OK)