#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  radio.py
#
#  Copyright 2016  <pi@raspberrypi>
#
#  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 2 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, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#
#

import os
from tkinter import *

Radio1 = '"http://www.listenlive.eu/bbcradio1.m3u"'
Radio2 = '"http://www.listenlive.eu/bbcradio2.m3u"'
Radio3 = '"http://www.listenlive.eu/bbcradio3.m3u"'
Radio4 = '"http://www.listenlive.eu/bbcradio4.m3u"'
Radio5 = '"http://www.listenlive.eu/bbc5live.m3u"'
Radio6 = "'http://www.listenlive.eu/bbc6music.m3u'"
Absolute80s = "'http://network.absoluteradio.co.uk/core/audio/mp3/live.pls?service=a8bb'"
Gem106 = "'http://webradio.radiomonitor.com/m3u/Gem-128.m3u'"
Capital = "'http://media-ice.musicradio.com/CapitalMP3.m3u'"
UncleWilliamsHeartFM = "'http://media-ice.musicradio.com/HeartWatfordMP3.m3u'"

def radio1():
	change_chanel(Radio1)
	stateText.delete(0.0,END)
	stateText.insert(END, "BBC Radio 1")
def radio2():
	change_chanel(Radio2)
	stateText.delete(0.0,END)
	stateText.insert(END, "BBC Radio 2")
def radio3():
	change_chanel(Radio3)
	stateText.delete(0.0,END)
	stateText.insert(END,"BBC Radio 3")
def radio4():
	change_chanel(Radio4)
	stateText.delete(0.0,END)
	stateText.insert(END, "BBC Radio 4")
def radio5():
	change_chanel(Radio5)
	stateText.delete(0.0,END)
	stateText.insert(END, "BBC Radio 5 live")
def radio6():
	change_chanel(Radio6)
	stateText.delete(0.0,END)
	stateText.insert(END, "BBC Radio 6 Music") # display the text
def absolute80s():
	change_chanel(Absolute80s) # set the chanel
	stateText.delete(0.0,END)
	stateText.insert(END, "Absolute 80s") # display the text
def gem106():
	change_chanel(Gem106)
	stateText.delete(0.0,END)
	stateText.insert(END, "Gem 106") # display the text
def capital():
	change_chanel(Capital)
	stateText.delete(0.0,END)
	stateText.insert(END, "Capital FM") # display the text
def Heart():
	change_chanel(UncleWilliamsHeartFM)
	stateText.delete(0.0,END)
	stateText.insert(END, "Heart(Hertfordshire)") # display the text
def stop():
	os.system("killall mplayer")
	stateText.delete(0.0,END)
	stateText.insert(END, "Ready")

def change_chanel(url):
	os.system("killall mplayer")
	os.system("mplayer -playlist {0} &".format(url))
def exitRadio():
	os.system("killall mplayer")
	os._exit(0)

os.system("python3 /usr/share/pi-tab/apt-fix.py") # check if mplayer is installed - if not: install it

root = Tk() # create a window
root.title("Radio")
#############################
#                           #
#      Button Creation      #
#                           #
#############################
bs = list()
stateText = Text(root,width=17,height=1)
bs.append(stateText)
r1Button = Button(root,text="Radio1 - BBC Radio one", command=radio1)
bs.append(r1Button)
r2Button = Button(root,text="Radio2 - BBC Radio two", command=radio2)
bs.append(r2Button)
r3Button = Button(root,text="Radio3 - BBC Radio three", command=radio3)
bs.append(r3Button)
r4Button = Button(root,text="Radio4 - BBC Radio four", command=radio4)
bs.append(r4Button)
r5Button = Button(root,text="Radio5 live - BBC radio five live", command=radio5)
bs.append(r5Button)
r6Button = Button(root,text="Radio6 - BBC Radio 6 Music",command=radio6)
bs.append(r6Button)
a80sButton = Button(root,text="Absolute 80s",command=absolute80s)
bs.append(a80sButton)
gemButton = Button(root,text="Gem 106",command=gem106)
bs.append(gemButton)
capitalButton = Button(root,text="Capital FM",command=capital)
bs.append(capitalButton)
stopButton = Button(root,text="Stop playing",command=stop)
bs.append(stopButton)
exitButton = Button(root,text="Exit",command=exitRadio)
bs.append(exitButton)
for b in bs:
	b.pack()
stateText.delete(0.0,END)
stateText.insert(END,"Ready")
root.mainloop() # display the window


import json
import random
import sqlite3
import math
import itertools
from scipy.sparse import hstack
from scipy import spatial
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.neural_network import MLPClassifier
from operator import add
import datetime

def get_input_network_feature(input_list, claim_triples, evidence_triples, nlp):
	consistent_count = input_list[0]
	inconsistent_count = input_list[1]
	count = 0
	for i in claim_triples:
		count += 1
		if count > 100:
			break
		claim_entity = i[0]
		claim_noun = i[1]
		claim_verb = i[2]
		for j in evidence_triples:
			evidence_entity = j[0]
			if claim_entity == evidence_entity:
				evidence_noun = j[1]
				evidence_verb = j[2]
				if claim_noun == evidence_noun:
					if nlp(claim_verb).similarity(nlp(evidence_verb)) >= 0.5:
						consistent_count += 1
					else:
						inconsistent_count += 1
			else:
				continue
	return [consistent_count, inconsistent_count]

def get_entity_noun_verb_triples(source_sents, nlp):
	doc = nlp(source_sents)
	triple_list = [] # possible entity-noun-verb triples
	for sentence in doc.sents:
		entity_list = []
		for entity in sentence.ents:
			if entity.label_ == "CARDINAL" or entity.label_ == "ORDINAL" or entity.label_ == "DATE":
				continue
			entity_word = entity.text
			entity_list.append(entity_word.replace(".", "").replace(" ","").replace("`","").replace("\"","").replace("\'",""))

		noun_list = [] # list of nouns in a claim
		verb_list = [] # list of verbs in a claim
		if len(entity_list) == 0:
			continue
		else:
			for token in sentence:
				if "VB" in token.tag_: # extract a list of verbs
					word = token.text
					lemma = lemmatizer(word.replace(".", "").replace(" ","").replace("`","").replace("\"","").replace("\'",""), token.pos_)[0]
					verb_list.append(lemma)
				elif "NN" in token.tag_: # extract a list of nouns
					word = token.text
					lemma = lemmatizer(word.replace(".", "").replace(" ","").replace("`","").replace("\"","").replace("\'",""), token.pos_)[0]
					if nlp.vocab[lemma.lower()].is_stop: # exclude stop words
						continue
					if lemma not in entity_list:
						noun_list.append(lemma)
			if len(noun_list) == 0 or len(verb_list) == 0:
				pass
			else:
				for i in itertools.product(entity_list, noun_list, verb_list):
					if len(triple_list) > 100:
						break
					triple_list.append(i)
		if len(triple_list) > 100:
			break
	return triple_list

# connecting to sqlite3 db where indices for wikipedia pages are stored
# the indices have been stored using "data_processing.py" included in the repository
# these indices will be used when retrieving relevant data for fact checking tasks
conn = sqlite3.connect('fever.db')
cursor = conn.cursor()
# a process for collecing index information of gold standard evidence at a documnet level
# it is for extracting a vocabulary, from the training data, for the word vector (i.e., 5000 most frequently appearing words) used in this algorithm
train_file = open('train.jsonl', "r") # open a file containing training data
train_wiki_page_index_set = set() # a set-typed variable to store the indices of wiki pages in the training data
for line in train_file:
	json_data = json.loads(line) # parse each line (or data point) as a json-typed element
	if json_data["label"] == "NOT ENOUGH INFO": # data points labeled as "NOT ENOUGH INFO" do not have corresponding gold standard documents, and thus no use for extracting the word vector
		continue
	for i in json_data["evidence"]:
		for j in i:
			cursor.execute("SELECT file_num, line_num FROM evidence_index WHERE id = ?", (j[2],)) # from the index db, we select the file number and the line number for correspodning document
			# exception handling for spanish characters with accents
			# this issue will be resolved in a later version
			try:
				temp = cursor.fetchone()
				file_num = temp[0]
				line_num = temp[1]
				train_wiki_page_index_set.add((file_num,line_num))
			except:
				continue
print("done extracting an initial set of vocabulary")

training_data_for_vocabulary = []
for element in train_wiki_page_index_set:
	file_num = element[0]
	line_num = element[1]
	if file_num < 10:
		file = open("wiki-00"+str(element[0])+".jsonl", "r")
	elif file_num < 100:
		file = open("wiki-0"+str(element[0])+".jsonl", "r")
	else:
		file = open("wiki-"+str(element[0])+".jsonl", "r")
	line_num_count = 1
	for line in file:
		if line_num_count == line_num:
			json_data = json.loads(line)
			training_data_for_vocabulary.append(json_data["text"])
			break # break the loop for searching documnets when the targeted one is retrieved
		else:
			pass
		line_num_count += 1

# Since, in the original baseline paper, the authors used both TF and TF-IDF vectors, we estimate them separtely
tfvectorizer = TfidfVectorizer(stop_words='english', max_features=5000, use_idf = False) # vectorizer for TF
tfidfvectorizer = TfidfVectorizer(stop_words='english', max_features=5000, use_idf = True) # vectorizer for TF-IDF
tfvectorizer.fit(training_data_for_vocabulary)
tfidfvectorizer.fit(training_data_for_vocabulary)
print("done word vectorization")

# packages needed for deriving sentiment features
import spacy
from spacy.lemmatizer import Lemmatizer
from spacy.lang.en import LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES
lemmatizer = Lemmatizer(LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES)
nlp = spacy.load('en_core_web_lg')

# count the number of support-labeled, refute-labeled, and not-enough-info-labled claims for a post-anlaysis
support_count = 0
refute_count = 0
not_enough_info_count = 0

