# # # # # # # # # # # # # # # # # # # # # # #
#    Homework Assignment #5: Basic Loops    #
# # # # # # # # # # # # # # # # # # # # # # #

"""
You're about to do an assignment called "Fizz Buzz", which is one of the
classic programming challenges. It is a favorite for interviewers, and a
shocking number of job-applicants can't get it right. But you won't be one
of those people. Here are the rules for the assignment (as specified by
Imran Gory):

Write a program that prints the numbers from 1 to 100.

But for multiples of three print "Fizz" instead of the number and
for the multiples of five print "Buzz".
For numbers which are multiples of both three and five print "FizzBuzz".

For extra credit, instead of only printing "fizz", "buzz", and "fizzbuzz",
add a fourth print statement: "prime". You should print this whenever you
encounter a number that is prime (divisible only by itself and one).
As you implement this, don't worry about the efficiency of the algorithm
you use to check for primes. It's okay for it to be slow.
"""

# First part of the homework:
# I used a for to print all the numbers from 1 to 100
for number in range(1,101):
  # First we check if the number is divisible by 3 and 5
  if number % 3 == 0 and number % 5 == 0:
      print("FizzBuzz")
  # Second, if the previous condition wasn't fulfilled, we check if it is only divisible by 3
  elif number % 3 == 0:
    print("Fizz")
  # Third, if the previous condition wasn't fulfilled, we check if it is only divisible by 5
  elif number % 5 == 0:
    print("Buzz")
  # Fourth, if none of the previous condition was fulfilled, then we just print the number.
  else:
    print(number)

### Extra credit

# I define a function to check if the number is prime or not comparing it with the first 100 numbers
def is_prime(number):
  counter = 0
  for divisor in range (1,101):
    if counter == 3:
      break
    else:
      if number >= divisor :
        if number % divisor == 0:
          counter += 1
        else:
          continue
      else:
        continue
  if counter == 1 or counter == 3:
    return False
  else:
    return True

# Then I use the same code from the first part of this homework just that I add the new function in the loop.
for number in range(1,101):
  if is_prime(number):
    print("prime")
  else:
    if number % 3 == 0 and number % 5 == 0:
      print("FizzBuzz")
    elif number % 3 == 0:
      print("Fizz")
    elif number % 5 == 0:
      print("Buzz")
    else:
      print(number)


def my_range(start,stop,step):
    if stop <= start:
        raise RuntimeError("start must be smaller than stop")
    else:
        i = start
        while i < stop:
            yield i
            i += step

for k in my_range(10,30,3):
    print(k)


#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the reverseArray function below.
# It is called array but in Python it is actually the "List data structure".
def reverseArray(a):
    length = len(a)
    i = 0
    b = []
    while i < length:
        b.append(a[length-1-i])
        i = i+1
    return b

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    arr_count = int(input())

    arr = list(map(int, input().rstrip().split()))

    res = reverseArray(arr)

    fptr.write(' '.join(map(str, res)))
    fptr.write('\n')

    fptr.close()


from typing import Tuple

import numpy as np
import torch
from torch.utils.data import DataLoader
import torchvision as tv

from .experiment_config import Config, DatasetType, HParams

def get_dataloaders(hparams: HParams, config: Config, device: torch.device) -> Tuple[DataLoader, DataLoader, DataLoader]:
  if hparams.dataset_type == DatasetType.CIFAR10:
    dataset = CIFAR10
  elif hparams.dataset_type == DatasetType.SVHN:
    dataset = SVHN
  else:
    raise KeyError

  train_key = {'split': 'train'} if hparams.dataset_type == DatasetType.SVHN else {'train': True}
  test_key = {'split': 'test'} if hparams.dataset_type == DatasetType.SVHN else {'train': False}
  train = dataset(hparams, config, device, download=True, **train_key)
  test = dataset(hparams, config, device, download=True, **test_key)

  train_loader = DataLoader(train, batch_size=hparams.batch_size, shuffle=True, num_workers=0)
  train_eval_loader = DataLoader(train, batch_size=5000, shuffle=False, num_workers=0)
  test_loader = DataLoader(test, batch_size=5000, shuffle=False, num_workers=0)
  return train_loader, train_eval_loader, test_loader

