#----------------------------------------------------#
#-                                                  -#
#-                Bogdan Polvanov                   -#
#-                 Project Euler                    -#
#-                    Task_26                       -#
#-                                                  -#
#----------------------------------------------------#

import time
import xlrd
from openpyxl import Workbook
from openpyxl import load_workbook

start = time.time()
#-------------------- working space ---------------------

book = xlrd.open_workbook("corect.xlsx")
book1 = xlrd.open_workbook("energiy_perekhodu.xlsx")
result = []
first_sheet = book.sheet_by_index(0)

energy = []
result = []
l = 0
lm =[]
sq= []
pr = [ ]
for n in range(1,70):# перербирає експерерментальні довжини хвиль
    stan = first_sheet.row_values(n)# відкриваємо кожний рядок book
    min_stan = float(stan[16])-float(stan[20])
    max_stan = float(stan[16]) + float(stan[20])
    sheet_name = book1.sheet_names()
    for i in range(0,len(sheet_name)):# перебирає аркуші
       # print(i)
        theor_sheet = book1.sheet_by_index(i)
        sj = theor_sheet.row_values(10)[2::]
        sj1 = theor_sheet.row_values(11)[2::]
        for fx in range(0,len(sj)):
            st = str(int(sj[fx]))+ '->' + str(int(sj1[fx]))
            energy.append(st)
        for k in range(13,theor_sheet.nrows): # проганяє експерементальну енергію через теоретичну
            check = theor_sheet.row_values(k)
            for n in range(2,len(check)):
                if min_stan <= check[n] <= max_stan:
                    nu = str(int(check[0])) + '->' + str(int(check[1])) # записуємо довжини хвиль у result
                    #result.append([sheet_name[i],nu,str(energy[n-2]),round(check[n],2),round(float(stan[16]),2),stan[20]])
                    pr.append([sheet_name[i],nu,str(energy[n-2]),round(check[n],2),round(float(stan[16]),2),stan[20]])

    result.append(pr[0])
    pr = []
      #  corect = []

      #  for ind in pr:# перевіряємо на схожість переходи
      #      corect.append(ind[3])
      #  if corect == []:
      #      continue
      #  elif corect != [] :
      #      for kn in  pr:
      #         if min(corect) == kn[3]:
      #             snd = []
      #             for kl in result:
      #                 snd.append(kl[3])
      #             if  min(corect) not in snd:
      #                result.append(kn)
      #  pr = []

wb = load_workbook('proper_1.xlsx')
ws1 = wb.get_sheet_by_name("Sheet1")
ws1.cell(row=1, column=1).value = 'state'
ws1.cell(row=1, column=2).value = 'nu'
ws1.cell(row=1, column=3).value = 'j'
ws1.cell(row=1, column=4).value = 'energy'
ws1.cell(row=1, column=5).value = 'eksp_energy'
ws1.cell(row=1, column=6).value = 'error'

for  m in range(2,len(result) + 2):
    ws1.cell(row=m, column=1).value = result[m-2][0]
    ws1.cell(row=m, column=2).value = result[m-2][1]
    ws1.cell(row=m, column=3).value = result[m-2][2]
    ws1.cell(row=m, column=4).value = result[m-2][3]
    ws1.cell(row=m, column=5).value = result[m-2][4]
    ws1.cell(row=m, column=6).value = result[m-2][5]
wb.save('proper_1.xlsx')

#-------------------    end    ---------------------
end = time.time()
print('time work - ',end - start)


#!/usr/bin/python

import matplotlib.pyplot as plt
import numpy as np
import math

k = 20.0
r = 0.4
b = 0.5
e = 0.7
c = 0.6

def CLx(x,y):
	return r*x*(1.0-x/k) - b*x*y

def CLxmod(x,y):
	return r*x - b*x*y

def CLy(x,y):
	return e*b*x*y - c*y

def CLymod(x,y):
	return e*b*x*y - c*y*y

def solve(x_,y_,t,n):
	x=[x_]
	y=[y_]
	tx=[0.0]
	ty=[0.0]
	tx_= 0.0
	ty_= 0.0
	h = t/n

	y_ += 0.5*h*CLy(x_,y_)
	ty_ += 0.5*h
	y.append(y_)
	ty.append(ty_)

	for i in range (0,n-1):
		x_ += h*CLx(x_,y_)
		tx_ += h
		x.append(x_)
		tx.append(tx_)

		y_ += h*CLy(x_,y_)
		ty_ += h
		y.append(y_)
		ty.append(ty_)

	x_ += h*CLx(x_,y_)
	tx_ += h
	x.append(x_)
	tx.append(tx_)

	y_ += 0.5*h*CLy(x_,y_)
	ty_ += 0.5*h
	y.append(y_)
	ty.append(ty_)

	return tx, x ,ty , y

def solve_y2(x_,y_,t,n):
	x=[x_]
	y=[y_]
	tx=[0.0]
	ty=[0.0]
	tx_= 0.0
	ty_= 0.0
	h = t/n

	y_ += 0.5*h*CLymod(x_,y_)
	ty_ += 0.5*h
	y.append(y_)
	ty.append(ty_)

	for i in range (0,n-1):
		x_ += h*CLx(x_,y_)
		tx_ += h
		x.append(x_)
		tx.append(tx_)

		y_ += h*CLymod(x_,y_)
		ty_ += h
		y.append(y_)
		ty.append(ty_)

	x_ += h*CLx(x_,y_)
	tx_ += h
	x.append(x_)
	tx.append(tx_)

	y_ += 0.5*h*CLymod(x_,y_)
	ty_ += 0.5*h
	y.append(y_)
	ty.append(ty_)

	return tx, x ,ty , y

def solvenocap(x_,y_,t,n):
	x=[x_]
	y=[y_]
	tx=[0.0]
	ty=[0.0]
	tx_= 0.0
	ty_= 0.0
	h = t/n

	y_ += 0.5*h*CLy(x_,y_)
	ty_ += 0.5*h
	y.append(y_)
	ty.append(ty_)

	for i in range (0,n-1):
		x_ += h*CLxmod(x_,y_)
		tx_ += h
		x.append(x_)
		tx.append(tx_)

		y_ += h*CLy(x_,y_)
		ty_ += h
		y.append(y_)
		ty.append(ty_)

	x_ += h*CLxmod(x_,y_)
	tx_ += h
	x.append(x_)
	tx.append(tx_)

	y_ += 0.5*h*CLy(x_,y_)
	ty_ += 0.5*h
	y.append(y_)
	ty.append(ty_)

	return tx, x ,ty , y

def solvenocap_y2(x_,y_,t,n):
	x=[x_]
	y=[y_]
	tx=[0.0]
	ty=[0.0]
	tx_= 0.0
	ty_= 0.0
	h = t/n

	y_ += 0.5*h*CLymod(x_,y_)
	ty_ += 0.5*h
	y.append(y_)
	ty.append(ty_)

	for i in range (0,n-1):
		x_ += h*CLxmod(x_,y_)
		tx_ += h
		x.append(x_)
		tx.append(tx_)

		y_ += h*CLymod(x_,y_)
		ty_ += h
		y.append(y_)
		ty.append(ty_)

	x_ += h*CLxmod(x_,y_)
	tx_ += h
	x.append(x_)
	tx.append(tx_)

	y_ += 0.5*h*CLymod(x_,y_)
	ty_ += 0.5*h
	y.append(y_)
	ty.append(ty_)

	return tx, x ,ty , y

def makegoodlist(x_,y_):
	if len(x_) == len(y_):
		return x_, y_
	if len(x_) > len(y_):
		x = []
		for i in range (0,len(y_)):
			x.append(x_[i])
		return x, y_
	if len(y_) > len(x_):
		y = []
		for i in range (0,len(x_)):
			y.append(y_[i])
		return x_, y

t1, x1, t2, x2 = solve(0.4,0.05,70.0,700)
t3, x3, t4, x4 = solve_y2(0.4,0.05,70.0,700)
t5, x5, t6, x6 = solvenocap(0.4,0.05,70.0,700)
t7, x7, t8, x8 = solvenocap_y2(0.4,0.05,70.0,700)

x_g1, y_g1 = makegoodlist(x1,x2)
x_g2, y_g2 = makegoodlist(x3,x4)
x_g3, y_g3 = makegoodlist(x5,x6)
x_g4, y_g4 = makegoodlist(x7,x8)

plt.figure()
plt.title("Phase space evolved out to t = 70")
plt.xlabel("Prey Population")
plt.ylabel("Predator Population")

plt.plot(x_g1, y_g1, label = "Capacity = %.1f, $y$ decline" %k)
plt.plot(x_g2, y_g2, label = "Capacity = %.1f, $y^2$ decline" %k)
plt.plot(x_g3, y_g3, label = "No Capacity, $y$ decline")
plt.plot(x_g4, y_g4, label = "No Capacity, $y^2$ decline")

plt.legend()
plt.show()


from hashmap import Hashmap

#Create a blank file named Text_Results.txt to output the test results to.
#Test results will be output using print() as well as saved in this file to be viewed later.
file = open("Test_Results.txt",'w')
file.truncate();
line = "Starting test:\n\n"
print(line)
file.write(line)

#create a bunch of key/value pairs in a list called Data to test the hashmap
Data = []
Data.append(["apple","fruit"])
Data.append(["asparagus","vegetable"])
Data.append(["milk","dairy"])
Data.append(["bread","grain"],)
Data.append(["grocerylist",["apple","asparagus","milk","bread"]])
Data.append(["number",25])
Data.append(["littlenumber",0.003])
Data.append(["bignumber",2500000])
Data.append(["negativenumber",-45])
Data.append(["monkey","primate"])
Data.append(["dog","canine"])

#Start Test
line = "Key/Value pairs initialized\nData set:\n" + str(Data) + "\n\n"
print(line)
file.write(line)

#Initialize map of size 10
map_size = 10
Map = Hashmap(map_size)

#Display empty hashmap
line = "Empty Hashmap of Size: " + str(map_size) + " created.\n" + str(Map.map) + "\n\n"
print(line)
file.write(line)

