"""FFMPEG backend for video editing"""

from pathlib import Path
import subprocess

import ffmpeg

import pypopquiz as ppq
import pypopquiz.backends.backend
import pypopquiz.io

class FFMpeg(ppq.backends.backend.Backend):
    """FFMPEG backend, implements interface from base-class"""

    def __init__(self, source_file: Path, display_graph: bool = False, width: int = 1280, height: int = 720) -> None:
        super().__init__(width, height)
        stream = ffmpeg.input(str(source_file))
        self.display_graph = display_graph
        self.stream_v = stream["v"]
        self.stream_a = stream["a"]
        self.version = ffmpeg_version()

    def trim(self, start_s: int, end_s: int) -> None:
        """Trims a video to a given start and end time measured in seconds"""
        self.stream_v = self.stream_v.trim(start=start_s, end=end_s).filter("setpts", "PTS-STARTPTS")
        self.stream_a = self.stream_a.filter("atrim", start=start_s, end=end_s).filter("asetpts", "PTS-STARTPTS")

    def repeat(self) -> None:
        """Concatenates a video and audio stream with itself to make a twice as long video"""
        stream_v = self.stream_v.split()
        stream_a = self.stream_a.asplit()
        joined = ffmpeg.concat(stream_v[0].filter("fifo"), stream_a[0].filter("afifo"),
                               stream_v[1].filter("fifo"), stream_a[1].filter("afifo"), v=1, a=1).node
        self.stream_v, self.stream_a = joined[0], joined[1]

    def fade_in_and_out(self, duration_s: int, video_length_s: int) -> None:
        """Adds a fade-in and fade-out to/from black for the audio and video stream"""
        stream_v = self.stream_v.filter("fade", type="in", start_time=0, duration=duration_s)
        self.stream_v = stream_v.filter("fade", type="out", start_time=video_length_s - duration_s,
                                        duration=duration_s)
        stream_a = self.stream_a.filter("afade", type="in", start_time=0, duration=duration_s)
        self.stream_a = stream_a.filter("afade", type="out", start_time=video_length_s - duration_s,
                                        duration=duration_s)

    def scale_video(self) -> None:
        """Scales the video and pads if necessary to the requested dimensions"""
        width = self.width
        height = self.height
        stream_v = self.stream_v.filter("scale", width=width, height=height, force_original_aspect_ratio=1)
        self.stream_v = stream_v.filter("pad", width=width, height=height, x="(ow-iw)/2", y="(oh-ih)/2", color="black")

    def draw_text_in_box(self, video_text: str, length: int, box_height: int, move: bool, top: bool) -> None:
        """Draws a semi-transparent box either at the top or bottom and writes text in it, optionally scrolling by"""
        width = self.width
        height = self.height
        y_location = 0 if top else height - box_height

        thickness = "fill" if self.version.startswith("N") else "max"  # Assume nightlies are new.
        stream_v = self.stream_v.drawbox(x=0, y=y_location, width=width, height=box_height, color="gray@0.5",
                                         thickness=thickness)
        x_location_text = "{:d} * t / {:d}".format(width, length) if move else "{:d} - text_w / 2".format(width // 2)
        y_location_text = int(box_height * 1 / 4) if top else int(height - box_height * 3 / 4)
        self.stream_v = stream_v.drawtext(text=video_text, fontcolor="white", fontsize=50,
                                          x=x_location_text, y=y_location_text)

    def run(self, file_name: Path) -> None:
        """Runs the ffmpeg command to create the video, applying all the filters"""
        output_stream = ffmpeg.output(self.stream_v, self.stream_a, str(file_name))
        if self.display_graph:
            output_stream.view(filename="ffmpeg_graph")  # optional visualisation of the graph
        ppq.io.log("Running ffmpeg...")
        ppq.io.log("")
        output_stream.run()
        ppq.io.log("")
        ppq.io.log("Completed ffmpeg, successfully generated result")

def ffmpeg_version() -> str:
    """Determine the ffmpeg version.

    Parses a line that looks like:
    "ffmpeg version N-91586-g90dc584d21 Copyright (c) 2000-2018 the FFmpeg developers"
    """
    res = None
    try:
        res = subprocess.check_output(['ffmpeg', '-version'])  # type: ignore
        # Need ignore, capture_output argument is not known to linter
    except subprocess.CalledProcessError:
        pass

    if res is None:
        raise RuntimeError("ffmpeg is probably not in the path.")

    version_str = res.decode('ascii').splitlines()[0]
    prefix = 'ffmpeg version '
    if not version_str.startswith(prefix):
        raise RuntimeError("Cannot parse ffmpeg version string.")

    # From here on, version string is assumed to be formatted as expected
    version_str = version_str[len(prefix):]
    version_chopped = version_str.split(' Copyright')[0]

    return version_chopped


# -*- coding: utf-8 -*-
"""
Created on Fri Mar 25 10:32:04 2016

@author: tai
"""

import PseudoFlow as PF
import SemiFlow as SF
import numpy as np

"""
This scipt defines the class Flow

"""

class Flow:

    def __init__(self,ide,ingress,egress,x,y,z,unit):

        self.id = ide
        self.ingress = ingress
        self.egress = egress
        self.x = x
        self.y = y
        self.z = z
        self.unit = unit
        self.path = np.array([])

    # this function build a flow equal to another
    def equal(self,f):

        self.id = f.id
        self.ingress = f.ingress
        self.egress = f.egress
        self.x = f.x
        self.y = f.y
        self.z = f.z
        self.unit = f.unit
        self.path = f.path

    def set_path(self,path):
        self.path = path

    def print_attribute(self):

        print( "id:{0}".format(self.id),
                "ingress:{0}".format(self.ingress),
                "egress:{0}".format(self.egress),
                "x:{0}".format(self.x),
               "y:{0}".format(self.y),
               "z:{0}".format(self.z),
               "unit:{0}".format(self.unit),
               "path:{0}".format(self.path))

    # this function cuts a flow into two semi_flows or into a pseudo_flow
    def cut(self,node_id):

        # if the node where to cut is not on the edge of the flow, we obtain 2 semi_flows
        if(node_id!=self.ingress and node_id!=self.egress):
             path = self.path

             s_path = np.array([])
             i = 0
             ref = path[i]
             while(ref!=node_id):
                 s_path = np.append(s_path,ref)
                 i+=1
                 ref = path[i]
             s_path = np.append(s_path,ref)

             e_path = np.array([])
             e_path = np.append(e_path,path[i:])

             # the sign of the semi_flows indicates whether the semi_flows
             # is at the beginning or the end of the father flow
             start = SF.SemiFlow(-self.id,self.ingress,node_id,self.x,self.unit,s_path)
             finish = SF.SemiFlow(self.id,node_id,self.egress,self.z,self.unit,e_path)

             return (start,finish)

        # if the node where to cut is at the edge, we obtain a pseudo_flow
        # the sign of the pseudo indicates whether we allocate z or x function
        if(node_id==self.ingress):

            return PF.PseudoFlow(self.id,self.ingress,self.egress,self.y,self.z,self.unit,self.path)

        if(node_id==self.egress):

            return PF.PseudoFlow(-self.id,self.ingress,self.egress,self.x,self.y,self.unit,self.path)


"""
Given a list of integers, write a function that will return a list, in which for each index the element will be the product of all the integers except for the element at that index

For example, an input of [1,2,3,4] would return [24,12,8,6] by performing [2×3×4,1×3×4,1×2×4,1×2×3]
"""

def array_mul(arr):
    result = [None] * len(arr)
    prod = 1
    i = 0

    while i < len(arr):
        result[i] = prod
        prod *= arr[i]
        i += 1

    prod = 1
    i = len(arr)-1

    while i >= 0:
        result[i] *= prod
        prod *= arr[i]
        i -= 1

    return result

print(array_mul([1,2,3,4]))

Problems/Product of Array Elements/script.py


# Evaluate both the ternary and full precision models against the noisy datasets
# Some imports are based of code from Zhu et al and thus they are not made public on github
import _init_paths
import os
import argparse
import torch
import torch.backends.cudnn as cudnn
import torchvision.datasets as dset
import torchvision.transforms as transforms
import models
import numpy as np
args = argparse.ArgumentParser().parse_args()

# IMAGE DATA FOLDER
args.image_folder = "adversarial/"
# FULL WEIGHTS
args.pretrained_full = "weights/cifar10-full/model_best.pth.tar"
# TERNARY WEIGHTS
args.pretrained_twn = "weights/cifar10-twn/model_restored.pth.tar"
# Other variables
args.data_path = "cifar.python"
args.arch = "resnet20"
args.batch_size = 128
args.workers = 16
args.ngpu = 0

def main(args):
  num_classes = 10

  mean = [x / 255 for x in [125.3, 123.0, 113.9]]
  std = [x / 255 for x in [63.0, 62.1, 66.7]]

  # Init model, criterion, and optimizer for both twn and full
  net_full = models.__dict__[args.arch](num_classes) #NOTE load the architecture
  net_twn = models.__dict__[args.arch](num_classes)

  net_full = torch.nn.DataParallel(net_full, device_ids=list(range(args.ngpu)))
  net_twn = torch.nn.DataParallel(net_twn, device_ids=list(range(args.ngpu)))

  pretrained_full = torch.load(args.pretrained_full, map_location={'cuda:0': 'cpu'}) #NOTE Load Pre-trained Model
  pretrained_twn = torch.load(args.pretrained_twn, map_location={'cuda:0': 'cpu'}) #NOTE Load Pre-trained Model

  try:
    net_full.load_state_dict(pretrained_full['state_dict']) #NOTE reconstructs the model
  except KeyError as e:
    print("Error - Full")
    print(e)

  try:
    net_twn.load_state_dict(pretrained_twn['state_dict']) #NOTE reconstructs the model
  except KeyError as e:
    print("Error - Ternary")
    print(e)

  module_num = 18
  counter = 0
  print("\nFull Precision Weights")
  for m in net_full.modules():
    if (counter == module_num):
      print(m.weight[0][0])
    counter += 1

  counter = 0
  print("Ternary Weights")
  for m in net_twn.modules():
    if (counter == module_num):
      print(m.weight[0][0])
    counter += 1

  # run through all the test datasets
  test_transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean, std)])
  # DEFAULT TEST DATA LOADER
  test_data = dset.CIFAR10(args.data_path, train=False, transform=test_transform, download=False)
  test_loader = torch.utils.data.DataLoader(test_data, batch_size=args.batch_size, shuffle=False, num_workers=args.workers, pin_memory=True)
  print("Full Model:")
  validate(test_loader, net_full)
  print("TWN Model:")
  validate(test_loader, net_twn)