def process_data(hparams: HParams, data_np: np.ndarray, targets_np: np.ndarray, device: torch.device, train: bool):
  # Scale data to [0,1] floats
  data_np = data_np / 255

  # Normalize data
  data_np = (data_np - data_np.mean(axis=(0,1,2))) / data_np.std(axis=(0,1,2))

  # NHWC -> NCHW
  data_np = data_np.transpose((0,3,1,2))

  # Numpy -> Torch
  data = torch.tensor(data_np, dtype=torch.float32)
  targets = torch.tensor(targets_np, dtype=torch.long)

  # Resize dataset
  dataset_size, offset = (hparams.train_dataset_size, 0) if train else (hparams.test_dataset_size, 1)
  if dataset_size is not None:
    rng = np.random.RandomState(hparams.data_seed + offset) if (hparams.data_seed is not None) else np.random
    indices = rng.choice(len(data), dataset_size, replace=False)
    indices = torch.from_numpy(indices)
    data = torch.index_select(data, 0, indices)
    targets = torch.index_select(targets, 0, indices)

  # Put both data and targets on GPU in advance
  return data.to(device), targets.to(device)

# https://gist.github.com/y0ast/f69966e308e549f013a92dc66debeeb4
# We need to keep the class name the same as base class methods rely on it
class CIFAR10(tv.datasets.CIFAR10):
  def __init__(self, hparams: HParams, config: Config, device: torch.device, *args, **kwargs):
    super().__init__(config.data_dir, *args, **kwargs)
    self.data, self.targets = process_data(hparams, self.data, np.array(self.targets), device, self.train)

  # Don't convert to PIL like torchvision default
  def __getitem__(self, index):
    return self.data[index], self.targets[index]

class SVHN(tv.datasets.SVHN):
  def __init__(self, hparams: HParams, config: Config, device: torch.device, *args, **kwargs):
    super().__init__(config.data_dir, *args, **kwargs)
    self.data = self.data.transpose((0, 2, 3, 1)) # NCHW -> NHWC (SVHN)
    self.data, self.labels = process_data(hparams, self.data, self.labels, device, self.split == 'train')

  def __getitem__(self, index):
    return self.data[index], self.labels[index]


import numpy as np
import pylab
import statistics
from math import *
import matplotlib.pyplot as plt
import pandas as pd
from scipy.stats import norm

if __name__ == '__main__':
    data_dict = np.load('mae_errors3.npy', allow_pickle=True).item()
    tlgrouths = pd.read_csv('C:/Users/Administrator/Documents/GitHub/tft/data_simulation/bottom02_info.csv',
                            index_col=0).reset_index(drop=True)
    test_sequence = pd.read_csv('C:/Users/Administrator/Documents/GitHub/tft/pytorch_forecasting/CPD/tl.csv')
    # tlgrouths = pd.read_csv('C:/Users/s3912230/Documents/GitHub/tft/pytorch_forecasting/CPD/bottom02_info.csv',
    #                         index_col=0).reset_index(drop=True)
    # test_sequence = pd.read_csv('C:/Users/s3912230/Documents/GitHub/tft/pytorch_forecasting/CPD/tl.csv')
    test_sequence = test_sequence[test_sequence['period'] == 0]
    training_cutoff = 2000 - 96
    for key, value in data_dict.items():
        site_id = key[:4]
        tank_id = key[-1]
        tank_info = tlgrouths[(tlgrouths['Site'] == site_id) & (tlgrouths['Tank'] == int(tank_id))]
        tank_sequence = test_sequence[(test_sequence['group_id'] == key)]
        test_seq = tank_sequence.iloc[training_cutoff:]
        test_seq = test_seq.reset_index(drop=True)
        test_seq['time_idx'] = test_seq.index

        startdate = tank_info.iloc[0]['Start_date']
        stopdate = tank_info.iloc[0]['Stop_date']
        temp_df = test_seq[test_seq['Time_DN'] > startdate]
        startindex = temp_df.iloc[0]['time_idx']
        temp_df = test_seq[test_seq['Time_DN'] > stopdate]
        stopindex = temp_df.iloc[0]['time_idx']
        fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(18, 12))
        inputs = test_seq['Var_tc_readjusted'].values
        ax1.plot(inputs, label='TC_var', color='red')
        ax1.axvline(x=startindex, color='green', linestyle='--')
        ax1.axvline(x=stopindex, color='green', linestyle='--')
        ax1.set_title('input')
        ax1.legend()
    #
        # Plot on the first subplot
        ax2.plot(value, label='errors', color='blue')
        ax2.set_title('Error trend')
        ax2.axvline(x=startindex, color='green', linestyle='--')
        ax2.axvline(x=stopindex, color='green', linestyle='--')
        ax2.legend()

        plt.tight_layout()

        # Show the plot
        plt.savefig(key+'_mar3.png')


import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt

'''
在工具栏中添加工具按钮时，默认不显示文字，添加的文字作为tooltip提示信息
'''