# each input contains the TF vectors of a claim and its evidences in a concatenated manner
# and the cosine similarity of the TF-IDF vectors of the claim and the evidences
X_train = []
# each output can be classified into 0=support, 1=refute, and 2=not-enough-info
y_train = []
exception_count = 0
train_file = open('train.jsonl', "r")
process_count = 0
for line in train_file:
	print(process_count, datetime.datetime.now())
	process_count += 1
	json_data = json.loads(line)
	claim_label = json_data["label"]
	# sentiment features of words in the claim_label
	# extract entities, nouns, and verbs from a claim
	claim_triple_list = get_entity_noun_verb_triples(json_data["claim"], nlp)

	network_input = [0,0] #initialize network input

	# vecotrize a claim with the pretrained TF and TF-IDF vectors
	claim_tf = tfvectorizer.transform([json_data["claim"]])
	claim_tfidf = tfidfvectorizer.transform([json_data["claim"]])
	try:
		evidence_text = []
		# for each claim whose gold label is "NOT ENOUGH INFO", we randonly generate three evidences since they do not have gold evidences
		if json_data["label"] == "NOT ENOUGH INFO":
			for i in range(3):
				random_file_num = random.randint(1,109)
				if random_file_num < 10:
					evidence_file = open("wiki-00"+str(random_file_num)+".jsonl", "r")
				elif random_file_num < 100:
					evidence_file = open("wiki-0"+str(random_file_num)+".jsonl", "r")
				else:
					evidence_file = open("wiki-"+str(random_file_num)+".jsonl", "r")
				max_count = 0
				for i in evidence_file:
					max_count += 1
				random_line_num = random.randint(0, max_count)

				if random_file_num < 10:
					evidence_file = open("wiki-00"+str(random_file_num)+".jsonl", "r")
				elif random_file_num < 100:
					evidence_file = open("wiki-0"+str(random_file_num)+".jsonl", "r")
				else:
					evidence_file = open("wiki-"+str(random_file_num)+".jsonl", "r")
				count = 1
				for evidence_line in evidence_file:
					if count == random_line_num:
						evidence_data = json.loads(evidence_line)
						evidence_text.append(evidence_data["text"])
						result_triple_list = get_entity_noun_verb_triples(evidence_data["text"], nlp)
						if len(result_triple_list) == 0:
							continue
						else:
							network_input = get_input_network_feature(network_input, claim_triple_list, result_triple_list, nlp)
					else:
						pass
					count += 1

		# for each claim whose gold label is either "SUPPORT" or "REFUTE", we retreived gold documents
		else:
			for i in json_data["evidence"]:
				evidence_count = 0 # limit the number of gold evidences attached to a claim to three
				for j in i:
					cursor.execute("SELECT file_num, line_num FROM evidence_index WHERE id = ?", (j[2],))
					temp = cursor.fetchone()
					file_num = temp[0]
					line_num = temp[1]
					if file_num < 10:
						evidence_file = open("wiki-00"+str(file_num)+".jsonl", "r")
					elif file_num < 100:
						evidence_file = open("wiki-0"+str(file_num)+".jsonl", "r")
					else:
						evidence_file = open("wiki-"+str(file_num)+".jsonl", "r")
					count = 1
					for evidence_line in evidence_file:
						if count == line_num:
							evidence_data = json.loads(evidence_line)
							evidence_text.append(evidence_data["text"])
							result_triple_list = get_entity_noun_verb_triples(evidence_data["text"], nlp)
							if len(result_triple_list) == 0:
								continue
							else:
								network_input = get_input_network_feature(network_input, claim_triple_list, result_triple_list, nlp)
						else:
							pass
						count += 1
					evidence_count += 1
				if evidence_count == 3:
					break
		# concantenate multiple evidences
		evidence_concat = ""
		for ev in evidence_text:
			evidence_concat += (" " + ev)
		# vecotrize evidences with the pretrained TF and TF-IDF vectors
		evidence_tf = tfvectorizer.transform([evidence_concat])
		evidence_tfidf = tfidfvectorizer.transform([evidence_concat])
		# estimate TF-IDF cosine similarity of the claim and the evidence vetors
		tfidf_cosine_similarity = 1 - spatial.distance.cosine(claim_tfidf.toarray(), evidence_tfidf.toarray())
		if math.isnan(tfidf_cosine_similarity):
			tfidf_cosine_similarity = 0
		# concatenation input vectors into one
		tf_vector = hstack((claim_tf, evidence_tf))
		input_vector = hstack((tf_vector, [tfidf_cosine_similarity], network_input))
		# append the final input vector
		X_train.append(input_vector.toarray()[0]) # take the first element since the "toarray()" returns 2-dim data strucute when 1-dim is needed
		# append the corresponding output
		if claim_label == "SUPPORTS":
			y_train.append(0)
			support_count += 1
		elif claim_label == "REFUTES":
			y_train.append(1)
			refute_count += 1
		else:
			y_train.append(2)
			not_enough_info_count += 1
	except Exception as e:
		print(e,json_data["claim"])
		exception_count += 1

print("done training data preparation")

# train a multi-layer perceptron
mlp = MLPClassifier()
mlp.fit(X_train, y_train)
print("done mlp model fitting")

# prepare test data
# same process for preparing training data
# for understanding the codes, refer to the comments on the codes for training data preparation
test_support_count = 0
test_refute_count = 0
test_not_enough_info_count = 0
X_test = []
y_test = []
test_exception_count = 0
test_file = open('test.jsonl', "r")
for line in test_file:
	json_data = json.loads(line)
	claim_label = json_data["label"]
	# sentiment features of words in the claim_label
	# extract entities, nouns, and verbs from a claim
	claim_triple_list = get_entity_noun_verb_triples(json_data["claim"], nlp)

	network_input = [0,0] #initialize network input

	# vecotrize a claim with the pretrained TF and TF-IDF vectors
	claim_tf = tfvectorizer.transform([json_data["claim"]])
	claim_tfidf = tfidfvectorizer.transform([json_data["claim"]])
	try:
		evidence_text = []
		# for each claim whose gold label is "NOT ENOUGH INFO", we randonly generate three evidences since they do not have gold evidences
		if json_data["label"] == "NOT ENOUGH INFO":
			for i in range(3):
				random_file_num = random.randint(1,109)
				if random_file_num < 10:
					evidence_file = open("wiki-00"+str(random_file_num)+".jsonl", "r")
				elif random_file_num < 100:
					evidence_file = open("wiki-0"+str(random_file_num)+".jsonl", "r")
				else:
					evidence_file = open("wiki-"+str(random_file_num)+".jsonl", "r")
				max_count = 0
				for i in evidence_file:
					max_count += 1
				random_line_num = random.randint(0, max_count)

				if random_file_num < 10:
					evidence_file = open("wiki-00"+str(random_file_num)+".jsonl", "r")
				elif random_file_num < 100:
					evidence_file = open("wiki-0"+str(random_file_num)+".jsonl", "r")
				else:
					evidence_file = open("wiki-"+str(random_file_num)+".jsonl", "r")
				count = 1
				for evidence_line in evidence_file:
					if count == random_line_num:
						evidence_data = json.loads(evidence_line)
						evidence_text.append(evidence_data["text"])
						result_triple_list = get_entity_noun_verb_triples(evidence_data["text"], nlp)
						if len(result_triple_list) == 0:
							continue
						else:
							network_input = get_input_network_feature(network_input, claim_triple_list, result_triple_list, nlp)
					else:
						pass
					count += 1

		# for each claim whose gold label is either "SUPPORT" or "REFUTE", we retreived gold documents
		else:
			for i in json_data["evidence"]:
				evidence_count = 0 # limit the number of gold evidences attached to a claim to three
				for j in i:
					cursor.execute("SELECT file_num, line_num FROM evidence_index WHERE id = ?", (j[2],))
					temp = cursor.fetchone()
					file_num = temp[0]
					line_num = temp[1]
					if file_num < 10:
						evidence_file = open("wiki-00"+str(file_num)+".jsonl", "r")
					elif file_num < 100:
						evidence_file = open("wiki-0"+str(file_num)+".jsonl", "r")
					else:
						evidence_file = open("wiki-"+str(file_num)+".jsonl", "r")
					count = 1
					for evidence_line in evidence_file:
						if count == line_num:
							evidence_data = json.loads(evidence_line)
							evidence_text.append(evidence_data["text"])
							result_triple_list = get_entity_noun_verb_triples(evidence_data["text"], nlp)
							if len(result_triple_list) == 0:
								continue
							else:
								network_input = get_input_network_feature(network_input, claim_triple_list, result_triple_list, nlp)
						else:
							pass
						count += 1
					evidence_count += 1
				if evidence_count == 3:
					break
		evidence_concat = ""
		for ev in evidence_text:
			evidence_concat += (" " + ev)
		evidence_tf = tfvectorizer.transform([evidence_concat])
		evidence_tfidf = tfidfvectorizer.transform([evidence_concat])
		tfidf_cosine_similarity = 1 - spatial.distance.cosine(claim_tfidf.toarray(), evidence_tfidf.toarray())
		if math.isnan(tfidf_cosine_similarity):
			tfidf_cosine_similarity = 0
		tf_vector = hstack((claim_tf, evidence_tf))
		input_vector = hstack((tf_vector, [tfidf_cosine_similarity], network_input))
		X_test.append(input_vector.toarray()[0])

		if claim_label == "SUPPORTS":
			y_test.append(0)
			test_support_count += 1
		elif claim_label == "REFUTES":
			y_test.append(1)
			test_refute_count += 1
		else:
			y_test.append(2)
			test_not_enough_info_count += 1
	except Exception as e:
		print(e, json_data["claim"])
		test_exception_count += 1
print("done test data preparation")