#Set the Hashmap to be filled with the first set of keys so that load = 1.0
line = "Set first " + str(map_size) + " keys: [ 'key' , value ]\n"
print(line)
file.write(line)
for i in range (0, map_size):
	result = Map.set(Data[i][0],Data[i][1])
	line = "\tSet: " + str(Data[i]) + "\n\t\tresult:" + str(result) + "\n"
	print(line)
	file.write(line)

#Print out Hashmap contents
line = "\nHashmap:\n" + str(Map.map) + "\n"
print(line)
file.write(line)

#Print out Load value
result = Map.load()
line = "\nLoad value = " + str(result) + "\n\n"
print(line)
file.write(line)

#Get values for every pair of entries in the hashmap
line = "Get values for all keys currently in map.\n"
print(line)
file.write(line)

for i in range (0, map_size):
	result = Map.get(Data[i][0])
	line = "\tGet: " + str(Data[i]) + "\n\t\tvalue: " + str(result) + "\n"
	print(line)
	file.write(line)

#Try to add elements beyond the maximum size, this should fail and have result = False
result = Map.load()
line = "\nProve Elements Can't Be Added Past Max Size:\n\n\tLoad value = " + str(result) + "\n\n"
print(line)
file.write(line)

result = Map.set(Data[10][0],Data[10][1])
line = "\tSet:" + str(Data[10]) + "\n\t\tresult:" + str(result) + "\n\n"
print(line)
file.write(line)

#Try to retrieve the key that failed to be added in the previous test. Should have value = None
result = Map.get(Data[10][0])
line = "\tGet: " + str(Data[10]) + "\n\t\tresult: " +str(result) + "\n\n"
print(line)
file.write(line)

if result == None:
	line = "\tSuccessfully prevented ['key', value] from being put in the full hashmap.\n\n"
	print(line)
	file.write(line)
else:
	line = "\tFailed test.\n"
	print(line)
	file.write(line)

#Output load to prove it hasn't changed
result = Map.load()
line = "\tLoad value = " + str(result) + "\n\n"
print(line)
file.write(line)

#Delete key: Data[4][0] from the hashmap
result = Map.delete(Data[4][0])
line = "Delete key from the table\n\n\tDelete: " + str(Data[4][0]) + "\n\t\tresult:" + str(result) + "\n\n"
print(line)
file.write(line)

#Output the load to prove it has changed
result = Map.load()
line = "\tLoad value = " + str(result) + "\n\n" + "Hashmap:\n" + str(Map.map) + "\n\n"
print(line)
file.write(line)

#Try to retrieve the deleted key from the hashmap
result = Map.get(Data[4][0])
line = "\nAttempt to retrieve the deleted key.\n\n\tGet:" + str(Data[4][0]) + "\n\t\tresult:" + str(result) + "\n"
print(line)
file.write(line)

#Indicate if the deletion was succesful
if result == None:
	line = "\n\tSuccessfully removed key from hashmap.\n"
	print(line)
	file.write(line)
else:
	line = "\n\tFailed test.\n"
	print(line)
	file.write(line)

#Rewrite the value assigned to key from Data[0] to a 'Different Value'
result = Map.set(Data[0][0],"Different Value")
line = "\nRewrite the value of key: " + str(Data[0][0]) + " with the value 'Different Value'\n\n\tresult = " + str(result) + "\n\n"
print(line)
file.write(line)

#Output the load to prove it has not changed. Include the hashmap as well.
result = Map.load()
line = "\tLoad value = " + str(result) + "\n\n" + "Hashmap:\n" + str(Map.map) + "\n\n"
print(line)
file.write(line)

#Delete the value of key from Data[0] to prove it's value has been changed.
result = Map.delete(Data[4][0])
line = "\nDelete changed key from the table\n\tDelete: " + str(Data[4][0]) + "\n\t\tresult:" + str(result) + "\n\n"
print(line)
file.write(line)

#Output the load to prove it has changed. Include the hashmap as well.
result = Map.load()
line = "\tLoad value = " + str(result) + "\n\n" + "Hashmap:\n" + str(Map.map) + "\n\n"
print(line)
file.write(line)

#Attempt to delete the value of key Data[0] after it has already been deleted to prove two identical keys did not exist
#and prove that deletion does nothing if the key is not present
result = Map.delete(Data[4][0])
line = "\nAttempt to delete changed key again from the table\n\n\tDelete: " + str(Data[4][0]) + "\n\t\tresult:" + str(result) + "\n\n"
print(line)
file.write(line)

if result == None:
	line = "\tSuccessfully changed value of key and deleted from hashmap without containing duplicate keys.\n\n"
	print(line)
	file.write(line)
else:
	line = "\tFailed test.\n\n"
	print(line)
	file.write(line)

#Output the load to prove it has not changed. Include the hashmap as well.
result = Map.load()
line = "\tLoad value = " + str(result) + "\n\n" + "Hashmap:\n" + str(Map.map) + "\n\n"
print(line)
file.write(line)


from pydoc import locate
import tensorflow as tf
import numpy as np
from seq2seq import tasks, models
from seq2seq.training import utils as training_utils
from seq2seq.tasks.inference_task import InferenceTask, unbatch_dict
import pprint
import logging
import pinyin_util as pu
#import eval as ev
#import ngram as ng

#unigram_dict, bigram_dict, dictionary = ng.load_model("model/ngrams_model")

class DecodeOnce(InferenceTask):
  '''
  Similar to tasks.DecodeText, but for one input only.
  Source fed via features.source_tokens and features.source_len
  '''
  def __init__(self, params, callback_func):
    super(DecodeOnce, self).__init__(params)
    self.callback_func=callback_func
    self._beam_accum = {
      "predicted_ids": [],
      "beam_parent_ids": [],
      "scores": [],
      "log_probs": []
    }
    self.top_k = 100

  @staticmethod
  def default_params():
    return {}

  def before_run(self, _run_context):
    fetches = {}
    fetches["predicted_tokens"] = self._predictions["predicted_tokens"]
    fetches["features.source_tokens"] = self._predictions["features.source_tokens"]
    fetches["beam_search_output.predicted_ids"] = self._predictions["beam_search_output.predicted_ids"]
    fetches["beam_search_output.beam_parent_ids"] = self._predictions["beam_search_output.beam_parent_ids"]
    fetches["beam_search_output.scores"] = self._predictions["beam_search_output.scores"]
    fetches["beam_search_output.log_probs"] = self._predictions["beam_search_output.log_probs"]
    return tf.train.SessionRunArgs(fetches)

  def after_run(self, _run_context, run_values):
    fetches_batch = run_values.results
    for fetches in unbatch_dict(fetches_batch):
      # Convert to unicode
      fetches["predicted_tokens"] = np.char.decode(
      fetches["predicted_tokens"].astype("S"), "utf-8")
      predicted_tokens = fetches["predicted_tokens"]

      #self._beam_accum["predicted_ids"].append(fetches["beam_search_output.predicted_ids"])
      #self._beam_accum["beam_parent_ids"].append(fetches["beam_search_output.beam_parent_ids"])
      #self._beam_accum["scores"].append(fetches["beam_search_output.scores"])
      #self._beam_accum["log_probs"].append(fetches["beam_search_output.log_probs"])

      self._beam_accum["predicted_ids"] = [fetches["beam_search_output.predicted_ids"]]
      self._beam_accum["beam_parent_ids"] = [fetches["beam_search_output.beam_parent_ids"]]
      self._beam_accum["scores"] = [fetches["beam_search_output.scores"]]
      self._beam_accum["log_probs"] = [fetches["beam_search_output.log_probs"]]

 #     print("\n\n")
#      print(self._beam_accum)
      #print(predicted_tokens)
#      print("\n\n")

      def beam_search_traceback(i, cur_id):
        if i == 0: return np.array([])
        else:
          cur_prediction = predicted_tokens[i-1:i,cur_id]
          parent_id = self._beam_accum["beam_parent_ids"][0][i-1][cur_id]
          return np.append(beam_search_traceback(i-1, parent_id), cur_prediction)

      # If we're using beam search we take the first beam
      # TODO: beam search top k
      if np.ndim(predicted_tokens) > 1:
        #predicted_tokens = predicted_tokens[:, 0]
        try:
          beam_search_predicted_tokens = []
          seq_len = predicted_tokens.shape[0]
          beam_width = predicted_tokens.shape[1]

          #for length in range(seq_len, 0, -1):

          #  for k in range(0, beam_width):
          #    parent_id = self._beam_accum["beam_parent_ids"][0][length - 1][k]
          #    log_prob = self._beam_accum["log_probs"][0][length - 1][k]
          #    #parent_log_prob = self._beam_accum["log_probs"][0][length - 2][parent_id]
          #    bigram_score = 0
          #    char_cur = predicted_tokens[length - 1, k]
          #    char_prev = predicted_tokens[length - 2, parent_id]
          #    if char_cur == "SEQUENCE_END":
          #      char_cur = "^"
          #    else:
          #      char_cur = char_cur[0]
          #    if char_prev == "SEQUENCE_END":
          #      char_prev = "^"
          #    else:
          #      char_prev = char_prev[len(char_prev) - 1]
          #    try:
          #      bigram_score = (bigram_dict[(char_prev, char_cur)]) / float(unigram_dict[char_prev])
          #    except ZeroDivisionError or KeyError:
          #      bigram_score = 0
          #    self._beam_accum["scores"][0][length - 1][k] = self._beam_accum["scores"][0][length -1][k] + 3 * bigram_score

          for length in range(1, seq_len):
            prediction_per_len = []
            for k in range(0, min(beam_width, self.top_k)):
              pred_tokens_k  = beam_search_traceback(length, k)
              prob_pred_token_k = self._beam_accum["scores"][0][length-1][k]
              if not _arreq_in_list(pred_tokens_k, prediction_per_len):
                prediction_per_len.append((pred_tokens_k, prob_pred_token_k))
            #prediction_per_len = sorted(prediction_per_len, key=lambda x: x[1], reverse=True)[:beam_width]
            beam_search_predicted_tokens.append(prediction_per_len)
          predicted_tokens = beam_search_predicted_tokens
        except IndexError as e:
          logging.exception("")
          print(self._beam_accum)
          print(predicted_tokens)
          predicted_tokens = []
          print("parents dim", np.ndim(self._beam_accum["beam_parent_ids"]))
          print("predicted tokends dim", np.ndim(predicted_tokens))

      fetches["features.source_tokens"] = np.char.decode(
          fetches["features.source_tokens"].astype("S"), "utf-8")
      source_tokens = fetches["features.source_tokens"]

      self.callback_func(source_tokens, predicted_tokens)