def noise_generator (tensor, s_vs_p = 0.5, amount = 0.004):
    out = tensor
    # Generate Salt '1' noise
    num_salt = np.ceil(amount * tensor.size * s_vs_p)
    coords = [np.random.randint(0, i - 1, int(num_salt))
          for i in tensor.shape]
    out[coords] = 255
    # Generate Pepper '0' noise
    num_pepper = np.ceil(amount * tensor.size * (1. - s_vs_p))
    coords = [np.random.randint(0, i - 1, int(num_pepper))
          for i in tensor.shape]
    out[coords] = 0
    return out

#NOTE net -> model, val_loader is the data loader, citerion is just a comparator module
def validate(val_loader, model):
  top1 = AverageMeter()
  top5 = AverageMeter()

  # switch to evaluate mode
  model.eval()

  #NOTE input is a tensor batch of images, target is a tensor of labels
  for i, (input, target) in enumerate(val_loader):
    input_var = torch.autograd.Variable(input, volatile=True) #NOTE constructs a variable from the input
    target_var = torch.autograd.Variable(target, volatile=True) #NOTE

    noisy_var = noise_generator(input_var, 0.5, 0.004)
    # compute output
    output = model(input_var)

    # measure accuracy
    prec1, prec5 = accuracy(output.data, target, topk=(1, 5)) #NOTE
    top1.update(prec1[0], input.size(0))
    top5.update(prec5[0], input.size(0))

  print('**Test** Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f} Error@1 {error1:.3f}'.format(top1=top1, top5=top5, error1=100-top1.avg))

  return top1.avg

def accuracy(output, target, topk=(1,)):
  """Computes the precision@k for the specified values of k"""
  maxk = max(topk)
  batch_size = target.size(0)

  _, pred = output.topk(maxk, 1, True, True)
  pred = pred.t()
  correct = pred.eq(target.view(1, -1).expand_as(pred))

  res = []
  for k in topk:
    correct_k = correct[:k].view(-1).float().sum(0)
    res.append(correct_k.mul_(100.0 / batch_size))
  return res

class AverageMeter(object):
  """Computes and stores the average and current value"""
  def __init__(self):
    self.reset()

  def reset(self):
    self.val = 0
    self.avg = 0
    self.sum = 0
    self.count = 0

  def update(self, val, n=1):
    self.val = val
    self.sum += val * n
    self.count += n
    self.avg = self.sum / self.count

main(args)


from button import Button
from all_image import *

class Menu:
    """
    Construct the menu for the start of the level_2.
    """
    def __init__(self, button_list, response):
        self.win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
        self.bg_image = MENU_BACKGROUND
        self.__buttons = button_list
        self.button_response = response

    def draw(self):
        """
        Draw everything here.
        :return: None
        """
        # draw background
        self.win.blit(self.bg_image, (0, 0))
        self.win.blit(LOGO_IMAGE_small, (1017, 2))
        # draw button
        for but in self.__buttons:
            self.win.blit(but.image, but.rect)
        pygame.display.update()

    def update(self):
        """
        Update for quit event and click button.
        :return game_quit: whether quit the level_2.
                self.button_response: used for changing to next page.
        """
        quit_game = False
        # event loop
        mouse_x, mouse_y = pygame.mouse.get_pos()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit_game = True
                return quit_game, self.button_response
            # player click action
            if event.type == pygame.MOUSEBUTTONDOWN:
                for btn in self.__buttons:
                    if btn.clicked(mouse_x, mouse_y):
                        self.button_response = btn.response
                        return quit_game, self.button_response
        return quit_game, self.button_response

    # 用繼承寫出三個主要頁面
    @classmethod
    def MainMenu(cls):  # 主頁面
        btn_list = [Button(LEVEL_BTN_IMAGE, "level menu", 400, 200),
                    Button(INTRO_BTN_IMAGE, "introduction", 800, 200),]
        main_menu = cls(btn_list, 'main menu')
        return main_menu

    @classmethod
    def LevelMenu(cls, level_state):  # 關卡選擇頁面
        btn_list = [Button(RETURN_IMAGE, "main menu", 75, 50)]
        Level_unlock = [Button(LV1_OP_BTN_IMAGE, "level_1", 200, 220),
                        Button(LV2_OP_BTN_IMAGE, "level_2", 400, 220),
                        Button(LV3_OP_BTN_IMAGE, "level_3", 600, 220),
                        Button(LV4_OP_BTN_IMAGE, "level_4", 800, 220),
                        Button(LV5_OP_BTN_IMAGE, "level_5", 1000, 220)]

        Level_locked = ["Level 1 has no locked problem.",
                        Button(LV2_CL_BTN_IMAGE, "level", 400, 220),
                        Button(LV3_CL_BTN_IMAGE, "level", 600, 220),
                        Button(LV4_CL_BTN_IMAGE, "level", 800, 220),
                        Button(LV5_CL_BTN_IMAGE, "level", 1000, 220)]

        # 如果關卡解鎖就放上解鎖圖按鈕
        btn_list.extend([Level_unlock[i] if level_state[i] else Level_locked[i] for i in range(5)])

        level_menu = cls(btn_list, 'level menu')
        return level_menu

class Introduction_Menu:
    def __init__(self):
        self.win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
        self.surf = pygame.surface.Surface((WIN_WIDTH, WIN_HEIGHT*2))
        self.bg_image = MENU_BACKGROUND
        self.__pages = [INTRODUCE01, INTRODUCE02]
        self.__buttons = [Button(RETURN_IMAGE, "main menu", 75, 50)]
        self.button_response = 'introduction'
        self.scroll = 0

    def draw(self):
        """
        Draw everything here.
        :return: None
        """
        self.win.blit(self.bg_image, (0, 0))
        # draw page
        for i, page in enumerate(self.__pages):
            self.surf.blit(page, (0, WIN_HEIGHT*i))

    def update(self):
        """
        Update for quit event and click button.
        :return game_quit: whether quit the level_2.
                self.button_response: used for changing to next page.
        """
        quit_game = False
        while not quit_game:
            # event loop
            mouse_x, mouse_y = pygame.mouse.get_pos()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    quit_game = True
                    return quit_game, self.button_response
                # player click action
                if event.type == pygame.MOUSEBUTTONDOWN:
                    for btn in self.__buttons:
                        if btn.clicked(mouse_x, mouse_y):
                            self.button_response = btn.response
                            return quit_game, self.button_response
                # 滾輪
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 4:
                        self.scroll = min(self.scroll + 100, 0)
                    if event.button == 5:
                        self.scroll = max(self.scroll - 100, -WIN_HEIGHT)

            self.win.blit(self.surf, (0, self.scroll))
            # draw button
            for but in self.__buttons:
                self.win.blit(but.image, but.rect)
            self.win.blit(LOGO_IMAGE_small, (1017, 2))
            pygame.display.update()


#!/usr/bin/env python
import gym
from IPython import embed

env = gym.make('CartPole-v0')
ac_space = env.action_space
for i_episode in range(20):
	observation = env.reset()
	for t in range(100):
		env.render()
		print(observation)
		action = raw_input("type action from {0,...,%i} and press enter: "%(ac_space.n-1))
		observation, reward, done, info = env.step(action)
		print(info)
		if done:
			# embed()
			print("Episode finished after {} timesteps".format(t+1))
			break


import random
import socket
import sys
import threading

def usage():
	print('Usage:')
	print('./proxy.py localhost localport remotehost remoteport')
	print('./proxy.py 192.0.0.2 6000 127.0.0.1 5000')

def handle(buffer):
	return buffer

def transfer(src, dst, direction):
	src_name = src.getsockname()
	src_address = src_name[0]
	src_port = src_name[1]
	dst_name = dst.getsockname()
	dst_address = dst_name[0]
	dst_port = dst_name[1]
	while True:
		buffer = src.recv(0x400)
		if len(buffer) == 0:
			print("[-] No data received! Breaking...")
			break
		# print "[+] %s:%d => %s:%d [%s]" % (src_address, src_port, dst_address, dst_port, repr(buffer))
		if direction:
			print(f'[+] {src_address}:{src_port} >>> {dst_address}:{dst_port} bytes: [{len(buffer)}]')
		else:
			print(f'[+] {dst_address}:{dst_port} >>> {src_address}:{src_port} bytes: [{len(buffer)}]')
		dst.send(handle(buffer))
	print(f'[-]  Closing connection! {src_address}:{src_port}')
	src.shutdown(socket.SHUT_RDWR)
	src.close()

	print(f'[-] Closing connection! {dst_address}:{dst_port}')
	dst.shutdown(socket.SHUT_RDWR)
	dst.close()

