# Write a function is_even that will return true if the passed-in number is even.

# YOUR CODE HERE
# Define function with 1 parameter (number)
def is_even(num1):
# Check if number is even using modulo
    if num1 % 2 == 0:
# Return True if num is even
        return True
# Read a number from the keyboard
num = input("Enter a number: ")
num = int(num)
print(is_even(num))

# Print out "Even!" if the number is even. Otherwise print "Odd"

# YOUR CODE HERE
def is_even2(num2):
    if num2 % 2 == 0:
        print("Even!")
    else:
        print("Odd")

is_even2(num)


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

from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, BatchNormalization
from keras.optimizers import SGD, Adam, RMSprop
from keras.callbacks import LearningRateScheduler
from keras.utils import np_utils
import keras.backend as K

from bnn.binary_ops import binary_tanh as binary_tanh_op
from bnn.binary_layers import BinaryDense

class DropoutNoScale(Dropout):
    '''Keras Dropout does scale the input in training phase, which is undesirable here.
    '''
    def call(self, inputs, training=None):
        if 0. < self.rate < 1.:
            noise_shape = self._get_noise_shape(inputs)

            def dropped_inputs():
                return K.dropout(inputs, self.rate, noise_shape,
                                 seed=self.seed) * (1 - self.rate)
            return K.in_train_phase(dropped_inputs, inputs,
                                    training=training)
        return inputs

def binary_tanh(x):
    return binary_tanh_op(x)

batch_size = 100
nb_epoch = 25
nb_classes = 10

H = 'Glorot'
kernel_lr_multiplier = 'Glorot'

# network
num_unit = 240
num_hidden = 3
use_bias = False

# learning rate schedule
lr_start = 1e-3
lr_end = 1e-4
lr_decay = (lr_end / lr_start)**(1. / nb_epoch)

# BN
epsilon = 1e-6
momentum = 0.9

# dropout
drop_in = 0.2
drop_hidden = 0.3

model = Sequential()
model.add(DropoutNoScale(drop_in, input_shape=(183,), name='drop0'))
for i in range(num_hidden):
    model.add(BinaryDense(num_unit, H=H, kernel_lr_multiplier=kernel_lr_multiplier, use_bias=use_bias,
              name='dense{}'.format(i+1)))
    model.add(BatchNormalization(epsilon=epsilon, momentum=momentum, name='bn{}'.format(i+1)))
    model.add(Activation(binary_tanh, name='act{}'.format(i+1)))
    model.add(DropoutNoScale(drop_hidden, name='drop{}'.format(i+1)))
model.add(BinaryDense(1, H=H, kernel_lr_multiplier=kernel_lr_multiplier, use_bias=use_bias,
          name='dense'))
model.add(BatchNormalization(epsilon=epsilon, momentum=momentum, name='bn'))

opt = Adam(lr=lr_start)
#model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['acc'])
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

lr_scheduler = LearningRateScheduler(lambda e: lr_start * lr_decay ** e)
from . import generate_numpys
print("merged ...")
X_train = generate_numpys.X_t
Y_train = generate_numpys.Y_t
X_test = generate_numpys.X_test
Y_test = generate_numpys.Y_test
'''
history = model.fit(X_train, Y_train,
                    batch_size=batch_size, nb_epoch=nb_epoch,
                    verbose=1, validation_data=(X_test, Y_test),
                    callbacks=[lr_scheduler])
'''
history = model.fit(X_train, Y_train,
                    batch_size=batch_size, nb_epoch=nb_epoch,
                    verbose=1, validation_data=(X_test, Y_test))
score = model.evaluate(X_test, Y_test, verbose=0)
import pickle
with open('forests_history.pkl', 'wb') as f:
    pickle.dump(history, f)
print('Test score:', score[0])
print('Test accuracy:', score[1])

y_pred = score = model.predict(X_test)

log_y = Y_test
log_predicted = y_pred

from sklearn.metrics import roc_curve
from sklearn.metrics import auc
import matplotlib.pyplot as plt
import numpy as np
print(history.history.keys())

'''
#log_y = np.array([1, 1, 0, 0])
#log_predicted =  np.array([0.1, 0.4, 0.35, 0.8])
fpr, tpr, thresholds = roc_curve(log_y, log_predicted, pos_label  = 1)
roc_auc = auc(log_y, log_predicted, reorder  = True)

# Plot ROC curve
#plt.plot(fpr, tpr, label='ROC curve (area = %0.3f)' % roc_auc)
plt.plot(fpr, tpr, label='BNN ROC curve')
plt.plot([0, 1], [0, 1], 'k--')  # random predictions curve
#plt.xlim([0.0, 1.0])
#plt.ylim([0.0, 1.0])
plt.xlabel('False Positive Rate or (1 - Specifity)')
plt.ylabel('True Positive Rate or (Sensitivity)')
plt.title('Receiver Operating Characteristic')
plt.legend(loc="lower right")
plt.savefig('foo.png')

def get_labels(path = 'labels.csv'):
    with open(path) as csv:
        content = csv.readlines()[0].lower()
        content  = content.replace('","', "TARA")
        content  = content.replace(',', " ")
        content  = content.replace('"', " ")
        content  = content.replace('\n', " ")
        content  = content.replace('TARA', " , ")
        content = content.split(",")
        return content

def get_indexes (term = 'shank'):
    labels = get_labels()
    return [b for b in range(len(labels)) if term in labels[b]]
'''


from calenderTools import *

d1 = "Jan 01, 2017"

d2 = ["Mar 22, 2017", "Apr 04, 2017", "Dec 31, 2017", "Jan 10, 2018", "Mar 04, 2019"]

for i in range(len(d2)):
    numDays12 = calculateDaysBetween(d1, d2[i])
    print("The number of days between", d1, " and", d2,  "is", numDays12)
    print("")


class OrderedStream:

    def __init__(self, n: int):
        self.ptr = 1
        self.values = {}

    def insert(self, idKey: int, value: str) -> List[str]:
        if idKey != self.ptr:
            self.values[idKey] = value
            return []
        stream = [value]
        self.ptr += 1
        while self.ptr in self.values:
            stream += [self.values[self.ptr]]
            self.ptr += 1
        return stream

# Your OrderedStream object will be instantiated and called as such:
# obj = OrderedStream(n)
# param_1 = obj.insert(idKey,value)


import torch
import torch.nn as nn

class Discriminator(nn.Module):

    def __init__(self):
        super(Discriminator, self).__init__()
        channels = [3, 64, 256, 512]

        self.leaky_relu = nn.LeakyReLU(0.2)
        self.sigmoid = nn.Sigmoid()
        self.conv1 = nn.Conv2d(channels[0], channels[1], kernel_size= 3, padding= 1)
        self.pool1 = nn.MaxPool2d((4, 4), (4, 4))
        self.conv2 = nn.Conv2d(channels[1], channels[2], kernel_size= 3, padding= 1)
        self.pool2 = nn.MaxPool2d((4, 4), (4, 4))
        self.conv3 = nn.Conv2d(channels[2], channels[3], kernel_size= 3, padding= 1)
        self.pool3 = nn.MaxPool2d((2, 2), (2, 2))

        self.fc1 = nn.Linear(channels[-1] * 2 * 2, 16)
        self.fc2 = nn.Linear(16, 1)

    def name(self):
        return 'd_01'

    def forward(self, x):
        x = self.leaky_relu(self.conv1(x))
        x = self.pool1(x)
        x = self.leaky_relu(self.conv2(x))
        x = self.pool2(x)
        x = self.leaky_relu(self.conv3(x))
        x = self.pool3(x)
        x = x.view(x.size(0), -1)
        x = self.leaky_relu(self.fc1(x))
        x = self.sigmoid(self.fc2(x))
        return x

def parameter_number(model):
    return sum(p.numel() for p in model.parameters() if p.requires_grad)

def unit_test():
    imgs = torch.zeros(10, 3, 64, 64)
    model = Discriminator()
    out = model(imgs)

    print('Parameter number: ',parameter_number(model))
    print('Input size: ', imgs.size())
    print('Output size:', out.size())

if __name__ == '__main__':
    unit_test()


USERS = [
    # Twitter usernames
    dict(
        id='pauleveritt',
        email='p@x.com',
        first_name='Firstie',
        last_name='Lastie',
        twitter='paulweveritt'
    ),
    dict(
        id='stormfburg',
        email='p@x.com',
        first_name='STORM',
        last_name='Fburg',
        twitter='stormfburg'
    ),
    dict(
        id='chrismcdonough',
        email='p2@x.com',
        first_name='Firstie',
        last_name='Lastie',
        twitter='chrismcdonough'
    ),
    dict(
        id='blaflamme',
        email='p2@x.com',
        first_name='Firstie',
        last_name='Lastie',
        twitter='blaiselaflamme'
    )
]

def get_user(property, value):
    for user in USERS:
        if user.get(property) == value:
            return user