# TODO: pass via args
MODEL_DIR = "/data/model/mixed_abbrs_05_31_wiki"

checkpoint_path = tf.train.latest_checkpoint(MODEL_DIR)

print("latest_checkpoint is ", checkpoint_path, "============================")

# Load saved training options
train_options = training_utils.TrainOptions.load(MODEL_DIR)

# Create the model
model_cls = locate(train_options.model_class) or \
  getattr(models, train_options.model_class)
model_params = train_options.model_params

model_params["inference.beam_search.beam_width"] = 100

model = model_cls(
    params=model_params,
    mode=tf.contrib.learn.ModeKeys.INFER)

# first dim is batch size
source_tokens_ph = tf.placeholder(dtype=tf.string, shape=(1, None))
source_len_ph = tf.placeholder(dtype=tf.int32, shape=(1,))

model(
  features={
    "source_tokens": source_tokens_ph,
    "source_len": source_len_ph
  },
  labels=None,
  params={
    "vocab_source": "/data/vocab/wiki",
    "vocab_target": "/data/vocab/wiki"
  }
)

saver = tf.train.Saver()

def _session_init_op(_scaffold, sess):
  saver.restore(sess, checkpoint_path)
  tf.logging.info("Restored model from %s", checkpoint_path)

scaffold = tf.train.Scaffold(init_fn=_session_init_op)
session_creator = tf.train.ChiefSessionCreator(scaffold=scaffold)

def _tokens_to_str(tokens):
  return " ".join(tokens).split("SEQUENCE_END")[0].strip()

# A hacky way to retrieve prediction result from the task hook...
prediction_dict = {}
def _save_prediction_to_dict(source_tokens, predicted_tokens):
  prediction_dict[_tokens_to_str(source_tokens)] = [[(_tokens_to_str(predicted_token[0]), predicted_token[1]) for predicted_token in predicted_tokens_len] for predicted_tokens_len in predicted_tokens]

def _arreq_in_list(target_ndarray, list_ndarrays):
      return next((True for elem in list_ndarrays if np.array_equal(elem[0], target_ndarray)), False)

sess = tf.train.MonitoredSession(
  session_creator=session_creator,
  hooks=[DecodeOnce({}, callback_func=_save_prediction_to_dict)])

# The main APIs exposed
def query_once(source_tokens):
  #print("received source tokens:", source_tokens)
  tf.reset_default_graph()
  source_tokens = source_tokens.split() + ["SEQUENCE_END"]
  sess.run([], {
      source_tokens_ph: [source_tokens],
      source_len_ph: [len(source_tokens)]
    })

  predictions_list = prediction_dict.pop(_tokens_to_str(source_tokens))
  #return predictions_list
  #return predictions_list
  #print("all result:")
  #print(predictions_list)
  result = sort_and_merge_predictions(predictions_list)
  #print("result to be returned:")
  #print(result)
  return result

def sort_and_merge_predictions(predictions_list):
    count_per_len = [10, 6, 3, 2, 1]
    cutoff_per_len = [-20., -5., -3., -3., -3.]
    flat_list = []
    num_keep = 1
    s = set()
    for i in range(0, len(predictions_list)):
      sublist = predictions_list[i]
      num_keep = count_per_len[i]
      cutoff = cutoff_per_len[i]
      ranked_sublist = sorted(sublist, key=lambda x: x[1], reverse=True)
      temp_list = []
      for t in ranked_sublist:
        if (t[0] not in s and 'UNK' not in t[0] and t[1] > cutoff):
          temp_list.append((t[0].replace(" ", ""), t[1]))
          s.add(t[0])
      flat_list.extend(temp_list[:num_keep])
    ranked = sorted(flat_list, key=lambda x: (len(x[0]), x[1]), reverse=True)
    print("after sorting:")
    print(ranked)
    return [x[0] for x in ranked]

def query(context, pinyin_str):
  # TODO: do not hard code window size here
  if (len(context) < 10):
    context = "^" * (10 - len(context)) + context
  context = " ".join(list(context)[-10:])
  pinyins = " ".join(list("".join(pinyin_str)))
  #return query_once(context + " | " + pinyins)
  #print("------------", context + " | " + pinyins)
  flat_predicted_list = query_once(context + " | " + pinyins)
  combine_with_unigram(flat_predicted_list, pinyin_str)
  res = [(x, pu.num_pinyins_used_in_predicton(x, pinyin_str)) for x in flat_predicted_list]
  print(res)
  return res

def combine_with_unigram(flat_predicted_list, pinyin_str):
  pinyin_tokens = pu.segment_with_hint(pinyin_str)
  # since flat_predicted_list will be sorted by length in reverse order
  # it is guaranteed that character with length 1 will be at the end
  # therefore, simply append single characters that are not in the original
  # predictions according to the first pinyin token
  if (len(pinyin_tokens) > 1):
    unigram_candidates = pu.get_pinyin_candidates(pinyin_tokens[0])
    flat_predicted_list += [x for x in unigram_candidates if x not in flat_predicted_list]

if __name__ == "__main__":
  tf.logging.set_verbosity(tf.logging.INFO)
  # current prediction time ~20ms
  #unigram_dict, bigram_dict, dictionary = ng.load_model("model/ngrams_model")
  samples = [
     u"^ 下 班 | h o u y i q i c h i f a n",
     u"^ … 还 以 为 你 关 机 | s h u i z h a o l e",
     u"^ 你 带 钥 匙 | m e i y o u a",
     u"^ 我 妹 妹 | t a",
     u"^ 我 弟 弟 | t a",
     u"^ 我 妈 妈 现 在 在 家 ，| t a",
     u"^ 我 爸 爸 现 在 在 家 , | t a",
     u"^ 我 叫 | w e n q i n g d a"
  ]
  #for sample_in in samples:
     #pprint.pprint(sample_in)
     #print(query_once(sample_in))
     #print()
  print(query("^下班", "houyiqichifan"))
  # print(query("^", "w"))
  # print(query("^", "wo"))
  # print(query("^我", "j"))
  # query("^我", "ji")
  # query("^我", "jia")
  # query("^我", "jiao")
  # query(u"^我叫", "w")
  # query(u"^我叫", "we")
  # query(u"^我叫", "wen")
  # query(u"^我叫", "wenq")
  # query(u"^我叫", "wenqi")
  # query(u"^我叫", "wenqin")
  # query(u"^我叫", "wenqing")
  # query(u"^我叫", "wenqingd")
  #query(u"^我叫", "wenqingda")
  #query(u"^下班", "houyiqichifan")


import sys
sys.stdin = open('input_1865.txt', 'r')

def probability(people_num, val):
    global ans, N
    if val <= ans:
        return
    if people_num == N:
        if val >= ans:
            ans = val
            return
    for i in range(N):
        if not used[i]:
            used[i] = True
            probability(people_num + 1, val * (arr[people_num][i] / 100))
            used[i] = False

for test_case in range(int(input())):
    N = int(input())
    arr = [list(map(int, input().split())) for _ in range(N)]
    number_list = [num for num in range(N)]
    used = [False] * N
    people_n, ans = 0, 0
    probability_value = 1 # 재귀 함수를 통해 계속 곱해질 확률 값이므로 1로 초기값 선언
    probability(people_n, probability_value)
    print('#{} {:.6f}'.format(test_case + 1, ans * 100))


from cx_Freeze import setup, Executable

base = None

executables = [Executable("tictactoe.py", base=base)]

includefiles = ['QTable.csv']
includes = ['numpy']

setup(
    name="TicTacToe",
    options={
        'build_exe': {'includes': includes, 'include_files': includefiles}},
    version="1.0",
    description='Testing',
    executables=executables
)


#!/usr/bin/python3
""" This script starts a flask application to storage all data in mysql"""

from flask import Flask, render_template
from models import storage
from models import State, City

app = Flask(__name__)
app.url_map.strict_slashes = False

@app.teardown_appcontext
def handleclose(self):
    """ method to handle close session """
    storage.close()

@app.route('/cities_by_states')
def showstates():
    """ route to tempplate for showing sstates """
    objects = storage.all(State)
    # print(objects)
    states = dict()
    cities = dict()
    for key, values in objects.items():
        a = key
        if "State" in key:
            states[key] = values
        if "City" in key:
            cities[key] = values
    # print(states)
    templatedata = {'Objects': objects}
    return render_template("8-cities_by_states.html", templatedata=cities,
                           states=states)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)


# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
# Modifications Copyright 2017 Abigail See
# Modifications made 2018 by Logan Lebanoff
#
# 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.
# ==============================================================================

"""This file contains code to process data into batches"""
import os
import pickle

import queue
from random import shuffle
from threading import Thread
import time
import numpy as np
import data
import nltk
import util
from absl import logging
import pg_mmr_functions

max_dec_sents = 10
chronological_ssi = True