print(exception_count, test_exception_count)
print(support_count, refute_count, not_enough_info_count) # distribution of outcomes in training data
print(test_support_count, test_refute_count, test_not_enough_info_count) # distribution of outcomes in test datda
print(mlp.score(X_test, y_test)) # accuary of the model
# for error analysis, write out prediction restuls in a separate text file
X_predicted = mlp.predict(X_test)
result = open("result_network_fast_part_unnormalized.txt", "w")
for i in range(len(X_predicted)):
	result.write(str(X_predicted[i]) + "\t" + str(y_test[i]) + "\n")


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 24 20:33:43 2019
@author: calsoft
"""

from flask_restful import Api,Resource # some class is a resource
from flask import Flask, jsonify
from flask import request
app = Flask(__name__)
api = Api(app)

@app.route("/")
def main_page():
    txt = "This is a simple calculator api having following function: \
           Add,Subtract,Multiply,Divide "
    return txt

def check_data(data,func_name):
    if (func_name == "Add" or func_name == "Sub" or func_name == "Mul"):
        if ("x" not in data or "y" not in data):
            return 301
        else:
            return 200
    if (func_name == "Div"):
        if ("x" not in data or "y" not in data):
            return 301
        elif int(data["y"]) == 0:
            return 302
        else:
            return 200

class Add(Resource):
      def post (self):
          data = request.get_json()
          a = check_data(data,"Add")
          if (a!=200):
              retjson={
                      'Message'   : "Missing Value" ,
                      'Status'    : a
                      }
              return jsonify(retjson)

          else:
              x = int(data["x"])
              y = int(data["y"])
              z = x+y
              retz = {
                       'Message'   : z ,
                       'Status'    : 200
           }
          return jsonify(retz)

class Sub(Resource):
      def post (self):
          data = request.get_json()
          a = check_data(data,"Sub")
          if (a!=200):
              retjson={
                      'Message'   : "Missing Value" ,
                      'Status'    : a
                      }
              return jsonify(retjson)

          else:
              x = int(data["x"])
              y = int(data["y"])
              z = x-y
              retz = {
                       'Message'   : z ,
                       'Status'    : 200
           }
          return jsonify(retz)

class Mul(Resource):
      def post (self):
          data = request.get_json()
          a = check_data(data,"Mul")
          if (a!=200):
              retjson={
                      'Message'   : "Missing Value" ,
                      'Status'    : a
                      }
              return jsonify(retjson)

          else:
              x = int(data["x"])
              y = int(data["y"])
              z = x*y
              retz = {
                       'Message'   : z ,
                       'Status'    : 200
           }
          return jsonify(retz)

class Div(Resource):
      def post (self):
          data = request.get_json()
          a = check_data(data,"Div")
          if (a!=200):
              retjson={
                      'Message'   : "Missing Value" ,
                      'Status'    : a
                      }
              return jsonify(retjson)

          else:
              x = int(data["x"])
              y = int(data["y"])
              z = x/y
              retz = {
                       'Message'   : z ,
                       'Status'    : 200
           }
          return jsonify(retz)

api.add_resource(Add,"/Add")
api.add_resource(Sub,"/Sub")
api.add_resource(Mul,"/Mul")
api.add_resource(Div,"/Div")

if __name__ == "__main__" :
    app.run(host="0.0.0.0",port=8909 ,debug=True)


"""________________________________________________________________
-------------------------------------------------------------------
Program:        Text editor
Author:         Tyler Jusczak
Date Modified : 11/06/20
Version :       1.0
Purpose:

    Simulate a deck of cards with images. Deal, shuffle, and get a new deck.