'''
Copyright (C) 2015 Pistiwique, Pitiwazou

Created by Pistiwique, Pitiwazou

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import bpy, subprocess
from os import listdir
from os.path import join, isfile
from ..function_utils.get_path import (get_addon_path,
                                       get_directory,
                                       get_library_path,
                                       )

def check_existing_IBL_Tool(world):
    """ Check if the AM_IBL_Worl setup exist """

    if world in bpy.data.worlds:
        return True
    return False

#------------------------------------------------------------------
#
#------------------------------------------------------------------

def update_projection(sef, context):
    AM = bpy.context.window_manager.asset_m
    IBL_world = bpy.data.worlds["AM_IBL_WORLD"]
    nodes = IBL_world.node_tree.nodes
    nodes['Environment'].projection = AM.projection
    nodes['Reflexion'].projection = AM.projection

#------------------------------------------------------------------
#
#------------------------------------------------------------------

def setup_node_editor():
    """ Setup the node editor """

    bpy.context.area.type = 'NODE_EDITOR'
    bpy.context.scene.render.engine = 'CYCLES'
    bpy.context.space_data.tree_type = 'ShaderNodeTree'
    bpy.context.space_data.shader_type = 'WORLD'

#------------------------------------------------------------------
#
#------------------------------------------------------------------

def get_ibl_from_thumbnail(ibl, dir):
    """ Get the ibl full path from the selected preview """

    extentions = (".hdr", ".exr", ".jpg", ".jpeg", ".png", ".tif")
    ibl_name = [f for f in listdir(dir) if f.endswith(extentions) and f.rsplit(".", 1)[0] == ibl.rsplit(".", 1)[0]]

    return ibl_name[0]

#------------------------------------------------------------------
#
#------------------------------------------------------------------

def generate_thumbnail_ibl(thumbnail_directory):
    """ Generate the thumbnails of the IBL """

    AM = bpy.context.window_manager.asset_m
    addon_path = get_addon_path()
    IBL_dir = get_directory("IBL")
    thumb_list = ";".join(AM.ibl_to_thumb)
    script_thumbnailer = join(addon_path, "background_tools", 'generate_ibl_thumbnail.py')
    blend_thumbnailer = join(addon_path, 'blend_tools', 'asset', 'thumbnailer.blend')
    subprocess.Popen([bpy.app.binary_path, blend_thumbnailer, '-b', '--python', script_thumbnailer, IBL_dir, thumb_list, thumbnail_directory, AM.thumb_ext])

#------------------------------------------------------------------
#
#------------------------------------------------------------------

def import_ibl_from_asset_management():
    """ Import and setup ibl """

    WM = bpy.context.window_manager
    AM = WM.asset_m
    addon_path = get_addon_path()
    library_path = get_library_path()
    ibl_node_group = "AM_IBL_Tool"
    blur_node_group = "ImageBlur"
    directory_path = get_directory("IBL")

    setup_node_editor()

    if not check_existing_IBL_Tool("AM_IBL_WORLD"):
        blendfile = join(addon_path, "blend_tools", "IBL", "IBL_Tool.blend")
        directory = join(blendfile, "NodeTree")

        IBL_world = bpy.data.worlds.new("AM_IBL_WORLD")
        IBL_world.use_nodes = True
        bpy.context.scene.world = IBL_world
        nodes = IBL_world.node_tree.nodes

        nodes.remove(nodes["Background"])

        with bpy.data.libraries.load(blendfile) as (data_from, data_to):
            if data_from.node_groups:
                bpy.ops.wm.append(filename=ibl_node_group, directory=directory)
                bpy.ops.wm.append(filename=blur_node_group, directory=directory)

        tex_coord_node = nodes.new("ShaderNodeTexCoord")
        tex_coord_node.location = -810, 260

        mapping_node = nodes.new("ShaderNodeMapping")
        mapping_node.location = -560, 280

        blur_node = nodes.new("ShaderNodeGroup")
        blur_node.location = -140, 200
        blur_node.name = blur_node_group
        blur_node.node_tree = bpy.data.node_groups[blur_node_group]

        env_node = nodes.new("ShaderNodeTexEnvironment")
        env_node.location = 100, 360
        env_node.name = "Environment"

        reflexion_node = nodes.new("ShaderNodeTexEnvironment")
        reflexion_node.location = 100, 120
        reflexion_node.name = "Reflexion"

        ibl_name = get_ibl_from_thumbnail(WM.AssetM_previews, directory_path)
        img = bpy.data.images.load(join(directory_path, ibl_name))
        env_node.image = img
        reflexion_node.image = img

        ibl_node = nodes.new("ShaderNodeGroup")
        ibl_node.location = 320, 300
        ibl_node.name = ibl_node_group
        ibl_node.node_tree = bpy.data.node_groups[ibl_node_group]

        output_node = nodes["World Output"]
        output_node.location = 550, 300

        tree = IBL_world.node_tree
        tree.links.new(tex_coord_node.outputs[3], mapping_node.inputs[0])
        tree.links.new(mapping_node.outputs[0], blur_node.inputs[0])
        tree.links.new(mapping_node.outputs[0], env_node.inputs[0])
        tree.links.new(blur_node.outputs[0], reflexion_node.inputs[0])
        tree.links.new(env_node.outputs[0], ibl_node.inputs[1])
        tree.links.new(reflexion_node.outputs[0], ibl_node.inputs[6])
        tree.links.new(ibl_node.outputs[0], output_node.inputs[0])

    else:
        IBL_world = bpy.data.worlds["AM_IBL_WORLD"]
        IBL_world.use_nodes = True
        bpy.context.scene.world = IBL_world
        nodes = IBL_world.node_tree.nodes
        ibl_name = get_ibl_from_thumbnail(WM.AssetM_previews, directory_path)

        if not "Reflexion" in IBL_world.node_tree.nodes:
            reflexion_node = nodes.new("ShaderNodeTexEnvironment")
            reflexion_node.location = 100, 120
            reflexion_node.name = "Reflexion"

            tree = IBL_world.node_tree
            tree.links.new(nodes['Mapping'].outputs[0], nodes['Environment'].inputs[0])
            tree.links.new(nodes['ImageBlur'].outputs[0], reflexion_node.inputs[0])
            tree.links.new(reflexion_node.outputs[0], nodes['AM_IBL_Tool'].inputs[6])

        if ibl_name in bpy.data.images:
            nodes["Environment"].image = bpy.data.images[ibl_name]
            nodes["Reflexion"].image = bpy.data.images[ibl_name]
        else:
            img = bpy.data.images.load(join(directory_path, ibl_name))
            nodes["Environment"].image = img
            nodes["Reflexion"].image = img

    if isfile(join(directory_path, WM.AssetM_previews.rsplit(".", 1)[0] + "_settings")):
        bpy.ops.wm.load_ibl_settings()

    else:
        nodes['Mapping'].rotation = (0.0, 0.0, 0.0)
        AM.projection = 'EQUIRECTANGULAR'
        nodes['ImageBlur'].inputs[1].default_value = 0.0
        IBL_world.cycles_visibility.camera = True
        bpy.context.scene.cycles.film_transparent = False
        nodes['AM_IBL_Tool'].inputs[0].default_value = 1.0
        nodes['AM_IBL_Tool'].inputs[2].default_value = 1.0
        nodes['AM_IBL_Tool'].inputs[3].default_value = 1.0
        nodes['AM_IBL_Tool'].inputs[4].default_value = (0.5, 0.5, 0.5, 1.0)
        nodes['AM_IBL_Tool'].inputs[5].default_value = 0.5
        nodes['AM_IBL_Tool'].inputs[7].default_value = 1.0
        nodes['AM_IBL_Tool'].inputs[8].default_value = 1.0
        nodes['AM_IBL_Tool'].inputs[9].default_value = (0.5, 0.5, 0.5, 1.0)
        nodes['AM_IBL_Tool'].inputs[10].default_value = 0.5

    bpy.context.area.type = 'VIEW_3D'
    cycles = bpy.context.scene.cycles
    if cycles.sample_clamp_direct == 0 and cycles.sample_clamp_indirect == 0:
        bpy.context.scene.cycles.sample_clamp_direct = 3
        bpy.context.scene.cycles.sample_clamp_indirect = 3


#copyright Vaibhav Raj 2018(email_ID:-vaibhav.raj.phe15@itbhu.ac.in,vaibhavraj46@gmail.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
#==========================================================================================================================

'''
A simple handwritten Devnagari numerals(0-9) classifier for training model.For training we would use the extracted version of the zip file :-'DevanagariHandwrittenCharacterDataset' that I've already uploaded.The extracted version needs to be saved along with the 'image_recog_train2.py'(file containing code for training the model) and 'image_recog_test2.py'(file containing code for classifying any random test image).
'''

#import modules
from PIL import Image
import numpy as np
import tensorflow as tf
import os
import re

'''
Algorithm to create two lists:-
(1)'image_batch' list for holding image color intensity matrix of all the handwritten devnagari numerals present in the train set of the extracted version of 'DevanagariHandwrittenCharacterDataset'.
(2)'labels' list for holding respective labels of the elements of 'image_batch'.
'''
L=[]
image_data=[]
labels=[]
path='DevanagariHandwrittenCharacterDataset\\DevanagariHandwrittenCharacterDataset\\Train'
l=os.listdir(path)
D=[]

for i in l:
    if(re.search('digit',i)):
        D.append(i)
        m=os.listdir(path+'\\'+i)
        L.append(m)

for j in range(len(m)):
    for k in D:
        d=int(k[::-1][0])
        n=L[d][j]
        imag=Image.open(path+'\\'+k+'\\'+n)
        image=imag.convert(mode='L')
        image_data.append(np.array(image,dtype=np.float32))
        labels.append(d)

image_data = np.multiply(image_data, 1.0/255.0)

image_batch = image_data.reshape(-1, 32,32,1)
labels=np.asarray(labels, dtype=np.int32)

#Creating placeholders:-image_batch_pl(for 'image_batch' list) and labels_pl(for 'labels' list):-
image_batch_pl=tf.placeholder(dtype=tf.float32,shape=[None,32,32,1],name='image_batch_pl')
labels_pl=tf.placeholder(dtype=np.int32,shape=[None])

'''
Creating CNN(convoluted neural network) model:-
'''

#Creating 1st convolution layer:-
conv1 = tf.layers.conv2d(inputs=image_batch_pl,filters=32,kernel_size=[5, 5],padding="same",activation=tf.nn.relu,name='conv1')

#creating 1st pooling layer:-
pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2,name='pool1')

#Creating 2nd convolution layer:-
conv2 = tf.layers.conv2d(inputs=pool1,filters=64,kernel_size=[5, 5],padding="same",activation=tf.nn.relu,name='conv2')

#Creating 2nd pooling layer:-
pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2,name='pool2')

#Flattening the pool2 matrix into vector:-
pool2_flat = tf.reshape(pool2, [-1, 8 * 8 * 64],name='pool2_flat')

#Creating fully connected layer 'dense' with RELU activation:-
dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu,name='dense')

#Creating dropout layer:-
dropout = tf.layers.dropout(inputs=dense, rate=0.25, training=True,name='dropout')

#Again creatinf a fully connected layer:-
logits = tf.layers.dense(inputs=dropout, units=10,name='logits')

#Applying softmax activation function to 'logits':-
cost=tf.nn.softmax(logits, name='cost')

'''
Model created:-
'''
#Converting the labels into one-hot vector:-
labelV=tf.one_hot(labels_pl,depth=10,name='labelV')

'''
Defining the loss function,optimizer,saver(for saving and restoring the session),batch size,iterations(as iters here),epochs(here its 30) along with initializing a new session and variables:-
'''
loss = -tf.reduce_sum(labelV*tf.log(cost),name='loss')
sess=tf.Session()
init=tf.global_variables_initializer()
sess.run(init)
train=tf.train.GradientDescentOptimizer(0.001).minimize(loss)
saver=tf.train.Saver()
batch_size=50
iter=(len(labels)//50)

'''
Training the model:-
'''
for h in range(20):
	for k in range(iter):
		sess.run(train,feed_dict={image_batch_pl:image_batch[batch_size*k:batch_size*(k+1)],labels_pl:labels[batch_size*k:batch_size*(k+1)]})

	print(("{0} epochs").format(h))

'''
Saving the session as a checkpoint file:-'./image_train2.ckpt' and printing the confirmation message:-
'''
save_path = saver.save(sess, './image_train2.ckpt')
print ("Model saved in file: ", save_path)


import re
import urllib2

from base import BaseHandler

class CheckBrokenLinksHandler(BaseHandler):
  def get(self):
    if not self.authenticate(author=True):
      return

    url = self.get_argument('url', '')
    if url:
      self.check_link(url)
      return

    self.display["user"] = self.get_author_user()

    all_content = self.models.content.get(
        username=self.display["user"].username)

    links = []
    for content in all_content:
      urls = re.findall(r'http://[^ <\'"]+', content.view, re.I | re.M)
      if urls:
        links.append({ 'content': content, 'urls': urls })
    self.display["links"] = links[:10]

    self.fill_template("check_broken_links.html")

  def check_link(self, url):
    try:
      response = urllib2.urlopen(url)
      self.write('1')
    except:
      self.write('0')


"""
Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses.

Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.

So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters.

Note:

Numbers of houses and heaters you are given are non-negative and will not exceed 25000.
Positions of houses and heaters you are given are non-negative and will not exceed 10^9.
As long as a house is in the heaters' warm radius range, it can be warmed.
All the heaters follow your radius standard and the warm radius will the same.

Example 1:
    Input: [1,2,3],[2]
    Output: 1
    Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.

Example 2:
    Input: [1,2,3,4],[1,4]
    Output: 1
    Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.
"""

# Time Limit Exceeded
def findRadius(houses, heaters):
    houses = sorted(houses)
    heaters = sorted(heaters)
    max_min_distance = 0
    for house in houses:
        print(max_min_distance)
        min_distance = None
        heater_index = 0
        while heater_index < len(heaters):
            distance = abs(heaters[heater_index] - house)
            if min_distance == None:
                min_distance = distance
            else:
                if distance < min_distance:
                    min_distance = distance
                else:
                    break
            heater_index += 1
        if min_distance > max_min_distance:
            max_min_distance = min_distance
    return max_min_distance

def findRadius2(houses, heaters):
    # sort the houses and heaters list
    houses = sorted(houses)
    heaters = sorted(heaters)
    # the closest heater of the last house in list
    last_heater_index = 0
    # the maximum value of minimum distance between a house and any heater
    max_min_distance = 0
    # iterate over the houses list
    for house in houses:
        # the minimum distance between the house and a heater
        min_distance = None
        # the index of the beginning point of the distance calculation
        heater_index = last_heater_index
        # iterate over the heaters, find the closest heater
        while heater_index < len(heaters):
            # calculate the distance
            distance = abs(heaters[heater_index] - house)
            if min_distance == None:
                min_distance = distance
            else:
                if distance <= min_distance:
                    min_distance = distance
                else:
                    break
            heater_index += 1
        # get the position of the closest heater
        last_heater_index = heater_index - 1
        # update the max min distance
        if min_distance > max_min_distance:
            max_min_distance = min_distance
    return max_min_distance

houses1 = [1, 2, 3]
heaters1 = [2]

houses2 = [1, 2, 3, 4]
heaters2 = [1, 4]

houses3 = [1,1,1,1,1,1,999,999,999,999,999]
heaters3 = [499,500,501]

houses4 = [282475249,622650073,984943658,144108930,470211272,101027544,457850878,458777923]
heaters4 = [823564440,115438165,784484492,74243042,114807987,137522503,441282327,16531729,823378840,143542612]

print(findRadius2(houses4, heaters4))


import json
from utils import get_tfpath
from flask import Flask, render_template, request, redirect

app = Flask(__name__, template_folder=".")
app.config["SECRET_KEY"] = "dQw4w9WgXcQ"

_HOST = "127.0.0.1"
_PORT = "9982"

@app.route("/")
def index():
    global ujson
    return render_template("get_sanitized.html", ujson=ujson)

def save_json(fdata):
    global ujson
    for key, value in fdata.items():
        item = ujson.get(key)
        if all([not item.get("is_answered"), value == "1"]):
            value = "0"
        elif value == "-3":
            ujson.pop(key)
            continue

        ujson.get(key).update({"type": value})

    path = get_tfpath("s_")
    with open(path, "w") as fp:
        json.dump(ujson, fp, indent=4)
        print("[info] Saved sanitized json to", path)

@app.route("/save", methods=["POST"])
def save():
    global ujson
    save_json(request.form.to_dict())
    return redirect("/")

def _run_server(data):
    global ujson
    ujson = data
    print(
        "\033[35m",
        "[info] PRESS CTRL-C WHEN YOU ARE DONE WITH SANITIZATION AND HAVE SUBMITTED.",
        "\033[0m",
        sep="",
    )
    app.run(host=_HOST, port=_PORT, debug=False)

def _get_sjson():
    global ujson
    app.do_teardown_appcontext()
    return ujson

def sanitize(ujson):
    _run_server(ujson)
    input(
        "\n[input] Sanitize questions and submit. Press to start converting sanitized result to docx.. "
    )
    return _get_sjson()


import sys
import nibabel as nib
import numpy
import argparse

def main(*args):

  helpText = "   Match the histogram of an image to the histogram of a reference image using information " \
             "from their segmentations."
  parser = argparse.ArgumentParser(description=helpText)

  helpText = "Reference image"
  parser.add_argument("ref", type=str, help=helpText)

  helpText = "Source image"
  parser.add_argument("src", type=str, help=helpText)

  helpText = "Reference segmentation"
  parser.add_argument("refSeg", type=str, help=helpText)

  helpText = "Source segmentation"
  parser.add_argument("srcSeg", type=str, help=helpText)

  helpText = "Output image"
  parser.add_argument("output", type=str, help=helpText)

  helpText = "ventricle label (default 5)"
  parser.add_argument("-ventLabel", type=int, help=helpText)

  helpText = "GM label (default 3)"
  parser.add_argument("-gmLabel", type=int, help=helpText)

  helpText = "WM label (default 2)"
  parser.add_argument("-wmLabel", type=int, help=helpText)

  helpText = "CSF label (default 1)"
  parser.add_argument("-csfLabel", type=int, help=helpText)

  #############################################################

  args = parser.parse_args()

  refImgName = args.ref
  srcImgName = args.src

  refSegName = args.refSeg
  srcSegName = args.srcSeg

  outImgName = args.output

  ventLabel = args.ventLabel
  gmLabel = args.gmLabel
  wmLabel = args.wmLabel
  csfLabel = args.csfLabel

  if ventLabel == None:
    ventLabel = 5
  if gmLabel == None:
    gmLabel = 3
  if wmLabel == None:
    wmLabel = 2
  if csfLabel == None:
    csfLabel = 1

  refImg = nib.load(refImgName)
  srcImg = nib.load(srcImgName)

  refImgData = refImg.get_data().squeeze()
  srcImgData = srcImg.get_data().squeeze()

  srcMin = numpy.min(srcImgData)
  srcMax = numpy.max(srcImgData)

  refMin = numpy.min(refImgData)
  refMax = numpy.max(refImgData)

  outImgData = srcImgData.copy()

  refSegImg = nib.load(refSegName)
  refSeg = refSegImg.get_data().squeeze()
  if not (refSeg.shape == refImgData.shape):
    raise Exception('Reference and its segmentation have different shapes')

  srcSegImg = nib.load(srcSegName)
  srcSeg = srcSegImg.get_data().squeeze()
  if not (srcSeg.shape == srcImgData.shape):
    raise Exception('Source image and its segmentation have different shapes')

  srcPts = [srcMin, srcMax]
  refPts = [refMin, refMax]

  # low and high percentiles
  vs = numpy.percentile(srcImgData, [1,99])
  srcPts = srcPts + list(vs)
  vs = numpy.percentile(refImgData, [1,99])
  refPts = refPts + list(vs)

  # CSF
  vs = srcImgData[ numpy.logical_or(srcSeg == csfLabel, srcSeg == ventLabel)]
  srcPts.append(numpy.mean(vs))
  vs = refImgData[numpy.logical_or(refSeg == csfLabel, refSeg == ventLabel)]
  refPts.append(numpy.mean(vs))

  # GM
  vs = srcImgData[srcSeg == gmLabel]
  srcPts.append(numpy.mean(vs))
  vs = refImgData[refSeg == gmLabel]
  refPts.append(numpy.mean(vs))

  # WM
  vs = srcImgData[srcSeg == wmLabel]
  srcPts.append(numpy.mean(vs))
  vs = refImgData[refSeg == wmLabel]
  refPts.append(numpy.mean(vs))

  ix = numpy.argsort(srcPts)
  srcPts = numpy.asarray(srcPts)[ix]
  refPts = numpy.asarray(refPts)[ix]

  x = numpy.ravel(srcImgData)

  y = numpy.interp(x, srcPts, refPts)

  y = numpy.reshape(y, srcImgData.shape)

  aff = srcImg.get_affine()
  outImg = nib.Nifti1Image(y, aff)
  nib.save(outImg, outImgName)

###############################################################

if __name__ == '__main__':
  sys.exit(main(*sys.argv))


#===============================================================================
# Copyright 2012 Jake Ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#===============================================================================

#============= enthought library imports =======================
from traits.api import HasTraits, Instance
from traitsui.api import View, Group
#============= standard library imports ========================
import numpy as np
import math
#============= local library imports  ==========================

from src.helpers.traitsui_shortcuts import instance_item
from src.graph.graph import Graph
from src.graph.error_bar_overlay import ErrorBarOverlay
from chaco.array_data_source import ArrayDataSource
from matplotlib.figure import Figure
from src.graph.mpl_editor import MPLFigureEditor
from matplotlib.cm import coolwarm

class FluxView(HasTraits):
    flux_2D = Instance(Graph)
    flux_3D = Instance(Figure, ())
    def replot(self, monitors, unknowns, regressor2D, regressor3D):

        self.replot2D(monitors, unknowns, regressor2D)
        self.replot3D(monitors, unknowns, regressor3D)

    def replot3D(self, monitors, unknowns, regressor):
        from mpl_toolkits.mplot3d import Axes3D

        fig = self.flux_3D
        ax = fig.gca(projection='3d')

        mx, my, mys, mye = zip(*[(pi.x, pi.y, pi.pred_j, pi.pred_j_err)
                                  for pi in monitors])
        x, y, ys, ye = zip(*[(pi.x, pi.y, pi.pred_j, pi.pred_j_err)
                             for pi in unknowns])

        x = np.array(x)
        y = np.array(y)

        ys = np.array(ys)
        mys = np.array(mys)

        w = max(x) - min(x)
        w = w * 1.25
        c = len(x)
        r = len(y)
        n = r * 2 - 1

        xx, yy = np.mgrid[0:n + 1, 0:n + 1]
        xx = xx / float(n) * w - w / 2.
        yy = yy / float(n) * w - w / 2.

        z = np.zeros((r * 2, c * 2))

        for i in range(r * 2):
            for j in range(c * 2):
                pt = (xx[i, j],
                      yy[i, j])
                v, _ = regressor.predict([pt])[0]
                z[i, j] = v

        ax.plot_surface(xx, yy, z, alpha=0.3,
                        rstride=1, cstride=1,
                        cmap=coolwarm,
                        linewidths=0
                        )

        ax.set_xlabel('X (mm)')
        ax.set_ylabel('Y (mm)')
        ax.set_zlabel('Z (%change)')
        self.flux_3D.canvas.draw()

    def replot2D(self, monitors, unknowns, regressor):
        g = self.flux_2D
        g.clear()
        g.new_plot()
        self._plot(g, monitors, use_predicted_value=False)

        self._plot(g, unknowns)
        if regressor:
            low, high = g.get_x_limits()
            fx = np.linspace(low, high, 200)
            fy = regressor.predict(fx)
            g.new_series(fx, fy, color='black')

            ly, uy = regressor.calculate_ci(fx)
            g.new_series(fx, ly, color='red', line_style='dash')
            g.new_series(fx, uy, color='red', line_style='dash')

    def _plot(self, graph, positions, use_predicted_value=True):
        xs = []
        ys = []
        es = []
        for pi in positions:
            if pi.pred_j:
#                #convert pi.x,pi.y to radians
                r = math.atan2(pi.x, pi.y)
                xs.append(r)
                if use_predicted_value:
                    ys.append(pi.pred_j)
                    es.append(pi.pred_j_err)
                else:
                    ys.append(pi.j)
                    es.append(pi.j_err)

        s, _ = graph.new_series(xs, ys, yerror=ArrayDataSource(data=es),
                                type='scatter', marker='circle', marker_size=2)
        ebo = ErrorBarOverlay(component=s, orientation='y')
        s.overlays.append(ebo)

        s.index_range.tight_bounds = False
        s.value_range.tight_bounds = False

    def traits_view(self):
        v = View(Group(
                       Group(instance_item('flux_2D'),
                             label='2D'
                             ),
                       Group(instance_item('flux_3D', editor=MPLFigureEditor()),
                             label='3D'
                             ),
                       layout='tabbed'
                       )

                 )
        return v

    def _flux_2D_default(self):
#        g = RegressionGraph(container_dict=dict(padding=5))
        g = Graph(container_dict=dict(padding=5))
        return g
#============= EOF =============================================


#!/usr/bin/env python

# encoding: utf-8

import csv

import time

import Levenshtein

threshold_similarity_co_name = 0.7

#threshold_similarity_people_name = 0.6 # 0.55 the threshold on the distance of two strings, if lower then the two strings are identical

def name_match(match_file1, match_file2, output_file_name, colume_name):

        # read file 'input_file_name' to obtain information about the user, such as fullname, twitter account, etc.

        match_dataset1 = [] # information read from match_dataset1.csv

        match_dataset2 = [] # information read from match_dataset2.csv

        first_row = True

        with open(match_file1, 'r') as inputFile :

                reader = csv.reader(inputFile)

                for row in reader:

                        if first_row:

                                first_row = False

                                continue

                        match_dataset1.append(row)

        first_row = True

        with open(match_file2, 'r') as inputFile :

                reader = csv.reader(inputFile)

                for row in reader:

                        if first_row:

                                first_row = False

                                continue

                        match_dataset2.append(row)

        output = []

        for row in match_dataset1:

                #row = match_dataset1[row_index, :]

                asx_code = row[0]

                company_name = row[1]

                print (row)

                matched = None

                for row2 in match_dataset2:

                        controllering_corproation = row2[0]

                        similarity_ratio = Levenshtein.ratio(company_name, controllering_corproation)

                        if similarity_ratio > threshold_similarity_co_name:

                                matched = True

                                print ("matched")

                                row.append(controllering_corproation)

                                output.append(row)

                                break

                        pass

                if not matched:

                        row.append("-")

                        output.append(row)

        with open(output_file_name, 'w', newline='') as outputFile:

                writer = csv.writer(outputFile)

                write_row_string = ["ASX code", "Controlled entities"]

                write_row_string.extend(colume_name)

                print (write_row_string)
                writer.writerow(write_row_string)

                writer.writerows(output)

if __name__ == '__main__':

        output_file_name = "./DataMatched0.csv"

        input1 = "./DataMatched.csv"

        input2 = "./Data_2014_2015.csv"

        colume_names = ["Match with 2014_2015"]

        name_match(input1, input2, output_file_name, colume_names)

        output_file_name = "./DataMatched1.csv"

        input1 = "./DataMatched0.csv"

        input2 = "./Data_2013_2014.csv"

        colume_names = ["Match with 2014_2015", "Match with 2013_2014"]

        name_match(input1, input2, output_file_name, colume_names)

        output_file_name = "./DataMatched2.csv"

        input1 = "./DataMatched1.csv"

        input2 = "./Data_2012_2013.csv"

        colume_names = ["Match with 2014_2015", "Match with 2013_2014", "Match with 2012_2013"]

        name_match(input1, input2, output_file_name, colume_names)

        output_file_name = "./DataMatched3.csv"

        input1 = "./DataMatched2.csv"

        input2 = "./Data_2011_2012.csv"

        colume_names = ["Match with 2014_2015", "Match with 2013_2014", "Match with 2012_2013", "Match with 2011_2012"]

        name_match(input1, input2, output_file_name, colume_names)

        output_file_name = "./DataMatched4.csv"

        input1 = "./DataMatched3.csv"

        input2 = "./Data_2010_2011.csv"

        colume_names = ["Match with 2014_2015", "Match with 2013_2014", "Match with 2012_2013", "Match with 2011_2012", "Match with 2010_2011"]

        name_match(input1, input2, output_file_name, colume_names)

        output_file_name = "./DataMatched5.csv"

        input1 = "./DataMatched4.csv"

        input2 = "./Data_2009_2010.csv"

        colume_names = ["Match with 2014_2015", "Match with 2013_2014", "Match with 2012_2013", "Match with 2011_2012", "Match with 2010_2011", "Match with 2009_2010"]

        name_match(input1, input2, output_file_name, colume_names)

        output_file_name = "./DataMatched6.csv"

        input1 = "./DataMatched5.csv"

        input2 = "./Data_2008_2009.csv"

        colume_names = ["Match with 2014_2015", "Match with 2013_2014", "Match with 2012_2013", "Match with 2011_2012", "Match with 2010_2011", "Match with 2009_2010", "Match with 2008_2009"]

        name_match(input1, input2, output_file_name, colume_names)

        print (threshold_similarity_co_name)


import sublime, json
from urllib.request import urlopen
from collections import deque

def load_completions(plugin_path):
	completions_data = {}
	for filename in ["lucee_tags","lucee_functions","lucee_member_functions","cfml_tags","cfml_functions","cfml_member_functions"]:
		completions_data[filename] = load_json_data(plugin_path, filename)

	# setup completion lists
	completions = {}
	for dialect in ["lucee","cfml"]:
		# tags
		completions[dialect + "_tags"] = []
		completions[dialect + "_tags_in_script"] = []
		completions[dialect + "_tag_attributes"] = {}
		for tag_name in sorted(completions_data[dialect + "_tags"].keys()):
			tag_attributes = completions_data[dialect + "_tags"][tag_name]
			completions[dialect + "_tags"].append(make_tag_completion(tag_name, dialect, tag_attributes[0]))
			completions[dialect + "_tags_in_script"].append(make_tag_completion(tag_name[(1 if dialect == "lucee" else 2):], dialect, tag_attributes[0]))
			completions[dialect + "_tag_attributes"][tag_name] = [(a + '\trequired', a + '="$1"') for a in tag_attributes[0]]
			completions[dialect + "_tag_attributes"][tag_name].extend([(a + '\toptional', a + '="$1"') for a in tag_attributes[1]])

		# functions
		completions[dialect + "_functions"] = [(funct + '\tfn (' + dialect + ')', funct + completions_data[dialect + "_functions"][funct]) for funct in sorted(completions_data[dialect + "_functions"].keys())]

		# member functions
		mem_func_comp = []
		for member_function_type in sorted(completions_data[dialect + "_member_functions"].keys()):
			for funct in sorted(completions_data[dialect + "_member_functions"][member_function_type].keys()):
				mem_func_comp.append( (funct + '\t' + member_function_type + '.fn (' + dialect + ')', funct + completions_data[dialect + "_member_functions"][member_function_type][funct]))
		completions[dialect + "_member_functions"] = mem_func_comp

	return completions

def load_json_data(plugin_path, filename):
	with open(plugin_path + '/json/' + filename + '.json', 'r') as f:
		json_data = f.read()
	return json.loads(json_data)

def make_tag_completion(tag, type, required_attrs):
	attrs = ''
	for index, attr in enumerate(required_attrs, 1):
		attrs += ' ' + attr + '="$' + str(index) + '"'
	return (tag + '\ttag (' + type + ')', tag + attrs)

def get_previous_word(view, pos):
	previous_word_start = view.find_by_class(pos, False, sublime.CLASS_WORD_START)
	previous_word = view.substr(sublime.Region(previous_word_start, pos)).strip().lower()
	return previous_word

def get_tag_name(view, pos):
	# walk backwards from cursor, looking for tag name scope
	for index in range(500):
		if view.match_selector(pos - index,"entity.name.tag"):
			tag_name_region = view.expand_by_class(pos - index, sublime.CLASS_WORD_START | sublime.CLASS_WORD_END, "</>;{}()")
			tag_name = view.substr(tag_name_region).lower()
			return tag_name
		if view.match_selector(pos - index,"punctuation.definition.tag.begin"):
			return None

def get_last_open_tag(view, pos):
	open_tags = deque()
	tag_starts = [r for r in view.find_by_selector("punctuation.definition.tag.begin") if r.end() <= pos]
	tag_ends = [r for r in view.find_by_selector("punctuation.definition.tag.end") if r.end() <= pos]

	# if lengths don't match don't bother trying to find last open tag
	if len(tag_starts) != len(tag_ends):
		return None

	for tag_start, tag_end in zip(tag_starts, tag_ends):
		tag_name_region = sublime.Region(tag_start.end(), view.find_by_class(tag_start.end(), True, sublime.CLASS_WORD_END, "/>"))
		tag_name = view.substr(tag_name_region)

		# if length is 1 then this is a tag opening punctuation
		if tag_start.size() == 1:

			if tag_end.size() > 1:
				# self closing tag has tag end of size 2 "/>" - skip these
				continue

			# check to exclude cfml tags that should not have a closing tag
			if tag_name in ["cfset","cfelse","cfelseif",":set",":else",":elseif"]:
				continue
			# check to exclude html tags that should not have a closing tag
			if tag_name in ["area","base","br","col","command","embed","hr","img","input","link","meta","param","source"]:
				continue

			open_tags.appendleft(tag_name)

		# if length is 2 then this is a tag closing punctuation
		if tag_start.size() == 2 and tag_name in open_tags:
			open_tags.remove(tag_name)

	return open_tags.popleft() if len(open_tags) > 0 else None

def get_support_function_name(view, pt):
	args_region = None
	function_call_arguments_scope = "meta.support.function-call.arguments.cfml"
	scope_count = view.scope_name(pt).count(function_call_arguments_scope)
	scope_to_find = " ".join([function_call_arguments_scope] * scope_count)
	for r in view.find_by_selector(scope_to_find):
		if r.contains(pt):
			args_region = r
			break
	if args_region:
		return view.substr(view.word(args_region.begin()-1)).lower()
	return None


import re
import csv

with open("phonebook_raw.csv", encoding='utf8') as f:
    rows = csv.reader(f, delimiter=",")
    contacts_list = list(rows)

phone_pattern = re.compile(
    r'(\+7|8)\s*\(*(\d{3})\)*\s*\-*(\d{3})\s*\-*(\d{2})\s*\-*(\d{2})')
extension_pattern = re.compile(r'\s*\(*(доб.)\s*(\d+)\)*\s*')
text_pattern = re.compile(
    r'(\w+[А-яЁё])\s*\,*(\w+[А-яЁё])\s*\,*(\w+[А-яЁё])*\,*(\w+[А-яЁё])*\,*(\w+[А-яЁё]\w+[А-яЁё –]*'
    r'\–*\s*)*\,*(\+*\d\s*\(*\d+\)*\-*\s*\d+\-*\d+\-*\d+\s*\(*\w*\.*\s*\d*\)*)*\,*([a-zA-Z0-9_.+-]'
    r'+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)*')

temp_list = []
for c in range(len(contacts_list)):
    if c == 0:
        temp_list.append(contacts_list[c])
    else:
        line = ','.join(contacts_list[c])
        result = re.search(text_pattern, line)
        temp_list.append(list(result.groups()))
        if temp_list[c][5] is not None:
            temp_list[c][5] = phone_pattern.sub(r'+7(\2)\3-\4-\5', temp_list[c][5])
            temp_list[c][5] = extension_pattern.sub(r' \1\2', temp_list[c][5])

final_list = []
for i in range(len(temp_list)):
    for s in range(len(temp_list)):
        if temp_list[i][0] == temp_list[s][0]:
            temp_list[i] = [x or y for x, y in zip(temp_list[i], temp_list[s])]
    if temp_list[i] not in final_list:
        final_list.append(temp_list[i])

with open("phonebook.csv", "w") as f:
    datawriter = csv.writer(f, delimiter=',')
    datawriter.writerows(final_list)


from django.contrib import admin
from django.urls import path, include
from home import views
urlpatterns = [
    path('', views.home, name='home'),
    path('about', views.about, name='about'),
    path('projects', views.projects, name='projects'),
    path('contact', views.contact, name='contact'),
    # path('login', views.login, name='login'),
    path('register', views.register, name='register'),
]


"""
This module contains the top-level routines for the quasisymmetric
stellarator construction.
"""

import logging
import numpy as np
from scipy.io import netcdf
#from numba import jit

#logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

class Qsc():
    """
    This is the main class for representing the quasisymmetric
    stellarator construction.
    """

    # Import methods that are defined in separate files:
    from .init_axis import init_axis, convert_to_spline
    from .calculate_r1 import _residual, _jacobian, solve_sigma_equation, \
        _determine_helicity, r1_diagnostics
    from .grad_B_tensor import calculate_grad_B_tensor, calculate_grad_grad_B_tensor, \
        Bfield_cylindrical, Bfield_cartesian, grad_B_tensor_cartesian, \
        grad_grad_B_tensor_cylindrical, grad_grad_B_tensor_cartesian
    from .calculate_r2 import calculate_r2
    from .calculate_r3 import calculate_r3, calculate_shear
    from .mercier import mercier
    from .r_singularity import calculate_r_singularity
    from .plot import plot, plot_boundary, get_boundary, B_fieldline, B_contour, plot_axis, flux_tube
    from .Frenet_to_cylindrical import Frenet_to_cylindrical, to_RZ
    from .to_vmec import to_vmec
    from .util import B_mag

    def __init__(self, rc, zs, rs=[], zc=[], nfp=1, etabar=1., sigma0=0., B0=1.,
                 I2=0., sG=1, spsi=1, nphi=61, B2s=0., B2c=0., p2=0., order="r1"):
        """
        Create a quasisymmetric stellarator.
        """
        # First, force {rc, zs, rs, zc} to have the same length, for
        # simplicity.
        nfourier = np.max([len(rc), len(zs), len(rs), len(zc)])
        self.nfourier = nfourier
        self.rc = np.zeros(nfourier)
        self.zs = np.zeros(nfourier)
        self.rs = np.zeros(nfourier)
        self.zc = np.zeros(nfourier)
        self.rc[:len(rc)] = rc
        self.zs[:len(zs)] = zs
        self.rs[:len(rs)] = rs
        self.zc[:len(zc)] = zc

        # Force nphi to be odd:
        if np.mod(nphi, 2) == 0:
            nphi += 1

        if sG != 1 and sG != -1:
            raise ValueError('sG must be +1 or -1')

        if spsi != 1 and spsi != -1:
            raise ValueError('spsi must be +1 or -1')

        self.nfp = nfp
        self.etabar = etabar
        self.sigma0 = sigma0
        self.B0 = B0
        self.I2 = I2
        self.sG = sG
        self.spsi = spsi
        self.nphi = nphi
        self.B2s = B2s
        self.B2c = B2c
        self.p2 = p2
        self.order = order
        self.min_R0_threshold = 0.3
        self._set_names()

        self.calculate()

    def change_nfourier(self, nfourier_new):
        """
        Resize the arrays of Fourier amplitudes. You can either increase
        or decrease nfourier.
        """
        rc_old = self.rc
        rs_old = self.rs
        zc_old = self.zc
        zs_old = self.zs
        index = np.min((self.nfourier, nfourier_new))
        self.rc = np.zeros(nfourier_new)
        self.rs = np.zeros(nfourier_new)
        self.zc = np.zeros(nfourier_new)
        self.zs = np.zeros(nfourier_new)
        self.rc[:index] = rc_old[:index]
        self.rs[:index] = rs_old[:index]
        self.zc[:index] = zc_old[:index]
        self.zs[:index] = zs_old[:index]
        nfourier_old = self.nfourier
        self.nfourier = nfourier_new
        self._set_names()
        # No need to recalculate if we increased the Fourier
        # resolution, only if we decreased it.
        if nfourier_new < nfourier_old:
            self.calculate()

    def calculate(self):
        """
        Driver for the main calculations.
        """
        self.init_axis()
        self.solve_sigma_equation()
        self.r1_diagnostics()
        if self.order != 'r1':
            self.calculate_r2()
            if self.order == 'r3':
                self.calculate_r3()

    def get_dofs(self):
        """
        Return a 1D numpy vector of all possible optimizable
        degrees-of-freedom, for simsopt.
        """
        return np.concatenate((self.rc, self.zs, self.rs, self.zc,
                               np.array([self.etabar, self.sigma0, self.B2s, self.B2c, self.p2, self.I2, self.B0])))

    def set_dofs(self, x):
        """
        For interaction with simsopt, set the optimizable degrees of
        freedom from a 1D numpy vector.
        """
        assert len(x) == self.nfourier * 4 + 7
        self.rc = x[self.nfourier * 0 : self.nfourier * 1]
        self.zs = x[self.nfourier * 1 : self.nfourier * 2]
        self.rs = x[self.nfourier * 2 : self.nfourier * 3]
        self.zc = x[self.nfourier * 3 : self.nfourier * 4]
        self.etabar = x[self.nfourier * 4 + 0]
        self.sigma0 = x[self.nfourier * 4 + 1]
        self.B2s = x[self.nfourier * 4 + 2]
        self.B2c = x[self.nfourier * 4 + 3]
        self.p2 = x[self.nfourier * 4 + 4]
        self.I2 = x[self.nfourier * 4 + 5]
        self.B0 = x[self.nfourier * 4 + 6]
        self.calculate()
        logger.info('set_dofs called with x={}. Now iota={}, elongation={}'.format(x, self.iota, self.max_elongation))

    def _set_names(self):
        """
        For simsopt, sets the list of names for each degree of freedom.
        """
        names = []
        names += ['rc({})'.format(j) for j in range(self.nfourier)]
        names += ['zs({})'.format(j) for j in range(self.nfourier)]
        names += ['rs({})'.format(j) for j in range(self.nfourier)]
        names += ['zc({})'.format(j) for j in range(self.nfourier)]
        names += ['etabar', 'sigma0', 'B2s', 'B2c', 'p2', 'I2', 'B0']
        self.names = names

    @classmethod
    def from_paper(cls, name, **kwargs):
        """
        Get one of the configurations that has been used in our papers.
        Available values for ``name`` are
        ``"r1 section 5.1"``,
        ``"r1 section 5.2"``,
        ``"r1 section 5.3"``,
        ``"r2 section 5.1"``,
        ``"r2 section 5.2"``,
        ``"r2 section 5.3"``,
        ``"r2 section 5.4"``, and
        ``"r2 section 5.5"``.
        These last 5 configurations can also be obtained by specifying an integer 1-5 for ``name``.
        The configurations that begin with ``"r1"`` refer to sections in
        Landreman, Sengupta, and Plunk, Journal of Plasma Physics 85, 905850103 (2019).
        The configurations that begin with ``"r2"`` refer to sections in
        Landreman and Sengupta, Journal of Plasma Physics 85, 815850601 (2019).

        You can specify any other arguments of the ``Qsc`` constructor
        in ``kwargs``. You can also use ``kwargs`` to override any of
        the properties of the configurations from the papers. For
        instance, you can modify the value of ``etabar`` in the first
        example using

        .. code-block::

          q = qsc.Qsc.from_paper('r1 section 5.1', etabar=1.1)
        """

        def add_default_args(kwargs_old, **kwargs_new):
            """
            Take any key-value arguments in ``kwargs_new`` and treat them as
            defaults, adding them to the dict ``kwargs_old`` only if
            they are not specified there.
            """
            for key in kwargs_new:
                if key not in kwargs_old:
                    kwargs_old[key] = kwargs_new[key]

        if name == "r1 section 5.1":
            """ The configuration from Landreman, Sengupta, Plunk (2019), section 5.1 """
            add_default_args(kwargs, rc=[1, 0.045], zs=[0, -0.045], nfp=3, etabar=-0.9)

        elif name == "r1 section 5.2":
            """ The configuration from Landreman, Sengupta, Plunk (2019), section 5.2 """
            add_default_args(kwargs, rc=[1, 0.265], zs=[0, -0.21], nfp=4, etabar=-2.25)

        elif name == "r1 section 5.3":
            """ The configuration from Landreman, Sengupta, Plunk (2019), section 5.3 """
            add_default_args(kwargs, rc=[1, 0.042], zs=[0, -0.042], zc=[0, -0.025], nfp=3, etabar=-1.1, sigma0=-0.6)

        elif name == "r2 section 5.1" or name == '5.1' or name == 1:
            """ The configuration from Landreman & Sengupta (2019), section 5.1 """
            add_default_args(kwargs, rc=[1, 0.155, 0.0102], zs=[0, 0.154, 0.0111], nfp=2, etabar=0.64, order='r3', B2c=-0.00322)

        elif name == "r2 section 5.2" or name == '5.2' or name == 2:
            """ The configuration from Landreman & Sengupta (2019), section 5.2 """
            add_default_args(kwargs, rc=[1, 0.173, 0.0168, 0.00101], zs=[0, 0.159, 0.0165, 0.000985], nfp=2, etabar=0.632, order='r3', B2c=-0.158)

        elif name == "r2 section 5.3" or name == '5.3' or name == 3:
            """ The configuration from Landreman & Sengupta (2019), section 5.3 """
            add_default_args(kwargs, rc=[1, 0.09], zs=[0, -0.09], nfp=2, etabar=0.95, I2=0.9, order='r3', B2c=-0.7, p2=-600000.)

        elif name == "r2 section 5.4" or name == '5.4' or name == 4:
            """ The configuration from Landreman & Sengupta (2019), section 5.4 """
            add_default_args(kwargs, rc=[1, 0.17, 0.01804, 0.001409, 5.877e-05],
                       zs=[0, 0.1581, 0.01820, 0.001548, 7.772e-05], nfp=4, etabar=1.569, order='r3', B2c=0.1348)

        elif name == "r2 section 5.5" or name == '5.5' or name == 5:
            """ The configuration from Landreman & Sengupta (2019), section 5.5 """
            add_default_args(kwargs, rc=[1, 0.3], zs=[0, 0.3], nfp=5, etabar=2.5, sigma0=0.3, I2=1.6, order='r3', B2c=1., B2s=3., p2=-0.5e7)

        elif name == "LandremanPaul2021QA" or name == "precise QA":
            """
            A fit of the near-axis model to the quasi-axisymmetric
            configuration in Landreman & Paul, arXiv:2108.03711 (2021).

            The fit was performed to the boozmn data using the script
            20200621-01-Extract_B0_B1_B2_from_boozxform
            """
            add_default_args(kwargs,
                             nfp=2,
                             rc=[1.0038581971135636, 0.18400998741139907, 0.021723381370503204, 0.0025968236014410812, 0.00030601568477064874, 3.5540509760304384e-05, 4.102693907398271e-06, 5.154300428457222e-07, 4.8802742243232844e-08, 7.3011320375259876e-09],
                             zs=[0.0, -0.1581148860568176, -0.02060702320552523, -0.002558840496952667, -0.0003061368667524159, -3.600111450532304e-05, -4.174376962124085e-06, -4.557462755956434e-07, -8.173481495049928e-08, -3.732477282851326e-09],
                             B0=1.006541121335688,
                             etabar=-0.6783912804454629,
                             B2c=0.26859318908803137,
                             nphi=99,
                             order='r3')

        elif name == "precise QA+well":
            """
            A fit of the near-axis model to the precise quasi-axisymmetric
            configuration from SIMSOPT with magnetic well.

            The fit was performed to the boozmn data using the script
            20200621-01-Extract_B0_B1_B2_from_boozxform
            """
            add_default_args(kwargs,
                             nfp=2,
                             rc=[1.0145598919163676, 0.2106377247598754, 0.025469267136340394, 0.0026773601516136727, 0.00021104172568911153, 7.891887175655046e-06, -8.216044358250985e-07, -2.379942694112007e-07, -2.5495108673798585e-08, 1.1679227114962395e-08, 8.961288962248274e-09],
                             zs=[0.0, -0.14607192982551795, -0.021340448470388084, -0.002558983303282255, -0.0002355043952788449, -1.2752278964149462e-05, 3.673356209179739e-07, 9.261098628194352e-08, -7.976283362938471e-09, -4.4204430633540756e-08, -1.6019372369445714e-08],
                             B0=1.0117071561808106,
                             etabar=-0.5064143402495729,
                             B2c=-0.2749140163639202,
                             nphi=99,
                             order='r3')

        elif name == "LandremanPaul2021QH" or name == "precise QH":
            """
            A fit of the near-axis model to the quasi-helically symmetric
            configuration in Landreman & Paul, arXiv:2108.03711 (2021).

            The fit was performed to the boozmn data using the script
            20211001-02-Extract_B0_B1_B2_from_boozxform
            """
            add_default_args(kwargs,
                             nfp=4,
                             rc=[1.0033608429348413, 0.19993025252481125, 0.03142704185268144, 0.004672593645851904, 0.0005589954792333977, 3.298415996551805e-05, -7.337736061708705e-06, -2.8829857667619663e-06, -4.51059545517434e-07],
                             zs=[0.0, 0.1788824025525348, 0.028597666614604524, 0.004302393796260442, 0.0005283708386982674, 3.5146899855826326e-05, -5.907671188908183e-06, -2.3945326611145963e-06, -6.87509350019021e-07],
                             B0=1.003244143729638,
                             etabar=-1.5002839921360023,
                             B2c=0.37896407142157423,
                             nphi=99,
                             order='r3')

        elif name == "precise QH+well":
            """
            A fit of the near-axis model to the precise quasi-helically symmetric
            configuration from SIMSOPT with magnetic well.

            The fit was performed to the boozmn data using the script
            20211001-02-Extract_B0_B1_B2_from_boozxform
            """
            add_default_args(kwargs,
                             nfp=4,
                             rc=[1.000474932581454, 0.16345392520298313, 0.02176330066615466, 0.0023779201451133163, 0.00014141976024376502, -1.0595894482659743e-05, -2.9989267970578764e-06, 3.464574408947338e-08],
                             zs=[0.0, 0.12501739099323073, 0.019051257169780858, 0.0023674771227236587, 0.0001865909743321566, -2.2659053455802824e-06, -2.368335337174369e-06, -1.8521248561490157e-08],
                             B0=0.999440074325872,
                             etabar=-1.2115187546668142,
                             B2c=0.6916862277166693,
                             nphi=99,
                             order='r3')

        else:
            raise ValueError('Unrecognized configuration name')

        return cls(**kwargs)

    @classmethod
    def from_cxx(cls, filename):
        """
        Load a configuration from a ``qsc_out.<extension>.nc`` output file
        that was generated by the C++ version of QSC. Almost all the
        data will be taken from the output file, over-writing any
        calculations done in python when the new Qsc object is
        created.
        """
        def to_string(nc_str):
            """ Convert a string from the netcdf binary format to a python string. """
            temp = [c.decode('UTF-8') for c in nc_str]
            return (''.join(temp)).strip()

        f = netcdf.netcdf_file(filename, mmap=False)
        nfp = f.variables['nfp'][()]
        nphi = f.variables['nphi'][()]
        rc = f.variables['R0c'][()]
        rs = f.variables['R0s'][()]
        zc = f.variables['Z0c'][()]
        zs = f.variables['Z0s'][()]
        I2 = f.variables['I2'][()]
        B0 = f.variables['B0'][()]
        spsi = f.variables['spsi'][()]
        sG = f.variables['sG'][()]
        etabar = f.variables['eta_bar'][()]
        sigma0 = f.variables['sigma0'][()]
        order_r_option = to_string(f.variables['order_r_option'][()])
        if order_r_option == 'r2.1':
            order_r_option = 'r3'
        if order_r_option == 'r1':
            p2 = 0.0
            B2c = 0.0
            B2s = 0.0
        else:
            p2 = f.variables['p2'][()]
            B2c = f.variables['B2c'][()]
            B2s = f.variables['B2s'][()]

        q = cls(nfp=nfp, nphi=nphi, rc=rc, rs=rs, zc=zc, zs=zs,
                B0=B0, sG=sG, spsi=spsi,
                etabar=etabar, sigma0=sigma0, I2=I2, p2=p2, B2c=B2c, B2s=B2s, order=order_r_option)

        def read(name, cxx_name=None):
            if cxx_name is None: cxx_name = name
            setattr(q, name, f.variables[cxx_name][()])

        [read(v) for v in ['R0', 'Z0', 'R0p', 'Z0p', 'R0pp', 'Z0pp', 'R0ppp', 'Z0ppp',
                           'sigma', 'curvature', 'torsion', 'X1c', 'Y1c', 'Y1s', 'elongation']]
        if order_r_option != 'r1':
            [read(v) for v in ['X20', 'X2c', 'X2s', 'Y20', 'Y2c', 'Y2s', 'Z20', 'Z2c', 'Z2s', 'B20']]
            if order_r_option != 'r2':
                [read(v) for v in ['X3c1', 'Y3c1', 'Y3s1']]

        f.close()
        return q

    def min_R0_penalty(self):
        """
        This function can be used in optimization to penalize situations
        in which min(R0) < min_R0_constraint.
        """
        return np.max((0, self.min_R0_threshold - self.min_R0)) ** 2


#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Tiago de Freitas Pereira <tiago.pereira@idiap.ch>
# Sat 20 Aug 15:43:10 CEST 2016

"""
  YOUTUBE database implementation of bob.bio.base.database.ZTDatabase interface.
  It is an extension of an SQL-based database interface, which directly talks to YOUTUBE database, for
  verification experiments (good to use in bob.bio.base framework).
"""

from .database import VideoBioFile
from bob.bio.base.database import ZTBioDatabase
from bob.bio.video.utils import FrameContainer, FrameSelector
import os
import bob.io.base

class YoutubeBioFile(VideoBioFile):

    def __init__(self, f):
        super(YoutubeBioFile, self).__init__(client_id=f.client_id, path=f.path, file_id=f.id)
        self._f = f

    def files(self, directory=None, extension=".jpg"):
        base_dir = self.make_path(directory, '')
        # collect all files from the data directory
        files = [os.path.join(base_dir, f) for f in sorted(os.listdir(base_dir))]
        # filter files with the given extension
        if extension is not None:
            files = [f for f in files if os.path.splitext(f)[1] == extension]
        return files

    def load(self, directory=None, extension=None, frame_selector=FrameSelector()):
        if extension in (None, '.jpg'):
            fc = FrameContainer()
            files = self.files(directory, extension)
            for f in frame_selector(files):
                file_name = os.path.join(self.make_path(directory, ''), f[0])
                fc.add(os.path.basename(file_name), bob.io.base.load(file_name))
            return fc
        else:
            return super(YoutubeBioFile, self).load(directory, extension)

class YoutubeBioDatabase(ZTBioDatabase):
    """
    YouTube Faces database implementation of :py:class:`bob.bio.base.database.ZTBioDatabase` interface.
    It is an extension of an SQL-based database interface, which directly talks to :py:class:`bob.db.youtube.Database` database, for
    verification experiments (good to use in ``bob.bio`` framework).
    """

    def __init__(
            self,
            original_directory=None,
            original_extension='.jpg',
            annotation_extension='.labeled_faces.txt',
            **kwargs
    ):
        from bob.db.youtube.query import Database as LowLevelDatabase
        self._db = LowLevelDatabase(original_directory,
                                    original_extension,
                                    annotation_extension)

        # call base class constructors to open a session to the database
        super(YoutubeBioDatabase, self).__init__(
            name='youtube',
            original_directory=original_directory,
            original_extension=original_extension,
            annotation_extension=annotation_extension,
            **kwargs)

    @property
    def original_directory(self):
        return self._db.original_directory

    @original_directory.setter
    def original_directory(self, value):
        self._db.original_directory = value

    def model_ids_with_protocol(self, groups=None, protocol=None, **kwargs):
        return self._db.model_ids(groups=groups, protocol=protocol)

    def tmodel_ids_with_protocol(self, protocol=None, groups=None, **kwargs):
        return self._db.tmodel_ids(protocol=protocol, groups=groups, **kwargs)

    def objects(self, groups=None, protocol=None, purposes=None, model_ids=None, **kwargs):
        retval = self._db.objects(groups=groups, protocol=protocol, purposes=purposes, model_ids=model_ids, **kwargs)
        return [YoutubeBioFile(f) for f in retval]

    def tobjects(self, groups=None, protocol=None, model_ids=None, **kwargs):
        retval = self._db.tobjects(groups=groups, protocol=protocol, model_ids=model_ids, **kwargs)
        return [YoutubeBioFile(f) for f in retval]

    def zobjects(self, groups=None, protocol=None, **kwargs):
        retval = self._db.zobjects(groups=groups, protocol=protocol, **kwargs)
        return [YoutubeBioFile(f) for f in retval]

    def annotations(self, myfile):
        return self._db.annotations(myfile._f)

    def client_id_from_model_id(self, model_id, group='dev'):
        return self._db.get_client_id_from_file_id(model_id)


from django.views import View
from articles.models import Article
from comments.models import Comment
from django.http import JsonResponse
from utils.decorators import fail_safe_api
from utils.models import nested_model_to_dict
from utils.request import parse_body, set_user
from utils.koora import deleteImageFor, generate_url_for, uploadImageFor, setTagsFor

class DetailAPIView(View):

    def dispatch(self, request, *args, **kwargs):
        set_user(request)
        if request.user.is_authenticated:
            parse_body(request, for_method=request.method)
        return super(DetailAPIView, self).dispatch(request, *args, **kwargs)

    @fail_safe_api(for_model=Article)
    def get(self, request, slug):

        article = Article.objects.get(slug=slug)

        content = {
            "status": 200,
            "data": {
                "article": nested_model_to_dict(article)
            },
            "meta": {
                "article_count": 1
            }
        }

        return JsonResponse(content)

    @fail_safe_api(for_model=Article, needs_authentication=True)
    def put(self, request, slug):

        article = Article.objects.get(slug=slug)
        article.title = request.PUT.get('title', '')
        article.content = request.PUT.get('content', '')
        article.category = request.PUT.get('category', '')

        image = request.FILES.get('article_image', False)

        post_type = request.PUT.get('post_type', 'public')
        article.is_private = post_type == 'private'

        if image:
            deleteImageFor(article)
            uploadImageFor(article, image, article.slug)

        article.remove_tags()

        tags = request.PUT.get('tags', '').strip().split(",")

        setTagsFor(article, tags)

        article.save()

        return JsonResponse({
          "status" : 200,
          "data" : {
              "article" : nested_model_to_dict(article)
          },
          "message" : "article updated"
        })

    @fail_safe_api(for_model=Article, needs_authentication=True)
    def post(self, request, slug):
        article = Article.objects.get(slug=slug)

        user = request.user

        content = request.POST.get('content', '')
        object_id = request.POST.get('object_id', 1)
        content_type = article.content_type

        created_comment = Comment.objects.create(
            user=user, content=content, object_id=object_id, content_type=content_type)

        return JsonResponse({
            "status" : 200,
            "data" : nested_model_to_dict(created_comment),
            "message" : "comment added",
            "meta" : {
                "article_count" : 1,
                "comment_count" : 1
            }
        })

    @fail_safe_api(for_model=Article, needs_authentication=True)
    def delete(self, request, slug):

        article = Article.objects.get(slug=slug)

        if article.image_url:
            deleteImageFor(article)
        article.delete()

        return JsonResponse({
            "status" : 200,
            "message" : 'article deleted'
        })


# EXAMPLE 1

try:
    print(5/0)
except ZeroDivisionError:
    print("You cannot divide using integer 0")

# EXAMPLE 2
print('Give me two numbers, and I will divide them')
print("Enter 'q' to quit")

while True:
    first_number = input('\nFirst number: ')
    if first_number == 'q':
        break
    second_number = input('Second number: ')
    if second_number == 'q':
        break
    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)

# EXAMPLE 3
'''Handling the FileNotFoundError Exception'''
filename = 'alice.txt'

try:
    with open(filename, encoding='utf-8') as f:
        contents = f.read()
except FileNotFoundError:
    print(f"Sorry, the file {filename} does not exist")
else:
    # Count the approxiamte number of words in the file.
    words = contents.split()
    number_of_words = len(words)
    print(f"The file {filename} has about {number_of_words} words")

# EXAMPLE 4
'''Working with multiple files'''
# creating a function to handling FileNotFoundError Exception

def count_words(filename):
    """Count the approximate number of words in a file"""
    try:
        with open(filename, encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        # print(f'Sorry, the file {filename} does not exist.')
        ## the following PASS statement makes the programme run without
        ## showing the user the output of the error..
        pass
    else:
        words = contents.split()
        number_of_words = len(words)
        print(f'The file {filename} has about {number_of_words} words')

filename = 'alice.txt'
count_words(filename)

filenames = ['alice.txt', 'little_women.txt', 'moby_dick.txt', 'siddhartha.txt']

for file in filenames:
    count_words(file)

# TASK...
'''10-6. Addition: One common problem when prompting for numerical input
occurs when people provide text instead of numbers. When you try to convert
the input to an int , you’ll get a ValueError . Write a program that prompts for
two numbers. Add them together and print the result. Catch the ValueError if
either input value is not a number, and print a friendly error message. Test your
program by entering two numbers and then by entering some text instead of a
number.'''

while True:
    num1 = input('Enter first  number ')
    num2 = input('Enter second number ')
    try:
        sum = int(num1) + int(num2)
        print(sum)
        break
    except ValueError:
        print('Please enter an integer')


# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# ==============================================================================
################################# AUTHOR: ######################################
############################# DIEGO PERGOLINI ##################################
# ==============================================================================
"""Script to train the DNC on a sentiment classification task."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
import json
import tensorflow as tf
from Utility import getConfiguration
from Utility import  memory_usage
import dnc
import argparse
import math
import time

parser = argparse.ArgumentParser()
parser.add_argument("--configuration", help="The configuration file")
args = parser.parse_args()
if args.configuration:
    print(args.configuration)
    FLAGS,numLines = getConfiguration(args.configuration)
else:
    FLAGS, numLines = getConfiguration("configuration.json")

if FLAGS.num_classes == 5:
    from ReviewReaderWithTitleFined import balancedGetDataset
    from ReviewReaderWithTitleFined import getBalancedReviewsAndOverall
elif FLAGS.num_classes == 2:
    from ReviewReaderTitle import balancedGetDataset
    from ReviewReaderTitle import getBalancedReviewsAndOverall

def run_model(input_sequence, output_size):
  """Runs model on input sequence."""

  access_config = {
      "memory_size": FLAGS.memory_size,
      "word_size": FLAGS.word_size,
      "num_reads": FLAGS.num_read_heads,
      "num_writes": FLAGS.num_write_heads,
  }
  controller_config = {
      "hidden_size": FLAGS.hidden_size,
  }
  clip_value = FLAGS.clip_value
  #Creo la cella dnc
  dnc_core = dnc.DNC(access_config, controller_config, output_size, clip_value)
  initial_state = dnc_core.initial_state(FLAGS.batch_size)

  #Funzione che ritorna una coppia (output,state), dove output in questo caso sara un tensore
  #di forma  [batch_size,max_time,cell.output_size] perche il flag time_major e impostato a False
  #se lo si setta a True invece la forma dell'output diventa [max_time,batch_size,cell.output_size].
  output_sequence, _ = tf.nn.dynamic_rnn(
      cell=dnc_core,
      inputs=input_sequence,
      time_major=False,
      initial_state=initial_state)

  return output_sequence

"""Addestra la DNC ed al termine di ogni epoca di addestramento viene effettuata una fase di test"""
def execute(dictSize,num_training_iterations, report_interval):
  max_lenght = FLAGS.max_lenght
    #Placeholder che andra' a contenere il batch di label relativa alle recensioni
  y_= tf.placeholder(tf.float32,shape=[FLAGS.batch_size,max_lenght,FLAGS.num_classes])

  #Placeholder che andra' a contenere il batch di recensioni opportunamente codificate
  x = tf.placeholder(tf.float32, [FLAGS.batch_size, max_lenght, dictSize])

  #Placeholder che andra' a contenere il batch di maschere da applicare per il calcolo della cross-entropy
  mask = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,max_lenght])

  #Richiamando il metodo run_model ottengo la sequenza prodotta dalla rete
  output_logits = run_model(x, FLAGS.num_classes)

  #Calcolo della cross entropy totale tra le labels e gli output prodotti dalla rete
  cross = tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=output_logits)

  #Calcolo l'errore relativo ai singoli batch, applicando una maschera che considera gli output prodotti dalla rete
  #solo negli unrolling corrispondenti a delle parole della recensione e non considerando quelli prodotti in corrispondenza
  #di padding. La maschera applicata fornisce peso via via crescente mano a mano che si procede verso le ultime parole
  #della recensione.
  batch_error = tf.reduce_sum(cross * mask, 1)

  #Faccio la media degli errori dei singoli batch
  total_error = tf.reduce_mean(batch_error)

  #Ricavo la polarita' che la rete ha indicato all'ultima parola di ogni recensione,
  prediction = tf.arg_max(output_logits[:,max_lenght-1], 1)

  #Ricavo la polarita' indicata dalle label
  expected = tf.arg_max(y_[:,max_lenght-1], 1)

  #Ricavo quante predizioni della polarita' sono state fatte correttamente
  correct_prediction = tf.equal(prediction, expected)

  #Ricavo cosi' l'accuratezza ottenuta in questo batch
  accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

  #Set up optimizer with global norm clipping.
  trainable_variables = tf.trainable_variables()
  grads, _ = tf.clip_by_global_norm(
      tf.gradients(total_error, trainable_variables), FLAGS.max_grad_norm)

  global_step = tf.get_variable(
      name="global_step",
      shape=[],
      dtype=tf.int64,
      initializer=tf.random_uniform_initializer(-1, 1),
      trainable=False,
      collections=[tf.GraphKeys.GLOBAL_VARIABLES, tf.GraphKeys.GLOBAL_STEP])

  #Placeholder che conterra' il learning rate
  learning_rate = tf.placeholder(tf.float32)

  optimizer = tf.train.RMSPropOptimizer(
      learning_rate, epsilon=FLAGS.optimizer_epsilon)

  #Passo di addestramento da eseguire per addestrare la rete
  train_step = optimizer.apply_gradients(
      zip(grads, trainable_variables), global_step=global_step)

  #Oggetto per salvare lo stato della rete.
  saver = tf.train.Saver()

  #Impostazione dei parametri relativi al salvataggio dello stato della rete.
  if FLAGS.checkpoint_interval > 0:
    hooks = [
        tf.train.CheckpointSaverHook(
            checkpoint_dir=FLAGS.checkpoint_dir,
            save_steps=FLAGS.checkpoint_interval,
            saver=saver)
    ]
  else:
    hooks = []

  #Viene scritto un file di log dell'esecuzione corrente.
  date = time.strftime("%b%d%H:%M:%S")
  outputFile = open("Experiment"+date+".txt",'w')

  with open(args.configuration) as data_file:
    configuration = json.load(data_file)
    outputFile.write(json.dumps(configuration))

  config = tf.ConfigProto()
  config.gpu_options.per_process_gpu_memory_fraction = 0.4
  #Viene inizializzata una sessione
  with tf.train.SingularMonitoredSession(
      hooks=hooks, checkpoint_dir=FLAGS.checkpoint_dir,config=config) as sess:

        #Il numero di istanze di training  e testing viene diviso per due perche' indica che il numero di recensioni
        # positive e negative siano uguali

        if FLAGS.num_classes ==5:
            numTraining = (FLAGS.num_training_iterations)
            numTesting = FLAGS.num_testing_iterations
            allLines = getBalancedReviewsAndOverall(numTraining,numTesting,FLAGS.dataset, FLAGS.max_lenght, FLAGS.random, FLAGS.seed)
        elif FLAGS.num_classes ==2:
            numTraining = (FLAGS.num_training_iterations // 2)
            numTesting = (FLAGS.num_testing_iterations // 2)
            #Vengono ottenute tutte le recensioni necessarie per training e testing
            allLines = getBalancedReviewsAndOverall(numTraining,numTraining,
                                                numTesting,numTesting,
                                                FLAGS.dataset,FLAGS.max_lenght,FLAGS.random,FLAGS.seed)

        #Viene inizializzato un generatore attraverso il quale ottenere mano a mano i vari batch di training e testing,
        # viene inoltre indicato quale modello word2vec debba essere utilizzato
        generator = balancedGetDataset(allLines,FLAGS.w2v_model,FLAGS)

        randomizer = random.Random(1)

        best_test_accuracy = 0

        date = time.strftime("%H:%M:%S")

#################TRAINING########################################################
        # Testing
        test_accuracy = 0
        total_test_accuracy = 0

        #################################################TESTING########################################################
        for test_iteration in range(0,(FLAGS.num_testing_iterations//FLAGS.batch_size)):

            datasetTest = next(generator)
            act_accuracy = sess.run(accuracy,
                                    {x: datasetTest[0],
                                     y_: datasetTest[1],
                                     mask: datasetTest[2]})
            test_accuracy += act_accuracy
            total_test_accuracy += act_accuracy
            if (test_iteration + 1) % report_interval == 0:

                tf.logging.info("%d: Avg testing accuracy %f.\n",
                                test_iteration+1, test_accuracy / report_interval
                                )
                info4 = str(test_iteration+1)+ ": Avg testing accuracy: "+str(test_accuracy / report_interval)+"\n"
                outputFile.write(info4)
                test_accuracy = 0
        tf.logging.info("Epoch: %d,Iteration: %d, Average Testing accuracy: %f\n",1, test_iteration+1,
                        total_test_accuracy /( FLAGS.num_testing_iterations//FLAGS.batch_size))
        info5 = "Epoch: "+str(1)+",Iteration: "+ str(test_iteration+1)+", Average Testing accuracy: "+str(total_test_accuracy /( FLAGS.num_testing_iterations//FLAGS.batch_size))+"\n"
        outputFile.write(info5)

        epoch_test_accuracy = total_test_accuracy /( FLAGS.num_testing_iterations//FLAGS.batch_size)
        if epoch_test_accuracy > best_test_accuracy:
            best_test_accuracy = epoch_test_accuracy

  date = time.strftime("%H:%M:%S")
  outputFile.close()

def main(unused_argv):
  tf.logging.set_verbosity(3)  # Print INFO log messages.

  execute(FLAGS.word_dimension,FLAGS.num_training_iterations, FLAGS.report_interval)

if __name__ == "__main__":
  tf.app.run()


#coding:gbk
"""
第一个小项目：Rock-paper-scissors-lizard-Spock
作者：陈李菡
日期：2021/05/26
"""

import random

# 0 - 石头
# 1 - 史波克
# 2 - 纸
# 3 - 蜥蜴
# 4 - 剪刀

# 以下为完成游戏所需要用到的自定义函数

def name_to_number(name):
    if name=="石头":
        return 0
    elif name=="史波克":
        return 1
    elif name=="纸":
        return 2
    elif name=="蜥蜴":
        return 3
    else:
        return 4
    """
    将游戏对象对应到不同的整数
    """

    # 使用if/elif/else语句将各游戏对象对应到不同的整数
    # 不要忘记返回结果

     #编写执行代码,代码完成后将pass删除

def number_to_name(number):
    if number==0:
        return "石头"
    elif number==1:
        return "史波克"
    elif number==2:
        return "纸"
    elif number==3:
        return "蜥蜴"
    else:
        return "剪刀"
    """
    将整数 (0, 1, 2, 3, or 4)对应到游戏的不同对象
    """

    # 使用if/elif/else语句将不同的整数对应到游戏的不同对象
    # 不要忘记返回结果

     #编写执行代码,代码完成后将pass删除

def rpsls(player_choice):
    print("-------- ")# 输出"-------- "进行分割
    print("你的选择是：%s"%player_choice)# 显示用户输入提示，用户通过键盘将自己的游戏选择对象输入，存入变量player_choice
    player_choice_number=name_to_number(player_choice)# 调用name_to_number()函数将用户的游戏选择对象转换为相应的整数，存入变量player_choice_number
    comp_number=random.randrange(0,5)# 利用random.randrange()自动产生0-4之间的随机整数，作为计算机随机选择的游戏对象，存入变量comp_number
    comp_choice=number_to_name(comp_number)# 调用number_to_name()函数将计算机产生的随机数转换为对应的游戏对象
    print("计算机的选择为：%s"%comp_choice)# 在屏幕上显示计算机选择的随机对象
    if player_choice_number==comp_number:
      print("您和计算机出的一样呢")
    elif player_choice_number==0 and (comp_number==4 or comp_number==3):
      print("您赢了！")
    elif player_choice_number==1 and (comp_number==4 or comp_number==0):
      print("您赢了！")
    elif player_choice_number==2 and (comp_number==0 or comp_number==1):
      print("您赢了！")
    elif player_choice_number==3 and (comp_number==1 or comp_number==2):
      print("您赢了！")
    elif player_choice_number==4 and (comp_number==2 or comp_number==3):
      print("您赢了！")
    else:
      print("计算机赢了")
    return
    # 利用if/elif/else 语句，根据RPSLS规则对用户选择和计算机选择进行判断，并在屏幕上显示判断结果

    # 如果用户和计算机选择一样，则显示“您和计算机出的一样呢”，如果用户获胜，则显示“您赢了”，反之则显示“计算机赢了”

     #根据以上提示编写执行代码，代码完成后删除掉pass

# 对程序进行测试
print("欢迎使用RPSLS游戏")
print("----------------")
print("请输入您的选择:")
choice_name=input()
rpsls(choice_name)