class Example(object):
    """Class representing a train/val/test example for text summarization."""

    def __init__(self, article, abstract_sentences, all_abstract_sentences, doc_indices, raw_article_sents, ssi, article_lcs_paths_list, vocab, hps):
        """Initializes the Example, performing tokenization and truncation to produce the encoder, decoder and target sequences, which are stored in self.

        Args:
            article: source text; a string. each token is separated by a single space.
            abstract_sentences: list of strings, one per abstract sentence. In each sentence, each token is separated by a single space.
            vocab: Vocabulary object
            hps: hyperparameters
        """
        self.hps = hps

        # Get ids of special tokens
        start_decoding = vocab.word2id(data.START_DECODING)
        stop_decoding = vocab.word2id(data.STOP_DECODING)

        # # Process the article
        # article_words = article.split()
        # if len(article_words) > hps.max_enc_steps:
        #     article_words = article_words[:hps.max_enc_steps]
        # self.enc_input = [vocab.word2id(w) for w in article_words] # list of word ids; OOVs are represented by the id for UNK token

        # Process the abstract
        abstract = ' '.join(abstract_sentences) # string
        abstract_words = abstract.split() # list of strings
        abs_ids = [vocab.word2id(w) for w in abstract_words] # list of word ids; OOVs are represented by the id for UNK token

        # Get the decoder input sequence and target sequence
        self.dec_input, self.target = self.get_dec_inp_targ_seqs(abs_ids, hps.max_dec_steps, start_decoding, stop_decoding)
        self.dec_len = len(self.dec_input)

        # If using pointer-generator mode, we need to store some extra info
        if hps.pointer_gen:

            if raw_article_sents is not None and len(raw_article_sents) > 0:
                # self.tokenized_sents = [util.process_sent(sent) for sent in raw_article_sents]
                self.tokenized_sents = [util.process_sent(sent, whitespace=True) for sent in raw_article_sents]
                if self.hps.sep:
                    for sent in self.tokenized_sents[:-1]:
                        sent.append(data.SEP_TOKEN)

                # Process the article
                article_words = util.flatten_list_of_lists(self.tokenized_sents)
                if len(article_words) > hps.max_enc_steps:
                    article_words = article_words[:hps.max_enc_steps]
                self.enc_input = [vocab.word2id(w) for w in
                                  article_words]  # list of word ids; OOVs are represented by the id for UNK token

                if len(all_abstract_sentences) == 1:
                    doc_indices = [0] * len(article_words)

                self.word_ids_sents, self.article_oovs = data.tokenizedarticle2ids(self.tokenized_sents, vocab)
                self.enc_input_extend_vocab = util.flatten_list_of_lists(self.word_ids_sents)
                if len(self.enc_input_extend_vocab) > hps.max_enc_steps:
                    self.enc_input_extend_vocab = self.enc_input_extend_vocab[:hps.max_enc_steps]
                self.enc_len = len(self.enc_input_extend_vocab) # store the length after truncation but before padding
            else:
                # Store a version of the enc_input where in-article OOVs are represented by their temporary OOV id; also store the in-article OOVs words themselves
                article_str = util.to_unicode(article)
                raw_article_sents = nltk.tokenize.sent_tokenize(article_str)
                self.tokenized_sents = [util.process_sent(sent) for sent in raw_article_sents]

                # Process the article
                article_words = util.flatten_list_of_lists(self.tokenized_sents)
                if len(article_words) > hps.max_enc_steps:
                    article_words = article_words[:hps.max_enc_steps]
                self.enc_input = [vocab.word2id(w) for w in
                                  article_words]  # list of word ids; OOVs are represented by the id for UNK token

                if len(all_abstract_sentences) == 1:
                    doc_indices = [0] * len(article_words)

                self.word_ids_sents, self.article_oovs = data.tokenizedarticle2ids(self.tokenized_sents, vocab)
                self.enc_input_extend_vocab = util.flatten_list_of_lists(self.word_ids_sents)
                # self.enc_input_extend_vocab, self.article_oovs = data.article2ids(article_words, vocab)
                if len(self.enc_input_extend_vocab) > hps.max_enc_steps:
                    self.enc_input_extend_vocab = self.enc_input_extend_vocab[:hps.max_enc_steps]
                self.enc_len = len(self.enc_input_extend_vocab) # store the length after truncation but before padding

            if self.hps.word_imp_reg:
                self.enc_importances = self.get_enc_importances(self.tokenized_sents, abstract_words)

            # Get a verison of the reference summary where in-article OOVs are represented by their temporary article OOV id
            abs_ids_extend_vocab = data.abstract2ids(abstract_words, vocab, self.article_oovs)

            # Overwrite decoder target sequence so it uses the temp article OOV ids
            _, self.target = self.get_dec_inp_targ_seqs(abs_ids_extend_vocab, hps.max_dec_steps, start_decoding, stop_decoding)

        if ssi is not None:
            # Translate the similar source indices into masks over the encoder input
            self.ssi_masks = []
            for source_indices in ssi:
                ssi_sent_mask = [0.] * len(raw_article_sents)
                for source_idx in source_indices:
                    if source_idx >= len(ssi_sent_mask):
                        a=0
                    ssi_sent_mask[source_idx] = 1.
                ssi_mask = pg_mmr_functions.convert_to_word_level(ssi_sent_mask, self.tokenized_sents)
                self.ssi_masks.append(ssi_mask)

            summary_sent_tokens = [sent.strip().split() for sent in abstract_sentences]
            if self.hps.ssi_data_path is None and len(self.ssi_masks) != len(summary_sent_tokens):
                raise Exception('len(self.ssi_masks) != len(summary_sent_tokens)')

            self.sent_indices = pg_mmr_functions.convert_to_word_level(list(range(len(summary_sent_tokens))), summary_sent_tokens).tolist()

        if article_lcs_paths_list is not None:
            if len(article_lcs_paths_list) > 1:
                raise Exception('Need to implement for non-sent_dataset')
            article_lcs_paths = article_lcs_paths_list[0]
            imp_mask = [0] * len(article_words)
            to_add = 0
            for source_idx, word_indices_list in enumerate(article_lcs_paths):
                if source_idx > 0:
                    to_add += len(self.tokenized_sents[source_idx-1])
                for word_idx in word_indices_list:
                    if word_idx + to_add >= len(imp_mask):
                        if len(imp_mask) == hps.max_enc_steps:
                            continue
                        else:
                            print (self.tokenized_sents, article_lcs_paths)
                            raise Exception('word_idx + to_add (%d) is larger than imp_mask size (%d)' % (word_idx + to_add, len(imp_mask)))
                    imp_mask[word_idx + to_add] = 1
            self.importance_mask = imp_mask

        # Store the original strings
        self.original_article = article
        self.raw_article_sents = raw_article_sents
        self.original_abstract = abstract
        self.original_abstract_sents = abstract_sentences
        self.all_original_abstract_sents = all_abstract_sentences

        self.doc_indices = doc_indices
        self.ssi = ssi
        self.article_lcs_paths_list = article_lcs_paths_list

    def get_enc_importances(self, tokenized_sents, abstract_words):
        lemmatize = True
        if lemmatize:
            article_sent_tokens_lemma = util.lemmatize_sent_tokens(tokenized_sents)
            summary_sent_tokens_lemma = util.lemmatize_sent_tokens([abstract_words])
        article_tokens = util.flatten_list_of_lists(article_sent_tokens_lemma)
        abstract_tokens = util.flatten_list_of_lists(summary_sent_tokens_lemma)
        enc_importances = [1. if token in abstract_tokens else 0. for token in article_tokens]
        return enc_importances

    def get_dec_inp_targ_seqs(self, sequence, max_len, start_id, stop_id):
        """Given the reference summary as a sequence of tokens, return the input sequence for the decoder, and the target sequence which we will use to calculate loss. The sequence will be truncated if it is longer than max_len. The input sequence must start with the start_id and the target sequence must end with the stop_id (but not if it's been truncated).

        Args:
            sequence: List of ids (integers)
            max_len: integer
            start_id: integer
            stop_id: integer

        Returns:
            inp: sequence length <=max_len starting with start_id
            target: sequence same length as input, ending with stop_id only if there was no truncation
        """
        inp = [start_id] + sequence[:]
        target = sequence[:]
        if len(inp) > max_len: # truncate
            inp = inp[:max_len]
            target = target[:max_len] # no end_token
        else: # no truncation
            target.append(stop_id) # end token
        assert len(inp) == len(target)
        return inp, target

    def pad_decoder_inp_targ(self, max_len, pad_id):
        """Pad decoder input and target sequences with pad_id up to max_len."""
        while len(self.dec_input) < max_len:
            self.dec_input.append(pad_id)
        while len(self.target) < max_len:
            self.target.append(pad_id)

    def pad_encoder_input(self, max_len, pad_id):
        """Pad the encoder input sequence with pad_id up to max_len."""
        while len(self.enc_input) < max_len:
            self.enc_input.append(pad_id)
        self.enc_input = self.enc_input[:max_len]       # TODO: This is a very hacky fix. This could be causing problems of misalignment between enc_input and enc_input_extend_vocab. Actually, the problem probably has to do with doing word tokenization on raw_article_sents (which turns into enc_input_ but then using article for enc_input
        if self.hps.pointer_gen:
            while len(self.enc_input_extend_vocab) < max_len:
                self.enc_input_extend_vocab.append(pad_id)
            self.enc_input_extend_vocab = self.enc_input_extend_vocab[:max_len]
        if self.hps.word_imp_reg:
            while len(self.enc_importances) < max_len:
                self.enc_importances.append(0.)
            self.enc_importances = self.enc_importances[:max_len]
        if self.hps.tag_tokens:
            while len(self.importance_mask) < max_len:
                self.importance_mask.append(0)
            self.importance_mask = self.importance_mask[:max_len]

    def pad_doc_indices(self, max_len, pad_id):
        """Pad the encoder input sequence with pad_id up to max_len."""
        while len(self.doc_indices) < max_len:
            self.doc_indices.append(pad_id)

    def pad_ssi_masks(self, max_len, max_enc_len, pad_id):
        self.ssi_masks_padded = []
        """Pad the encoder input sequence with pad_id up to max_len."""
        for idx in range(len(self.ssi_masks)):
            """Pad the encoder input sequence with pad_id up to max_len."""
            # self.ssi_masks[idx] = np.pad(self.ssi_masks[idx], (0, max_enc_len-len(self.ssi_masks[idx])), 'constant', constant_values=(pad_id, pad_id))
            if len(self.ssi_masks[idx]) < max_enc_len:
                to_add = np.pad(self.ssi_masks[idx], (0, max_enc_len-len(self.ssi_masks[idx])), 'constant', constant_values=(pad_id, pad_id))
            else:
                to_add = self.ssi_masks[idx][:max_enc_len]
            self.ssi_masks_padded.append(to_add)

        while len(self.ssi_masks_padded) < max_len:
            self.ssi_masks_padded.append([pad_id] * max_enc_len)
        self.ssi_masks_padded = self.ssi_masks_padded[:max_len]
        self.ssi_masks_padded = np.array(self.ssi_masks_padded)

    def pad_sent_indices(self, max_len, pad_id):
        """Pad decoder input and target sequences with pad_id up to max_len."""
        while len(self.sent_indices) < max_len:
            self.sent_indices.append(pad_id)
        self.sent_indices = self.sent_indices[:max_len]

    def are_ssi_in_max_enc_steps(self, max_len):
        cur_token_idx = 0
        sent_idx_at_400 = 100000
        for sent_idx, sent_tokens in enumerate(self.tokenized_sents):
            for token in sent_tokens:
                cur_token_idx += 1
                if cur_token_idx >= max_len:
                    sent_idx_at_400 = sent_idx
                    break
            if cur_token_idx >= max_len:
                break
        for source_indices in self.ssi:
            for source_idx in source_indices:
                if source_idx >= sent_idx_at_400:
                    return False
        return True

    def fix_outside_and_empty_masks(self, max_enc_steps, max_enc_seq_len):
        cur_token_idx = 0
        sent_idx_at_400 = 100000
        for sent_idx, sent_tokens in enumerate(self.tokenized_sents):
            for token in sent_tokens:
                cur_token_idx += 1
                if cur_token_idx >= max_enc_steps:
                    sent_idx_at_400 = sent_idx
                    break
            if cur_token_idx >= max_enc_steps:
                break
        new_masks = []
        for source_indices_idx, source_indices in enumerate(self.ssi):
            should_make_all_ones = False
            for source_idx in source_indices:
                if source_idx >= sent_idx_at_400:
                    should_make_all_ones = True
            if len(source_indices) == 0:
                should_make_all_ones = True

            if should_make_all_ones:
                new_masks.append([1] * max_enc_steps)
            else:
                new_masks.append(self.ssi_masks[source_indices_idx])
        self.ssi_masks = new_masks