def server(local_host, local_port, remote_host, port_list, max_connections):

	server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

	try:
		server_socket.bind((local_host, local_port))
		print(f'Server bound to {local_host}:{local_port}')

	except Exception as e:
		print(f'Failed to bind to {local_host}:{local_port}')
		print('Check for already open port and/or permissions')
		print(f'[X] Error message: {e}')
		usage()
		sys.exit(0)

	server_socket.listen(max_connections)

	print(f'[+]Server listening on {local_host}:{local_port}')

	while True:
		remote_port = port_list[random.randint(0, len(port_list)-1)]
		local_socket, local_address = server_socket.accept()
		print(f'[+] Receiving incoming connection from {local_address[0]}:{local_address[1]}')
		print(f'[+] Trying to connect to remote server on {remote_host}:{remote_port}')

		remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

		try:
			remote_socket.connect((remote_host, remote_port))
			print(f'Connect to {local_host}:{local_port} to get content of {remote_host}:{remote_port}')

		except Exception as e:
			print(f'[!] Could not connect to server on {remote_host}:{remote_port}')
			print(f'[X] Error message: {e}')
			break

		print('[+] Tunnel opened! Transferring Data...')

		src = threading.Thread(target=transfer, args=(remote_socket, local_socket, False))

		rmt = threading.Thread(target=transfer, args=(local_socket, remote_socket, True))

		src.start()
		rmt.start()

	print('[-] Releasing resources')
	remote_socket.shutdown(socket.SHUT_RDWR)
	remote_socket.close()
	local_socket.shutdown(socket.SHUT_RDWR)
	local_socket.close()

	print('[-] Closing server...')
	server_socket.shutdown(socket.SHUT_RDWR)
	server_socket.close()
	print('[-] Server shutdown')

def main():
	local_host = '127.0.0.1'
	local_port = 7000

	remote_host = '127.0.0.1'
	remote_port_list = [5020, 5021]

	max_connections = 0x10

	server(local_host, local_port, remote_host, remote_port_list, max_connections)

if __name__ == '__main__':
	main()


from data_importers.management.commands import BaseDemocracyCountsCsvImporter

class Command(BaseDemocracyCountsCsvImporter):
    council_id = "EST"
    addresses_name = "2021-02-23T13:27:13.045364/Democracy Club - Polling Districts.csv"
    stations_name = "2021-02-23T13:27:13.045364/Democracy Club - Polling Stations.csv"
    elections = ["2021-05-06"]

    def address_record_to_dict(self, record):
        rec = super().address_record_to_dict(record)

        if rec and rec["postcode"] in ["ST14 8SG"]:
            # Spurious polling place for one property
            return None

        return rec

    def station_record_to_dict(self, record):
        # Shobnall Primary School
        if record.stationcode == "BP_21":
            record = record._replace(
                xordinate="422735", yordinate="323640", postcode="DE14 2BB"
            )

        # St Giles Church, Croxden Lane
        if record.stationcode == "AA_63":
            record = record._replace(
                xordinate="406486", yordinate="339871", postcode="ST14 5JG"
            )

        return super().station_record_to_dict(record)


import cuis_preprocess
from keras.preprocessing.text import Tokenizer
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Embedding, Dense, Dropout, GlobalMaxPooling1D
from keras.optimizers import Adam
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, roc_auc_score, roc_curve, auc
from sklearn.model_selection import train_test_split
from keras.callbacks import TensorBoard

if __name__ == "__main__":
    tokenizer = Tokenizer()
    tokenizer.fit_on_texts(cuis_preprocess.X_train)
    X_train_sequences = tokenizer.texts_to_sequences(cuis_preprocess.X_train)
    X_test_sequences = tokenizer.texts_to_sequences(cuis_preprocess.X_test)
    #X_val_sequences = tokenizer.texts_to_sequences(cuis_preprocess.X_val)
    word_index = tokenizer.word_index
    vocabulary_size = len(word_index)+1
    maxLen = len(max(X_train_sequences, key=len))
    X_train_sequences = sequence.pad_sequences(X_train_sequences, maxlen=maxLen)
    X_test_sequences = sequence.pad_sequences(X_test_sequences, maxlen=maxLen)
    #X_val_sequences = sequence.pad_sequences(X_val_sequences, maxlen=maxLen)

    # model
    model = Sequential()
    model.add(Embedding(vocabulary_size, 150, input_length=maxLen))
    model.add(GlobalMaxPooling1D())
    model.add(Dropout(0.5))
    model.add(Dense(1, activation='sigmoid'))
    adam = Adam(lr=0.001)
    model.compile(loss='binary_crossentropy',
                  optimizer=adam,
                  metrics=['accuracy'])
    tensorboard = TensorBoard(log_dir="logs/max2")
    x = model.fit(X_train_sequences,
                  cuis_preprocess.y_train,
                  validation_split=0.2,
                  batch_size=1,
                  epochs=20,
                  callbacks=[tensorboard])

    # train validation compare
    X_train_tmp, X_test_tmp, y_train_tmp, y_test_tmp = train_test_split(X_train_sequences,
                                                                        cuis_preprocess.y_train,
                                                                        test_size=0.2,
                                                                        random_state=1)
    train_pred = model.predict_proba(x=X_train_tmp,
                                     batch_size=1)
    fpr, tpr, _ = roc_curve(y_train_tmp, train_pred)
    print("max model training roc auc: " + str(auc(fpr, tpr)))
    val_pred = model.predict_proba(x=X_test_tmp,
                                   batch_size=1)
    fpr, tpr, _ = roc_curve(y_test_tmp, val_pred)
    print("max model validation roc auc: " + str(auc(fpr, tpr)))

    # graph
    class_pred = model.predict_classes(X_test_sequences, batch_size=16)
    acc = accuracy_score(cuis_preprocess.y_test, class_pred)
    print("deep max model test set accuracy " + str(acc))

    prob_pred = model.predict_proba(X_test_sequences, batch_size=16)
    roc_auc = roc_auc_score(cuis_preprocess.y_test, prob_pred) * 100
    print('{:0.2}'.format(roc_auc))

    loss = x.history['loss']
    val_loss = x.history['val_loss']
    epochs = range(1, len(loss) + 1)
    plt.plot(epochs, loss, 'b', color='b', label='Training loss')
    plt.plot(epochs, val_loss, 'b', color='g', label='Validation loss')
    plt.title('Traning and Validation loss')
    plt.xlabel('Epochs')
    plt.ylabel('Loss')
    plt.legend()
    plt.savefig("/home/sshah33/Readmission/Graphs/max_1.png")

    plt.clf()
    acc = x.history['acc']
    val_acc = x.history['val_acc']
    plt.plot(epochs, acc, 'b', color='b', label='Training acc')
    plt.plot(epochs, val_acc, 'b', color='g', label='Validation acc')
    plt.title('Traning and Validation Accuracy')
    plt.xlabel('Epochs')
    plt.ylabel('Acc')
    plt.legend()
    plt.savefig("/home/sshah33/Readmission/Graphs/max_2.png")

    fpr, tpr, _ = roc_curve(cuis_preprocess.y_test, prob_pred)
    roc_auc = auc(fpr, tpr)
    plt.figure()
    lw = 2
    plt.plot(fpr, tpr, color='darkorange',
             lw=lw, label='ROC curve (area = %0.2f)' % roc_auc)
    plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver Operating Characteristic')
    plt.legend(loc="lower right")
    plt.savefig("/home/sshah33/Readmission/Graphs/max_3.png")


from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from .forms import *
from .models import *
from django.contrib import messages
from django.shortcuts import redirect
import datetime
from datetime import date
import json
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