class Toolbar(QMainWindow):
    def  __init__(self):
        super(Toolbar, self).__init__()
        self.iniui()
    def iniui(self):
        self.setWindowTitle("toolbar demo ")
        self.resize(300,400)

        tb1=self.addToolBar('file')
        new=QAction(QIcon(r'D:\QTproject\Image\python_text_x_64px_8857_easyicon.net.png'),'new',self)
        tb1.addAction(new)
        open = QAction(QIcon(r'D:\QTproject\Image\python_text_x_64px_8857_easyicon.net.png'), 'open', self)
        tb1.addAction(open)
        #可以设置同时显示文字和图标
        tb1.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        #可以创建多个菜单栏，他们会显示在同一行，但是采用不同的菜单栏进行区分
        tb2 = self.addToolBar('file')
        new = QAction(QIcon(r'D:\QTproject\Image\python_text_x_64px_8857_easyicon.net.png'), 'new', self)
        tb2.addAction(new)
        open = QAction(QIcon(r'D:\QTproject\Image\python_text_x_64px_8857_easyicon.net.png'), 'open', self)
        tb2.addAction(open)
        # 可以设置同时显示文字和图标
        tb2.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        tb1.actionTriggered.connect(self.toolbtpressed)
        tb2.actionTriggered.connect(self.toolbtpressed)
    def toolbtpressed(self,a):
       print('被点击的是：',a.text())

if __name__ == '__main__':
    app=QApplication (sys.argv)
    window=Toolbar()
    window.show()
    sys.exit(app.exec_())


from pathlib import Path

def main(input):
    lines = [in_line for in_line in input.split("\n")]
    prio = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

    part1 = 0
    for line in lines:
        length = int(len(line) / 2)
        first = set(line[:length])
        second = set(line[length:])
        same = first & second
        part1 += prio.index(same.pop()) + 1

    part2 = 0
    while lines:
        first = set(lines.pop())
        second = set(lines.pop())
        third = set(lines.pop())
        same = first & second & third
        part2 += prio.index(same.pop()) + 1

    return part1, part2

if __name__ == "__main__":
    input_file = "input.txt"
    #input_file = "test_input.txt"
    with (Path(__file__).parent / input_file).open() as input:
        print(main(input.read()))


# -*- coding: utf-8 -*-
"""
Created on Wed Jan 25 14:10:51 2017

@author: nigul
"""

from astropy.stats import LombScargle
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

import os
import os.path

n = 5000
t_max = 500.0
season_period = 10.0
num_seasons = np.floor(t_max / season_period)
season_size = 10.0
nyquist = float(n) / t_max / 2
t = np.linspace(0, t_max, n)
#t = np.random.randint(t_max, size=n)+np.random.rand(n)
#season_starts = np.floor(t/season_period) * season_period
#t = t[np.where(np.logical_and(t >= season_starts, t < season_starts + season_size))]
print(len(t))
mu = 0
sigma = 1
freqs = np.linspace(0, nyquist/100, 100)
#y = np.sin(0.5*t) + np.random.normal(mu, sigma, len(t))

#y = np.random.normal(mu, sigma, num_seasons)
#y = np.repeat(y, n / num_seasons)
#t = t[:len(y)]

y = np.zeros(len(t))
season_start = 0
season_mean_var = 1
season_var = 1
season_mean = np.random.normal(0, season_mean_var)
for i in np.arange(0, len(t)):
    if (t[i] >= season_start + season_period):
        season_start += season_period
        season_mean = np.random.normal(0, season_mean_var)
    y[i] = np.random.normal(season_mean, season_var)

mean = np.mean(y)
std = np.std(y)
y -= mean
y /= std

power = LombScargle(t, y, nterms=1).power(freqs, normalization='psd')#/np.var(y)
plt.plot(t, y, 'b+')
plt.savefig("mixed_whitenoise_dat.png")
plt.close()
plt.plot(freqs, power, "b-")
plt.savefig("mixed_whitenoise_spec.png")
plt.close()


from flask import g, render_template, Markup
from flask import current_app as app
from flask_restful import Resource
from functional import seq
from appname.error import InvalidUsage
from appname.db import StaticDataModel, UserModel
from appname.apitools import spec, Swagger, ApiResponse,\
    get_args, ApiParam, EnumConstraint, LengthConstraint
import appname.apitools as apitools
from mongoengine import ValidationError