class Batch(object):
    """Class representing a minibatch of train/val/test examples for text summarization."""

    def __init__(self, example_list, hps, vocab):
        """Turns the example_list into a Batch object.

        Args:
             example_list: List of Example objects
             hps: hyperparameters
             vocab: Vocabulary object
        """
        self.pad_id = vocab.word2id(data.PAD_TOKEN) # id of the PAD token used to pad sequences
        self.init_encoder_seq(example_list, hps) # initialize the input to the encoder
        self.init_decoder_seq(example_list, hps) # initialize the input and targets for the decoder
        if example_list[0].ssi is not None:
            self.init_ssi_masks(example_list, hps)
        self.store_orig_strings(example_list) # store the original strings

    def init_encoder_seq(self, example_list, hps):
        """Initializes the following:
                self.enc_batch:
                    numpy array of shape (batch_size, <=max_enc_steps) containing integer ids (all OOVs represented by UNK id), padded to length of longest sequence in the batch
                self.enc_lens:
                    numpy array of shape (batch_size) containing integers. The (truncated) length of each encoder input sequence (pre-padding).
                self.enc_padding_mask:
                    numpy array of shape (batch_size, <=max_enc_steps), containing 1s and 0s. 1s correspond to real tokens in enc_batch and target_batch; 0s correspond to padding.

            If hps.pointer_gen, additionally initializes the following:
                self.max_art_oovs:
                    maximum number of in-article OOVs in the batch
                self.art_oovs:
                    list of list of in-article OOVs (strings), for each example in the batch
                self.enc_batch_extend_vocab:
                    Same as self.enc_batch, but in-article OOVs are represented by their temporary article OOV number.
        """
        # Determine the maximum length of the encoder input sequence in this batch
        max_enc_seq_len = max([ex.enc_len for ex in example_list])

        # Pad the encoder input sequences up to the length of the longest sequence
        for ex in example_list:
            ex.pad_encoder_input(max_enc_seq_len, self.pad_id)
            ex.pad_doc_indices(max_enc_seq_len, 0)

        # Initialize the numpy arrays
        # Note: our enc_batch can have different length (second dimension) for each batch because we use dynamic_rnn for the encoder.
        self.enc_batch = np.zeros((hps.batch_size, max_enc_seq_len), dtype=np.int32)
        self.enc_lens = np.zeros((hps.batch_size), dtype=np.int32)
        self.enc_padding_mask = np.zeros((hps.batch_size, max_enc_seq_len), dtype=np.float32)
        self.doc_indices = np.zeros((hps.batch_size, max_enc_seq_len), dtype=np.float32)

        # Fill in the numpy arrays
        for i, ex in enumerate(example_list):
            self.enc_batch[i, :] = ex.enc_input[:]
            self.enc_lens[i] = ex.enc_len
            for j in range(ex.enc_len):
                self.enc_padding_mask[i][j] = 1
            self.doc_indices[i, :] = ex.doc_indices[:max_enc_seq_len]

        # For pointer-generator mode, need to store some extra info
        if hps.pointer_gen:
            # Determine the max number of in-article OOVs in this batch
            self.max_art_oovs = max([len(ex.article_oovs) for ex in example_list])
            # Store the in-article OOVs themselves
            self.art_oovs = [ex.article_oovs for ex in example_list]
            # Store the version of the enc_batch that uses the article OOV ids
            self.enc_batch_extend_vocab = np.zeros((hps.batch_size, max_enc_seq_len), dtype=np.int32)
            for i, ex in enumerate(example_list):
                self.enc_batch_extend_vocab[i, :] = ex.enc_input_extend_vocab[:]

        if hps.word_imp_reg:
            self.enc_importances = np.zeros((hps.batch_size, max_enc_seq_len), dtype=np.float32)
            for i, ex in enumerate(example_list):
                self.enc_importances[i, :] = ex.enc_importances[:]

        if hps.tag_tokens:
            self.importance_masks = np.zeros((hps.batch_size, max_enc_seq_len), dtype=np.int32)
            for i, ex in enumerate(example_list):
                self.importance_masks[i, :] = ex.importance_mask[:]

    def init_decoder_seq(self, example_list, hps):
        """Initializes the following:
                self.dec_batch:
                    numpy array of shape (batch_size, max_dec_steps), containing integer ids as input for the decoder, padded to max_dec_steps length.
                self.target_batch:
                    numpy array of shape (batch_size, max_dec_steps), containing integer ids for the target sequence, padded to max_dec_steps length.
                self.dec_padding_mask:
                    numpy array of shape (batch_size, max_dec_steps), containing 1s and 0s. 1s correspond to real tokens in dec_batch and target_batch; 0s correspond to padding.
                """
        # Pad the inputs and targets
        for ex in example_list:
            ex.pad_decoder_inp_targ(hps.max_dec_steps, self.pad_id)

        # Initialize the numpy arrays.
        # Note: our decoder inputs and targets must be the same length for each batch (second dimension = max_dec_steps) because we do not use a dynamic_rnn for decoding. However I believe this is possible, or will soon be possible, with Tensorflow 1.0, in which case it may be best to upgrade to that.
        self.dec_batch = np.zeros((hps.batch_size, hps.max_dec_steps), dtype=np.int32)
        self.target_batch = np.zeros((hps.batch_size, hps.max_dec_steps), dtype=np.int32)
        self.dec_padding_mask = np.zeros((hps.batch_size, hps.max_dec_steps), dtype=np.float32)

        # Fill in the numpy arrays
        for i, ex in enumerate(example_list):
            self.dec_batch[i, :] = ex.dec_input[:]
            self.target_batch[i, :] = ex.target[:]
            for j in range(ex.dec_len):
                self.dec_padding_mask[i][j] = 1

    def init_ssi_masks(self, example_list, hps):
        # Determine the maximum length of the encoder input sequence in this batch
        max_enc_seq_len = max([ex.enc_len for ex in example_list])

        for ex in example_list:
            ex.fix_outside_and_empty_masks(hps.max_enc_steps, max_enc_seq_len)
        for ex_idx, ex in enumerate(example_list):
            ex.pad_ssi_masks(max_dec_sents, max_enc_seq_len, 0.)

        self.ssi_masks_padded = np.stack([ex.ssi_masks_padded for ex in example_list])
        # self.ssi_masks_padded = np.ones([len(example_list), max_dec_sents, max_enc_seq_len], dtype=float)

        batch_sent_indices = []
        for ex_idx, ex in enumerate(example_list):
            ex.pad_sent_indices(hps.max_dec_steps, 0)
            new_sent_indices = []
            for sent_idx in ex.sent_indices:
                new_sent_indices.append([ex_idx, sent_idx])
            batch_sent_indices.append(new_sent_indices)
        self.batch_sent_indices = np.array(batch_sent_indices, dtype=np.int32)

    def store_orig_strings(self, example_list):
        """Store the original article and abstract strings in the Batch object"""
        self.original_articles = [ex.original_article for ex in example_list] # list of lists
        self.raw_article_sents = [ex.raw_article_sents for ex in example_list]
        self.tokenized_sents = [ex.tokenized_sents for ex in example_list]
        self.word_ids_sents = [ex.word_ids_sents for ex in example_list]
        self.original_abstracts = [ex.original_abstract for ex in example_list] # list of lists
        self.original_abstracts_sents = [ex.original_abstract_sents for ex in example_list] # list of list of lists
        self.all_original_abstracts_sents = [ex.all_original_abstract_sents for ex in example_list] # list of list of list of lists
        if example_list[0].ssi is not None:
            self.ssis = [ex.ssi for ex in example_list]
            self.ssi_masks = [ex.ssi_masks for ex in example_list]
        if example_list[0].article_lcs_paths_list is not None:
            self.article_lcs_paths_lists = [ex.article_lcs_paths_list for ex in example_list]