def slot(request):
    if not request.user.is_manager:
        return HttpResponse('
Customer
')
    else:
        if request.method=="POST":
            form=time_slot_form(request.POST)
            if form.is_valid():
                ini_time=form.cleaned_data["ini_time"]
                end_time=form.cleaned_data["end_time"]
                obj=Time_slots.objects.create(int_time=ini_time,end_time=end_time)
                obj.save()
                messages.success(request, "Slot successfully added")
                return redirect('/book/')
            else:
                messages.MessageFailure(request, 'Not created')
        form=time_slot_form()
        x=datetime.datetime.now().date()+datetime.timedelta(days=advance.objects.get(pk=1).no_days)
        context={'form':form,'x':x}
        return render(request,'book/slot_form.html',context)

def date(i):
    return i.date

def home(request):
    if not request.user.is_manager:
        booking1=Bookings.objects.all()
        booking1=sorted(booking1,key=date,reverse=True)
        for i in booking1:
            print(i.date)
        booking=[]
        for i in booking1:
            if i.user==request.user:
                booking.append(i)
        a=[]
        b=""
        for x in booking:
            b=b+str(x.room.name)+"  "
            b=b+str((x.date.strftime('%A %d %B %Y')))+"  "
            b=b+str(x.slot_id.int_time)
            b=b+"  To  "+str(x.slot_id.end_time)
            a.append((b,x.pk,bool(datetime.datetime.combine(x.date,x.slot_id.int_time)>datetime.datetime.now())))
            b=""
        print(a)
        contex={'a':a}
        return render(request,'book/home.html',contex)
    else:
        date1=datetime.datetime.now().date()
        x=Bookings.objects.filter(date=date1)
        a=[]
        b={}
        c=[]
        for i in x:
            b["roomname"]=str(i.room.name)
            b["status"]="Booked"
            b["intt"]=str(i.slot_id.int_time)
            b["endt"]=str(i.slot_id.end_time)
            b["user"]=str(i.user)
            a.append(b)
            b={}
        for i in Room.objects.all():
            if i not in [z.room for z in x]:
                b["roomname"]=str(i.name)
                b["status"]="Vaccant"
                c.append(b)
                b={}
        context={'a':a,'c':c,'date1':date1}
        return render(request,'book/m_home.html',context)

def book(request):
    if not request.user.is_manager:
        if request.method=="POST":
            form=bookings_form(request.POST)
            if form.is_valid():
                date=form.cleaned_data["date"]
                time_slot=Time_slots.objects.get(pk=form.cleaned_data["time_slot"])
                booking=[i.room for i in Bookings.objects.filter(date=date).filter(slot_id=time_slot)]
                for i in Room.objects.all():
                    if i not in booking:
                        break
                obj=Bookings.objects.create(user=request.user,date=date,slot_id=time_slot,room=i)
                obj.save()
                messages.success(request, "Slot successfully added")
                return redirect('/book/')
            else:
                print(form)
                messages.MessageFailure(request, 'Not created')
        form=bookings_form()
        context={'form':form,'max':advance.objects.get(pk=1).no_days}
        return render(request,'book/book_form.html',context)
    else:
        return HttpResponse('
Manager
')

def edit(request,id):
    if not request.user.is_manager:
        if request.method=="POST":
           form=bookings_form(request.POST)
           print("hi")
           if form.is_valid():
                print("hi")
                date=form.cleaned_data["date"]
                time_slot=Time_slots.objects.get(pk=form.cleaned_data["time_slot"])
                booking=[i.room for i in Bookings.objects.filter(date=date).filter(slot_id=time_slot)]
                Bookings.objects.get(pk=id).delete()
                for i in Room.objects.all():
                    if i not in booking:
                        break
                obj=Bookings.objects.create(user=request.user,date=date,slot_id=time_slot,room=i)
                obj.save()
                messages.success(request, "Slot successfully added")
                return redirect('/book/')
        booking=Bookings.objects.get(pk=id)
        print(booking.slot_id.pk)
        form=bookings_form(initial={'time_slot':booking.slot_id.pk,'date':booking.date})
        contest={'form':form}
        return render(request,'book/book_form.html',contest)

def cancle(request,id):
    if not request.user.is_manager:
        boooking=Bookings.objects.get(pk=id)
        boooking.delete()
        return redirect('/book/')
    else:
        return HttpResponse('
Manager
')

def ajax(request):
    print("Hi")
    date=request.GET.get('date')
    x=Bookings.objects.filter(date=date)
    a=[]
    b=[]
    for i in x:
        b.append(str(i.room.name))
        b.append("Booked")
        b.append(str(i.slot_id.int_time))
        b.append(str(i.slot_id.end_time))
        b.append(str(i.user))
        a.append(b)
        b=[]
    for i in Room.objects.all():
        if i not in [z.room for z in x]:
            b.append(str(i.name))
            b.append("Vaccant")
            for y in range(3):
                b.append("NA")
            a.append(b)
            b=[]
    context={'a':a}
    return JsonResponse(context)

def desc(request):
    if request.user.is_manager:
        dep=dependent.objects.all()
        for i in range(len(dep)):
            if datetime.datetime.now().date()<(dep[i].date):
                break
        x=dependent.objects.filter(date=dep[max(i-1,0)].date)
        time=[]
        for i in x:
            time.append(i.time_slot)
        x=datetime.datetime.now().date()+datetime.timedelta(days=advance.objects.get(pk=1).no_days)
        y=1
        if datetime.datetime.now().date() in [z.date for z in dep]:
            y=0
        context={'time':time,'date1':datetime.datetime.now().date(),'date2':x,'y':y}
        return render(request,'book/time_slot.html',context)

def edits(request,id):
    if request.user.is_manager:
        if request.method=="POST":
            form=time_slot_form(request.POST)
            if form.is_valid():
                ini_time=form.cleaned_data["ini_time"]
                end_time=form.cleaned_data["end_time"]
                obj=Time_slots.objects.create(int_time=ini_time,end_time=end_time)
                obj.save()
                x=datetime.datetime.now().date()+datetime.timedelta(days=advance.objects.get(pk=1).no_days)
                for i in Time_slots.objects.all():
                    if not i.pk==id:
                        dependent.objects.create(date=x,time_slot=i).save()
                messages.success(request, "Slot successfully added")
                return redirect('/book/edit/slots')
        slot=Time_slots.objects.get(pk=id)
        x=datetime.datetime.now().date()+datetime.timedelta(days=advance.objects.get(pk=1).no_days)
        print(x)
        form=time_slot_form()
        context={'form':form,'x':x,'in':slot.int_time,'out':slot.end_time}
        return render(request,'book/slot_form.html',context)

def cancles(request,id):
    x1=datetime.datetime.now().date()+datetime.timedelta(days=advance.objects.get(pk=1).no_days)
    dep=dependent.objects.all()
    for i in range(len(dep)):
        if datetime.datetime.now().date()<(dep[i].date):
            break
    y=dependent.objects.filter(date=dep[max(i-1,0)].date)
    for i in y:
        if not i.time_slot.pk==id:
            dependent.objects.create(date=x1,time_slot=i.time_slot).save()
    return redirect('/book/edit/slots')

def ajaxs(request):
    date=request.GET.get('date')
    print(date)
    dep=dependent.objects.all()
    print(dep[0].date)
    for i in range(len(dep)):
        if str(date)<str(dep[i].date):
            break
    x=dependent.objects.filter(date=dep[max(i-1,0)].date)
    a=[]
    b=[]
    for i in x:
        b.append(i.time_slot.int_time)
        b.append(i.time_slot.end_time)
        b.append(i.time_slot.pk)
        a.append(b)
        b=[]
    print(a)
    context={'a':a}
    return JsonResponse(context)

def add_room(request):
    if request.user.is_manager:
        if request.method=="POST":
            form=room_form(request.POST)
            if form.is_valid():
                name=form.cleaned_data["name"]
                Room.objects.create(name=name).save()
                return redirect('/book/')
        form=room_form()
        contex={'form':form}
        return render(request,'book/add_room.html',contex)
    else:
        return HttpResponse('
Customer
')

def change_days(request):
    if request.user.is_manager:
        if request.method=="POST":
            form=max_d(request.POST)
            if form.is_valid():
                days=form.cleaned_data["days"]
                obj=advance.objects.get(pk=1)
                obj.no_days=days
                obj.save()
                return redirect('/book/')
        form=max_d()
        contex={'form':form,'days':advance.objects.get(pk=1).no_days}
        return render(request,'book/change_days.html',contex)
    else:
        return HttpResponse('
Customer
')

@csrf_exempt
def slot_api(request):
    if request.method=="POST":
        print(request.body)
        data=request.body.decode('utf-8')
        received_json_data = json.loads(data)
        time1=received_json_data["int_time"]
        time2=received_json_data["end_time"]
        x=Time_slots.objects.create(int_time=time1,end_time=time2)
        x.save()
        return JsonResponse({'begin':x.int_time,'end':x.end_time})
    else:
        data=Time_slots.objects.all()
        a=[]
        b={}
        for i in data:
            b["start"]=i.int_time
            b["end"]=i.end_time
            a.append(b)
            b={}
        return JsonResponse({'a':a})


import subprocess
import os
import time

proc = None

def start(args, logfile, errfile):
    global proc
    proc = subprocess.Popen(
        "exec $PY2_GUNICORN app:app -c gunicorn_conf.py",
        cwd="flask", stderr=errfile, stdout=logfile, shell=True)
    return 0

def stop(logfile, errfile):
    global proc
    if proc is None:
        return 0
    proc.terminate()
    proc = None
    time.sleep(1)

    p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
    out, err = p.communicate()
    for line in out.splitlines():
      if 'gunicorn' in line:
        errfile.write("Killing: " + line + "\n")
        pid = int(line.split()[1])
        os.kill(pid, 15)
    return 0


"""
DeployMangaer for deploying software with fbuild
"""
from __future__ import absolute_import

import os
import sys
import platform
import subprocess
import logging
import traceback
import json
from copy import deepcopy

from common.platformdict import PlatformDict
from common.abstract import _AbstractFLaunchData, FLaunchDataError
from common import log
from common import utils
from common import constants
from common import communicate

from .parse import BuildCommandParser
from .buildfile import BuildFile
from .abstract_manager import _AbstractManager

class DeployManager(_AbstractManager):
    """
    Deployment!
    """
    type_ = 'deploy'

    def __init__(self, app, arguments, build_file, source_dir=None):
        _AbstractManager.__init__(self, app, arguments, build_file, source_dir=source_dir)
        build_file.add_attribute('version', self.version)
        self._stage = 'none'

    def run_deploy(self):
        """
        Execute the deployment.
        """
        self.setup_environment()
        self.prerequisite_check()
        self._pre_deploy_commands()
        if self.deploy():
            self._post_deploy_commands()

    def run_registration(self):
        """
        Execute a registratino process
        """
        self.setup_environment()
        if not self.arguments.skip_validation:
            self._verify_existence()
        else:
            logging.warning('Releasing package without file validation')

        result = communicate.register_package(
            self.package,
            self.version,
            method='post',
            launch_data=None,
            force=self.arguments.force,
            pre_release=self.arguments.beta
        )
        return result

    @property
    def stage(self):
        return self._stage

    @property
    def version(self):
        return self.arguments.version

    def deploy(self):
        """
        The deployment process starts here!
        :return: bool
        """
        if not (self.arguments.transfer):
            # This was only a predeploy, nothing to do
            logging.info("Predeploy Only")
            return False

        self._stage = 'deploy'
        logging.debug(':Deploy:')
        with log.log_indent():

            deploy_descrpitor = self.build_file[self.type_]
            deploy_commands = deploy_descrpitor['commands']
            self.build_commands(None, deploy_commands)

        return True

    # -- Private Methods

    def _verify_existence(self):
        """
        Verify that the version we're looking for exists globally. This
        requires a machine that can reach all points - which is a bit of
        a tough ask when considering the nature of the active disk
        architecture...
        :return: None
        """
        # TODO!
        return

    def _pre_deploy_commands(self):
        """
        Using the build file, identify if we have any commands to process
        with our environment and then do it!
        :return: None
        """
        self._stage = 'pre_deploy'

        logging.debug(':Pre Deploy:')
        with log.log_indent():

            deploy_descrpitor = self.build_file[self.type_]

            condition = deploy_descrpitor['pre_deploy_conditions']
            pre_deploy = deploy_descrpitor['pre_deploy']
            self.build_commands(condition, pre_deploy, 'Pre')

    def _post_deploy_commands(self):
        """
        Using the build file, identify if we have any commands to process
        with our environment and then do it!
        :return: None
        """
        self._stage = 'post_deploy'
        deploy_descrpitor = self.build_file[self.type_]

        logging.debug(':Post Deploy:')
        with log.log_indent():

            deploy_descrpitor = self.build_file[self.type_]

            condition = deploy_descrpitor['post_deploy_conditions']
            post_deploy = deploy_descrpitor['post_deploy']
            self.build_commands(condition, post_deploy, 'Post')


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('rtiapp', '0002_auto_20151104_1356'),
    ]

    operations = [
        migrations.CreateModel(
            name='UserActivity',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('activity_type', models.CharField(max_length=50, choices=[(b'comment_rti', b'comment_rti'), (b'like_rti', b'like_rti'), (b'follow_rti', b'follow_rti'), (b'edit_comment_rti', b'edit_comment_rti'), (b'delete_comment_rti', b'delete_comment_rti'), (b'unlike_rti', b'unlike_rti'), (b'unfollow_rti', b'unfollow_rti'), (b'follow_user', b'unfollow_user')])),
                ('entry_date', models.DateTimeField(auto_now_add=True)),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


"""
Each ListNode holds a reference to its previous node
as well as its next node in the List.
"""
class ListNode:
    def __init__(self, value, prev=None, next=None):
        self.prev = prev
        self.value = value
        self.next = next

"""
Our doubly-linked list class. It holds references to
the list's head and tail nodes.
"""
class DoublyLinkedList:
    def __init__(self, node=None):
        self.head = node
        self.tail = node
        self.length = 1 if node is not None else 0
        self.old_node = self.head

    def __len__(self):
        return self.length

    """
    Wraps the given value in a ListNode and inserts it
    as the new head of the list. Don't forget to handle
    the old head node's previous pointer accordingly.
    """
    def add_to_head(self, value):
        new_node = ListNode(value)
        self.length += 1
        #change head to point to new node
        if self.head is None and self.tail is None:
            self.head = new_node
            self.tail = new_node
            return
        else:
            #change head to point to next
            old_head = self.head
            self.head = new_node
            self.head.next = old_head

    """
    Removes the List's current head node, making the
    current head's next node the new head of the List.
    Returns the value of the removed Node.
    """
    def remove_from_head(self):
        if self.head is None and self.tail is None:
            return
        elif self.head.next is None:
            self.length -= 1
            old_head = self.head
            self.head = None
            self.tail = None
            return old_head.value
        else:
            old_head = self.head
            self.head = self.head.next
            self.head.prev = None
            self.length -= 1
            return old_head.value

    """
    Wraps the given value in a ListNode and inserts it
    as the new tail of the list. Don't forget to handle
    the old tail node's next pointer accordingly.
    """
    def add_to_tail(self, value):
        new_node = ListNode(value)
        if self.head is None and self.tail is None:
            self.head = new_node
            self.tail = new_node
        else:
            self.tail.next = new_node
            # none <-> head <-> number <-> tail -> new_node
            new_node.prev = self.tail
            # none <-> head <-> number <-> tail <-> new_node
            self.tail = new_node
            # none <-> head <-> number <-> number <-> new_node(tail) -> None
        self.length += 1
    """
    Removes the List's current tail node, making the
    current tail's previous node the new tail of the List.
    Returns the value of the removed Node.
    """
    def remove_from_tail(self):
        #access the tail value
        if self.head is None and self.tail is None:
            return
        self.length -= 1
        if self.head.next is None and self.head is not None:
            value = self.head.value
            self.head = None
            self.tail = None
            return value
        n = self.head
        value = self.tail.value
        # None <-> Head <-> number(Tail) -> None
        while n.next is not None:
            n = n.next
        # None <-> Head <-> number <-> Tail -> None

        self.tail = n.prev
        #None <-> Head <-> number(Tail) <-> number -> None
        n.prev = None
        self.tail.next = None
        n = None
        return value
        #None <-> Head <-> number(Tail) -> None

    """
    Removes the input node from its current spot in the
    List and inserts it as the new head node of the List.
    """
    def move_to_front(self, node):
        self.delete(node)

        self.add_to_head(node.value)

        return self.head.value

    """
    Removes the input node from its current spot in the
    List and inserts it as the new tail node of the List.
    """
    def move_to_end(self, node):
        self.delete(node)
        self.add_to_tail(node.value)
        return self.tail.value

    """
    Deletes the input node from the List, preserving the
    order of the other elements of the List.
    """
    def delete(self, node):
        if self.length < 1:
            return
        if self.length > 1:
            if node is self.head:
                self.remove_from_head()
            elif node is self.tail:
                #self.tail = self.tail.prev
                self.remove_from_tail()
            else:
                self.length -= 1
                next_node = node.next
                prev_node = node.prev
                next_node.prev = prev_node
        elif self.length == 1:
            self.head = None
            self.tail = None
            self.length = 0

    """
    Finds and returns the maximum value of all the nodes
    in the List.
    """
    def get_max(self):
        if self.head is None and self.tail is None:
            return None
        max = self.head.value
        current = self.head
        while current is not None:
            #compare value with max
            if current.value > max:
                max = current.value
            current = current.next
        return max

dl = DoublyLinkedList(ListNode(9))
print("head is: ", str(dl.head.value))
print("tail is: ", str(dl.tail.value))
dl.add_to_head(2)
dl.add_to_head(4)
print("head is: ", str(dl.head.value))
print("tail is: ", str(dl.tail.value))
dl.add_to_tail(6)
print("head is add tail: ", str(dl.head.value))
print("tail is add tail: ", str(dl.tail.value))
print("tail is add tail: ", str(dl.tail.prev))
print("==============================")
dl.remove_from_head()
print("head is: ", str(dl.head.value))
print("tail is: ", str(dl.tail.value))
print("================================")
dl.remove_from_tail()
print("head is: ", str(dl.head.value))
#print("tail is: ", str(dl.tail.value))


# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")

# https://app.codility.com/demo/results/trainingJZRTFC-6P2/
def binary_search(start, end, arr):
    if start + 1 == end:
        return start
    if arr[(start + end) // 2] == (start + end) // 2:
        return binary_search((start + end) // 2, end, arr)
    else:
        return binary_search(start, (start + end) // 2, arr)

def solution(A):
    # write your code in Python 3.6

    B = sorted(A)
    B.insert(0, 0)
    N = len(B)

    result = B[binary_search(0, N, B)]

    return  result + 1


#!/usr/bin/env python

"""
Subrequests to do things like range requests, content negotiation checks,
and validation.
"""

__author__ = "Mark Nottingham <mnot@mnot.net>"
__copyright__ = """\
Copyright (c) 2008-2011 Mark Nottingham

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

from cgi import escape as e
import random
import time

from redbot.fetch import RedFetcher
from redbot.response_analyse import f_num
import redbot.speak as rs

class SubRequest(RedFetcher):
    """
    A subrequest of a "main" ResourceExpertDroid, made to perform additional
    behavioural tests on the resource.

    it both adorns the given red's state, and saves its own state in the
    given red's subreqs dict.
    """
    def __init__(self, red, name):
        self.base = red.state
        req_hdrs = self.modify_req_hdrs()
        RedFetcher.__init__(self, self.base.uri, self.base.method, req_hdrs,
                            self.base.req_body, red.status_cb, [], name)
        self.base.subreqs[name] = self.state

    def modify_req_hdrs(self):
        """
        Usually overidden; modifies the request's headers.

        Make sure it returns a copy of the orignals, not them.
        """
        return list(self.base.orig_req_hdrs)

    def setMessage(self, subject, msg, subreq=None, **kw):
        self.base.setMessage(subject, msg, self.state.type, **kw)

class ConnegCheck(SubRequest):
    """
    See if content negotiation for compression is supported, and how.

    Note that this depends on the "main" request being sent with
    Accept-Encoding: gzip
    """
    def modify_req_hdrs(self):
        return [h for h in self.base.orig_req_hdrs
            if h[0].lower() != 'accept-encoding']

    def preflight(self):
        if "gzip" in self.base.parsed_hdrs.get('content-encoding', []):
            return True
        else:
            self.base.gzip_support = False
            return False

    def done(self):
        if self.state.res_body_len > 0:
            savings = int(100 *
                (
                    (float(self.state.res_body_len) - \
                    self.base.res_body_len
                    ) / self.state.res_body_len
                )
            )
        else:
            savings = 0
        self.base.gzip_support = True
        self.base.gzip_savings = savings
        if savings >= 0:
            self.setMessage('header-content-encoding',
                rs.CONNEG_GZIP_GOOD,
                savings=savings,
                orig_size=f_num(self.state.res_body_len),
                gzip_size=f_num(self.base.res_body_len)
            )
        else:
            self.setMessage('header-content-encoding',
                rs.CONNEG_GZIP_BAD,
                savings=abs(savings),
                orig_size=f_num(self.state.res_body_len),
                gzip_size=f_num(self.base.res_body_len)
            )
        vary_headers = self.base.parsed_hdrs.get('vary', [])
        if (not "accept-encoding" in vary_headers) \
        and (not "*" in vary_headers):
            self.setMessage('header-vary header-%s', rs.CONNEG_NO_VARY)
        # TODO: verify that the status/body/hdrs are the same;
        # if it's different, alert
        no_conneg_vary_headers = self.state.parsed_hdrs.get('vary', [])
        if 'gzip' in self.state.parsed_hdrs.get('content-encoding', []) or \
           'x-gzip' in self.state.parsed_hdrs.get('content-encoding', []):
            self.setMessage('header-vary header-content-encoding',
                                 rs.CONNEG_GZIP_WITHOUT_ASKING)
        if no_conneg_vary_headers != vary_headers:
            self.setMessage('header-vary',
                rs.VARY_INCONSISTENT,
                conneg_vary=e(", ".join(vary_headers)),
                no_conneg_vary=e(", ".join(no_conneg_vary_headers))
            )
        if self.state.parsed_hdrs.get('etag', 1) \
           == self.base.parsed_hdrs.get('etag', 2):
            self.setMessage('header-etag', rs.ETAG_DOESNT_CHANGE)
            # TODO: weakness?

class RangeRequest(SubRequest):
    "Check for partial content support (if advertised)"

    def modify_req_hdrs(self):
        req_hdrs = list(self.base.req_hdrs)
        if len(self.base.res_body_sample) != 0:
            sample_num = random.randint(0, len(self.base.res_body_sample) - 1)
            sample_len = min(
                96, len(self.base.res_body_sample[sample_num][1])
            )
            self.range_start = self.base.res_body_sample[sample_num][0]
            self.range_end = self.range_start + sample_len
            self.range_target = \
                self.base.res_body_sample[sample_num][1][:sample_len + 1]
            # TODO: uses the compressed version (if available. Revisit.
            req_hdrs += [
                ('Range', "bytes=%s-%s" % (self.range_start, self.range_end))
            ]
        return req_hdrs

    def preflight(self):
        if 'bytes' in self.base.parsed_hdrs.get('accept-ranges', []):
            if len(self.base.res_body_sample) == 0:
                return False
            if self.range_start == self.range_end:
                # wow, that's a small body.
                return False
            return True
        else:
            self.base.partial_support = False
            return False

    def done(self):
        if self.state.res_status == '206':
            # TODO: check entity headers
            # TODO: check content-range
            ce = 'content-encoding'
            if ('gzip' in self.base.parsed_hdrs.get(ce, [])) == \
               ('gzip' not in self.state.parsed_hdrs.get(ce, [])):
                self.setMessage(
                    'header-accept-ranges header-content-encoding',
                    rs.RANGE_NEG_MISMATCH
                )
                return
            if self.state.parsed_hdrs.get('etag', 1) == \
              self.base.parsed_hdrs.get('etag', 2):
                if self.state.res_body == self.range_target:
                    self.base.partial_support = True
                    self.setMessage('header-accept-ranges', rs.RANGE_CORRECT)
                else:
                    # the body samples are just bags of bits
                    self.base.partial_support = False
                    self.setMessage('header-accept-ranges',
                        rs.RANGE_INCORRECT,
                        range="bytes=%s-%s" % (
                            self.range_start, self.range_end
                        ),
                        range_expected=e(
                            self.range_target.encode('string_escape')
                        ),
                        range_expected_bytes = f_num(len(self.range_target)),
                        range_received = e(
                            self.state.res_body.encode('string_escape')
                        ),
                        range_received_bytes = f_num(self.state.res_body_len)
                    )
            else:
                self.setMessage('header-accept-ranges', rs.RANGE_CHANGED)

        # TODO: address 416 directly
        elif self.state.res_status == self.base.res_status:
            self.base.partial_support = False
            self.setMessage('header-accept-ranges', rs.RANGE_FULL)
        else:
            self.setMessage('header-accept-ranges',
                rs.RANGE_STATUS,
                range_status=self.state.res_status,
                enc_range_status=e(self.state.res_status)
            )

class ETagValidate(SubRequest):
    "If an ETag is present, see if it will validate."

    def modify_req_hdrs(self):
        req_hdrs = list(self.base.req_hdrs)
        if self.base.parsed_hdrs.has_key('etag'):
            weak, etag = self.base.parsed_hdrs['etag']
            if weak:
                weak_str = "W/"
                # TODO: message on weak etag
            else:
                weak_str = ""
            etag_str = '%s"%s"' % (weak_str, etag)
            req_hdrs += [
                ('If-None-Match', etag_str),
            ]
        return req_hdrs

    def preflight(self):
        if self.base.parsed_hdrs.has_key('etag'):
            return True
        else:
            self.base.inm_support = False
            return False

    def done(self):
        if self.state.res_status == '304':
            self.base.inm_support = True
            self.setMessage('header-etag', rs.INM_304, self.state)
            # TODO : check Content- headers, esp. length.
        elif self.state.res_status == self.base.res_status:
            if self.state.res_body_md5 == self.base.res_body_md5:
                self.base.inm_support = False
                self.setMessage('header-etag', rs.INM_FULL)
            else:
                self.setMessage('header-etag', rs.INM_UNKNOWN)
        else:
            self.setMessage('header-etag',
                rs.INM_STATUS,
                inm_status = self.state.res_status,
                enc_inm_status = e(self.state.res_status)
            )
        # TODO: check entity headers

class LmValidate(SubRequest):
    "If Last-Modified is present, see if it will validate."

    def modify_req_hdrs(self):
        req_hdrs = list(self.base.req_hdrs)
        if self.base.parsed_hdrs.has_key('last-modified'):
            date_str = time.strftime(
                '%a, %d %b %Y %H:%M:%S GMT',
                time.gmtime(self.base.parsed_hdrs['last-modified'])
            )
            req_hdrs += [
                ('If-Modified-Since', date_str),
            ]
        return req_hdrs

    def preflight(self):
        if self.base.parsed_hdrs.has_key('last-modified'):
            return True
        else:
            self.base.ims_support = False
            return False

    def done(self):
        if self.state.res_status == '304':
            self.base.ims_support = True
            self.setMessage('header-last-modified', rs.IMS_304)
            # TODO : check Content- headers, esp. length.
        elif self.state.res_status == self.base.res_status:
            if self.state.res_body_md5 == self.base.res_body_md5:
                self.base.ims_support = False
                self.setMessage('header-last-modified', rs.IMS_FULL)
            else:
                self.setMessage('header-last-modified', rs.IMS_UNKNOWN)
        else:
            self.setMessage('header-last-modified',
                rs.IMS_STATUS,
                ims_status = self.state.res_status,
                enc_ims_status = e(self.state.res_status)
            )
        # TODO: check entity headers


# Self and __init__() functions:-

"""
Self is used to specify the arguments. Self keeps the ability to automatically access anything without calling the function.
"""

# class Officers:
#     Pension = 15000

#     def printdetails(self):
#         return f"Employee name is {self.name}.\nEmployee's post is {self.post}.\nEmployee salary is {self.salary}\n  "
#
#     def __init__(self, name, post, salary):
#         self.name = name
#         self.post = post
#         self.salary = salary

# Mukesh = Officers()
# Ramesh = Officers()

# Mukesh.name = "Mukesh"
# Mukesh.post = "Senior manager"
# Mukesh.salary = 40000

# Ramesh.name = "Ramesh"
# Ramesh.post = "Personal Assistant"
# Ramesh.salary = 30000

# print(Mukesh.printdetails())
# print(Ramesh.printdetails())

"""
In the above function which is printdetails(self), self stands as a common representative prefix for any object. Whenever
an object is called with printdetails() function the representative prefix will get replaced by the particular object.
As per the above code, If we call function with object "Mukesh", then the function will return "Mukesh.name" and "Mukesh.salary"
simultaneously.

Note1 :- If the corresponding object or variables do not exist, then python will throw an error. Make sure to check everything
         before making a function call.

Note2 :- As this topic is about self function we used it as a common representative for any object called along with the
         function. But you can anything else in it's place rather than "self" everytime. For Ex:- element, yourself, etc.
"""

# Constructor and __init__() function :-

"""
The method of giving arguments to the class is called as a constructor. As you can't directly insert any property into
an object and you need to present them through constructor, init() function is used.
Ex:-

"""

# Salman = Officers()
# Shahrukh = Officers()

"""
Salman and shahrukh are the objects here which are created using class constructor, i.e Officers(). If we use class constructor
to enter properties directly into object Salman, then it will give an error. It is because even if Officers has a paranthesis
but still the class isn't addressed by the user to accept any type of arguments and thus, class will give an error after
failing to find a common representative of that argument. To let the class accept arguments from user, __init__ function
is used.
"""
# Creating an init function in class Officers :-

class Officers:                              # Class creation without any arguments
    Pension = 15000                          # Class variable

    def __init__(self, Rename, Repost, Resalary):  # This function will take values from an object and assign the values as received.
        self.name = Rename                         # here, name is a instance variable and Rename is the argument received
        self.post = Repost                         # from user whose value is going to assign to the object-variable pair.
        self.salary = Resalary

"""
Here, the init function is declared inside class Officers. We have created the first __init__() function which will work
as a constructor whenever user will operate it with an object. here,

self --> self is an argument which will be used by init() to identify the main object of the class to which user wants
         to assign values. It is a representative of the under-construction object. For Ex:- If Ramesh is the object, then
         self will represent him and values will be assigned to it afterwards.

name --> "name" values is assigned to instance property. Whatever values is a assigned to instance's propert or variable,
          will be the new value of that property. "Self" will represent object and name will represent it's variable or
          property. Rename will be the argument which will be the messenger of value from user to the object-instance pair.

Salary and post --> both properties follow the same mechanism as first property "name".

To apply this function, ou don't need to call it. You just need to declare an object with class constructor and then write
corresponding arguments similar to the representative arguments user have set in the init() function.

Ex:- We will take sarvesh as object and then will assign value.
"""

# sarvesh = Officers("Mr.Sarvesh Kumar", "Clerk", 15060)

"""
In the above statement,
1. Sarvesh is the object we have created using Officers() constructor.

2. "Mr.Sarvesh Kumar", "Clerk", 15060 will stand for the representative arguments Rename, Repost and Resalary in init function

Now you can easily check the assigned values to the properties of instances.
"""

# print(sarvesh.name)

"""
The above print statement will be acknowledged by the value and will print it. The main question is when we didn't called
init function how did the values were updated or printed accurately? The answer is still constructor's abilities.

When we declared object "Sarvesh" through class constructor and added arguments inside it, Class Officers looked for a
function who will take the arguments and store them. here, init function was the function which was used to receive arguments
from user without giving any error like "No arguments in the function but 3 were given".

The advantage of init() function is that you can ultimately assign values to the particular properties whenever a user creates
an object and creates object-variable in it.

The init() function saves a lot of time which would have been wasted mercilessly on creating object, creating variables
and then assigning them values again and again. As all this schedule is fixed into init() function, User needs to just
declare an object using class constructor and then fill up class constructor's parenthesis.
"""


# FILES/FOLDERS 002 - MEDIUM
# Get a list of all [txt|csv|whatever files in a directory].  Open each one and
# print it to the screen (or print the numbers of lines in the file, or the
# first line - whatever.  Touch each file one way or another.)

from os import listdir
from os.path import isfile, join

mypath = "/Users/awernicke/Documents/GitHub/learn_python/original_code/jc_tutorial_challenges/text_files"

paths_to_files = []
files_and_directories = listdir(mypath)
for file_and_directory_name in files_and_directories:
    path_to_file_or_dir = join(mypath, file_and_directory_name)
    if isfile(path_to_file_or_dir):
        paths_to_files.append(path_to_file_or_dir)

for file in paths_to_files:
    with open(file) as file:
        content = file.read()
        print(content)


#Modeling - Naive Bayes
import pandas as pd
from sklearn.naive_bayes import GaussianNB  #Naive Bayes model
from sklearn import model_selection #k-fold validation
from sklearn.cross_validation import train_test_split #split the data into train and test data
data=pd.read_csv('English_outputpreprocessing.csv')
n1=len(data)
l=list(data[0:0])
l1=l.index('Q. 1 /5.00')

def model_NB(qs,qe,st): #Modelling & Accuracy
    NB1=pd.DataFrame(data.iloc[0:n1,qs:qe]) #particular section data
    NB2=pd.DataFrame(data.iloc[0:n1,st]) #particular section label
    X_train, X_test, y_train, y_test = train_test_split(NB1, NB2, test_size = 0.25, random_state = 0) #Training & Testing data
    clf = GaussianNB() #Gaussian Naive Bayes model
    clf.fit(X_train,y_train.values.ravel())  #fit our data into model
    test=clf.predict(X_test) #predict the test data
    kfold = model_selection.KFold(n_splits=15) #k-fold cross validation
    accuracy = model_selection.cross_val_score(clf,X_train,y_train.values.ravel(), cv=kfold) # find accuracy
    return test,accuracy.mean()*100

vocab=model_NB(l1,l1+9,l1+38)
print("Vocabulary Section: ",vocab[0])
print("accuracy Vocabulary: ",vocab[1])
grammar=model_NB(l1+9,l1+18,l1+39)
print("Grammar Section",grammar[0])
print("accuracy Vocabulary: ",grammar[1])
reading=model_NB(l1+18,l1+30,l1+40)
print("Reading Section",reading[0])
print("accuracy Reading: ",reading[1])
Computer=model_NB(l1+30,l1+35,l1+41)
print("Computer Section",Computer[0])
print("accuracy Computer: ",Computer[1])
writing=model_NB(l1+35,l1+38,l1+42)
print("Writing Section",writing[0])
print("accuracy Writing: ",writing[1])


# coding: utf-8

# -----------------------------------------------------------------------------------
# <copyright company="Aspose Pty Ltd" file="MailStorageOptions.py">
#   Copyright (c) 2003-2023 Aspose Pty Ltd
# </copyright>
# <summary>
#   Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in all
#  copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#  SOFTWARE.
# </summary>
# -----------------------------------------------------------------------------------

import pprint
import re  # noqa: F401

import six

class MailStorageOptions(object):
    """
    Provides options for rendering Mail storage (Lotus Notes, MBox) data files.
    """

    """
    Attributes:
      swagger_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    swagger_types = {
        'text_filter': 'str',
        'address_filter': 'str',
        'max_items': 'int'
    }

    attribute_map = {
        'text_filter': 'TextFilter',
        'address_filter': 'AddressFilter',
        'max_items': 'MaxItems'
    }

    def __init__(self, text_filter=None, address_filter=None, max_items=None, **kwargs):  # noqa: E501
        """Initializes new instance of MailStorageOptions"""  # noqa: E501

        self._text_filter = None
        self._address_filter = None
        self._max_items = None

        if text_filter is not None:
            self.text_filter = text_filter
        if address_filter is not None:
            self.address_filter = address_filter
        if max_items is not None:
            self.max_items = max_items

    @property
    def text_filter(self):
        """
        Gets the text_filter.  # noqa: E501

        The keywords used to filter messages.  # noqa: E501

        :return: The text_filter.  # noqa: E501
        :rtype: str
        """
        return self._text_filter

    @text_filter.setter
    def text_filter(self, text_filter):
        """
        Sets the text_filter.

        The keywords used to filter messages.  # noqa: E501

        :param text_filter: The text_filter.  # noqa: E501
        :type: str
        """
        self._text_filter = text_filter

    @property
    def address_filter(self):
        """
        Gets the address_filter.  # noqa: E501

        The email-address used to filter messages by sender or recipient.  # noqa: E501

        :return: The address_filter.  # noqa: E501
        :rtype: str
        """
        return self._address_filter

    @address_filter.setter
    def address_filter(self, address_filter):
        """
        Sets the address_filter.

        The email-address used to filter messages by sender or recipient.  # noqa: E501

        :param address_filter: The address_filter.  # noqa: E501
        :type: str
        """
        self._address_filter = address_filter

    @property
    def max_items(self):
        """
        Gets the max_items.  # noqa: E501

        The maximum number of messages or items for render. Default value is 0 - all messages will be rendered  # noqa: E501

        :return: The max_items.  # noqa: E501
        :rtype: int
        """
        return self._max_items

    @max_items.setter
    def max_items(self, max_items):
        """
        Sets the max_items.

        The maximum number of messages or items for render. Default value is 0 - all messages will be rendered  # noqa: E501

        :param max_items: The max_items.  # noqa: E501
        :type: int
        """
        if max_items is None:
            raise ValueError("Invalid value for `max_items`, must not be `None`")  # noqa: E501
        self._max_items = max_items

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, MailStorageOptions):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        return not self == other


import datetime
from numpy import random
print('happyjourney')
current_date_time = datetime.datetime.now()
print(current_date_time)
train_no = random.randint(9,size=(5))
print('train_no:',train_no)

area = {'chengalpattu': 1, 'paranur': 2, 'singaperumal': 3, 'kovil': 4, 'maraimalai nagar': 5, 'kattangulattur': 6,
        'potheri': 7, 'guduvancheri': 8, 'Urappakkam': 9, 'Vandalur': 10, 'Perungulattur': 11, 'tambaram': 12,  'Chrompet': 13,
        'pallavarm': 14, 'tirusulam': 15, 'minambakkam': 16, 'palavanthangal': 17, 'st Thomas Mount': 18,
        'guindy': 19, 'saidapet': 20, 'mambalam': 21, 'kodambakkam': 22, 'nungambakkam': 23, 'chetpet': 24,
        'egmore': 25, 'park': 26, 'fort': 27, 'mearina beach': 28, 'basent bridge': 29}

s = input('enter your starting point')
d = input('enter your destination reach')
price = 10
i = area[s]
j = area[d]
x = j - i
a = 10

if x <16:
     print(price)

else:
    c = price + 20
    print(c)


# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Logic for clustering similar symbols."""

import collections
import logging
import re

# Refer to models.SymbolGroup.Cluster() for pydoc
def ClusterSymbols(symbols):
  # http://unix.stackexchange.com/questions/223013/function-symbol-gets-part-suffix-after-compilation
  # Example name suffixes:
  #     [clone .part.322]  # GCC
  #     [clone .isra.322]  # GCC
  #     [clone .constprop.1064]  # GCC
  #     [clone .11064]  # clang

  # Step 1: Create name map, find clones, collect star syms into replacements.
  logging.debug('Creating name -> symbol map')
  clone_indices = []
  indices_by_full_name = {}
  # (section_name, name, full_name) -> [(index, sym),...]
  replacements_by_tup = collections.defaultdict(list)
  for i, symbol in enumerate(symbols):
    if symbol.name.startswith('**'):
      # "symbol gap 3" -> "symbol gaps"
      name = re.sub(r'\s+\d+( \(.*\))?$', 's', symbol.name)
      replacements_by_tup[(symbol.section_name, name, None)].append((i, symbol))
    elif symbol.full_name:
      if symbol.full_name.endswith(']') and ' [clone ' in symbol.full_name:
        clone_indices.append(i)
      else:
        indices_by_full_name[symbol.full_name] = i

  # Step 2: Collect same-named clone symbols.
  logging.debug('Grouping all clones')
  group_names_by_index = {}
  for i in clone_indices:
    symbol = symbols[i]
    # Multiple attributes could exist, so search from left-to-right.
    stripped_name = symbol.name[:symbol.name.index(' [clone ')]
    stripped_full_name = symbol.full_name[:symbol.full_name.index(' [clone ')]
    name_tup = (symbol.section_name, stripped_name, stripped_full_name)
    replacement_list = replacements_by_tup[name_tup]

    if not replacement_list:
      # First occurance, check for non-clone symbol.
      non_clone_idx = indices_by_full_name.get(stripped_name)
      if non_clone_idx is not None:
        non_clone_symbol = symbols[non_clone_idx]
        replacement_list.append((non_clone_idx, non_clone_symbol))
        group_names_by_index[non_clone_idx] = stripped_name

    replacement_list.append((i, symbol))
    group_names_by_index[i] = stripped_name

  # Step 3: Undo clustering when length=1.
  # Removing these groups means Diff() logic must know about [clone] suffix.
  to_clear = []
  for name_tup, replacement_list in replacements_by_tup.iteritems():
    if len(replacement_list) == 1:
      to_clear.append(name_tup)
  for name_tup in to_clear:
    del replacements_by_tup[name_tup]

  # Step 4: Replace first symbol from each cluster with a SymbolGroup.
  before_symbol_count = sum(len(x) for x in replacements_by_tup.itervalues())
  logging.debug('Creating %d symbol groups from %d symbols. %d clones had only '
                'one symbol.', len(replacements_by_tup), before_symbol_count,
                len(to_clear))

  len_delta = len(replacements_by_tup) - before_symbol_count
  grouped_symbols = [None] * (len(symbols) + len_delta)
  dest_index = 0
  src_index = 0
  seen_tups = set()
  replacement_tup_by_index = {}
  for name_tup, replacement_list in replacements_by_tup.iteritems():
    for tup in replacement_list:
      replacement_tup_by_index[tup[0]] = name_tup

  sorted_items = replacement_tup_by_index.items()
  sorted_items.sort(key=lambda tup: tup[0])
  for index, name_tup in sorted_items:
    count = index - src_index
    grouped_symbols[dest_index:dest_index + count] = (
        symbols[src_index:src_index + count])
    src_index = index + 1
    dest_index += count
    if name_tup not in seen_tups:
      seen_tups.add(name_tup)
      group_symbols = [tup[1] for tup in replacements_by_tup[name_tup]]
      grouped_symbols[dest_index] = symbols._CreateTransformed(
          group_symbols, name=name_tup[1], full_name=name_tup[2],
          section_name=name_tup[0])
      dest_index += 1

  assert len(grouped_symbols[dest_index:None]) == len(symbols[src_index:None])
  grouped_symbols[dest_index:None] = symbols[src_index:None]
  logging.debug('Finished clustering symbols.')
  return grouped_symbols


import sys
import os.path
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sympy as sym
from sympy import Array
from numba import jit,autojit
from mpmath import *
import math
import periodicpointexp2 as periodic
import Jacobian
import csum_crosse2
import scatteringphase as scp

#周期点周りでグルっと一周させる．その様にすることで，
#帰ってきて，実領域をふらふらと動き回る軌道を探したい．

#parameter
dimension = 2
k = 3.0
xf = 1.2
xb = 1.0
stdrad = 0.02
e2 = k * xf * (np.exp(-8 * xb * (2 * xf - xb)) / (1 - np.exp(-32 * xf * xb)))
W_s = [[],[]]
W_u = [[],[]]
traj = [np.array([]),np.array([])]

#kicking potentialの時間微分
def dotV(x):
    return k * x * np.exp(-8 * x**2) - e2 * (np.exp(-8 * pow(x - xb, 2)) -  np.exp(-8 * pow(x + xb, 2)))

def dotV_s(x):
    return k * x * exp(-8 * x**2) - e2 * (exp(-8 * pow(x - xb, 2)) -  exp(-8 * pow(x + xb, 2)))

def V(x):
    return - (k/16) * np.exp(-8 * (x[0] ** 2)) - ((e2/(2 * (8 ** 0.5))) * np.sqrt(np.pi)) * (math.erf( (8 ** 0.5)* (x[0] - xb)) - math.erf((8 ** 0.5) *( x[0] + xb)))

class KScatteringMap:
    def __init__(self,k,xf,xb):
        self.k = k
        self.xf = xf
        self.xb = xb
    #正の時間方向の写像
    def U(self,qp):
        return np.array([ qp[0] + qp[1] - 0.5 * dotV(qp[0]) , qp[1] - 0.5 * dotV(qp[0]) - 0.5 * dotV(qp[0] + qp[1] - 0.5 * dotV(qp[0])) ])
    #逆写像
    def Ui(self,qp):
        return (qp[0] - qp[1] - 0.5 * dotV(qp[0]), qp[1] + 0.5 * dotV(qp[0]) + 0.5 * dotV(qp[0] - qp[1] - 0.5 * dotV(qp[0])))
    def U_arb(self,qp):
        return np.array([mpf(qp[0] - qp[1] - 0.5 * dotV_s(qp[0])),mpf(qp[1] - 0.5 * dotV_s(qp[0]) - 0.5 * dotV_s(qp[0] + qp[1] - 0.5 * dotV_s(qp[0])))])

def CACOS(z):#mountain Oock cosの値から複素のcomplex thetaを返すよ
	xi = 2 * math.atan(np.real((1 - z) ** 0.5) /np.real((1 + z) ** 0.5) )
	eta = math.asinh( np.imag( (np.conj(1 +z) ** 0.5) *  ((1-z) ** 0.5)  ))
	return xi + 1j * eta

def CASIN(z):
    xi = math.atan( np.real(z) / np.real( (1-z) ** 0.5 * ( 1 +z ) ** 0.5 ))
    eta = math.asinh( np.imag( np.conj(1-z) ** 0.5 *  (1 +z) ** 0.5 ) )
    return xi + 1j * eta

def ScattMapt(qp):
    for i in range(step):
        qp =  cmap.U(qp)
    return qp

def load():
	data = np.loadtxt("theta.txt")
def gettheta(cpoint):#cpoint から　thetaを得る． Kahan, W: Branch cuts for complex elementary functionを参照
    I = cpoint[0] **2 + cpoint[1] ** 2
    cosine =  cpoint[0]/(I ** (1/2) )
    sine = cpoint[1]/(I ** (1/2))
    theta = CACOS(cosine) #まずcosineに処理を施す
    theta2 = CASIN(sine)
    print(theta)
    print(theta2)
    if theta.real < 0:
        theta = theta.real + 2 * np.pi + 1j * theta.imag
    return theta

def CACOS(z):#mountain Oock cosの値から複素のcomplex thetaを返すよ
    xi = 2 * math.atan(np.real((1 - z) ** 0.5) /np.real((1 + z) ** 0.5) )
    eta = math.asinh( np.imag( (np.conj(1 +z) ** 0.5) *  ((1-z) ** 0.5)  ))
    return xi + 1j * eta

def CASIN(z):
    xi = math.atan( np.real(z) / np.real( (1-z) ** 0.5 * ( 1 +z ) ** 0.5 ))
    eta = math.asinh( np.imag( np.conj(1-z) ** 0.5 *  (1 +z) ** 0.5 ) )
    return xi + 1j * eta

def connector(theta):#本来なら最初に書くべき
    q = stdrad * np.cos(theta)
    p = stdrad * np.sin(theta)
    return np.array([q,p])

def generatorfunc(I,theta):#母関数
    return (I/2) * (theta - np.sin(2 * theta))

def action(x_cross,periodicpoint):
	S = 0
	i = 0
	prepoint  = x_cross
	print(x_cross)

	while True:
		prepoint = x_cross
		theta = gettheta(x_cross)
		pretheta = theta
		preI = x_cross[0] ** 2 + x_cross[1] ** 2
		print(x_cross)
		x_cross =  cmap.U(x_cross)
		theta = gettheta(x_cross)
		print(theta)
		I = x_cross[0] ** 2 +  x_cross[1] ** 2
		# S += 0.5 * x_cross[1] ** 2 + V(x_cross) - x_cross[1] * ( - 0.5 * dotV(x_cross[0]) - 0.5 * dotV(x_cross[0] + x_cross[1] - 0.5 * dotV(x_cross[0]) ) )#終わりから始めを引け
		S += 0.5 * (x_cross[1] ** 2) + V(prepoint) - x_cross[1] * ( x_cross[0] - prepoint[0] ) + generatorfunc(I,theta) - generatorfunc(preI,pretheta)
		if i == 0:
			S -= V(prepoint)
		print("S = ",S)
		i += 1
		print(i)
		print('x_cross = ',x_cross)
		if  np.linalg.norm(x_cross - periodicpoint)  < 10 ** (-5) or np.linalg.norm(np.imag(x_cross)) < 5 * 10 ** (-5) :
			S -= V(prepoint)
			print("Im(Smin)= " ,S.imag)
			print('x_cross = ',x_cross)
			return S.imag
		if np.linalg.norm(x_cross) > 10:
			return np.inf
		if i > 1000:
			return np.inf

cmap = KScatteringMap(k,xf,xb)
def main():
	period = 4
	data = np.loadtxt("section_s_period{}.txt".format(period))
	print(data)
	theta = data[:,2] + 1j * data[:,3]
	points = connector(theta)
	periodicpoints = np.array([data[:,0],data[:,1]])
	print(periodicpoints)
	actions = np.array([])
	for i in range(len(theta)):
		point = points[:,i]
		periodicpoint = periodicpoints[:,i]
		newaction  = action(point,periodicpoint)
		actions = np.append(newaction,actions)
	print(actions)

if __name__ == "__main__":
	main()


import configparser
import os

path_dir = os.path.dirname(os.path.abspath(__file__))

config_defaults = {
    'git_branching':
        {
            'enc': 'ascii',
            'region': 'us-east-1',
            'pipeline_template': 'pipeline_templates/ci_pipeline.json',
            'policy_template': 'policy_templates/ecr_repo_policy.json'
        },
}

config = configparser.ConfigParser(defaults=config_defaults)
config.read(os.path.join(path_dir, 'config.cfg'))