___________________________________________________________________
-------------------------------------------------------------------"""
from breezypythongui import EasyFrame
from tkinter import PhotoImage
from deck import Deck

class CardDemo(EasyFrame):

    def __init__(self):
        """Creates the dice, and sets up the Images and labels
        for the two dice to be displayed, the state label,
        and the two command buttons."""
        EasyFrame.__init__(self, title = "Card Demo")
        self.setSize(220, 200)
        self.mainDeck = Deck()
        self.dealtCard = "b"

        self.cardPanel = self.addPanel(row = 0, column = 0)

        self.deckLabel1 = self.cardPanel.addLabel("", row = 0,
                                       column = 0,
                                       sticky = "NSEW")
        self.stateLabel = self.cardPanel.addLabel("", row = 1, column = 0,
                                        sticky = "NSEW",
                                        columnspan = 2)

        self.buttonPanel = self.addPanel(row = 1, column = 0)
        self.buttonPanel.addButton(row = 2, column = 0,
                       text = "Deal",
                       command = self.deal)
        self.buttonPanel.addButton(row = 2, column = 1,
                       text = "Shuffle",
                       command = self.shuffle)
        self.buttonPanel.addButton(row = 2, column = 2,
                       text = "New deck",
                       command = self.newDeck)

        self.refreshImages()

    def deal(self):
        """Displays the top card and removes it from the deck"""
        self.dealtCard = self.mainDeck.deal()
        self.refreshImages()

    def shuffle(self):
        self.mainDeck.shuffle()
        self.refreshImages()

    def newDeck(self):
        self.mainDeck.reset()
        self.dealtCard = "b"
        self.refreshImages()

    def refreshImages(self):
        """Updates the images in the window."""
        fileName1 = "DECK/" + str(self.dealtCard) + ".gif"
        self.image1 = PhotoImage(file = fileName1)
        self.deckLabel1["image"] = self.image1
        if self.dealtCard != "b":
            print(self.dealtCard)
            self.stateLabel["text"] = self.mainDeck.getName(str(self.dealtCard))

def main():
    CardDemo().mainloop()

if __name__ == "__main__":
    main()


#   The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

#   Find the sum of all the primes below two million.

import datetime;
import math;

def timer_function(f):
    startTime = datetime.datetime.now();
    f();
    endTime = datetime.datetime.now();
    c = endTime - startTime;
    print ("Sec: ", c.seconds, "Mic: ", c.microseconds);

N = 2000000
array = [z for z in range(0, N)];
array[0] = 0;
array[1] = 0;

# [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]    generate
# [1, 1, 2, 3, 1, 5, 1, 7, 1, 9,  1, 11,  1, 13,  1, 15,  1, 17,  1, 19]    remove 2s
# [1, 1, 2, 3, 1, 5, 1, 7, 1, 1,  1, 11,  1, 13,  1,  1,  1, 17,  1, 19]    remove 3s

limit = math.sqrt(N);

for z in range(2,math.ceil(limit)):
    for y in range(z + z, N, z):
        array[y] = 0;
#    print (array);

print (sum(array));


"""This file is used for the visualization of the trends in Greenhouse Gases
and carbon emissions.
Resources:
- https://www.geeksforgeeks.org/box-plot-in-python-using-matplotlib/
- https://www.kite.com/python/answers/how-to-color-a-scatter-plot-by-category-using-matplotlib-in-python
- https://plotly.com/python/box-plots/
- https://towardsdatascience.com/how-to-create-an-animated-choropleth-map-with-less-than-15-lines-of-code-2ff04921c60b
"""
from typing import List

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
import plotly.graph_objects as go
import plotly.express as px

from data_manager import Dataset, group_by_values

def data_by_tags_country_year(filepath: str,
                              tags: List[str],
                              countries_or_years: list,
                              country_or_year: int) -> List[List[float]]:
    """The function would take in the filepath of the dataset from which it would extract the data
    convert every variable in the row into its appropriate datatype and then filter out the data
    containing only the tags we want, and only for the countries or years we want, and then return
    emission values separately for all the countries or years.

    @param filepath: the path of the dataset
    @param tags: list of all the categories of emissions we want in the data
    @param countries_or_years: The countries or years for which we want the data
    @param country_or_year: 0 or 1 based on if we want to categorise by country or year
    @return: Return a list containing lists for every countries emission value
    """

    # extract dataset and covert all variables into their respective datatype
    dataset = Dataset(filepath=filepath, types=[str, int, float, str])

    # keeping rows with tags we want
    dataset.filter_by_value(3, tags)

    # splitting by countries
    grouped_data = group_by_values(dataset, country_or_year)

    # Extracting emission values for the countries we want to analyze
    countries_so_far = []

    for county in countries_or_years:
        county_data = grouped_data[county]
        countries_so_far.append(county_data.extract_column(2))

    return countries_so_far

def data_by_tags(filepath: str,
                 tags: List[str],
                 country_filter: List[str] = None,
                 year_filter: List[int] = None) -> List[List]:
    """The function would take in the filepath of the dataset from which it would extract the data
    convert every variable in the row into its appropriate datatype and then filter out the data
    containing only the tags we want, and return the emission values along side the respective
    country and year.

    We can pass in optional lists to only get rows with specific country or year

    @param filepath: the path of the dataset
    @param tags: list of all the categories of emissions we want in the data
    @param country_filter: list of countries we want data for
    @param year_filter: list of years we want data for
    @return: Return a list with emission value alongside the respective country and year
    """

    # extract dataset and covert all variables into thir respective datatype
    dataset = Dataset(filepath=filepath, types=[str, int, float, str])

    # keeping rows with tags we want
    dataset.filter_by_value(3, tags)

    # filtering countries and years
    if country_filter:
        dataset.filter_by_value(0, country_filter)
    if year_filter:
        dataset.filter_by_value(1, year_filter)

    # extract the values, countries and years
    values = dataset.extract_column(2)
    countries = dataset.extract_column(0)
    year = dataset.extract_column(1)

    return [values, countries, year]

def tidy_gdp_data(filepath: str) -> Dataset:
    """Transform the data for plotting purposes. It will remove all the columns with year before 1990 and
    after 2016, and convert columns to their respective data type.

    :param filepath: path of the dataset
    :return: transformed dataset object
    """
    # loading data
    raw_data = Dataset(filepath)

    # creating new dataset object
    data = Dataset(dataset=[])

    # making the data tidy
    for row in raw_data.get():
        for element_index in range(4, len(row)):

            value = row[element_index]
            year = 1960 + element_index - 4

            if 1990 <= year <= 2016:
                data.push([row[0], row[1], row[2], row[3], year, value])

    data.remove_na()

    data.transform([str, str, str, str, int, float])

    return data

# Plot1
def plot_all_countries_peryear(filepath: str) -> None:
    """ Plots 5 boxplots showing amount of nitrogen triflouride (NF3) emissions (kilotonnes) in all
    countries taken together over the years 2010, 2011, 2012, 2013 and 2014.

    Through this visualization, it is easier to understand correlation of how increased development
    has affected Nitrogen Triflouride emissions in recent years.

    @param filepath: the path of the dataset
    """

    years = [2010, 2011, 2012, 2013, 2014]

    tags = ['nitrogen_trifluoride_nf3_emissions_in_kilotonne_co2_equivalent']

    data = data_by_tags_country_year(filepath, tags, years, 1)
    x1 = np.array(data[0])  # NF3 emissions for all countries in 2010
    x2 = np.array(data[1])  # NF3 emissions for all countries in 2011
    x3 = np.array(data[2])  # NF3 emissions for all countries in 2012
    x4 = np.array(data[3])  # NF3 emissions for all countries in 2013
    x5 = np.array(data[4])  # NF3 emissions for all countries in 2014

    plt.boxplot((x1, x2, x3, x4, x5), notch=False, sym="o", labels=["2010",
                                                                    "2011",
                                                                    "2012",
                                                                    "2013",
                                                                    "2014"])
    plt.xlabel("Region/Country", fontsize=15)
    plt.ylabel("Aggregated Emissions of Gases (in kilotonnes) ", fontsize=9)

    plt.title("Aggregated Nitrogen Triflouride emissions for 5 years (from all countries) ",
              fontsize=10,
              fontweight="bold")

    plt.show()

# Plot2
def plot_scatter_n2o(filepath: str) -> None:
    """Plots a scatterplot showing amount of nitrous oxide (N2O) emissions (kilotonnes) in USA,
    Canada and the European Union each year (between 1990 and 2014).

    This helps us to understand trends of nitrous oxide emissions in 3 countries with very
    different demographics. (Canada - Low population Density, EU - Higher Population Density,
    USA - Large scale industrialization)

    @param filepath: the path of the dataset
    """

    countries = ['Canada', 'United States of America', 'European Union']

    tags = [
        'nitrous_oxide_n2o_emissions_without_land_use_land_use_change_and_forestry_lulucf_in_kilotonne_co2_equivalent']

    data = data_by_tags(filepath, tags, country_filter=countries)

    y = data[0]  # emission data
    labels = data[1]  # list of countries
    x = data[2]  # list of years

    data = pd.DataFrame({"X Value": x, "Y Value": y, "Category": labels})

    groups = data.groupby("Category")  # to group the data by region/country

    for name, group in groups:
        plt.plot(group["X Value"], group["Y Value"], marker="o", linestyle="-", label=name)

    plt.xlabel("Years", fontsize=15)
    plt.ylabel("Emissions of Gases (in kilotonnes)", fontsize=15)
    plt.title("Nitrous Oxide emissions each year")
    plt.legend()
    plt.show()

# Plot3
def scatterboxplot_sparsely_pop(filepath: str) -> None:
    """ Plots a scatterplot and a box plot together showing distribution of amount of carbon
    dioxide (CO2) emissions (kilotonnes) in Austria, Belarus and Bulgaria in the 24 year period
    (between 1990 and 2014).

    This plot studies and visualizes details of total carbon dioxide emissions in sparsely
    populated countries. The scatterplot shows each year's emissions data for the 3 aforementioned
    countries and the boxplot aggregates and visualizes this data.

    @param filepath: the path of the dataset
    """
    countries = ['Austria', 'Belarus', 'Bulgaria']

    tags = [
        'carbon_dioxide_co2_emissions_without_land_use_land_use_change_and_forestry_lulucf_in_kilotonne_co2_equivalent']

    data = data_by_tags_country_year(filepath, tags, countries, 0)

    y0 = data[0]
    y1 = data[1]
    y2 = data[2]

    emission_values = [y0, y1, y2]

    colors = ['rgba(93, 164, 214, 0.5)', 'rgba(255, 144, 14, 0.5)', 'rgba(44, 160, 101, 0.5)',
              'rgba(255, 65, 54, 0.5)', 'rgba(207, 114, 255, 0.5)', 'rgba(127, 96, 0, 0.5)']

    fig = go.Figure()

    for xd, yd, cls in zip(countries, emission_values, colors):
        fig.add_trace(go.Box(
            y=yd,
            name=xd,
            boxpoints='all',
            jitter=0.5,
            whiskerwidth=0.2,
            fillcolor=cls))

    fig.update_layout(
        title='Carbon Dioxide (CO2) Emissions in kilotonnes for 3 sparsely populated countries (from 1990 - 2014)',
        margin=dict(
            l=40,
            r=30,
            b=80,
            t=100),
        paper_bgcolor='rgb(243, 243, 243)',
        plot_bgcolor='rgb(243, 243, 243)',
        showlegend=False
    )

    fig.show()

# Plot4
def plot_scatter_boxplot_1990_2014(filepath: str) -> None:
    """Plots a scatterplot and a box plot together showing distribution of hydrofluorocarbon (hfcs)
    emissions in 1990, 2002 and 2014 (in all countries taken together).

    This tells us about trends of changes in hydroflourocarbon emissions in 1990, 2002 and 2014.
    This helps to correlate increased industrialization over the years with release of more
    pollutants. The scatterplot shows each country's emissions data for the 3 aforementioned years
    and the boxplot aggregates and visualizes this data.

    @param filepath: the path of the dataset
    """
    years = [1990, 2002, 2014]

    tags = ['hydrofluorocarbons_hfcs_emissions_in_kilotonne_co2_equivalent']

    data = data_by_tags_country_year(filepath, tags, years, 1)

    y0 = data[0]
    y1 = data[1]
    y2 = data[2]

    emission_values = [y0, y1, y2]

    colors = ['rgba(93, 164, 214, 0.5)', 'rgba(255, 144, 14, 0.5)', 'rgba(44, 160, 101, 0.5)',
              'rgba(255, 65, 54, 0.5)', 'rgba(207, 114, 255, 0.5)', 'rgba(127, 96, 0, 0.5)']

    fig = go.Figure()

    for xd, yd, cls in zip(years, emission_values, colors):
        fig.add_trace(go.Box(
            y=yd,
            name=xd,
            boxpoints='all',
            jitter=0.5,
            whiskerwidth=0.2,
            fillcolor=cls))

    fig.update_layout(
        title='Hydrofluorocarbon (hfcs) Emissions in kilotonnes by all countries (aggregated together) '
              'for 1990, 2002, 2014 ',
        margin=dict(
            l=40,
            r=30,
            b=80,
            t=100),
        paper_bgcolor='rgb(243, 243, 243)',
        plot_bgcolor='rgb(243, 243, 243)',
        showlegend=False
    )

    fig.show()

def plot_emission_per_gdp(filepath: str) -> None:
    """Plots a Choropleth map showing the distribution of CO2 emissions (kg per PPP $ of GDP)
    for all countries in the dataset.

    @param filepath:the path of the dataset
    """
    data = tidy_gdp_data(filepath)

    df = pd.DataFrame({'country': data.extract_column(0),
                       'code': data.extract_column(1),
                       'year': data.extract_column(4),
                       'CO2 emissions (kg per PPP $ of GDP)': data.extract_column(5)})

    fig = px.choropleth(df,
                        locations='country',
                        color='CO2 emissions (kg per PPP $ of GDP)',
                        animation_frame='year',
                        locationmode='country names',
                        scope='world',
                        range_color=(min(data.extract_column(5)), max(data.extract_column(5))),
                        title='CO2 emissions (kg per PPP $ of GDP) by country',
                        height=600
                        )

    fig.show()

def dist_2016(filepath: str) -> None:
    """The function plots a pie chart for percentage contribution of different
    countries for CO2 emissions (kg per PPP $ of GDP) for 2016.

    @param filepath: path of teh dataset
    """
    data = tidy_gdp_data(filepath)

    data.filter_by_value(4, [2016])

    total_in_world = sum(data.extract_column(5))

    values = [value / total_in_world for value in data.extract_column(5)]

    df = pd.DataFrame({'country': data.extract_column(0),
                       'code': data.extract_column(1),
                       'year': data.extract_column(4),
                       'CO2 emissions (kg per PPP $ of GDP)': values})

    fig = px.pie(df,
                 values='CO2 emissions (kg per PPP $ of GDP)',
                 names='country'
                 )

    fig.show()

if __name__ == '__main__':
    import python_ta

    python_ta.check_all(config={
        'extra-imports': ['plotly.express',
                          'plotly.graph_objects',
                          'matplotlib.pyplot',
                          'typing',
                          'data_manager',
                          'numpy',
                          'pandas'],
        'allowed-io': [],
        'max-line-length': 150,
        'disable': ['R1705', 'C0200']
    })


# -*- coding: utf-8 -*-
from datetime import timedelta, datetime
from openerp import models, fields, api, exceptions, _
from openerp.exceptions import ValidationError
from dateutil.relativedelta import relativedelta
from openerp.osv import osv
import openerp.addons.decimal_precision as dp
import time
import tools

class academic_year(models.Model):
    _name = 'oschool.academic_year'
    _rec_name = 'code'

    name = fields.Char(string="Designation", required=True)
    code = fields.Char(string="Code", required=True)
    date_start = fields.Date(string="Start Date", required=True)
    date_stop = fields.Date(string="End Date", required=True)
    period_ids = fields.Many2many('account.period', string="Period")
    company_id = fields.Many2one('res.company', 'Company')
    state = fields.Selection([
                                 ('new', "New"),
                                 ('current', "Current"),
                                 ('closed', "Closed"),
                             ], default='new')

    def _generate_periods(self,cr,uid, date_start,date_stop, context=None):
        current_user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
        periods = self.pool.get('account.period').search(cr,uid,[('date_start','>=',date_start),('date_start','<=',date_stop), ('code','not ilike','00'),('company_id','=',current_user.company_id.id)])
        tmp =[]
        for period in periods:
            tmp.append(period)
        return [[6, False, tmp]]

    def create(self, cr, uid, vals, context=None):

        date_start = datetime.strptime(vals['date_start'], '%Y-%m-%d')
        date_stop = datetime.strptime(vals['date_stop'], '%Y-%m-%d')
        dat_start = "%s-%s-01" % (date_start.year,date_start.month)
        date_stop = "%s-%s-01" % (date_stop.year,date_stop.month)
        vals['period_ids'] = self._generate_periods(cr,uid,dat_start,date_stop)
        current_user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
        current = self.search(cr, uid, [('state', '=', 'new'),('company_id','=', current_user.company_id.id)], context=context)
        if len(current) > 0:
            raise ValidationError("School year with the new state already exist")
        new_id = super(academic_year, self).create(cr, uid, vals, context=context)
        return new_id

    def write(self, cr, uid, ids, values, context = None):

        if values.has_key('date_start'):
            date_start = datetime.strptime(values['date_start'], '%Y-%m-%d')
        else:
            for fy in self.browse(cr, uid, ids, context=context):
                date_start = datetime.strptime(fy.date_start, '%Y-%m-%d')
        if values.has_key('date_stop'):
            date_stop = datetime.strptime(values['date_stop'], '%Y-%m-%d')
        else:
            for fy in self.browse(cr, uid, ids, context=context):
                date_stop = datetime.strptime(fy.date_stop, '%Y-%m-%d')

        dat_start = "%s-%s-01" % (date_start.year,date_start.month)
        date_stop = "%s-%s-01" % (date_stop.year,date_stop.month)
        values['period_ids'] =  self._generate_periods(cr,uid,dat_start,date_stop)
        res = super(academic_year, self).write(cr, uid, ids, values, context = context)
        return res

    def action_new(self, cr, uid, ids, context=None):
        current_user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
        current = self.search(cr, uid, [('state', '=', 'new'),('company_id','=',current_user.company_id.id)])
        if len(current) > 0:
            raise ValidationError("School year with the new state already exist")
        return self.write(cr, uid, ids, {'state': 'new'})

    def action_current(self, cr, uid, ids, context=None):
        return self.write(cr, uid, ids, {'state': 'current'})

    def action_closed(self, cr, uid, ids, context=None):
        return self.write(cr, uid, ids, {'state': 'closed'})

    _sql_constraints = [
        ('code_unique',
         'UNIQUE(code,company_id)',
         "The code must be unique"),
        ('name_unique',
         'UNIQUE(name,company_id)',
         "The name must be unique"),
        ('check_date',
         'CHECK(date_start < date_stop)',
         "Start Date Must be Below End Date"),
    ]

    _defaults = {
        'company_id': tools.get_default_company,
    }

class groups(models.Model):
    _name = 'oschool.groups'

    name = fields.Char(string="Group designation", required=True)
    code = fields.Char(string="Code", required=True)
    number_of_places = fields.Integer(string="Number of places", required=True)
    class_ids = fields.One2many('oschool.classes', 'code', 'Classes')
    seq = fields.Integer(string="Sequence",required=True, help="This field determine the order of the groups, is required for transport report")
    company_id = fields.Many2one('res.company', 'Company')

    _defaults = {
        'company_id': tools.get_default_company,
    }

    _sql_constraints = [
        ('code_unique',
         'UNIQUE(code,company_id)',
         "Group code must be unique"),
        ('name_unique',
         'UNIQUE(name,company_id)',
         "The name must be unique"),
        ('seq_unique',
         'UNIQUE(seq)',
         "Group sequence must be unique")
    ]

class classes(models.Model):
    _name = 'oschool.classes'

    name = fields.Char(string="Classroom designation", required=True)
    code = fields.Char(string="Code", required=True)
    group = fields.Many2one('oschool.groups', 'Groupe', ondelete='cascade')
    company_id = fields.Many2one('res.company', 'Company')

    _defaults = {
        'company_id': tools.get_default_company,
    }
    _sql_constraints = [
        ('code_unique',
         'UNIQUE(code,company_id)',
         "Le code de la classe doit etre unique"),
        ('name_unique',
         'UNIQUE(name,company_id)',
         "The name must be unique")
    ]

class pos_category(models.Model):
    _inherit = 'pos.category'

    price = fields.Float(string="Price")
    place_number = fields.Integer(string="place number")
    academic_year = fields.Many2one('oschool.academic_year', ondelete='cascade', string="Academic year")
    start_date_registration = fields.Date(string='Start Registration Date')
    stop_date_registration = fields.Date(string='End Registration Date')
    date_start = fields.Date(string='Start Date')
    date_stop = fields.Date(string='End Date')
    services_ids = fields.One2many('product.template', 'pos_categ_id', ondelete='cascade', string='Months')
    product_category = fields.Many2one('product.category', string="Category Type")
    cash = fields.Boolean(default=False, string="Cash")
    school_product_type = fields.Selection(
        [('service', 'Service'), ('registration', 'Registration'), ('club', 'Club'), ('event', 'Event'),
         ('study', 'Study'), ('extra', 'Extra'), ('transport', 'Transport')])
    groups = fields.Many2one('oschool.groups', 'Groupe', ondelete='cascade')
    excluded_services_ids = fields.Many2many('pos.category', 'service_category_rel', 'category_id', 'service_id', string='Excluded services')
    company_id = fields.Many2one('res.company', 'Company')

    @api.one
    @api.onchange('academic_year')
    def _set_start_stop_date(self):
        self.date_start = self.academic_year.date_start
        self.date_stop = self.academic_year.date_stop

    _sql_constraints = [
        ('check_date',
         'CHECK(date_start <= date_stop)',
         "Start Date Must be Below End Date"),
        ('check_registration_date',
         'CHECK(start_date_registration < stop_date_registration)',
         "Start Date Registration Must be Below End Date registration"),
        ('check_registration_date_stop_date',
         'CHECK(stop_date_registration <= date_stop)',
         "Stop Date Registration Must be Below End Date"),
        ('name_unique',
         'UNIQUE(name,academic_year)',
         "This record already exists for this academic year"),
    ]

    _defaults = {
        'company_id': tools.get_default_company,
    }

    def generate_months_clubs(self, cr, uid, ids, context=None, interval=1):
        company_id = self.pool.get('res.users')._get_company(cr, uid, context=context)
        property_account_income_extra = self.pool.get('account.account').search(cr, uid, [('code', '=', '7050005'),('company_id','=',company_id)])
        if not property_account_income_extra:
            raise ValidationError("There is not account with code 7050005")
        period_obj = self.pool.get('product.template')
        for fy in self.browse(cr, uid, ids, context=context):
            ds = datetime.strptime(fy.date_start, '%Y-%m-%d')
            while ds.strftime('%Y-%m-%d') < fy.date_stop:
                de = ds + relativedelta(months=interval, days=-1)
                if de.strftime('%Y-%m-%d') > fy.date_stop:
                    de = datetime.strptime(fy.date_stop, '%Y-%m-%d')

                period_obj.create(cr, uid, {
                    'name': "%s %s" % (fy.name, ds.strftime('%m/%Y')),
                    'pos_categ_id': fy.id,
                    'type': 'service',
                    'available_in_pos': True,
                    'property_account_income': property_account_income_extra[0],
                    'list_price': fy.price,
                    'subscription_month': ds.strftime('%m/%Y'),
                    'school_product_type': fy.school_product_type,
                    'academic_year': fy.academic_year.id,
                    'categ_id': fy.product_category.id,
                    'cash': fy.cash,
                    'company_id': fy.company_id.id,
                })
                ds = ds + relativedelta(months=interval)
        return True

    def generate_inscriptions(self, cr, uid, ids, context=None, interval=1):
        company_id = self.pool.get('res.users')._get_company(cr, uid, context=context)
        property_account_income_inscription = self.pool.get('account.account').search(cr, uid, [('code', '=', '7050004'),('company_id','=',company_id)])
        if not property_account_income_inscription:
            raise ValidationError("There is not account with code 7050004")
        period_obj = self.pool.get('product.template')
        sequence = 1
        for fy in self.browse(cr, uid, ids, context=context):
            if (fy.academic_year.state) == "current" or (fy.academic_year.state) == "closed":
                error = "You cannot generate inscriptions year that have '%s' status" % _(fy.academic_year.state)
                raise ValidationError(error)
            period_obj.create(cr, uid, {
                'name': "%s %s" % (_("Inscription"), fy.academic_year.code),
                'pos_categ_id': fy.id,
                'type': 'service',
                'available_in_pos': True,
                'property_account_income': property_account_income_inscription[0],
                'school_product_type': fy.school_product_type,
                'academic_year': fy.academic_year.id,
                'categ_id': fy.product_category.id,
                'inscription_sequence': sequence,
            })
            sequence = sequence + 1
            period_obj.create(cr, uid, {
                'name': "%s %s" % (_("Rénscription"), fy.academic_year.code),
                'pos_categ_id': fy.id,
                'type': 'service',
                'available_in_pos': True,
                'property_account_income': property_account_income_inscription[0],
                'school_product_type': fy.school_product_type,
                'academic_year': fy.academic_year.id,
                'categ_id': fy.product_category.id,
                'inscription_sequence': sequence,
            })

    def generate_months_study(self, cr, uid, ids, context=None, interval=1):
        company_id = self.pool.get('res.users')._get_company(cr, uid, context=context)
        property_account_income = self.pool.get('account.account').search(cr, uid, [('code', '=', '7050001'),('company_id','=',company_id)])
        if not property_account_income:
            raise ValidationError("There is not account with code 7050001")
        period_obj = self.pool.get('product.template')
        for fy in self.browse(cr, uid, ids, context=context):
            ds = datetime.strptime(fy.academic_year.date_start, '%Y-%m-%d')
            while ds.strftime('%Y-%m-%d') < fy.academic_year.date_stop:
                de = ds + relativedelta(months=interval, days=-1)
                if de.strftime('%Y-%m-%d') > fy.academic_year.date_stop:
                    de = datetime.strptime(fy.academic_year.date_stop, '%Y-%m-%d')

                period_obj.create(cr, uid, {
                    'name': "%s %s" % (fy.name, ds.strftime('%m/%Y')),
                    'pos_categ_id': fy.id,
                    'type': 'service',
                    'available_in_pos': True,
                    'list_price': fy.price,
                    'property_account_income': property_account_income[0],
                    'subscription_month': ds.strftime('%m/%Y'),
                    'school_product_type': fy.school_product_type,
                    'academic_year': fy.academic_year.id,
                    'cash': fy.cash,
                    'categ_id': fy.product_category.id,

                })
                ds = ds + relativedelta(months=interval)

    def generate_months_service(self, cr, uid, ids, context=None, interval=1):
        company_id = self.pool.get('res.users')._get_company(cr, uid, context=context)
        property_account_income = self.pool.get('account.account').search(cr, uid, [('code', '=', '7050002'),('company_id','=',company_id)])
        if not property_account_income:
            raise ValidationError("There is not account with code 7050002")
        period_obj = self.pool.get('product.template')
        for fy in self.browse(cr, uid, ids, context=context):
            ds = datetime.strptime(fy.date_start, '%Y-%m-%d')
            while ds.strftime('%Y-%m-%d') < fy.date_stop:
                de = ds + relativedelta(months=interval, days=-1)
                if de.strftime('%Y-%m-%d') > fy.date_stop:
                    de = datetime.strptime(fy.date_stop, '%Y-%m-%d')

                period_obj.create(cr, uid, {
                    'name': "%s %s" % (fy.name, ds.strftime('%m/%Y')),
                    'pos_categ_id': fy.id,
                    'type': 'service',
                    'available_in_pos': True,
                    'list_price': fy.price,
                    'property_account_income': property_account_income[0],
                    'subscription_month': ds.strftime('%m/%Y'),
                    'school_product_type': fy.school_product_type,
                    'categ_id': fy.product_category.id,
                    'academic_year': fy.academic_year.id,
                    'cash': fy.cash,
                })
                ds = ds + relativedelta(months=interval)

    def unlink(self, cr, uid, ids, context=None):
        product_obj = self.pool.get('product.product')
        product_tmpl_obj = self.pool.get('product.template')
        pos_order_line_obj = self.pool.get('pos.order.line')
        for id in ids:
            category = self.browse(cr, uid, id)
            product_tmpl_ids = product_tmpl_obj.search(cr, uid,
                                    [('pos_categ_id','=',id),
                                     ('school_product_type','=',category.school_product_type)])

            for product_tmpl_id in product_tmpl_ids:
                product_ids = product_obj.search(cr, uid,[('product_tmpl_id','=',product_tmpl_id)])
                for product_id in product_ids:
                    pos_order_line_ids = pos_order_line_obj.search(cr, uid,[('product_id','=',product_id)])
                    if pos_order_line_ids:
                        #product = product_obj.browse(cr, uid, product_id)
                        msg = "One or more command was created for the category {0}.".format(category.name)
                        raise exceptions.Warning(msg)
                        return False
            product_tmpl_obj.unlink(cr, uid, product_tmpl_ids, context)
            super(pos_category, self).unlink(cr, uid, id, context)
        return True

class product_template(models.Model):
    _inherit = 'product.template'

    subscription_month = fields.Char(string='Subscription Month')
    cash = fields.Boolean(default=False, string="Cash")
    school_product_type = fields.Selection(
        [('service', 'Service'), ('registration', 'Registration'), ('club', 'Club'), ('event', 'Event'),
         ('study', 'Study'), ('extra', 'Extra'), ('transport', 'Transport')])
    inscription_sequence = fields.Integer(string="sequence")

class hr_employee(models.Model):
    _name = 'hr.employee'
    _inherit = 'hr.employee'
    _description = 'Driver Information'

    licence_no = fields.Char(string='Licence No', size=50)
    company_id = fields.Many2one('res.company', 'Company')

    _defaults = {
        'company_id': tools.get_default_company,
    }

class parents_categories(models.Model):
    _inherit = 'product.pricelist.item'

    _defaults = {
        'base': 1,
    }

class oschool_account_journal(models.Model):
    _inherit = 'account.journal'

    cash = fields.Boolean(default=False, string="Cash")
    registration = fields.Boolean(default=False, string="Registration")
    extra = fields.Boolean(default=False, string="Extra")
    is_check = fields.Boolean(default=False, string="Is check")

class pos_session_opening(osv.osv_memory):
    _inherit = 'pos.session.opening'

    company_id = fields.Many2one('res.company', 'Company')

    _defaults = {
        'company_id': tools.get_default_company,
    }
    def oschool_open_session_cb(self, cr, uid, ids, context=None):
        assert len(ids) == 1, "you can open only one session at a time"
        proxy = self.pool.get('pos.session')
        wizard = self.browse(cr, uid, ids[0], context=context)
        if not wizard.pos_session_id:
            values = {
                'user_id': uid,
                'config_id': wizard.pos_config_id.id,
            }
            session_id = proxy.create(cr, uid, values, context=context)
            s = proxy.browse(cr, uid, session_id, context=context)
            if s.state == 'opened':
                return self.oschool_open_ui(cr, uid, ids, context=context)
            return self._open_session(session_id)
        return self._open_session(wizard.pos_session_id.id)

    def oschool_open_ui(self, cr, uid, ids, context=None):
        data = self.browse(cr, uid, ids[0], context=context)
        context = dict(context or {})
        context['active_id'] = data.pos_session_id.id
        obj = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'oschool', 'main_oschool_menu')[1]
        return {
            'type': 'ir.actions.client',
            'name': 'Point of Sale Menu',
            'tag': 'reload',
            'params': {'menu_id': obj},
        }

    def oschool_open_existing_session_cb_close(self, cr, uid, ids, context=None):
        wizard = self.browse(cr, uid, ids[0], context=context)
        wizard.pos_session_id.signal_workflow('cashbox_control')
        return self.oschool_open_session_cb(cr, uid, ids, context)

    def oschool_open_session_cb(self, cr, uid, ids, context=None):

        view_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'oschool', 'oschool_pos_session_form')

        assert len(ids) == 1, "you can open only one session at a time"
        proxy = self.pool.get('pos.session')
        wizard = self.browse(cr, uid, ids[0], context=context)
        if not wizard.pos_session_id:
            values = {
                'user_id': uid,
                'config_id': wizard.pos_config_id.id,
            }
            session_id = proxy.create(cr, uid, values, context=context)
            s = proxy.browse(cr, uid, session_id, context=context)
            if s.state == 'opened':
                return self.oschool_open_ui(cr, uid, ids, context=context)
            return self._oschool_open_session(session_id, view_id, context)
        return self._oschool_open_session(wizard.pos_session_id.id, view_id,context)

    def _oschool_open_session(self, session_id, view_id, context):

        return {
            'name': _('Session'),
            'view_type': 'form',
            'view_mode': 'form,tree',
            'res_model': 'pos.session',
            'res_id': session_id,
             # 'view_id': [view_id],
            'view_id': False,
            'type': 'ir.actions.act_window',
        }

class pos_session(osv.osv):

    _inherit = 'pos.session'

    company_id = fields.Many2one('res.company', 'Company')

    _defaults = {
        'company_id': tools.get_default_company,
    }

    def wkf_action_close(self, cr, uid, ids, context=None):
        # Close CashBox
        for record in self.browse(cr, uid, ids, context=context):
            for st in record.statement_ids:
                if abs(st.difference) > st.journal_id.amount_authorized_diff:
                    # The pos manager can close statements with maximums.
                    if not self.pool.get('ir.model.access').check_groups(cr, uid, "point_of_sale.group_pos_manager"):
                        raise osv.except_osv(_('Error!'),
                                             _(
                                                 "Your ending balance is too different from the theoretical cash closing (%.2f), the maximum allowed is: %.2f. You can contact your manager to force it.") % (
                                             st.difference, st.journal_id.amount_authorized_diff))
                if (st.journal_id.type not in ['bank', 'cash']):
                    raise osv.except_osv(_('Error!'),
                                         _("The type of the journal for your payment method should be bank or cash "))
                getattr(st, 'button_confirm_%s' % st.journal_id.type)(context=context)
        self._confirm_orders(cr, uid, ids, context=context)
        self.write(cr, uid, ids, {'state': 'closed'}, context=context)

        obj = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'oschool', 'main_oschool_menu')[1]
        return {
            'type': 'ir.actions.client',
            'name': 'Point of Sale Menu',
            'tag': 'reload',
            'params': {'menu_id': obj},
        }

    def open_frontend_cb(self, cr, uid, ids, context=None):
        if not context:
            context = {}
        if not ids:
            return {}
        for session in self.browse(cr, uid, ids, context=context):
            if session.user_id.id != uid:
                raise osv.except_osv(
                    _('Error!'),
                    _(
                        "You cannot use the session of another users. This session is owned by %s. Please first close this one to use this point of sale." % session.user_id.name))
        context.update({'active_id': ids[0]})
        obj = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'oschool', 'main_oschool_menu')[1]
        return {
            'type': 'ir.actions.client',
            'name': 'Point of Sale Menu',
            'tag': 'reload',
            'params': {'menu_id': obj},
        }

class product_template(models.Model):
    _inherit = 'product.template'

    academic_year = fields.Many2one('oschool.academic_year', ondelete='cascade', string="Academic year")

    _sql_constraints = [
        ('unique_oschool_product', 'unique(academic_year,company_id, school_product_type, subscription_month, pos_categ_id)',
         'The record must be unique by year'),
        ('unique_oschool_inscription_by_year',
         'unique(academic_year, company_id,school_product_type, inscription_sequence, categ_id)',
         'The registration must be unique by year')
    ]


from api.scripts.add_user import add_user
from tornado.options import define, options, parse_command_line

if __name__ == "__main__":

    # Configuration options.
    define("command", default="User", help="Configuration option to execute.")
    parse_command_line()

    command = None
    prompt = ''
    continue_execution = True
    command_heading = ''

    if options.command == "User":
        command = add_user
        prompt = "Do you wish to continue adding users?" + " (Y/N) "
        command_heading = "Adding a user"

    print(command_heading)
    print("====================================")

    # Execute command in a loop until the user is done
    while continue_execution:
        command()
        confirmation = input(prompt)
        if confirmation == "N":
            continue_execution = False


import os

import pytest
from _pytest.fixtures import SubRequest
from flask.app import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm.scoping import scoped_session

from app import create_app
from app.extensions.database import sql as _db

TEST_DB = "tests.db"
TEST_DB_PATH = f"{os.path.dirname(os.path.dirname(__file__))}/{TEST_DB}"
TEST_DATABASE_URI = "sqlite:///" + TEST_DB_PATH

# noinspection PyShadowingNames
@pytest.yield_fixture(scope="session")
def app(request: SubRequest) -> Flask:
    settings = {"TESTING": True, "SQLALCHEMY_DATABASE_URI": TEST_DATABASE_URI}
    app = create_app("testing", settings)
    ctx = app.app_context()
    ctx.push()

    def teardown():
        ctx.pop()

    request.addfinalizer(teardown)
    return app

# noinspection PyShadowingNames
@pytest.fixture(scope="session")
def db(app: Flask, request: SubRequest) -> SQLAlchemy:
    """
    Session-wide tests database.
    http://alexmic.net/flask-sqlalchemy-pytest/
    """

    if os.path.exists(TEST_DB_PATH):
        os.unlink(TEST_DB_PATH)

    def teardown():
        _db.drop_all()
        os.unlink(TEST_DB_PATH)

    _db.app = app
    _db.create_all()

    request.addfinalizer(teardown)
    return _db

@pytest.fixture(scope="function")
def session(db: SQLAlchemy, request: SubRequest) -> scoped_session:
    """
    Creates a new data session for a tests.
    http://alexmic.net/flask-sqlalchemy-pytest/
    """
    connection = db.engine.connect()
    transaction = connection.begin()

    options = dict(bind=connection, binds={})
    session = db.create_scoped_session(options=options)

    db.session = session

    def teardown():
        transaction.rollback()
        connection.close()
        session.remove()

    request.addfinalizer(teardown)
    return session


import gzip
import urllib
import urllib2
import hashlib
import time
import chardet

from decorator import decorator
from copy import copy
from urlparse import urlparse
from StringIO import StringIO

from traffgroup.core.model.site import Site
from traffgroup.core.X.mako import render_template
from traffgroup.core.X.xflask import g, request, capp
from traffgroup.core.X.utils import XRedis
from traffgroup.x.util.func import url_append

def url(url, q=None, **kwargs):
    if not q:
        q = {}

    # pass all other params too
    nazavod_url_vars = ['project', 'marker', 'flow', 'id', 'sign', 'gttl']
    for var_name, var_val in filter(lambda var: var[0] not in nazavod_url_vars,
                                    request.values.items()):
        kwargs[var_name] = var_val

    kwargs.update({'marker':    g.marker,
                   'sign':      g.nsign,
                   'gttl':      g.gttl,
                   'marker':    g.marker,
                   'project':   g.project,
                   'flow':      g.flow})
    return url_append(url, q, **kwargs)

def get_footer(host):
    if not host:
        return ''
    xredis = XRedis(db=2)
    footer = xredis.get(host)
    if footer:
        return footer

    req = urllib2.Request(url=host)
    footer = urllib2.urlopen(req).read()
    try:
        if 'footer_begin' in footer:
            offer_parts = footer.split('footer_begin')
            pre_footer = '
'
            footer = pre_footer + offer_parts[1].split('footer_end')[0]           #TODO: shitty shit, find out another way
    except:
        pass

    xredis.setex(host, 86400, footer)
    return footer

def get_terms(host):
    if not host:
        return ''

    xredis = XRedis(db=3)
    terms = xredis.get(host)
    if terms:
        return terms

    req = urllib2.Request(url=host)
    terms = urllib2.urlopen(req).read()
    xredis.setex(host, 86400, terms)
    return terms

def is_member_valid(key=None):
    """
    Validates member by access key
    @param key {string}
    @returns True if valid and False otherwise
    """
    if not key:
        key = (request.args.get('access', '') or
               request.cookies.get('access',''))
    key_parts = key.split(':')
    if len(key_parts) != 4:
        return False

    sub_id, ts_start, duration, signature = key_parts
    if (time.time() > int(ts_start) + int(duration) or
        hashlib.md5(sub_id + ts_start + duration +
                    Site.Globals.SALT).hexdigest() != signature):
        return False
    return True

class Template(object):
    def __init__(self, tmpl, **kwargs):
        self.template = copy(tmpl)
        self.extras = dict(kwargs)

    def __call__(self, action_):
        return decorator(self.wrap_action, action_)

    @staticmethod
    def tmpl_path(tmpl_name):
        return '/paysite/%s/%s/%s' % (g.root_design.templates_folder,
                                      g.scheme, tmpl_name)

    def wrap_action(self, action_, *args, **kwargs):
        g.action_result = action_(*args, **kwargs)
        for k, v in self.extras.iteritems():
            setattr(g, k, v)

        return render_template(Template.tmpl_path(self.template))

def urldecode(url):
    res = {}
    for item in url.split('&'):
        key_val = item.split('=')
        res[urllib.unquote_plus(key_val[0])] = urllib.unquote_plus(key_val[1])
    return res

def fetch(url, post_data=None):
    """
    Get data at url
    @param url: url
    @param post_data: dict
    @return: data, content_type (css and html supported at this moment)
    """

    content_type = '%s; charset=utf-8'

    url = urllib2.unquote(url)
    req = urllib2.Request(url)
    if post_data:
        post_data = urllib.urlencode(request.values)

    # replace urllib2 user agent for prevent browser dependent
    # web site behavior
    req.add_header('User-Agent',
                   'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 '
                   '(KHTML, like Gecko) Chrome/28.0.1468.0 '
                   'Safari/537.36')
    req.add_header('Accept-encoding', 'gzip')
    req.add_header('Accept-Language', request.headers.get('Accept-Language'))

    try:
        resp = urllib2.build_opener().open(req, post_data)
        resp_info = resp.info()
        target_url = resp.geturl()
        content_type = (content_type %
                        ('text/css' if 'text/css' in resp_info.get('Content-Type')
                         else 'text/html'))
        if resp_info.get('Content-Encoding') == 'gzip':
            buf = StringIO(resp.read())
            f = gzip.GzipFile(fileobj=buf)
            page_data = f.read()
        else:
            page_data = resp.read()
        data = unicode(page_data, chardet.detect(page_data)['encoding'])
    except (urllib2.HTTPError, urllib2.URLError, ValueError) as e:
        capp.logger.exception(e)
        data = None
        target_url = url
        content_type = None

    return data, target_url, content_type


import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]#db_name
mycol = mydb["customers"]#tables

mylist = [
  { "_id": 1, "name": "John", "address": "Highway 37"},
  { "_id": 2, "name": "Peter", "address": "Lowstreet 27"},
  { "_id": 3, "name": "Amy", "address": "Apple st 652"},
  { "_id": 4, "name": "Hannah", "address": "Mountain 21"},
  { "_id": 5, "name": "Michael", "address": "Valley 345"},
  { "_id": 6, "name": "Sandy", "address": "Ocean blvd 2"},
  { "_id": 7, "name": "Betty", "address": "Green Grass 1"},
  { "_id": 8, "name": "Richard", "address": "Sky st 331"},
  { "_id": 9, "name": "Susan", "address": "One way 98"},
  { "_id": 10, "name": "Vicky", "address": "Yellow Garden 2"},
  { "_id": 11, "name": "Ben", "address": "Park Lane 38"},
  { "_id": 12, "name": "William", "address": "Central st 954"},
  { "_id": 13, "name": "Chuck", "address": "Main Road 989"},
  { "_id": 14, "name": "Viola", "address": "Sideway 1633"}
]

try:
	print("yo!")
	#uncomment to insert
	x = mycol.insert_many(mylist)
	#print list of the _id values of the inserted documents:
	print(x.inserted_ids)
except:
	print("mylist already exist!")

#find only one
x = mycol.find_one()
print(x)

# #loop and print without id
# for x in mycol.find({},{ "_id": 0, "name": 1, "address": 1 }):
#   print(x)

# #loop and print all without address
# for x in mycol.find({},{ "address": 0 }):
#   print(x)

#search query by address
# myquery = { "address": "Park Lane 38" }
# mydoc = mycol.find(myquery)

# for x in mydoc:
#   print(x)

#Find documents where the address starts with the letter "S" or higher:
# myquery = { "address": { "$gt": "S" } }
# mydoc = mycol.find(myquery)

# for x in mydoc:
#   print(x)

#Find documents where the address starts with the letter "S":
# myquery = { "address": { "$regex": "^S" } }
# mydoc = mycol.find(myquery)

# for x in mydoc:
#   print(x)

# Sort the result alphabetically by name:
#-----> sort("name", 1) #ascending
#-----> sort("name", -1) #descending
# mydoc = mycol.find().sort("name")
# for x in mydoc:
#   print(x)

# #Delete the document with the address "Mountain 21":
# myquery = { "address": "Mountain 21" }
# mycol.delete_one(myquery)

# #Delete all documents were the address starts with the letter S:
# myquery = { "address": {"$regex": "^S"} }
# x = mycol.delete_many(myquery)
# print(x.deleted_count, " documents deleted.")

#Delete all documents in the "customers" collection:
# x = mycol.delete_many({})
# print(x.deleted_count, " documents deleted.")

#Dtop collection
#mycol.drop()

#Change the address from "Valley 345" to "Canyon 123":
myquery = { "address": "Valley 345" }
newvalues = { "$set": { "address": "Canyon 123" } }
mycol.update_one(myquery, newvalues)
#print "customers" after the update:
for x in mycol.find():
  print(x)


from setuptools import setup

package_name = "hybridset"
version = '1.0'
url = 'https://gitlab.com/yahya-abou-imran/hybridset'
url_fmt = '/-/archive/v{version}/archive.zip/{package_name}-v{version}.zip'
download_url = (
    url + url_fmt.format(version=version, package_name=package_name)
)
description=('Mutable set storing apart hashables and unhashables values')
try:
    import pypandoc
    long_description = pypandoc.convert_file('README.md', 'rst')
except(IOError, ImportError):
    long_description = open('README.md').read()

setup(
    name=package_name,
    description=description,
    long_description=long_description,
    long_description_content_type='text/markdown',
    version=version,
    author='Yahya Abou Imran',
    author_email='yahya-abou-imran@pm.me',
    license='GPLv3',
    url=url,
    download_url=download_url,
    packages=[package_name],
)


# local config helper stuff
try:
    import ISStreamer.configutil as configutil
except ImportError:
    import configutil
try:
    import ISStreamer.version as version
except ImportError:
    import version
import uuid
from capture import *

# python 2 and 3 conversion support
import sys
if (sys.version_info < (2,7,0)):
    sys.stderr.write("You need at least python 2.7.0 to use the ISStreamer")
    exit(1)
elif (sys.version_info >= (3,0)):
    import http.client as httplib
else:
    import httplib
import json
# time stuff
import datetime
import time
# performance stuff
import threading
import collections

class Streamer:
    CoreApiBase = ""
    Bucket = ""
    ClientKey = ""
    PubKey = ""
    SubKey = ""
    Channel = ""
    BufferSize = 10
    LogIterations = 0
    StreamApiBase = ""
    LogQueue = None
    DebugLevel = 0
    SessionId = ""
    IsClosed = True
    def __init__(self, bucket="", client_key="", ini_file_location=None, debug_level=0, buffer_size=10):
        config = configutil.getConfig(ini_file_location)

        if (config == None and bucket=="" and client_key == ""):
            raise Exception("config not found and arguments empty")

        if (bucket == ""):
            bucket_name = config["bucket"]
        else:
            bucket_name = bucket
        if (client_key == ""):
            self.ClientKey = config["clientKey"]
        else:
            self.ClientKey = client_key

        #self.LogQueue = Queue.Queue(self.BufferSize)
        self.BufferSize = buffer_size
        self.LogQueue = collections.deque()

        self.CoreApiBase = config["core_api_base"]
        self.StreamApiBase = config["stream_api_base"]
        self.set_bucket(bucket_name)
        self.DebugLevel = debug_level
        self.IsClosed = False

        self.console_message("ClientKey: {clientKey}".format(clientKey=self.ClientKey))
        self.console_message("core_api_base: {api}".format(api=self.CoreApiBase))
        self.console_message("stream_api_base: {api}".format(api=self.StreamApiBase))

    def set_bucket(self, new_bucket, retries=3):

        def __create_bucket(new_bucket, bucket_id, client_key):
            api_base = self.CoreApiBase
            conn = None
            if (self.CoreApiBase.startswith('https://')):
                api_base = self.CoreApiBase[8:]
                self.console_message("core api base domain: {domain}".format(domain=api_base), level=2)
                conn = httplib.HTTPSConnection(api_base)
            else:
                api_base = self.CoreApiBase[7:]
                self.console_message("core api base domain: {domain}".format(domain=api_base), level=2)
                conn = httplib.HTTPConnection(api_base)
            resource = "/api/v1/buckets"
            headers = {
                'Content-Type': 'application/json',
                'User-Agent': 'PyStreamer v' + version.__version__
            }
            body = {
                'bucketId': bucket_id,
                'bucketName': new_bucket,
                'clientKey': client_key
            }

            def ___ship(retry_attempts, wait=0):
                if (retry_attempts <= 0):
                    if (self.DebugLevel >= 2):
                        raise Exception("bucket create failed")
                    else:
                        self.console_message("ISStreamer failed to create or find bucket after a number of attempts", level=0)
                        return

                try:
                    if (wait > 0):
                        time.sleep(wait)
                    conn.request("POST", resource, json.dumps(body), headers)
                    response = conn.getresponse()

                    if (response.status >= 200 and response.status < 300):
                        self.console_message("bucket created successfully!", level=2)
                    elif (response.status == 401 or response.status == 403):
                        self.console_message("ClientKey not authorized")
                        raise Exception("ClientKey not authorized")
                    else:
                        self.console_message("ISStreamer failed to setup the bucket on attempt {atmpt}. StatusCode: {sc}; Reason: {r}".format(sc=response.status, r=response.reason, atmpt=retry_attempts))
                        raise Exception("ship exception")
                except:
                    self.console_message("exception creating bucket on attempt {atmpt}.".format(atmpt=retry_attempts))
                    retry_attempts = retry_attempts - 1
                    ___ship(retry_attempts, 1)

            ___ship(retries)

        self.SessionId = str(uuid.uuid4())
        self.Bucket = new_bucket
        t = threading.Thread(target=__create_bucket, args=(new_bucket, self.SessionId, self.ClientKey))
        t.daemon = False
        t.start()

    def console_message(self, message, level=1):
        if (self.DebugLevel >= level):
            print(message)

    def ship_messages(self, messages, retries=3):
        api_base = self.StreamApiBase
        conn = None
        if (self.StreamApiBase.startswith('https://')):
            api_base = self.StreamApiBase[8:]
            self.console_message("ship messages: stream api base domain: {domain}".format(domain=api_base), level=2)
            conn = httplib.HTTPSConnection(api_base)
        else:
            api_base = self.StreamApiBase[7:]
            self.console_message("ship messages: stream api base domain: {domain}".format(domain=api_base), level=2)
            conn = httplib.HTTPConnection(api_base)
        resource = "/batch_logs"
        headers = {
            'Content-Type': 'application/json',
            'User-Agent': 'PyStreamer v' + version.__version__,
            'X-IS-ClientKey': self.ClientKey
        }

        def __ship(retry_attempts, wait=0):
            self.console_message("ship: beginning message ship!", level=2)
            if (retry_attempts <= 0):

                if (self.DebugLevel >= 2):
                    raise Exception("shipping logs failed.. network issue?")
                print('This is the point to add data control')   #To do catch the data store it then wait for network and send
                if(internet_on() == False):
                    Dump('temp.tmp', json.dumps(messages))   #dumps messages to file
                else:
                    self.console_message("ship: ISStreamer failed to ship the logs after a number of attempts {msgs}".format(msgs=json.dumps(messages)), level=0)

                    return

            try:
                if (wait > 0):
                    time.sleep(wait)
                conn.request('POST', resource, json.dumps(messages), headers)
                response = conn.getresponse()

                if (response.status >= 200 and response.status < 300):
                    self.console_message("ship: success!", level=2)
                else:
                    self.console_message("ship: failed on attempt {atmpt} (StatusCode: {sc}; Reason: {r})".format(sc=response.status, r=response.reason, atmpt=retry_attempts))
                    raise Exception("ship exception")
            except:
                self.console_message("ship: exception shipping logs on attempt {atmpt}.".format(atmpt=retry_attempts))
                retry_attempts = retry_attempts - 1
                __ship(retry_attempts, 1)

        __ship(retries)

    def flush(self):
        messages = []
        self.console_message("flush: checking queue", level=2)
        isEmpty = False
        while not isEmpty:
            try:
                m = self.LogQueue.popleft()
                messages.append(m)
            except IndexError:
                isEmpty = True
                self.console_message("flush: queue empty...", level=2)
        if len(messages) > 0:
            self.console_message("flush: queue not empty, shipping", level=2)
            self.ship_messages(messages)
        self.console_message("flush: finished flushing queue", level=2)

    def log_object(self, obj, signal_prefix=None, epoch=None):
        if (epoch == None):
            epoch = time.time()

        if (signal_prefix == None):
            signal_prefix = str(type(obj).__name__)

        if (type(obj).__name__ == 'list'):
            i = 0
            for val in obj:
                signal_name = "{}_{}".format(signal_prefix, i)
                self.log(signal_name, val, epoch=epoch)
                i += 1
        elif (type(obj).__name__ == 'dict'):
            for key in obj:
                signal_name = "{}_{}".format(signal_prefix, key)
                self.log(signal_name, obj[key], epoch=epoch)
        else:
            for attr in dir(obj):
                if not isinstance(getattr(type(obj), attr, None), property):
                    continue
                signal_name = "{}_{}".format(signal_prefix, attr)
                self.log(signal_name, getattr(obj, attr), epoch=epoch)

    def log(self, signal, value, epoch=None):
        def __ship_ten():
            i = self.BufferSize
            messages = []
            while(i > 0):
                try:
                    m = self.LogQueue.popleft()
                    messages.append(m)
                except IndexError:
                    i = 0
                    self.console_message("ship10: queue empty for now, less than 10")
                i = i - 1

            self.console_message("ship10: shipping", level=2)
            self.ship_messages(messages)
            self.console_message("ship10: finished shipping", level=2)

        timeStamp = time.time()
        gmtime = datetime.datetime.fromtimestamp(timeStamp)

        if epoch != None:
            try:
                gmtime = datetime.datetime.fromtimestamp(epoch)
                timeStamp = epoch
            except:
                self.console_message("epoch was overriden with invalid time, using current timstamp instead")

        formatted_gmTime = gmtime.strftime('%Y-%m-%d %H:%M:%S.%f')
        self.console_message("{time}: {signal} {value}".format(signal=signal, value=value, time=formatted_gmTime))

        if (len(self.LogQueue) >= self.BufferSize):
            self.console_message("log: queue size approximately at or greater than buffer size, shipping!", level=10)
            t = threading.Thread(target=__ship_ten)
            t.daemon = False
            t.start()

        self.console_message("log: queueing log item", level=2)
        log_item = {
            "b": self.Bucket,
            "sn": signal,
            "v": value,
            "e": timeStamp,
            "tid": self.SessionId
        }
        self.LogQueue.append(log_item)

    def close(self):
        self.IsClosed = True
        self.flush()

    def __del__(self):
        """Try to close/flush the cache before destruction"""
        try:
            if (not self.IsClosed):
                self.flush()
        except:
            if (self.DebugLevel >= 2):
                raise Exception("failed to close the buffer, make sure to explicitly call close() on the Streamer")
            else:
                self.console_message("failed to close the buffer, make sure to explicitly call close() on the Streamer", level=1)


from typing import *

def solve(n: int, q: int, a: List[int], l: List[int], r: List[int]) -> List[int]:
    b = [0] * (n + 1)
    for i in range(n):
        b[i + 1] = b[i] + a[i]
    ans = [-1] * q
    for j in range(q):
        ans[j] = b[r[j]] - b[l[j]]
    return ans

def main() -> None:
    n = int(input())
    q = int(input())
    a = list(map(int, input().split()))
    l = list(range(q))
    r = list(range(q))
    for i in range(q):
        l[i], r[i] = map(int, input().split())
    ans = solve(n, q, a, l, r)
    for i in range(q):
        print(ans[i])

if __name__ == '__main__':
    main()


from datetime import datetime

from django.utils.timezone import make_aware

from settings.tasks import exec_command
from systems.commands.index import CommandMixin

import re
import json
import string
import random

class ScheduleMixin(CommandMixin('schedule')):

    def get_schedule_from_representation(self, representation):
        schedule = self.get_interval_schedule(representation)

        if not schedule:
            schedule = self.get_datetime_schedule(representation)
        if not schedule:
            schedule = self.get_crontab_schedule(representation)

        if not schedule:
            self.error("'{}' is not a valid schedule format.  See --help for more information".format(representation))

        return schedule

    def normalize_schedule_time(self, time_string):
        return make_aware(datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S"))

    def set_periodic_task(self):
        schedule = self.schedule

        if schedule:
            begin = self.schedule_begin
            end = self.schedule_end

            schedule_map = {
                'task_interval': 'interval',
                'task_crontab': 'crontab',
                'task_datetime': 'clocked'
            }
            options = self.options.export()
            options['_user'] = self.active_user.name
            task = {
                schedule_map[schedule.facade.name]: schedule,
                'task': 'zimagi.command.exec',
                'user': self.active_user,
                'args': json.dumps([self.get_full_name()]),
                'kwargs': json.dumps(options)
            }
            if begin:
                task['start_time'] = begin
            if end:
                task['expires'] = end

            self._scheduled_task.store(self.get_schedule_name(), **task)

            self.success("Task '{}' has been scheduled to execute periodically".format(self.get_full_name()))
            return True

        return False

    def set_queue_task(self):
        if self.push_queue:
            options = self.options.export()
            options['_user'] = self.active_user.name
            exec_command.delay(self.get_full_name(), **options)
            self.success("Task '{}' has been pushed to the queue to execute in the background".format(self.get_full_name()))
            return True

        return False

    def get_schedule_name(self):
        return "{}:{}{}".format(
            self.get_full_name().replace(' ', '-'),
            datetime.now().strftime("%Y%m%d%H%M%S"),
            random.SystemRandom().choice(string.ascii_lowercase)
        )

    def get_interval_schedule(self, representation):
        interval = self._task_interval.model
        schedule = None
        period_map = {
            'D': interval.DAYS,
            'H': interval.HOURS,
            'M': interval.MINUTES,
            'S': interval.SECONDS
        }

        match = re.match(r'^(\d+)([DHMS])$', representation, flags = re.IGNORECASE)
        if match:
            schedule, created = self._task_interval.store(representation,
                every = match.group(1),
                period = period_map[match.group(2).upper()],
            )
        return schedule

    def get_crontab_schedule(self, representation):
        schedule = None

        match = re.match(r'^([\*\d\-\/\,]+) ([\*\d\-\/\,]+) ([\*\d\-\/\,]+) ([\*\d\-\/\,]+) ([\*\d\-\/\,]+)$', representation)
        if match:
            schedule, created = self._task_crontab.store(representation,
                minute = match.group(1),
                hour = match.group(2),
                day_of_week = match.group(3),
                day_of_month = match.group(4),
                month_of_year = match.group(5)
            )
        return schedule

    def get_datetime_schedule(self, representation):
        schedule = None

        match = re.match(r'^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$', representation)
        if match:
            schedule, created = self._task_datetime.store(representation,
                clocked_time = make_aware(datetime.strptime(representation, "%Y-%m-%d %H:%M:%S")),
            )
        return schedule