class Batcher(object):
    """A class to generate minibatches of data. Buckets examples together based on length of the encoder sequence."""

    BATCH_QUEUE_MAX = 100 # max number of batches the batch_queue can hold

    def __init__(self, data_path, vocab, hps, single_pass, cnn_500_dm_500=False, example_generator=None):
        """Initialize the batcher. Start threads that process the data into batches.

        Args:
            data_path: tf.Example filepattern.
            vocab: Vocabulary object
            hps: hyperparameters
            single_pass: If True, run through the dataset exactly once (useful for when you want to run evaluation on the dev or test set). Otherwise generate random batches indefinitely (useful for training).
        """
        self._data_path = data_path
        self._vocab = vocab
        self._hps = hps
        self._single_pass = single_pass
        self._cnn_500_dm_500 = cnn_500_dm_500
        self._example_generator = example_generator

        # Initialize a queue of Batches waiting to be used, and a queue of Examples waiting to be batched
        self._batch_queue = queue.Queue(self.BATCH_QUEUE_MAX)
        self._example_queue = queue.Queue(self.BATCH_QUEUE_MAX * self._hps.batch_size)

        # Different settings depending on whether we're in single_pass mode or not
        if single_pass:
            self._num_example_q_threads = 1 # just one thread, so we read through the dataset just once
            self._num_batch_q_threads = 1	# just one thread to batch examples
            self._bucketing_cache_size = 1 # only load one batch's worth of examples before bucketing; this essentially means no bucketing
            self._finished_reading = False # this will tell us when we're finished reading the dataset
        else:
            self._num_example_q_threads = 16 # num threads to fill example queue
            self._num_batch_q_threads = 4	# num threads to fill batch queue
            self._bucketing_cache_size = 100 # how many batches-worth of examples to load into cache before bucketing

        # Start the threads that load the queues
        self._example_q_threads = []
        for _ in range(self._num_example_q_threads):
            self._example_q_threads.append(Thread(target=self.fill_example_queue))
            self._example_q_threads[-1].daemon = True
            self._example_q_threads[-1].start()
        self._batch_q_threads = []
        for _ in range(self._num_batch_q_threads):
            self._batch_q_threads.append(Thread(target=self.fill_batch_queue))
            self._batch_q_threads[-1].daemon = True
            self._batch_q_threads[-1].start()

        # Start a thread that watches the other threads and restarts them if they're dead
        if not single_pass: # We don't want a watcher in single_pass mode because the threads shouldn't run forever
            self._watch_thread = Thread(target=self.watch_threads)
            self._watch_thread.daemon = True
            self._watch_thread.start()

    def next_batch(self):
        """Return a Batch from the batch queue.

        If mode='decode' or 'calc_features' then each batch contains a single example repeated beam_size-many times; this is necessary for beam search.

        Returns:
            batch: a Batch object, or None if we're in single_pass mode and we've exhausted the dataset.
        """
        # If the batch queue is empty, print a warning
        if self._batch_queue.qsize() == 0:
            logging.warning('Bucket input queue is empty when calling next_batch. Bucket queue size: %i, Input queue size: %i', self._batch_queue.qsize(), self._example_queue.qsize())
            if self._single_pass and self._finished_reading:
                logging.info("Finished reading dataset in single_pass mode.")
                return None

        batch = self._batch_queue.get() # get the next Batch
        return batch

    def fill_example_queue(self):
        """Reads data from file and processes into Examples which are then placed into the example queue."""

        if self._example_generator is None:
            input_gen = self.text_generator(
                data.example_generator(self._data_path, self._single_pass, self._cnn_500_dm_500, is_original=('with_coref' not in self._data_path)))
        else:
            input_gen = self.text_generator(self._example_generator)
        if self._hps.pg_mmr and self._hps.ssi_data_path != '':  # if use pg_mmr and bert
            print (util.bcolors.OKGREEN + "Loading SSI from BERT at %s" % os.path.join(self._hps.ssi_data_path, 'ssi.pkl') + util.bcolors.ENDC)
            with open(os.path.join(self._hps.ssi_data_path, 'ssi.pkl')) as f:
                ssi_triple_list = pickle.load(f)
                # ssi_list = [ssi_triple[1] for ssi_triple in ssi_triple_list]
        else:
            ssi_triple_list = None
        counter = 0
        while True:
            try:
                (article,
                 abstracts, doc_indices_str, raw_article_sents, ssi, article_lcs_paths_list) = next(input_gen)  # read the next example from file. article and abstract are both strings.
            except StopIteration:  # if there are no more examples:
                logging.info("The example generator for this example queue filling thread has exhausted data.")
                if self._single_pass:
                    logging.info(
                        "single_pass mode is on, so we've finished reading dataset. This thread is stopping.")
                    self._finished_reading = True
                    if ssi_triple_list is not None and counter < len(ssi_triple_list):
                        raise Exception('Len of ssi list (%d) is greater than number of examples (%d)' % (len(ssi_triple_list), counter))
                    break
                else:
                    raise Exception("single_pass mode is off but the example generator is out of data; error.")
            if ssi_triple_list is not None:
                if counter >= len(ssi_triple_list):
                    raise Exception('Len of ssi list (%d) is less than number of examples (>=%d)' % (len(ssi_triple_list), counter))
                ssi_length_extractive = ssi_triple_list[counter][2]
                ssi = ssi_triple_list[counter][1]
                ssi = ssi[:ssi_length_extractive]

            article = article
            abstracts = [abstract for abstract in abstracts]
            if type(doc_indices_str) != str:
                doc_indices_str = doc_indices_str
            raw_article_sents = [sent for sent in raw_article_sents]

            all_abstract_sentences = [[sent.strip() for sent in data.abstract2sents(
                abstract)] for abstract in abstracts]
            if len(all_abstract_sentences) != 0:
                abstract_sentences = all_abstract_sentences[0]
            else:
                abstract_sentences = []
            doc_indices = [int(idx) for idx in doc_indices_str.strip().split()]
            # join_separator = ' [SEP] ' if self._hps.sep else ' '
            if self._hps.by_instance:   # if we are running iteratively on only instances (a singleton/pair + a summary sentence), not the whole article
                for abs_idx, abstract_sentence in enumerate(abstract_sentences):
                    inst_ssi = ssi[abs_idx]
                    if len(inst_ssi) == 0:
                        continue
                    inst_abstract_sentences = abstract_sentence
                    inst_raw_article_sents = util.reorder(raw_article_sents, inst_ssi)
                    inst_article = ' '.join([' '.join(util.process_sent(sent, whitespace=True)) for sent in inst_raw_article_sents])
                    inst_doc_indices = [0] * len(inst_article.split())
                    inst_article_lcs_paths_list = article_lcs_paths_list[abs_idx]

                    if len(inst_article) == 0:  # See https://github.com/abisee/pointer-generator/issues/1
                        logging.warning(
                            'Found an example with empty article text. Skipping it.\n*********************************************')
                    elif len(inst_article.strip().split()) < 3 and self._hps.skip_with_less_than_3:
                        print(
                            'Article has less than 3 tokens, so skipping\n*********************************************')
                    elif len(inst_abstract_sentences.strip().split()) < 3 and self._hps.skip_with_less_than_3:
                        print(
                            'Abstract has less than 3 tokens, so skipping\n*********************************************')
                    else:
                        inst_example = Example(None, [inst_abstract_sentences], all_abstract_sentences, None, inst_raw_article_sents, None, [inst_article_lcs_paths_list], self._vocab, self._hps)
                        self._example_queue.put(inst_example)
            else:
                example = Example(None, abstract_sentences, all_abstract_sentences, None, raw_article_sents, ssi, article_lcs_paths_list, self._vocab, self._hps)  # Process into an Example.
                self._example_queue.put(example)  # place the Example in the example queue.

            # print "example num", counter
            counter += 1

    def fill_batch_queue(self):
        """Takes Examples out of example queue, sorts them by encoder sequence length, processes into Batches and places them in the batch queue.

        In decode mode, makes batches that each contain a single example repeated.
        """
        while True:

            # print 'hi'
            if self._hps.mode != 'decode' and self._hps.mode != 'calc_features':
                # Get bucketing_cache_size-many batches of Examples into a list, then sort
                inputs = []
                for _ in range(self._hps.batch_size * self._bucketing_cache_size):
                    inputs.append(self._example_queue.get())
                inputs = sorted(inputs, key=lambda inp: inp.enc_len) # sort by length of encoder sequence

                # Group the sorted Examples into batches, optionally shuffle the batches, and place in the batch queue.
                batches = []
                for i in range(0, len(inputs), self._hps.batch_size):
                    batches.append(inputs[i:i + self._hps.batch_size])
                if not self._single_pass:
                    shuffle(batches)
                for b in batches:	# each b is a list of Example objects
                    self._batch_queue.put(Batch(b, self._hps, self._vocab))

            elif self._hps.mode == 'decode': # beam search decode mode
                ex = self._example_queue.get()
                batch = preprocess_batch(ex, self._hps.batch_size, self._hps, self._vocab)
                self._batch_queue.put(batch)
            else:   # calc features mode
                inputs = []
                for _ in range(self._hps.batch_size * self._bucketing_cache_size):
                    inputs.append(self._example_queue.get())
                    # print "_ %d"%_
                # print "inputs len%d"%len(inputs)
                # Group the sorted Examples into batches, and place in the batch queue.
                batches = []
                for i in range(0, len(inputs), self._hps.batch_size):
                    # print i
                    batches.append(inputs[i:i + self._hps.batch_size])

                # if not self._single_pass:
                #     shuffle(batches)
                for b in batches:	# each b is a list of Example objects
                    self._batch_queue.put(Batch(b, self._hps, self._vocab))

    def watch_threads(self):
        """Watch example queue and batch queue threads and restart if dead."""
        while True:
            time.sleep(60)
            for idx,t in enumerate(self._example_q_threads):
                if not t.is_alive(): # if the thread is dead
                    logging.error('Found example queue thread dead. Restarting.')
                    new_t = Thread(target=self.fill_example_queue)
                    self._example_q_threads[idx] = new_t
                    new_t.daemon = True
                    new_t.start()
            for idx,t in enumerate(self._batch_q_threads):
                if not t.is_alive(): # if the thread is dead
                    logging.error('Found batch queue thread dead. Restarting.')
                    new_t = Thread(target=self.fill_batch_queue)
                    self._batch_q_threads[idx] = new_t
                    new_t.daemon = True
                    new_t.start()

    def text_generator(self, example_generator):
        """Generates article and abstract text from tf.Example.

        Args:
            example_generator: a generator of tf.Examples from file. See data.example_generator"""
        # i = 0
        while True:
            # i += 1
            e = next(example_generator) # e is a tf.Example
            abstract_texts = []
            raw_article_sents = []
            # if self._hps.pg_mmr or '_sent' in self._hps.dataset_name:
            try:
                # names_to_types = [('raw_article_sents', 'string_list'), ('similar_source_indices', 'delimited_list_of_tuples'), ('summary_text', 'string'), ('corefs', 'json'), ('article_lcs_paths_list', 'delimited_list_of_list_of_lists')]
                names_to_types = [('raw_article_sents', 'string_list'), ('similar_source_indices', 'delimited_list_of_tuples'), ('summary_text', 'string_list'), ('corefs', 'json'), ('article_lcs_paths_list', 'delimited_list_of_list_of_lists')]
                if self._hps.dataset_name == 'duc_2004':
                    names_to_types[2] = ('summary_text', 'string_list')

                # raw_article_sents, ssi, groundtruth_summary_text, corefs, article_lcs_paths_list = util.unpack_tf_example(
                #     e, names_to_types)
                raw_article_sents, ssi, groundtruth_summary_sents, corefs, article_lcs_paths_list = util.unpack_tf_example(
                    e, names_to_types)
                groundtruth_summary_text = '\n'.join(groundtruth_summary_sents)
                article_sent_tokens = [util.process_sent(sent) for sent in raw_article_sents]
                article_text = ' '.join([' '.join(sent) for sent in article_sent_tokens])
                if self._hps.dataset_name == 'duc_2004':
                    abstract_sentences = [['<s> ' + sent.strip() + ' </s>' for sent in
                                          gt_summ_text.strip().split('\n')] for gt_summ_text in groundtruth_summary_text]
                    abstract_sentences = [abs_sents[:max_dec_sents] for abs_sents in abstract_sentences]
                    abstract_texts = [' '.join(abs_sents) for abs_sents in abstract_sentences]
                else:
                    abstract_sentences = ['<s> ' + sent.strip() + ' </s>' for sent in groundtruth_summary_text.strip().split('\n')]
                    abstract_sentences = abstract_sentences[:max_dec_sents]
                    abstract_texts = [' '.join(abstract_sentences)]
                if 'doc_indices' not in e.features.feature or len(e.features.feature['doc_indices'].bytes_list.value) == 0:
                    num_words = len(article_text.split())
                    doc_indices_text = '0 ' * num_words
                else:
                    doc_indices_text = e.features.feature['doc_indices'].bytes_list.value[0]
                sentence_limit = 1 if self._hps.singles_and_pairs == 'singles' else 2
                ssi = util.enforce_sentence_limit(ssi, sentence_limit)
                ssi = ssi[:max_dec_sents]
                article_lcs_paths_list = util.enforce_sentence_limit(article_lcs_paths_list, sentence_limit)
                article_lcs_paths_list = article_lcs_paths_list[:max_dec_sents]
                ssi, article_lcs_paths_list = util.make_ssi_chronological(ssi, article_lcs_paths_list)
            except:
                logging.error('Failed to get article or abstract from example')
                raise
                # continue
            # else:
            #     try:
            #         article_text = e.features.feature['article'].bytes_list.value[0] # the article text was saved under the key 'article' in the data files
            #         for abstract in e.features.feature['abstract'].bytes_list.value:
            #             abstract_texts.append(abstract) # the abstract text was saved under the key 'abstract' in the data files
            #         if 'doc_indices' not in e.features.feature or len(e.features.feature['doc_indices'].bytes_list.value) == 0:
            #             num_words = len(article_text.split())
            #             doc_indices_text = '0 ' * num_words
            #         else:
            #             doc_indices_text = e.features.feature['doc_indices'].bytes_list.value[0]
            #         for sent in e.features.feature['raw_article_sents'].bytes_list.value:
            #             raw_article_sents.append(sent) # the abstract text was saved under the key 'abstract' in the data files
            #         ssi = None
            #         article_lcs_paths_list = None
            #     except ValueError:
            #         logging.error('Failed to get article or abstract from example\n*********************************************')
            #         raise
            #         # continue
            if len(article_text)==0: # See https://github.com/abisee/pointer-generator/issues/1
                logging.warning('Found an example with empty article text. Skipping it.\n*********************************************')
            elif len(article_text.strip().split()) < 3 and self._hps.skip_with_less_than_3:
                print('Article has less than 3 tokens, so skipping\n*********************************************')
            elif len(abstract_texts[0].strip().split()) < 3 and self._hps.skip_with_less_than_3:
                print('Abstract has less than 3 tokens, so skipping\n*********************************************')
            else:
                # print i
                yield (article_text, abstract_texts, doc_indices_text, raw_article_sents, ssi, article_lcs_paths_list)