mail_example = dict(
    title='example title ',
    details=('this is example' +
            '

its next line' ),
)

class HelpList(Resource):
    @spec('/help', 'Get help data list',
        responses=[
            ApiResponse(200, 'Succeed', dict(data=[mail_example]))
        ]
    )
    def get(self):
        try:
            help_data = list(HelpDataModel.objects)
            return dict(
                data=seq(help_data).map(lambda x: x.marshall()).list())
        except ValidationError:
            raise InvalidUsage("Help Data Not Found", status_code=404)

class Contact(Resource):
    @spec('/help/contact', 'Send Contact mail to us',
        header_params=[
            *Swagger.Params.Authorization
        ],
        body_params=[
            ApiParam('email',
                     'user email to receive answer',
                     constraints=[LengthConstraint(5, 100)]),
            ApiParam('title',
                    'user question title',
                    constraints=[LengthConstraint(2)]),
            ApiParam('details',
                    'user question details',
                    constraints=[LengthConstraint(10)]),
            ApiParam('type',
                    'user question type(Auth/Device/Etc)',
                    default='Etc',
                    constraints=[EnumConstraint(['Auth', 'Device', 'Etc'])])
          ],
        responses=[
            ApiResponse(200, 'Succeed', dict(result=True)),
            ApiResponse.error(500, 'Email Server Error')
        ]
    )
    def post(self):
        args = get_args()
        email = args['email']
        title = args['title']
        details = args['details']

        try:
            user = UserModel.objects.get(email=email)
        except UserModel.DoesNotExist:
            user = None

        try:
            if user:
                name = user.name
            else:
                name = ''

            template = render_template(
                'mail.template.html',
                name=name,
                details=Markup(details))
            charset = 'UTF-8'
            response = apitools.email_client.send_email(
                Destination={
                    'ToAddresses': [
                        app.config['CONTACT_EMAIL']
                    ],
                    'CcAddresses': [
                        email,
                    ],
                },
                Message=dict(
                    Subject=dict(
                        Data=title,
                        Charset='utf8'),
                    Body=dict(Html=dict(Charset='utf8', Data=template))
                ),
                Source=app.config['CONTACT_EMAIL'])
        except Exception as ex:
            print(ex)
            raise InvalidUsage("Email Server Error: {}".format(ex), 500)

        return dict(result=True)


#!/usr/bin/env python
"""
    This code reduces the dimensionality of a dataset using t-SNE.
    It has several options:
        * --exp_name: Name of the experiment. Useful if you want to do several
        experiments with different target dimensions.
        * --representations_file: Pth file containing the data to reduce. This file
        is one of the representation_files generated  by the code "feature_extraction.py"
        that are usually stored in "../models/MNIST_EXP_ID/CompressedRepresentations/"
        * --target_dim: Dimension wanted for the dimensionality reduction

    It generates various folders in ../models/MNIST_EXP_ID/Projections/ named
    EmbeddedRepresentations_perpVal_lrVal_earlyExVal_dimVal. These folders contains
    five files:
        - labels_ID.pth: List of labels of the different 2D/3D points generated
        by t-SNE.
        - originalImages_ID.pth: List of images representing the different 2D/3D
        points generated by TSNE.
        - representations_ID.pth: List of the 2D/3D points generated by t-SNE.
        - tsne_params.json: Parameters used to obtain the projected points.
        - dataSplits_ID.pth: List indicating if samples i is from the training
        set or the testing set.
"""
import os
import argparse
import numpy as np
from sklearn.manifold import TSNE
import pickle
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pickle
from matplotlib import image
import json

def rearangeData(data):
    """
        Function that puts the data of the list of points under the right format:

        Arguments:
        ----------
        data: list
            List where each element is a dict that correspond to one epoch of the training
            process. Each dict contains two keys:
                - 'compressed_representation': List where each element is the
                output of a batch for the given epoch.
                - 'label': List where each element are the labels of the output of a
                batch for a given epoch

        Returns:
        --------
        newData: list
            List containing the data points to plot. The elements of the list
            are dictionaries with two keys:
                - 'compressed_representation': List where each element is one
                output for that epoch
                - 'label': List where each element is the label of the corresponding
                output point in the output list
    """
    newData = []
    for epochData in data:
        newOutput, newOriginalImage, newLabel, newDataSplits = [], [], [], []
        # Labels
        for labelLists in epochData['label']:
            nbSamplesBatch = len(labelLists)# It's the same as len(labelLists[1]), ..,. len(labelLists[9])
            for i in range(nbSamplesBatch):
                newLabel.append(int(labelLists[i]))
        # Auto-encoder representations
        for outputLists in epochData['compressed_representation']:
            for output in outputLists:
                newOutput.append(output.cpu().detach().numpy())
        # Original images
        for original_image_list in epochData['original_image']:
            for originalImage in original_image_list:
                if (type(originalImage) == str):
                    sample_data = np.asarray(Image.open(originalImage))/255.
                    if (len(sample_data.shape) == 3):
                        sample_data = np.moveaxis(sample_data, 2, 0) # Because in pytorch the channel has to be in the first position
                    else:
                        sample_data = sample_data.reshape((1, sample_data.shape[0], sample_data.shape[1]))
                    image = torch.tensor(sample_data)
                    originalImage = image.type("torch.FloatTensor") # To avoid problems with types
                newOriginalImage.append(originalImage.cpu().detach().numpy())
        # Split type of the sample (train or test splits)
        if ('data_split' in epochData):
            for dataSplitLists in epochData['data_split']:
                for dataSplit in dataSplitLists:
                    newDataSplits.append(dataSplit)
        newData.append({'compressed_representation': newOutput, 'original_image': newOriginalImage, 'label': newLabel, 'data_split':newDataSplits})
    return newData

def main():
    # =========================================================================#
    # Construct the argument parser
    ap = argparse.ArgumentParser()
    # Add the arguments to the parser
    ap.add_argument("--exp_name", default='tSNE_GridSearch', help="Name of the experiment", type=str)
    ap.add_argument("--representations_file", required=False, help="Pth file containing the data to reduce", type=str)
    ap.add_argument("--target_dim", required=False, default=2, help="Target dimension of the embedded representation (2 or 3)", type=int)
    ap.add_argument("--use_default_params_tsne", default=False, help="True if want to use the default parameters for t-SNE instead of doing a GridSearch", type=bool)
    args = vars(ap.parse_args())

    # Points file and target dim
    exp_name = args['exp_name']
    representations_file = args['representations_file']
    target_dim = args['target_dim']
    use_default_params_tsne = args['use_default_params_tsne']

    #==========================================================================#
    # Creating the folder with the projections
    # =========================================================================#
    model_folder = '/'.join(representations_file.split('/')[:-2])
    projections_folder = model_folder + '/Projections_{}_'.format(exp_name)
    inc = 0
    while (os.path.isdir(projections_folder + str(inc))):
        inc += 1
    projections_folder = projections_folder + str(inc) + '/'
    os.mkdir(projections_folder)

    #==========================================================================#
    # Parameters for the tgrid search experiment
    # =========================================================================#
    if (use_default_params_tsne):
        perplexities = [30.0]
        early_exaggerations = [12.0]
        learning_rates = [200]
        n_iter = 1000
    else:
        # perplexities = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
        perplexities = [10, 30, 50]
        # early_exaggerations = [5, 10, 25, 50, 75, 100, 200, 500]
        early_exaggerations = [50, 250, 500]
        # learning_rates = [10, 50, 100, 500, 1000]
        learning_rates = [10, 100, 1000]
        n_iter = 3000

    #==========================================================================#
    #==========================================================================#
    #==========================================================================#
    for perplexity in perplexities:
        for early_exaggeration in early_exaggerations:
            for learning_rate in learning_rates:
                parameters_dict = {
                                    'perplexity': perplexity,
                                    'early_exaggeration': early_exaggeration,
                                    'learning_rate': learning_rate,
                                    'n_iter': n_iter,
                                    'n_jobs': 4
                                  }

                # Loading the representations
                with open(representations_file, "rb") as fp:   # Unpickling
                    data = pickle.load(fp)

                # Seing if there is any data to process
                noData = True
                for element in data:
                    if len(element['compressed_representation']) > 0:
                        noData = False
                        break
                if (noData):
                    print("The file {} does not contain any compressed representations to reduce".format(representations_file))
                else:
                    # Rearanging data
                    data = rearangeData(data)

                    final_representations = data[-1] # To only get the representations obtained
                    # at the last epoch

                    #==========================================================================#
                    # Applying t-SNE
                    representation_list = []
                    for representation in final_representations['compressed_representation']:
                        if (len(representation.shape) == 3): # This is needed becayse
                        # the input of t-SNE should be a vector
                            representation_list.append(representation.reshape(representation.shape[0]*representation.shape[1]*representation.shape[2]))
                        elif (len(representation.shape) == 1):
                            representation_list.append(representation)
                        else:
                            raise ValueError("Wrong dimensions for the representations: {}".format(representation.shape))
                    representation_list = np.array(representation_list)

                    print("=======> Starting TSNE")
                    if (target_dim == 3):
                        tsneInstance = TSNE(n_components=3, perplexity=parameters_dict['perplexity'], early_exaggeration=parameters_dict['early_exaggeration'], learning_rate=parameters_dict['learning_rate'], n_jobs=parameters_dict['n_jobs'])
                    elif (target_dim == 2):
                        tsneInstance = TSNE(n_components=2, perplexity=parameters_dict['perplexity'], early_exaggeration=parameters_dict['early_exaggeration'], learning_rate=parameters_dict['learning_rate'], n_jobs=parameters_dict['n_jobs'])
                    else:
                        raise ValueError("Dimension {} for the embedded representation is not valid".format(target_dim))
                    embedded_representations = tsneInstance.fit_transform(representation_list)
                    print("The method converged in {} iterations".format(tsneInstance.n_iter))
                    print("=======> Ending TSNE")

                    # Creating the folder where we are going to store the different files of the
                    # embedded representations
                    inc = 0
                    folderName = projections_folder +\
                                '/EmbeddedRepresentations_perp{}_lr{}_earlyEx{}_dim{}'.format(parameters_dict['perplexity'],\
                                                                                parameters_dict['learning_rate'],\
                                                                                parameters_dict['early_exaggeration'],\
                                                                                target_dim)
                    while (os.path.isdir(folderName + '_' + str(inc))):
                        inc += 1
                    folderName = folderName + '_' + str(inc)
                    os.mkdir(folderName)
                    print("Saving Embedded Representations at: {}".format(folderName))
                    # Saving the embedded points got with T-SNE
                    embReprFileName = folderName + "/representations"
                    inc = 0
                    while os.path.isfile(embReprFileName+'_'+str(inc)+'.pth'):
                        inc +=1
                    embReprFileName += '_'+str(inc)+'.pth'
                    with open(embReprFileName, "wb") as fp:   #Pickling
                        pickle.dump(embedded_representations, fp)
                    # Saving the original images
                    originalImagesFileName = folderName + "/images"
                    inc = 0
                    while os.path.isfile(originalImagesFileName+'_'+str(inc)+'.pth'):
                        inc +=1
                    originalImagesFileName += '_'+str(inc)+'.pth'
                    with open(originalImagesFileName, "wb") as fp:   #Pickling
                        pickle.dump(np.array(final_representations['original_image']), fp)
                    # Saving the labels
                    labelsFileName = folderName + "/labels"
                    inc = 0
                    while os.path.isfile(labelsFileName+'_'+str(inc)+'.pth'):
                        inc +=1
                    labelsFileName += '_'+str(inc)+'.pth'
                    with open(labelsFileName, "wb") as fp:   #Pickling
                        pickle.dump(final_representations['label'], fp)
                    # Saving the data splits of the samples (i.e. if they are train or test samples)
                    dataSplitsFileName = folderName + "/dataSplits"
                    inc = 0
                    while os.path.isfile(dataSplitsFileName+'_'+str(inc)+'.pth'):
                        inc +=1
                    dataSplitsFileName += '_'+str(inc)+'.pth'
                    with open(dataSplitsFileName, "wb") as fp:   #Pickling
                        pickle.dump(final_representations['data_split'], fp)
                    # Saving the parameters used to train TSNE
                    with open(folderName + '/tsne_params.json', 'w') as outfile:
                        json.dump(parameters_dict, outfile)

if __name__=="__main__":
    main()


def scalmul(a,b):
    c = []
    for i in range(len(a)):
        it =a[i]*b
        c = c +[it]
    return c

vector = [1,2,4,5,6,7]
print(scalmul(vector,3))


"""
Created on Jan 21, 2017
@auther: Milinda Samaraweera
This program creates input files using data from SD files to be used in creating candidate lists to be used in cfm-id
"""
from rdkit import Chem
import csv
import sys

def cfm_input(sd_file,save_file,filter):

	f = open(save_file+'_'+filter+'_input_cfmid.txt', 'wt')
	writer = csv.writer(f,delimiter='\t',lineterminator='\n')
	suppl = Chem.SDMolSupplier(sd_file)

	if len(suppl)==0:
		print("Zero candidates remaining after RI filter...")
		sys.exit()

	for idx,mol in enumerate(suppl):

		if mol is None:
				print ("Error Reading SD entry: " + str(idx))
				log_file.write("Error Reading SD entry " + str(idx)+'\n')
				continue

		d = mol.GetPropsAsDict()

		try:
			Identifier=int(d.get('Identifier', None))
		except:
			Identifier=(str(d.get('Identifier', None)))

		writer.writerow((Identifier, str(Chem.MolToSmiles(mol))))

	f.close()

def main():
	pass

if __name__ == "__main__":
    main()


import os

import unittest
import h5py

from xanespy.utilities import prog

class XanespyTestCase(unittest.TestCase):

    def run(self, *args, **kwargs):
        prog.quiet = True
        return super().run(*args, **kwargs)

    def assertApproximatelyEqual(self, actual, expected,
                                 tolerance=0.01, msg=None):
        """Assert that 'actual' is within relative 'tolerance' of
        'expected'."""
        # Check for lists
        if isinstance(actual, list) or isinstance(actual, tuple):
            for a, b in zip(actual, expected):
                self.assertApproximatelyEqual(a, b, tolerance=tolerance)
        else:
            diff = abs(actual - expected)
            acceptable_diff = abs(expected * tolerance)
            if diff > acceptable_diff:
                msg = "{actual} is not close to {expected}"
                self.fail(msg=msg.format(actual=actual, expected=expected))


from _DATATYPES import TreeNode
#Question: Given a BST, find the minimum difference between any two nodes
#Solution: Traverse in order, keep track of the previous node, and find the difference between current one. The minimun difference must be between two consecutive nodes because we are travelling in order!
#Difficulty: Easy

class Solution(object):
    #Value of previous node, set to -infinity intitially
    previousVal = float('-inf')
    #The minimum difference between the nodes, set to infinity initially
    minDifference = float('inf')
    def minDiffInBST(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        #Define the recursive helper that travels in order
        def rec(r):
            #If left node exists go left
            if r.left: rec(r.left)
            #Set the min difference to be the min of itself or the difference between current and previous nodes
            self.minDifference = min(self.minDifference, (r.val - self.previousVal))
            #Set the previous node to be the current node
            self.previousVal = r.val
            #IF right node exists go right
            if r.right: rec(r.right)
        #Run recursive helper
        rec(root)
        #Return original tree root
        return self.minDifference


#Authors: Luca Bolognini & Matteo Antonio Inajetovic

from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
import os
import numpy as np
from numpy.core.fromnumeric import argmax
import pandas as pd
################# Parameters #########################
path = './Instances/'
data_path='./Instances_fin/'
output_smt_path_ext='./smt_out_extended/'
output_smt_path_base='./smt_out_base/'
elem = os.listdir(path)

###################### Methods ######################
def data_file_reader (read_path, file, sol = False):
    print('Reading Data files, wait...\n')

    with open(read_path + file, 'rt', ) as f:
        if not sol:
            line = f.readlines()
            lines= [line[i].split() for i in range(len(line))]
            widths = [lines[i][0] for i in range(2,len(lines)-2)]
            heights  = [lines[i][1] for i in range(2,len(lines)-2)]
            posx = None
            posy = None
        else:
            line = f.readlines()
            lines= [line[i].split() for i in range(len(line))]
            widths = [lines[i][0] for i in range(2,len(lines))]
            heights  = [lines[i][1] for i in range(2,len(lines))]
            posx = [lines[i][2] for i in range(2,len(lines))]
            posy = [lines[i][3] for i in range(2,len(lines))]

    w = lines[0][0]
    h = lines[0][1]
    n = lines[1][0]

    return w, h, n, widths, heights, posx, posy

def output_writer(read_path, write_path, sol_source, ext='.txt', rot =False):

    if rot:
        fl= pd.read_excel(io= sol_source, names=['X','Y','R'])
    else:
        fl= pd.read_excel(io= sol_source, names=['X','Y'])
    r = 0
    for file in os.listdir(read_path):
        w, h, n, widths, heights,_,_ = data_file_reader(read_path, file)
        x = fl['X'][r].split(',')
        y = fl['Y'][r].split(',')
        if rot:
            rotation = fl['R'][r].split('r')
            rotation.reverse()
        x.reverse()
        y.reverse()
        with open(write_path + w +'x'+ h +'-out'+ ext, 'w') as out:
            out.write( w +' '+ h +'\n'
                     + n + '\n')
            for i in range(0, int(n)):
                if not rot:
                    out.write(widths[i] +' '+ heights[i] +'  '+ x[i] +' '+ y[i]+'\n')
                else:
                    out.write(widths[i] +' '+ heights[i] +'  '+ x[i] +' '+ y[i]+ rotation[i] +'\n')
        r+=1

def solution_output (path, file_name = "every"):

    """Path = directory containing the solution
     File name = "LxL-out.txt" where l is the paper length, if default or "every" then all solution are sequentially inspected"""

    if file_name == "every":
        for file in os.listdir(path):
            output_visualizer(path, file)
    else:
            output_visualizer(path, file_name)

def output_visualizer (out_path, file_name = "8x8-out.txt", border_reduction = 0.15):

    """
    visualizes the solutions given the path containing the output instances with the positions solutions
    """
    dim, _, _, width, height,posx,posy = data_file_reader(out_path, file_name, sol = True)

    colors = ['blue','green','yellow','red','orange',
              'purple','black','pink', 'cyan','gold',
              'silver','indigo', 'aquamarine', 'beige',
              'magenta','teal','aqua', 'lavender',
              'crimson', 'orchid']

    rotations = np.zeros(len(posx))

    fig = plt.figure()
    ax = fig.add_subplot(111)

    for i in range(len(posx)):
        if rotations[i]:
            rect = Rectangle((int(posx[i]), int(posy[i])), float(height[i])-border_reduction, float(width[i])-border_reduction, color = colors[i % len(colors)], ec ='black', label = i+1)
        else:
            rect = Rectangle((int(posx[i]), int(posy[i])), float(width[i])-border_reduction, float(height[i])-border_reduction, color = colors[i % len(colors)], ec ='black', label = i+1)

        ax.add_patch(rect)

    plt.title(dim + 'x' + dim)
    plt.xlim(-0.15,float(dim) +1.25)
    plt.ylim(-0.15,float(dim) +1.25)
    #plt.legend()
    plt.show()

def solution_visualizer (posx, posy, width, height, dim,rotations):
    """
    visualizes a solution given the positions obtained with the solver
    """
    colors = [  'blue','green','yellow','red','orange',
                'purple','black','pink', 'cyan','gold',
                'aqua','indigo', 'aquamarine', 'beige',
                'magenta','teal','silver', 'lavender',
                'crimson', 'orchid']

    fig = plt.figure()
    ax= fig.add_subplot(111)

    for i in range(len(posx)):
       if rotations[i]==True:
           print('Present {} with w = {} and h = {} has been rotated'.format(i,width[i], height[i]))
           rect = Rectangle((posx[i], posy[i]),height[i] , width[i], color = colors[i % len(colors)],label=i, ec ='white')
           ax.add_patch(rect)
       else:
           rect = Rectangle((posx[i], posy[i]), width[i], height[i], color = colors[i % len(colors)], label=i,ec ='white')
           ax.add_patch(rect)

    plt.xlim(0,dim)
    plt.ylim(0,dim)
    plt.legend()
    plt.show()

def reordering(sizes,widths,heights,resx,resy,n):
    """
    function implemented to reorder the positions results when using the SB constraint
    to output the results sorted like the input instances.
    """
    new_widths = [i for i,_ in sizes]
    new_heights = [i for _,i in sizes]

    posx=[]
    posy=[]
    for a,b in zip(widths,heights):
        for i in range(n):
            if a == new_widths[i] and b == new_heights[i]:
                x=resx[i]
                y=resy[i]
        posx.append(x)
        posy.append(y)

    return posx,posy

###########CALL UTILS#############
solution_output(output_smt_path_ext, "every")

#print('DONE')


# -*- coding: utf-8 -*-
import os, unittest
from io import BytesIO
from chappie.client.aws import S3Client

class TestS3Client(unittest.TestCase):
    def setUp(self):
        """ """
        self.client = S3Client()
        self.client.bucket = "bucket-test-w37ryifgckcbjqiu4yrf78qy3874yr8cwfc"

        self.params_dict = {
            "Service": 's3'
        }
        file_obj = BytesIO(b'test')
        self.params_dict = self.client.upload_file(file_obj, 'chappie-test/tmp/', 'test.txt', self.params_dict)

    def test_file_upload(self):
        """Test upload of file data"""

        self.assertIsInstance(self.params_dict, dict)
        self.assertEqual(self.params_dict.get('Bucket'), self.client.bucket)
        self.assertEqual(self.params_dict.get('Key'), 'chappie-test/tmp/test.txt')

    def test_file_download(self):
        """Test download of file data"""

        filedata = self.client.download_file(self.params_dict)

        self.assertIsInstance(filedata, bytes)
        self.assertEqual(filedata.decode(), 'test')

    def test_get_url(self):
        """Test get file access url"""

        url = self.client.get_url(self.params_dict)
        self.assertGreater(len(url), 0)

    def test_delete_file(self):
        """Test file delete"""

        status = self.client.delete_file(self.params_dict)


# 처음에는 각 좌표의 중점을 찾아서 각 변의 길이를 구해서 삼각형으로 쪼개서 계산하려 했다.
# 하지만 쉽지않았다. -> 좌표를 가지고 각 변의 길이를 구해내는게 어려웠다.
# 신발끈 공식 -> 가능한 이유 다각형을 이루는 순서대로 값이 들어옴
import sys
n = int(sys.stdin.readline())
x = []
y = []

for i in range(n):
    a,b = map(int,sys.stdin.readline().split())
    x.append(a)
    y.append(b)

x.reverse()
y.reverse()
x.append(x[0])
y.append(y[0])
upTotal = 0
downTotal =0
for i in range(n):
    upTotal += x[i] * y[i+1]
    downTotal += y[i] * x[i+1]
result = round(abs(upTotal-downTotal)/2,1)
print(result)