def get_delimited_list_of_lists(example, name):
    text = get_string(example, name)
    return [[int(i) for i in (l.strip().split(' ') if l != '' else [])] for l in text.strip().split(';')]

def get_string(example, name):
    return example.features.feature[name].bytes_list.value[0]

def preprocess_example(article, groundtruth_summ_sents, doc_indices_str, raw_article_sents, article_lcs_paths_list, hps, vocab):
    if len(groundtruth_summ_sents) != 0:
        abstract_sentences = groundtruth_summ_sents[0]
    else:
        abstract_sentences = []
    doc_indices = [int(idx) for idx in doc_indices_str.strip().split()]
    example = Example(article, abstract_sentences, groundtruth_summ_sents, doc_indices, raw_article_sents, None, article_lcs_paths_list, vocab, hps)  # Process into an Example.
    return example

def preprocess_batch(ex, batch_size, hps, vocab):
    b = [ex for _ in range(batch_size)]
    batch = Batch(b, hps, vocab)
    return batch

def create_batch(article, groundtruth_summ_sents, doc_indices_str, raw_article_sents, article_lcs_paths_list, batch_size, hps, vocab):
    ex = preprocess_example(article, groundtruth_summ_sents, doc_indices_str, raw_article_sents, article_lcs_paths_list, hps, vocab)
    batch = preprocess_batch(ex, batch_size, hps, vocab)
    return batch


# coding=UTF-8

############ Import modules ##################

import function_config as fc
from time import sleep
import RPi.GPIO as GPIO             # Documentation: https://sourceforge.net/p/raspberry-gpio-python/wiki/Home/
import time                         # Documentation: https://docs.python.org/3/library/time.html
import datetime                     # Documentation: https://docs.python.org/3/library/datetime.html
import board                        # Documentation: https://pypi.org/project/board/
import adafruit_dht                 # Documentation: https://circuitpython.readthedocs.io/projects/dht/en/latest/#
import matplotlib.pyplot as plt     # Documentation: https://matplotlib.org/api/pyplot_api.html

# GPIO setup
GPIO.setwarnings(False)       # Disable warnings about pin configuration being something other than the default
GPIO.setmode(GPIO.BCM)        # Use Broadcom pinout

# Data config
#gogn = np.empty((0,7), float)   # Býr til gagnatöflu með 7 dálkum sem tekur bara við int gildum. Dálkar: [timi,hitastig,duty_cycle,tach_hall_rpm, rakastig, heater_is_on, oskgildi]
#maxDeltaT = 0.2     # Hámarks hitamismunur á seinustu mælingu og mælingunni sem var fyrir 10 mælingum til að við skilgreinum okkur við jafnvægi
#oskgildi = 20       # Óskgildið sem stýringin reynir að ná. Skilgreint við herbergishitastig og er sett upp síðar.

# Fan config
FAN_GPIO_PIN = 20       # BCM pin used to drive PWM fan
PWM_FREQ = 25000        # [Hz] 25kHz for PWM control
PWM_OFF = 0             # the PWM_duty_cycle 0%
PWM_MAX = 100           # the PWM_duty_cycle 100%
TACH_GPIO_PIN = 21      # BCM pin for reading the tachometer
tach_count_time = 2          # seconds for counting sensor changes
fan_is_on = False       # Boolean variable. False if fan is off and True if fan is on
FAN_OFF=PWM_OFF         # If no relay connection, this sets the fan speed to the lowest setting (230 RPM - https://www.arctic.ac/en/F12-PWM/AFACO-120P2-GBA01). If relay connection, use the relay to cut the power to the fan to turn it off.
last_duty_cycle = 0     # Used to know what the last duty cycle set was in order to input the value to gogn
# Setting up relay for FAN
RELAY_FAN_GPIO_PIN = 26         # BCM pin used to turn RELAY for FAN ON/OFF
GPIO.setup(RELAY_FAN_GPIO_PIN, GPIO.OUT, initial=GPIO.HIGH) # HIGH MEANS RELAY IS OFF

# PWM used to control the fan's speed
GPIO.setup(FAN_GPIO_PIN, GPIO.OUT, initial=GPIO.LOW)  # Set FAN_GPIO_PIN as output with the initial value GPIO.LOW
#fan = GPIO.PWM(FAN_GPIO_PIN,PWM_FREQ)                 # create a PWM instance called fan
# tachometer - from a hall sensor located in the fan
GPIO.setup(TACH_GPIO_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# Setting up relay for Heater
RELAY_HEATER_GPIO_PIN = 16  # BCM pin used to turn RELAY for HEATER ON/OFF
GPIO.setup(RELAY_HEATER_GPIO_PIN, GPIO.OUT, initial=GPIO.HIGH) # HIGH MEANS RELAY IS OFF
heater_is_on = False       # Boolean variable. False if heater is off and True if heater is on

# Sensor config
sensor_cache_clear_time = 2 # Hversu langan tíma við þurfum að bíða eftir því að mælirinn tæmi minnið sitt ef hann nær ekki að mæla (a.m.k. 2 sekúndur)
dhtDevice = adafruit_dht.DHT22(board.D5)
UPPHAFSHITASTIG = 0 # Upphafshitastig
hitastig = 0  # Breyta til að fylgjast með hitastigi
deltaT = 0 # breyta til að fylgjast með breyting á hitastigi
UPPHAFSRAKASTIG = 0 # Upphafsrakastig
rakastig = 0 # breyta til að fylgjast með rakastigi
deltaH = 0 # Breyta til að fylgjast með breytingu á rakastigi (e. humidity)

############ Define functions ##################
hiti = fc.measureTemp()
print('hitastig: ', hiti)

fc.fanOn()
fc.setFanSpeed(100)
time.sleep(60)
fc.setFanSpeed(0)
fc.fanOff
hiti = fc.measureTemp()
print('hitastig: ', hiti)

#----------- Núllstilla viftu og hitara í lok keyrslu -----------#
fc.setFanSpeed(0) #slokkva á viftu
fc.fanOff()
fc.heaterOff()
GPIO.cleanup() # resets all GPIO ports used by this function


from collections import namedtuple

from base import Transformer

List = namedtuple("List", "depth type")

class RstProcessor(Transformer):
    list_stack = []
    inside_frame = False

    name = "RestructuredText processor"

    # Indicates if the processor wants to proces the given file or not
    def wants(self, source):
        return source.endswith('.tex.rst')

    # Get the target file name
    def target(self, source):
        return source.replace('.tex.rst', '.tex')

    # Checks that no list is still open
    def end(self):
        if self.list_stack:
            self.logger.error("Something went wrong in list handling")

    # start a list
    def start_list(self, depth, type):
        self.list_stack.append(List(depth, type))

        if type == 1:
            self.print_line("\\begin{itemize}")
        elif type == 2:
            self.print_line("\\begin{enumerate}")

    # end the previous list
    def end_list(self):
        prev = self.list_stack[-1]

        if prev.type == 1:
            self.print_line("\\end{itemize}")
        elif prev.type == 2:
            self.print_line("\\end{enumerate}")

        self.list_stack.pop()

    # Handle a list item
    def handle_item(self, depth, type):
        if self.list_stack:
            prev = self.list_stack[-1]

            if prev.type == type:
                if prev.depth < depth:
                    self.start_list(depth, type)
                else:
                    while prev.depth > depth:
                        self.end_list()

                        if not self.list_stack:
                            break

                        prev = self.list_stack[-1]

                    if not self.list_stack:
                        self.start_list(depth, type)

            else:
                if prev.depth == depth:
                    self.end_list()
                    self.start_list(depth, type)
                elif prev.depth < depth:
                    self.start_list(depth, type)
                else:
                    while prev.depth > depth:
                        self.end_list()

                        if not self.list_stack:
                            break

                        prev = self.list_stack[-1]

                    if not self.list_stack:
                        self.start_list(depth, type)

        else:
            self.start_list(depth, type)

    # Handle lists
    def handle_lists(self, line):
        stripped = line.lstrip()

        # Compute the depth of the list based on the number of spaces
        # before the * char
        depth = len(line) - len(stripped)

        if stripped.startswith('1.'):
            self.handle_item(depth, 2)

            return "\item " + stripped.replace("1.", "", 1)

        elif stripped.startswith('*'):
            self.handle_item(depth, 1)

            return "\item " + stripped.replace("*", "", 1)

        else:
            while self.list_stack:
                self.end_list()

            return line

    # End frame
    def end_frame(self):
        if self.inside_frame:
            self.print_line("\\end{frame}")
            self.inside_frame = False

    # Handle frames
    def handle_frames(self, line):
        stripped = line.rstrip()

        if stripped.startswith('.. frame:: '):
            self.end_frame()

            frame_name = stripped.replace('.. frame:: ', "")
            self.inside_frame = True

            return "\\begin{frame}[fragile]{" + frame_name + "}"
        elif stripped.startswith('.. sframe:: '):
            self.end_frame()

            frame_name = stripped.replace('.. sframe:: ', "")
            self.inside_frame = True

            self.print_line("\section{" + frame_name + "}")

            return "\\begin{frame}[fragile]{" + frame_name + "}"
        elif stripped.startswith('.. ssframe:: '):
            self.end_frame()

            frame_name = stripped.replace('.. ssframe:: ', "")
            self.inside_frame = True

            self.print_line("\subsection{" + frame_name + "}")

            return "\\begin{frame}[fragile]{" + frame_name + "}"
        elif stripped.startswith('.. toc::'):
            toc_name = stripped.replace('.. toc::', "")
            toc_name = toc_name.strip()

            # By default full TOC is shown
            if not toc_name:
                toc_name = "main"

            if toc_name == "main":
                self.print_line("\\begin{frame}{Table of Contents}")
                self.print_line("\\tableofcontents[hidesubsections]")
                self.print_line("\\end{frame}")
            elif toc_name == "current":
                self.print_line("\\begin{frame}{Table of Contents}")
                self.print_line("\\tableofcontents[currentsection,hideothersubsections]")
                self.print_line("\\end{frame}")
            elif toc_name == "shallow":
                self.print_line("\\begin{frame}{Table of Contents}")
                self.print_line("\\begingroup");
                self.print_line("\\setcounter{tocdepth}{1}");
                self.print_line("\\tableofcontents[currentsection]");
                self.print_line("\\endgroup");
                self.print_line("\\end{frame}")

            return "";

        elif stripped.startswith('\end{document}'):
            self.end_frame()
        elif stripped.startswith('\section'):
            self.end_frame()
        elif stripped.startswith('\subsection'):
            self.end_frame()
        elif stripped.startswith('\subsubsection'):
            self.end_frame()

        return line

    # Handle some ReST style
    def handle_style(self, line, rst_begin, rst_end, latex):
        first_index = line.find(rst_begin)

        while first_index != -1:
            second_index = line.find(rst_end, first_index+len(rst_begin))

            if second_index == -1:
                break

            if second_index - first_index > len(rst_begin):
                line = line[:first_index] + \
                    "\\" + latex + "{" + \
                    line[first_index+len(rst_begin):second_index] + \
                    "}" + \
                    line[second_index+len(rst_end):]

            first_index = line.find(rst_begin, second_index+len(rst_end))

        return line

    # Handle inline code
    def handle_inline(self, line):
        return self.handle_style(line, ":code:`", "`", "cppi")

    # Handle bold
    def handle_bold(self, line):
        return self.handle_style(line, "**", "**", "textbf")

    # Handle emphasis
    def handle_emphasis(self, line):
        return self.handle_style(line, "*", "*", "textit")

    # Handle sections
    def handle_code(self, lines):
        inside_code = False

        for line in lines:
            stripped = line.rstrip()

            if stripped.startswith('.. code:: '):
                code = stripped.replace('.. code:: ', "")
                code = code.strip()

                if not code:
                    code = "cpp"

                inside_code = True

                self.print_line("%__rst_ignore__")
                self.print_line("\\begin{" + code + "code}")
            elif inside_code and not stripped.startswith('  '):
                inside_code = False
                self.print_line("\\end{" + code + "code}")
                self.print_line("%__rst_ignore__")
                self.print_line(line)
            else:
                self.print_line(line)

    # Handle sections
    def handle_sections(self, lines):
        levels = []

        ignored = False

        for i in range(len(lines) - 2):
            first_line = lines[i]
            second_line = lines[i+1]

            if "__rst_ignore__" in first_line:
                ignored = not ignored
                self.print_line(first_line)
                continue

            if ignored:
                self.print_line(first_line)
                continue

            if len(first_line) > 0 and len(second_line) > 0:
                c = 0
                char = second_line[0]
                if char in ('#', '-', '_', '*', '+'):
                    while c < len(second_line) and second_line[c] is char:
                        c = c + 1

                if c >= 3 and c <= len(first_line):
                    if char not in levels:
                        levels.append(char)

                    index = levels.index(char)

                    if index is 0:
                        self.print_line("\section{" + first_line + "}")
                    elif index is 1:
                        self.print_line("\subsection{" + first_line + "}")
                    elif index is 2:
                        self.print_line("\subsubsection{" + first_line + "}")
                    else:
                        self.print_line("Section too deep:" + first_line)

                    lines[i+1] = ""
                else:
                    self.print_line(first_line)
            else:
                self.print_line(first_line)

        # Print the very last line
        self.print_line(lines[len(lines) - 1])

    # Process a single file
    def process_lines(self, lines, step):
        ignored = False

        # Handle code blocks
        if step is 0:
            self.handle_code(lines)

            return True

        # Handle sections
        if step is 1:
            self.handle_sections(lines)

            return True

        for line in lines:
            if "__rst_ignore__" in line:
                ignored = not ignored
                self.print_line(line)
                continue

            if ignored:
                self.print_line(line)
                continue

            # Handle frames
            if step is 2:
                self.print_line(self.handle_frames(line))

            # Handle lists
            if step is 3:
                self.print_line(self.handle_lists(line))

            # Handle styles
            if step is 4:
                # Handle inline code
                processed = self.handle_inline(line)

                # Handle bold
                processed = self.handle_bold(processed)

                # Handle emphasis
                processed = self.handle_emphasis(processed)

                self.print_line(processed)

        return step < 4


import db
db = db.DB()

def list():
    ''' lists all options '''
    options = []
    def children(option):
        ''' recursively adds children to an option '''
        with db.cursor() as cur:
            cur.execute("""
            SELECT * FROM options
            WHERE parent_id = %s;""",
            (option['option_id'],))
            option['children'] = cur.fetchall()
        for child in option['children']:
            child = children(child)
        return option

    with db.cursor() as cur:
        cur.execute("""
            SELECT * FROM options
            WHERE parent_id IS NULL;""")
        options = cur.fetchall()
        for o in options:
            o = children(o)
    return options

def add(description, uom=None, component=None, parent_id=None):
    with db.cursor() as cur:
        cur.execute(
            """
            INSERT INTO options(description, uom, component, parent_id)
            VALUES(%s, %s, %s, %s)
            RETURNING option_id;""",
            (description, uom, component, parent_id))
        return cur.fetchone()['option_id']

if __name__ == "__main__":
    LEVEL = 0

    def print_op(o):
        global LEVEL
        current_level = LEVEL
        LEVEL += 1
        if not o['children']:
            LEVEL = current_level
        for child in o['children']:
            dashes = "|"
            for i in range(0, LEVEL):
                dashes += "---"
            print(dashes, child['option_id'], child['description'])
            print_op(child)

    options = list()
    for option in options:
        print(option['option_id'], option['description'])
        print_op(option)
        LEVEL = 0


import random

def encript(plaintText,key):
    enc = []
    for i in range(len(plainText)) :
        enc.append( ord(plainText[i]) + key[i] )

    return enc

def decript(encriptText,key):
    dec = []
    for i in range(len(encriptText)):
        dec.append( chr(encriptText[i] - key[i] ) )
    return ''.join(dec)

plainText = 'secret text'
key = [int(random.random()*x*100) for x in range(len(plainText))]

print('Key is {}.'.format(key))

enc = encript(plainText,key)
dec = decript(enc,key)
print('Encrypted text is: {}'.format(enc))

print('Decrypted text is: {}'.format(dec))