from copy import deepcopy

class Cart:
    def __init__(self, direction):
        self.direction = direction
        self.next_intersection = 0
        if self.direction in ['>', '<']:
            self.on_track = '-'
        else:
            self.on_track = '|'
        self.left = {'v':'>', '>':'^', '^':'<', '<':'v'}
        self.right = {'v':'<', '<':'^', '^':'>', '>':'v'}

    def __repr__(self):
        return '\'' + self.direction + '\''

    def __str__(self):
        return '\'' + self.direction + '\''

    def intersection(self):
        self.next_intersection += 1
        if self.next_intersection > 3:
            self.next_intersection = 1
        if self.next_intersection == 1:
            self.direction = self.left[self.direction]
        elif self.next_intersection == 2:
            self.direction = self.direction
        elif self.next_intersection == 3:
            self.direction = self.right[self.direction]

    def __eq__(self, other):
        if self.direction == other:
            return True
        return False

    def replace_track(self, new_track):
        if new_track == '+':
            self.intersection()
        elif new_track == '\\' and self.direction in ['v', '^']:
            self.direction = self.left[self.direction]
        elif new_track == '\\' and self.direction in ['>', '<']:
            self.direction = self.right[self.direction]
        elif new_track == '/' and self.direction in ['v', '^']:
            self.direction = self.right[self.direction]
        elif new_track == '/' and self.direction in ['>', '<']:
            self.direction = self.left[self.direction]
        old_track = self.on_track
        self.on_track = new_track
        return old_track

def read_input(filename):
    with open(filename) as file:
        lines = file.readlines()
    result = []
    for line in lines:
        result.append(list(line.rstrip()))
    return result

def first_part(input_list, remove_if_crash=False):
    tick = 0
    current_grid = deepcopy(input_list)
    original = deepcopy(input_list)
    carts = 0
    for row in range(len(original)):
        for col in range(len(original[row])):
            c = original[row][col]
            if c == 'v' or c == '^' or c == '>' or c == '<':
                current_grid[row][col] = Cart(c)
                carts += 1
    new_grid = deepcopy(current_grid)
    while True:
        tick += 1
        print("tick: " + str(tick) + " and carts: " + str(carts))
        if carts <= 1 and remove_if_crash:
            for row in range(0, len(current_grid)):
                for col in range(0, len(current_grid[row])):
                    if current_grid[row][col] in ['v','^','<','>']:
                        return (col, row)
        for row in range(0, len(current_grid)):
            for col in range(0, len(current_grid[row])):
                current_char = current_grid[row][col]
                if current_char == 'v':
                    if new_grid[row+1][col] in ['v','^','<','>']:
                        if remove_if_crash:
                            new_grid[row+1][col] = new_grid[row+1][col].on_track
                            new_grid[row][col] = new_grid[row][col].on_track
                            carts -= 2
                            continue
                        else:
                            return (col,row+1)
                    new_grid[row][col] = current_char.replace_track(new_grid[row+1][col])
                    new_grid[row+1][col] = current_char
                elif current_char == '^':
                    if new_grid[row-1][col] in ['v','^','<','>']:
                        if remove_if_crash:
                            new_grid[row-1][col] = new_grid[row-1][col].on_track
                            new_grid[row][col] = new_grid[row][col].on_track
                            carts -= 2
                            continue
                        else:
                            return (col,row-1)
                    new_grid[row][col] = current_char.replace_track(new_grid[row-1][col])
                    new_grid[row-1][col] = current_char
                elif current_char == '>':
                    if new_grid[row][col+1] in ['v','^','<','>']:
                        if remove_if_crash:
                            new_grid[row][col+1] = new_grid[row][col+1].on_track
                            new_grid[row][col] = new_grid[row][col].on_track
                            carts -= 2
                            continue
                        else:
                            return (col+1,row)
                    new_grid[row][col] = current_char.replace_track(new_grid[row][col+1])
                    new_grid[row][col+1] = current_char
                elif current_char == '<':
                    if new_grid[row][col-1] in ['v','^','<','>']:
                        if remove_if_crash:
                            new_grid[row][col-1] = new_grid[row][col-1].on_track
                            new_grid[row][col] = new_grid[row][col].on_track
                            carts -= 2
                            continue
                        else:
                            return (col-1,row)
                    new_grid[row][col] = current_char.replace_track(new_grid[row][col-1])
                    new_grid[row][col-1] = current_char
        current_grid = deepcopy(new_grid)

def second_part(input_list):
	return first_part(input_list, True)

lst = read_input("input")
print(first_part(lst))
print(second_part(lst))


from PyQt5.QtWidgets import QTextBrowser
from PyQt5.QtGui import QCursor
from PyQt5.QtCore import Qt
import markdown

class Intro(QTextBrowser):
    def __init__(self):
        super().__init__()
        markdown_content = """
####
1. 请选择资料夹路径
2. 点“Start”按钮即可开始产生资料集
3. 产生的资料如下
	* dataset dir
    	-- param_norm.csv (标准化后的参数 50组)
        -- param_denorm.csv (还原后的参数 50组)
        -- 0.jpg、1.jpg、.....49.jpg (总共50张照片)
"""
        html = markdown.markdown(markdown_content)
        self.setHtml(html)
        self.setStyleSheet(
            """
            font-family:微软正黑体;
            font-weight: bold;
            font-size: 15pt;
            """
        )
        self.viewport().setCursor(QCursor(Qt.IBeamCursor))


"""Define a handler that serves static files.
"""
import datetime
import mimetypes
import rfc822
import os
import stat
import time

from aspen import mode, configuration
from aspen.exceptions import ConfigError
from aspen.handlers.autoindex import wsgi as autoindex_handler
from aspen.handlers.http import HTTP403

# WSGI callable
# =============

class WSGI(object):

    def __init__(self):
        """Hide global conf access to avoid triggering on import. See issue 137.
        """

        # Configure directory browsing.
        # =============================
        # @@: Also, this validation crap should be abstracted at some point.

        autoindex = configuration.conf.static.get('autoindex', None)
        if autoindex is None:
            autoindex = True # default
        elif autoindex.lower() == 'yes':
            autoindex = True
        elif autoindex.lower() == 'no':
            autoindex = False
        else:
            raise ConfigError( "autoindex must be 'yes' or 'no'"
                             , "__/etc/aspen.conf"
                             , -1 # lineno
                              )
        self.directory = autoindex and autoindex_handler or HTTP403

    def __call__(self, environ, start_response):
        """Serve a static file off of the filesystem.

        In staging and deployment modes, we honor any 'If-Modified-Since'
        header, an HTTP header used for caching.

        XXX: look at Luke Arno's ACK GPL and some others ... Etags? Iteration?

        """

        path = environ['PATH_TRANSLATED']
        if not os.path.exists(path):
            start_response('404 Not Found', [('Content-Type', 'text/plain')])
            return ['Resource not found.']
        elif os.path.isdir(path):
            return self.directory(environ, start_response)
        else:
            assert os.path.isfile(path) # sanity check

        # Get basic info from the filesystem and start building a response.
        # =================================================================

        stats = os.stat(path)
        mtime = stats[stat.ST_MTIME]
        size = stats[stat.ST_SIZE]
        content_type = mimetypes.guess_type(path)[0] or 'text/plain'

        # Support 304s, but only in staging and production modes.
        # =======================================================

        status = '200 OK'
        if mode.stprod:
            ims = environ.get('HTTP_IF_MODIFIED_SINCE', '')
            if ims:
                mod_since = rfc822.parsedate(ims)
                last_modified = time.gmtime(mtime)
                if last_modified[:6] <= mod_since[:6]:
                    status = '304 Not Modified'

        # Set up the response.
        # ====================

        headers = []
        headers.append(('Last-Modified', rfc822.formatdate(mtime)))
        headers.append(('Content-Type', content_type))
        headers.append(('Content-Length', str(size)))

        start_response(status, headers)
        if status == '304 Not Modified':
            return []
        else:
            return open(path, 'rb') # need 'rb' for Windows (issue 92)

wsgi = WSGI() # singleton


"""This module provides utility methods and constants for working with strings."""

import itertools
from raspy.illegal_argument_exception import IllegalArgumentException

DEFAULT_PAD_CHAR = ' '
"""Default padding character"""

EMPTY = ""
"""Represents an empty string."""

def is_null_or_empty(string_val):
    """Null or empty string check.

    A utility method to check to see if the specified string is null or empty.

    :param str string_val: The value to check.
    :returns: True if null or empty; Otherwise, False.
    :rtype: bool
    """
    if string_val and string_val.strip():
        return False
    return True

def create(char, length):
    """Create a string.

    Create a string from the specified character or string.

    :param str char: The character or string to create the string from. If
    null or an empty string, then DEFAULT_PAD_CHAR is used instead.
    :param int length: The number of instances or the specified character of
    the specified character or string to construct the string from.
    :returns: The created string.
    :rtype: str
    """
    if is_null_or_empty(char):
        char = DEFAULT_PAD_CHAR

    string_buf = EMPTY
    for the_char in itertools.repeat(char, length):
        string_buf += the_char

    return string_buf

def pad_left(data, padding_char, length):
    """Pad the left side of the specified string.

    Adds the specified padding characters to the left side of the specified
    string.

    :param str data: The string to pad.
    :param str padding_char: The character or string to pad the specified
    string with. If null or empty string, the DEFAULT_PAD_CHAR will be used
    instead.
    :param int length: The number of pad characters or instances of string to
    inject.
    :returns: The padded version of the string.
    :rtype: str
    """
    if is_null_or_empty(padding_char):
        padding_char = DEFAULT_PAD_CHAR

    string_buf = EMPTY
    for the_char in itertools.repeat(padding_char, length):
        string_buf += the_char

    string_buf += data
    return string_buf

def pad_right(data, padding_char, length):
    """Pad the right side of the specified string.

    Adds the specified padding characters to the right side of the specified
    string.

    :param str data: The string to pad.
    :param str padding_char: The character or string to pad the specified
    string with. If null or empty string, DEFAULT_PAD_CHAR will be used
    instead.
    :param int length: The number of padding characters or instances of string
    to use.
    :returns: The padded version of the string.
    :rtype: str
    """
    if is_null_or_empty(padding_char):
        padding_char = DEFAULT_PAD_CHAR

    string_buf = data
    for the_char in itertools.repeat(padding_char, length):
        string_buf += the_char

    return string_buf

def pad(data, padding_char, length):
    """Pad the specified string on both sides.

    Adds the specified padding character(s) to both sides of the specified
    string.

    :param str data: The string to pad.
    :param str padding_char: The character or string to pad the specified
    string with. If null or empty string, DEFAULT_PAD_CHAR will be used
    instead.
    :param int length: The number of characters or instances of string to pad
    on both sides.
    :returns: The padded version of the string.
    :rtype: str
    """
    if is_null_or_empty(padding_char):
        padding_char = DEFAULT_PAD_CHAR

    padded = create(padding_char, length)
    string_buf = padded + data + padded
    return string_buf

def pad_center(data, char, length):
    """Pad the center of the specified string.

    Adds the specified padding character(s) to the center of the specified
    string.

    :param str data: The string to pad.
    :param str char: The character or string to pad the center of the
    specified string with. If null or empty string, DEFAULT_PAD_CHAR will be
    used instead.
    :param int length: The number of characters or instances of string to pad
    the center with.
    :returns: The padded version of the string.
    :rtype: str
    :raises raspy.illegal_argument_exception.IllegalArgumentException: if data
    param is null or not a string.
    """
    if is_null_or_empty(data):
        raise IllegalArgumentException("data param must be a string.")

    if is_null_or_empty(char):
        char = DEFAULT_PAD_CHAR

    if len(data) > 2 and length > 0:
        first_half = data[:len(data) / 2]
        second_half = data[len(data) / 2:len(data)]
        padding_char = create(char, length)
        string_buf = first_half + padding_char + second_half
        return string_buf

    return data

def ends_with(strn, suffix):
    """Check to see if the specified string ends with the suffix.

    Checks the specified string to see if it ends with the specified suffix.

    :param str strn: The string to check.
    :param str suffix: The suffix to search the specified string for.
    :returns: True if the string ends with the specified suffix; Otherwise,
    False.
    :rtype: bool
    """
    return strn.endswith(suffix)

def starts_with(strn, prefix):
    """Check to see if string begins with the prefix.

    Checks to see if the specified string begins with the specified prefix.

    :param str strn: The string to check.
    :param str prefix: The prefix to search the specified string for.
    :returns: True if the string starts with the specified prefix; Otherwise,
    False.
    :rtype: bool
    """
    return strn.startswith(prefix)

def trim(strn):
    """Trim whitespace from string.

    Trims all whitespace from the beginning and end of the specified string.

    :param str strn: The string to trim.
    :returns: The resulting (trimmed) string.
    :rtype: str
    """
    if is_null_or_empty(strn):
        return EMPTY

    return strn.strip()

def contains(strn, substr):
    """Check to see if string contains string.

    Checks to see if the specified string contains the specified substring.

    :param str strn: The string to check.
    :param str substr: The string to search for.
    :returns: True if at least one instance of the specified substring was
    found within the specified string; Otherwise, False.
    :rtype: bool
    """
    try:
        strn.index(substr)
        return True
    except ValueError:
        return False

def convert_string_to_byte(strn):
    """Convert string value to byte.

    Converts the specified string value to a bit array (byte).

    :param str strn: The string representing a byte value (ie. '00000000').
    :returns: The byte value.
    :rtype: array
    """
    result = []
    for _key, val in enumerate(strn):
        string_array = []
        char = ord(val)
        while char:
            string_array.append(char & 0xFF)
            char >>= 8
        result += reversed(string_array)

    return result


evens = 0
odds = 0
while True:
    num = input("enter a number")
    if not num:
        break
    if not num.isnumeric():
        continue
    num = int(num)
    if num % 2 ==0:
        evens += num

    else:
        odds += num

print(f"even values added =>{evens}")
print(f"odd values added=>{odds}")


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
ans=0
t=False
def countz(self, root, targetSum,cnt):
    global ans
    if (root==None):
        return(False)
    elif(root.left==None and root.right==None):
        print(cnt)
        if(cnt+root.val==targetSum):
            print("d")
            ans+=1
            return(True)
        return(False)

    cnt+=root.val

    t1=countz(self, root.left, targetSum,cnt)
    if(t1):
        return(True)
    t2=countz(self, root.right, targetSum,cnt)
    if(t2):
        return(True)
    return(False)
class Solution(object):
    def hasPathSum(self, root, targetSum):
        """
        :type root: TreeNode
        :type targetSum: int
        :rtype: bool
        """
        cnt=0
        if not (root):
            return(False)
        return(countz( self,root, targetSum,cnt))


from os import path

import numpy as np
import os

dnld_dir = path.expanduser('~/Downloads')
in_dir = path.join(dnld_dir, 'coat')
in_train_file = path.join(in_dir, 'train.ascii')
in_test_file = path.join(in_dir, 'test.ascii')
feat_dir = path.join(in_dir, 'user_item_features')
user_feat_file = path.join(feat_dir, 'user_features.ascii')

cur_dir = path.dirname(path.realpath(__file__))
dataset = path.basename(__file__).split('.')[0]
out_dir = path.join(cur_dir, dataset)
if not path.exists(out_dir):
  os.makedirs(out_dir)
out_train_file = path.join(out_dir, 'train.data')
out_test_file = path.join(out_dir, 'test.data')
out_stat_file = path.join(out_dir, 'data.stat')
out_user_file = path.join(out_dir, 'user.attr')

train_mat = np.loadtxt(in_train_file)
num_users, num_items = train_mat.shape
train_users, train_items = train_mat.nonzero()
train_size = np.count_nonzero(train_mat)

test_mat = np.loadtxt(in_test_file)
test_users = []
test_items = []
test_size = 0
for u, i in zip(*test_mat.nonzero()):
  if train_mat[u, i] > 0:
    continue
  test_users.append(u)
  test_items.append(i)
  test_size += 1

num_males = 0
num_females = 0
user_feat_mat = np.loadtxt(user_feat_file)
with open(out_user_file, 'w') as fout:
  for u in range(num_users):
    if user_feat_mat[u, 0] == 1:
      assert user_feat_mat[u, 1] == 0
      attr = 'M'
      num_males += 1
    else:
      assert user_feat_mat[u, 1] == 1
      attr = 'F'
      num_females += 1
    fout.write('%d\t%s\n' % (u, attr))

with open(out_stat_file, 'w') as fout:
  fout.write('#users=%d\n' % (num_users))
  fout.write('#items=%d\n' % (num_items))
  fout.write('#train=%d\n' % (train_size))
  fout.write('#test=%d\n' % (test_size))
  fout.write('#male=%d\n' % (num_males))
  fout.write('#female=%d\n' % (num_females))

with open(out_train_file, 'w') as fout:
  for u, i in zip(train_users, train_items):
    fout.write('%d\t%d\t%d\n' % (u, i, train_mat[u, i]))

with open(out_test_file, 'w') as fout:
  for u, i in zip(test_users, test_items):
    fout.write('%d\t%d\t%d\n' % (u, i, test_mat[u, i]))

all_mat = train_mat + test_mat
all_users, all_items = all_mat.nonzero()
num_all = np.count_nonzero(all_mat)
train_size = int(0.8 * num_all) + 1
indexes = np.random.permutation(num_all)
with open(out_train_file, 'w') as fout:
  for j in range(train_size):
    j = indexes[j]
    u = all_users[j]
    i = all_items[j]
    if train_mat[u, i] > 0:
      fout.write('%d\t%d\t%d\n' % (u, i, train_mat[u, i]))
    else:
      assert test_mat[u, i] > 0
      fout.write('%d\t%d\t%d\n' % (u, i, test_mat[u, i]))
with open(out_test_file, 'w') as fout:
  for j in range(test_size, num_all):
    j = indexes[j]
    u = all_users[j]
    i = all_items[j]
    if train_mat[u, i] > 0:
      fout.write('%d\t%d\t%d\n' % (u, i, train_mat[u, i]))
    else:
      assert test_mat[u, i] > 0
      fout.write('%d\t%d\t%d\n' % (u, i, test_mat[u, i]))


import subprocess as sp
import time
import os
from demos.utils.k8s import  cleanCluster, waitPod, getNodeIP
from demos.utils.common import runcmd , createPeer, applyPeer, printHeader

# cluster class represents a cloud cluster for deploying the ClusterLink gateway.
class cluster:
    def __init__(self, name, zone,platform,machineType="small"):
        self.name        = name
        self.zone        = zone
        self.platform    = platform
        self.machineType = machineType
        self.port        = 443
        self.ip          = ""
        self.nodeIP      = "" # the IP of the worker node

    # createCluster creates a K8s cluster on cloud platform.
    def createCluster(self, runBg):
        print(f"create {self.name} cluster , zone {self.zone} , platform {self.platform}")
        bgFlag = " &" if runBg else ""
        if self.platform == "gcp":
            flags = "  --machine-type n2-standard-4" if self.machineType=="large" else "" #e2-medium
            cmd=f"gcloud container clusters create {self.name} --zone {self.zone} --num-nodes 1 --tags tcpall {flags} {bgFlag}"
            print(cmd)
            os.system(cmd)
        elif self.platform == "aws": #--instance-selector-vcpus 2  --instance-selector-memory 4 --instance-selector-cpu-architecture arm64
            cmd =f"eksctl create cluster --name {self.name} --region {self.zone} -N 1  {flags}  {bgFlag}"
            print(cmd)
            os.system(cmd)

        elif self.platform == "ibm":
            vlanPrivateIp=sp.getoutput(f"ibmcloud ks vlans --zone {self.zone} |fgrep private |cut -d ' ' -f 1")
            vlanPublicIp=sp.getoutput(f"ibmcloud ks vlans --zone {self.zone}  |fgrep public |cut -d ' ' -f 1")
            print("vlanPublicIp:",vlanPublicIp)
            vlanPrivateString = "--private-vlan " + vlanPrivateIp  if (vlanPrivateIp != "" and "FAILED" not in vlanPrivateIp) else ""
            if (vlanPublicIp  != "" and "FAILED" not in vlanPublicIp):
                vlanPublicString  = "--public-vlan "  + vlanPublicIp
            else:
                vlanPublicString= ""
                vlanPrivateString = vlanPrivateString + " --private-only " if (vlanPrivateString != "") else ""

            cmd= f"ibmcloud ks cluster create  classic  --name {self.name} --zone={self.zone} --flavor u3c.2x4 --workers=1 {vlanPrivateString} {vlanPublicString} {bgFlag}"
            print(cmd)
            os.system(cmd)
        else:
            print ("ERROR: Cloud platform {} not supported".format(self.platform))

    # startCluster deploys Clusterlink into the cluster.
    def startCluster(self, testOutputFolder, logLevel="info",dataplane="envoy"):
        self.checkClusterIsReady()
        createPeer(self.name,testOutputFolder, logLevel, dataplane)
        applyPeer(self.name,testOutputFolder)
        self.createLoadBalancer()
        self.nodeIP = getNodeIP(num=1)

    # useCluster sets the context for the input kind cluster.
    def useCluster(self):
        print(f"\n CONNECT TO: {self.name} in zone: {self.zone} ,platform: {self.platform}\n")
        connectFlag= False
        while (not connectFlag):
            if self.platform == "gcp":
                PROJECT_ID=sp.getoutput("gcloud info --format='value(config.project)'")
                cmd=f"gcloud container clusters  get-credentials {self.name} --zone {self.zone} --project {PROJECT_ID}"
                print(cmd)
            elif self.platform == "aws":
                cmd=f"aws eks --region {self.zone} update-kubeconfig --name {self.name}"
            elif self.platform == "ibm":
                cmd=f"ibmcloud ks cluster config --cluster {self.name}"
            else:
                print (f"ERROR: Cloud platform {self.platform} not supported")
                exit(1)

            out=sp.getoutput(cmd)
            print(f"connection output: {out}")
            connectFlag = False if ("ERROR" in out or "WARNING" in out or "Failed" in out) else True
            if not connectFlag:
                time.sleep(30) #wait more time to connection
            return out

    # checkClusterIsReady set the context for the input kind cluster.
    def checkClusterIsReady(self):
        connectFlag= False
        while (not connectFlag):
            out=self.useCluster()
            connectFlag = False if ("ERROR" in out or "Failed" in out or "FAILED" in out) else True
            time.sleep(20)

        print(f"\n Cluster Ready: {self.name} in zone: {self.zone} ,platform: {self.platform}\n")

    # replace the container registry ip according to the proxy platform.
    def replaceSourceImage(self,yamlPath,imagePrefix):
        with open(yamlPath, 'r') as file:
            yamlContent = file.read()

        # Replace "image:" with the image prefix
        updatedYamlContent = yamlContent.replace("image: ", "image: " + imagePrefix)

        # Write the updated YAML content to a new file
        with open(yamlPath, 'w') as file:
            file.write(updatedYamlContent)

        print(f"Image prefixes have been added to the updated YAML file: {yamlPath}")

    # loadService deploys image and wait until the pod is ready.
    def loadService(self,name, image, yaml, namespace="default"):
        printHeader(f"Create {name} (client) service in {self.name}")
        self.useCluster()
        runcmd(f"kubectl create -f {yaml}")
        waitPod(name,namespace)

    # deleteCluster deletes the K8s cluster.
    def deleteCluster(self, runBg=False):
        bgFlag= "&" if runBg else ""
        print(f"Deleting cluster {self.name}")
        if self.platform == "gcp" :
            os.system(f"yes |gcloud container clusters delete {self.name} --zone {self.zone} {bgFlag}")
        elif self.platform == "aws":
            os.system(f"eksctl delete cluster --region {self.zone} --name {self.name} {bgFlag}")
        elif self.platform == "ibm":
            os.system(f"yes |ibmcloud ks cluster rm --force-delete-storage --cluster {self.name} {bgFlag}")
        else:
            print ("ERROR: Cloud platform {} not supported".format(self.platform))

    # cleanCluster clean all the services and deployment in the K8s cluster.
    def cleanCluster(self):
        print("Start clean cluster")
        self.useCluster()
        cleanCluster()

    # createLoadBalancer creates load-balancer to external access.
    def createLoadBalancer(self,port="443", externalIp=""):
        runcmd(f"kubectl expose deployment cl-dataplane --name=cl-dataplane-load-balancer --port={port} --target-port={port} --type=LoadBalancer")
        gwIp=""
        if externalIp !="":
            runcmd("kubectl patch svc cl-dataplane-load-balancer -p "+ "\'{\"spec\": {\"type\": \"LoadBalancer\", \"loadBalancerIP\": \""+ externalIp+ "\"}}\'")
            gwIp= externalIp
        while gwIp =="":
            print("Waiting for cl-dataplane ip...")
            gwIp=sp.getoutput('kubectl get svc -l app=cl-dataplane  -o jsonpath="{.items[0].status.loadBalancer.ingress[0].ip}"')
            time.sleep(10)
        self.ip = gwIp
        return gwIp


import os
import sys
import zipfile
from subprocess import PIPE, run
from xml.dom.minidom import parseString

def find_settings_file(docx):
	file_list = ["word_rels/settings.xml.rels", "word/_rels/settings.xml.rels"]
	for i in range(len(file_list)):
		if file_list[i] in docx.namelist():
			return file_list[i]

def find_docx_get_C2(base_dir):
	for i in os.listdir(base_dir):
		path = os.path.join(base_dir, i)
		if ".docx" in path:
			docx = zipfile.ZipFile(path)
			settings_file = find_settings_file(docx)
			xml = parseString(docx.read(settings_file))
			result = run(["md5", path], stdout=PIPE, stderr=PIPE, universal_newlines=True)
			print (result.stdout.replace("\n", ""), "-", xml.getElementsByTagName('Relationship')[0].getAttribute("Target"))
		if os.path.isdir(path):
			find_docx_get_C2(path)

base_dir = sys.argv[1]

if __name__ == "__main__":
	find_docx_get_C2(base_dir)


import os, warnings
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'  # or any {'0', '1', '2'}
warnings.filterwarnings('ignore')

from trainer_VAE import VAETrainer
import matplotlib.pyplot as plt
import pandas as pd, numpy as np
import sys
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler, StandardScaler

def encode_hourly_data(latent_dim=64, num_hidden_layers=2):
    model_dir = f'./vae_model/latent_dim_{latent_dim}_layers_{num_hidden_layers}/'
    model_file_pref = f'model_'
    vae = VAETrainer.load_model(model_dir, model_file_pref)
    vae.summary()

    scaler = StandardScaler()
    train_data = np.load('./datasets/hourly_train.npy')
    scaler.fit(train_data)

    data = scaler.transform(train_data)
    n_data = len(data) // 24 - 1
    encode = np.zeros((24, n_data, vae.latent_dim))
    for i in range(0, len(data) - 24 - 1):
        day_data = data[i:i+24]
        encode[i % 24][i // 24] = vae.encode(day_data)
    print('data shape : ', data.shape)
    print('encoded shape : ', encode.shape)
    np.save('./datasets/encoded_train.npy', encode)

    test_data = np.load('./datasets/hourly_test.npy')
    data = scaler.transform(test_data)
    n_data = len(data) // 24
    encode = np.zeros((n_data, vae.latent_dim))
    for i in range(0, len(data), 24):
        day_data = data[i:i+24]
        encode[i//24] = vae.encode(day_data)
    print('data shape : ', data.shape)
    print('encoded shape : ', encode.shape)
    np.save('./datasets/encoded_test.npy', encode)

def encode_file_nonoverlap(vae, in_file):
    data = np.load(in_file)
    n_data = len(data) // 24
    encode = np.zeros((n_data, vae.latent_dim))
    for i in range(0, len(data), 24):
        day_data = data[i:i+24]
        encode[i//24] = vae.encode(day_data)
    print('data shape : ', data.shape)
    print('encoded shape : ', encode.shape)
    return encode

def encode_file_overlap(vae, in_file):
    data = np.load(in_file)
    n_data = len(data) // 24 - 1
    encode = np.zeros((24, n_data, vae.latent_dim))
    for i in range(0, len(data) - 24 - 1):
        day_data = data[i:i+24]
        encode[i % 24][i // 24] = vae.encode(day_data)
    print('data shape : ', data.shape)
    print('encoded shape : ', encode.shape)
    return encode


class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        def rev(start,end):
            while start<end:
                nums[start],nums[end]=nums[end],nums[start]
                start+=1
                end-=1
        k=k%len(nums)
        rev(0,len(nums)-1)
        rev(0,k-1)
        rev(k,len(nums)-1)


# -*- coding: utf-8 -*-
import scrapy
from scrapy.spiders import Rule, CrawlSpider
from scrapy.linkextractors import LinkExtractor
from douban.items import MusicItem,MusicReviewItem
import re

class DoubanscrapySpider(CrawlSpider):

    name = 'doubanscrapy'
    allowed_domains = ['music.douban.com']
    start_urls = ['https://music.douban.com/tag/华语']

    rules = (
        Rule(LinkExtractor(allow=r"/tag/((\d+)|([\u4e00-\u9fa5]+)|(\w+))$")),
        Rule(LinkExtractor(allow=r"/tag/((\d+)|([\u4e00-\u9fa5]+)|(\w+))\?start=\d+\&type=T$")),
        Rule(LinkExtractor(allow=r"/subject/\d+/reviews\?sort=time$")),
        Rule(LinkExtractor(allow=r"/subject/\d+/reviews\?sort=time\&start=\d+$")),
        Rule(LinkExtractor(allow=r"/subject/\d+/$"), callback='parse_music', follow=True),
        Rule(LinkExtractor(allow=r"/comments/$"),callback='parse_review', follow=True)
    )

    def parse_music(self, response):
        item = MusicItem()
        try:
            item['music_name'] = response.xpath('//*[@id="wrapper"]/h1/span/text()').extract()[0]
            content = "".join(response.xpath('//*[@id="info"]').extract())
            info = response.xpath('//*[@id="info"]/span').extract()
            item['music_alias'] = ""
            for i in range(0, len(info)):
                if "又名" in info[i]:
                    if i == 0:
                        item['music_alias'] = response.xpath('//*[@id="info"]/text()').extract()[1]\
                        .replace("\xa0", "").replace("\n", "").rstrip()
                    if i == 1:
                        item['music_alias'] = response.xpath('//*[@id="info"]/text()').extract()[2]\
                        .replace("\xa0", "").replace("\n", "").rstrip()
                    if i == 2:
                        item['music_alias'] = response.xpath('//*[@id="info"]/text()').extract()[3]\
                        .replace("\xa0", "").replace("\n", "").rstrip()

                if "表演者" in info[i]:
                    if i == 0:
                        item['music_singer'] = "|".join(
                            response.xpath('//*[@id="info"]/span[1]/span/a/text()').extract()
                        )
                    elif i == 1:
                        item['music_singer'] = "|".join(
                            response.xpath('//*[@id="info"]/span[2]/span/a/text()').extract()
                        )
                    elif i == 2:
                        item['music_singer'] = "|".join(
                            response.xpath('//*[@id="info"]/span[3]/span/a/text()').extract()
                        )
                    else:
                        item['music_singer'] = ""
                if "发行时间" in info[i]:
                    nbsp = re.findall(r"发行时间:(.*?)
",content,re.S)
                    item['music_time'] = "".join(nbsp).replace("\xa0", "").replace("\n", "").replace(" ", "")
                if "流派" in info[i]:
                    nbsp = re.findall(r"流派:(.*?)
", content, re.S)
                    item['music_kind'] = "".join(nbsp).replace("\xa0", "").replace("\n", "").replace(" ", "")
                if "专辑类型" in info[i]:
                    nbsp = re.findall(r"专辑类型:(.*?)
", content, re.S)
                    item['music_type'] = "".join(nbsp).replace("\xa0", "").replace("\n", "").replace(" ", "")
                if "介质" in info[i]:
                    nbsp = re.findall(r"介质:(.*?)
", content, re.S)
                    item['music_medium'] = "".join(nbsp).replace("\xa0", "").replace("\n", "").replace(" ", "")
                if "出版者" in info[i]:
                    nbsp = re.findall(r"出版者:(.*?)
", content, re.S)
                    item['music_publisher'] = "".join(nbsp).replace("\xa0", "").replace("\n", "").replace(" ", "")

            try:
                item['music_rating'] = "".join(response.xpath(
                    '//*[@class="rating_self clearfix"]/strong/text()').extract())
                item['music_votes'] = "".join(response.xpath(
                     '//*[@class="rating_self clearfix"]/div/div[@class="rating_sum"]/a/span/text()').extract())
            except Exception as error:
                item['music_rating'] = '0'
                item['music_votes'] = '0'
                print(error)

            li_list = response.xpath('//*[@id="db-rec-section"]/div')
            for li in li_list:
                item['music_recommend'] = " ".join(li.xpath('dl/dt/dd/text()').extract())

            item['music_tags'] = "|".join(response.xpath('//*[@id="db-tags-section"]/div/a/text()').extract())
            item['music_url'] = response.url
            item['music_song'] = response.xpath('//*[class="track-list"]/div/div/text').extract()

            item['music_introduction'] = "".join(response.xpath('//*[@class="all hidden"]/text()').extract()).replace("\u3000","").rstrip()

            yield item
        except Exception as err:
            print((err))


#!/usr/bin/env python3
import sys
import re

if len(sys.argv) != 2:
	name = input('element name: ')
else:
	name = sys.argv[1]

if re.search('[^A-Z0-9-]', name):
	print('element names should only contain uppercase letters, digits and hyphens (you can change the Name property of the element to whatever later though, which is what shows up in menus)')
	input('Press [Enter] to close.')
	sys.exit(1)

path = 'src/simulation/elements/' + name + '.cpp'

def get_elements():
	elements = dict()
	with open('src/simulation/ElementNumbers.h', 'r') as numbers:
		for nm, pt in re.findall('ELEMENT_DEFINE\\s*\\(\\s*(\\S+)\\s*,\\s*(\\d+)\\s*\\)', numbers.read()):
			elements[nm] = int(pt)
	return elements

elements = get_elements()
if name in elements:
	print('element already exists')
	input('Press [Enter] to close.')
	sys.exit(1)

max_id = 0
for nm, pt in elements.items():
	pt_id = int(pt)
	if max_id < pt_id:
		max_id = pt_id
new_id = max_id + 1

with open(path, 'w') as elem:
	elem.write(r"""#include "simulation/ElementCommon.h"

static int update(UPDATE_FUNC_ARGS);
static int graphics(GRAPHICS_FUNC_ARGS);

void Element::Element_{0}()
{{
	Identifier = "DEFAULT_PT_{0}";
	Name = "{0}";
	Colour = PIXPACK(0xFFFFFF);
	MenuVisible = 1;
	MenuSection = SC_SPECIAL;
	Enabled = 1;

	// element properties here

	Update = &update;
	Graphics = &graphics;
}}

static int update(UPDATE_FUNC_ARGS)
{{
	// update code here

	return 0;
}}

static int graphics(GRAPHICS_FUNC_ARGS)
{{
	// graphics code here
	// return 1 if nothing dymanic happens here

	return 0;
}}

""".format(name))
	elem.close()

print('element file \'{0}\' successfully created '.format(path))

lines = []

with open('src/simulation/ElementNumbers.h', 'r') as numbers:
    line = numbers.readline()
    while line:
        lines.append(line)
        line = numbers.readline()

with open('src/simulation/ElementNumbers.h', 'w') as numbers:
    for line in lines:
        numbers.write(line)
        if str(max_id) in line:
            numbers.write('ELEMENT_DEFINE({0}, {1});\n'.format(name, str(new_id)))


class PhoneBook:
    def __init__(self, name, number):
        self.name = name
        self.number = number

def save_contact():
    contacts = {}
    print("이름과 전화번호를 입력하세요")
    name = input("이름 : ")
    number = input("전화 : ")
    contact = PhoneBook(name, number)
    contacts[contact.name] = contact.number
    if name == 'q':
        find_contact(contacts)
    return contacts

def find_contact(contacts):
    print("전화번호 검색합니다")
    while True:
        name = input("이름을 입력하세요 : ")
        if name in contacts:
            return contacts[name]

while True:
    save_contact()


import json

from discord.ext import commands

from core.decorators import check_permissions
from core.infractions_manager import InfractionEmbedBuilder

class Infraction(commands.Cog):
    command_name = "infraction"

    # Get commands.json
    with open("core/commands.json", "r") as commands_json:
        command_info = json.load(commands_json)["commands"][command_name]

    def __init__(self, bot:commands.Bot):
        self.bot = bot

    @commands.command(name = command_name,
                    usage=command_info['usage'],
                    aliases=command_info['aliases'],
                    description=command_info['description']
    )
    @commands.guild_only()
    @commands.has_permissions(kick_members=True)
    @commands.cooldown(1, 1, commands.BucketType.member)
    @check_permissions
    async def infraction(self, ctx:commands.Context, infraction_id:int):
        # Get infraction
        infraction = self.bot.infractions_manager.getInfraction(infraction_id=infraction_id)

        # If infraction not exists
        if infraction is None:
            msg = await self.bot.replyOrSend(
                message=ctx.message,
                content="Cette infraction n'existe pas"
            )
            try: await msg.delete(delay=3)
            except: pass

        # Send embed if infraction exists
        else:
            # Get infraction embed
            builder = InfractionEmbedBuilder(infraction) # define embed builder
            builder.addMember(await self.bot.fetch_user(infraction.member_id))
            builder.addAction()
            builder.addReason()
            builder.setColor(self.bot.settings["defaultColors"]["sanction"])
            builder.author = await self.bot.fetch_user(infraction.moderator_id)
            builder.build()
            embed = builder.embed # get embed

            await self.bot.replyOrSend(
                message=ctx.message,
                embed=embed
            )

        # delete command
        try: await ctx.message.delete()
        except: pass

def setup(bot:commands.Bot):
    bot.add_cog(Infraction(bot))


import os
import sys
import json
import random
import subprocess

random.seed(42)

print("Start Retrainings")

sampling_seed = int(sys.argv[1])
n_coll = int(sys.argv[2])
n_u = int(sys.argv[3])
n_int = int(sys.argv[4])
folder_path = sys.argv[5]
validation_size = float(sys.argv[6])
network_properties = json.loads(sys.argv[7])
shuffle = sys.argv[8]
cluster = sys.argv[9]
GPU = str(sys.argv[10])
n_retrain = int(sys.argv[11])

seeds = list()
for i in range(n_retrain):
    seeds.append(random.randint(1, 500))
print(seeds)
import numpy as np
seeds = np.array(seeds)
seeds = (seeds - min(seeds))*49/(max(seeds) -min(seeds))
seeds = np.round(seeds).astype(np.int)

os.mkdir(folder_path)

for retrain in range(len(seeds)):
    folder_path_retraining = folder_path + "/Retrain_" + str(retrain)
    arguments = list()
    arguments.append(str(sampling_seed))
    arguments.append(str(n_coll))
    arguments.append(str(n_u))
    arguments.append(str(n_int))
    arguments.append(str(folder_path_retraining))
    arguments.append(str(validation_size))
    if sys.platform == "linux" or sys.platform == "linux2" or sys.platform == "darwin":
        arguments.append("\'" + str(network_properties).replace("\'", "\"") + "\'")
    else:
        arguments.append(str(network_properties).replace("\'", "\""))
    arguments.append(str(seeds[retrain]))
    arguments.append(shuffle)

    if sys.platform == "linux" or sys.platform == "linux2" or sys.platform == "darwin":
        if cluster == "true":
            if GPU != "None":
                string_to_exec = "bsub -W 12:00 -R \"rusage[mem=16384,ngpus_excl_p=1]\" -R \"select[gpu_model0==" + GPU + "]\" python3 wPINNS.py  "
                print(string_to_exec)
            else:
                string_to_exec = "bsub -W 12:00 -R \"rusage[mem=8192]\" python3 wPINNS.py  "
        else:
            string_to_exec = "python3 AdversarialPINNS.py "
        for arg in arguments:
            string_to_exec = string_to_exec + " " + arg
        os.system(string_to_exec)
    else:
        python = os.environ['PYTHON36']
        p = subprocess.Popen([python, "AdversarialPINNS.py"] + arguments)
        p.wait()


from OCC.Core.Quantity import Quantity_Color, Quantity_NOC_ALICEBLUE, Quantity_NOC_ANTIQUEWHITE, Quantity_NOC_BLACK, Quantity_NOC_MATRAGRAY, Quantity_NOC_YELLOW, Quantity_NOC_PERU
from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_MakeEdge, BRepBuilderAPI_Transform, BRepBuilderAPI_MakeFace
from OCC.Core.gp import gp_Ax1, gp_Ax2, gp_Dir, gp_Pnt, gp_Trsf, gp_Vec, gp_Pln, gp_Ax3
from OCC.Display.OCCViewer import rgb_color
from OCC.Core.AIS import AIS_Shape, AIS_Shaded, AIS_TexturedShape, AIS_WireFrame
from OCC.Core.Prs3d import Prs3d_LineAspect, Prs3d_Drawer

from bcad.binterpreter.singleton import Singleton
from bcad.binterpreter.scl_util import unstringify, Noval, is_var_set
from bcad.binterpreter.colorname_map import colorname_map

from logging import debug, info, warning, error, critical

DISP_MODE_NONE = 0
DISP_MODE_SHADED = 1
DISP_MODE_HLR = 2
DISP_MODE_WIREFRAME = 3

class SCLShape(object):
    def __init__(self, shape):
        self.trsf = gp_Trsf()
        self.shape = shape
        self.shape_color = Noval
        self.display_mode = DISP_MODE_NONE
        self.style = "main"
        self.hidden = False

    def set_hidden(self, hidden):
        self.hidden = hidden

    def is_hidden(self):
        return self.hidden

    def set_linestyle(self, name):
        if (name == "hidden"):
            debug("Set hidden line style")
            self.style = "hidden"
        if (name == "main_projection"):
            debug("Set main_projection line style")
            self.style = "main_projection"

    def set_shape_color(self, shape_color):
        self.shape_color = shape_color

    def get_shape_color(self):
        return self.shape_color

    def color(self, color):
        debug("Trying to set color: %s"%(color,))
        new_color = Noval
        if (type(color)==list):
            c = color[:]
            if (len(c)<4):
                c.append(1.0)
            new_color = rgb_color(c[0], c[1], c[2])
        else:
            if (unstringify(color) not in colorname_map):
                warning("Unknown color: %s"%(color,))
            else:
                new_color = Quantity_Color(colorname_map[unstringify(color)])
        if not is_var_set(self.shape_color):
            self.shape_color = new_color

    def get_shape(self):
        return self.shape

    def transform(self, trsf):
        self.trsf = trsf
        self.transform_shape()

    def transform_shape(self):
        self.shape = BRepBuilderAPI_Transform(self.shape, self.trsf, True).Shape()

    def display_hidden(self):
        ais_shp = AIS_Shape(self.shape)
        ais_shp.SetWidth(0.1)
        ais_shp.SetTransparency(0.10)
        ais_shp.SetColor(rgb_color(0,0,0))
        aspect = ais_shp.Attributes().WireAspect()
        aspect.SetColor(rgb_color(0,0,0))
        aspect.SetTypeOfLine(1)
        ais_context.Display(ais_shp, True)

    def display_main_projection(self):
        ais_shp = AIS_Shape(self.shape)
        ais_shp.SetWidth(5)
        #ais_shp.SetTransparency(0)
        #ais_shp.SetColor(rgb_color(0,0,0))
        aspect = ais_shp.Attributes().WireAspect()
        aspect.SetColor(rgb_color(0,0,0))
        aspect.SetTypeOfLine(0)
        ais_context.Display(ais_shp, True)

    def display_main(self):
        ais_context = Singleton.sd.display.GetContext()
        ais_shp = AIS_Shape(self.shape)
        ais_shp.SetWidth(2.0)
        ais_shp.SetTypeOfHLR(2)
        if (is_var_set(self.shape_color)):
            ais_shp.SetColor(self.shape_color)
        else:
            ais_shp.SetColor(Quantity_Color(Quantity_NOC_PERU))
        if (self.display_mode == DISP_MODE_WIREFRAME):
            ais_context.SetDisplayMode(ais_shp, AIS_WireFrame, True)
        else:
            ais_context.SetDisplayMode(ais_shp, AIS_Shaded, True)
        ais_context.Display(ais_shp, False)

    def display(self, writer=None):
        #debug("shape Display")
        if self.shape != None:
            if (writer != None):
                writer.Transfer(self.shape)
            else:
                #debug("Line style is %s"%(self.style,))
                ais_context = Singleton.sd.display.GetContext()
                if (self.style == 'hidden'):
                    self.display_hidden()
                elif (self.style == 'main_projection'):
                    self.display_main_projection()
                else:
                    self.display_main()
        else:
            #warning("Empty shape")
            pass


import numpy as np
from numpy import eye, dot, linalg
from triqs.gf import *
from triqs.lattice import *
from triqs.lattice.lattice_tools import *
from math import pi

import unittest

class test_brillouin_zone(unittest.TestCase):

    def test_mesh_point_construction(self):

        # ---- Sr2RuO4 lattice : 3 x 3 x 3
        #units = np.array([[1.,0.,0.],[0.,1.,0.],[0.,0.,1.]])

        units = [[-1.9315,  1.9315,  6.362 ],
                 [ 1.9315, -1.9315,  6.362 ],
                 [ 1.9315,  1.9315, -6.362 ]]

        nk = 3
        dims = [nk]*3
        bl     = BravaisLattice(units)
        bz     = BrillouinZone(bl)
        k_mesh = MeshBrZone(bz, dims)

        tol = 1e-9

        for idx, (k, k_val) in enumerate(zip(k_mesh, k_mesh.values())):

            assert( max(abs(k.value - k_val)) < tol )

            a = idx // nk**2
            b = ( idx - nk**2 * a ) // nk
            c = idx - nk**2 * a - nk * b

            idx_vec = np.array([a, b, c])

            didx = k_mesh.to_data_index(idx_vec)
            assert( didx == idx )

            idx_vec_ref = k_mesh.to_index(didx)
            assert( max(abs(idx_vec - idx_vec_ref)) < tol )

            k_ref = idx_vec / nk @ bz.units
            assert( max(abs(k.value - k_ref)) < tol )

    def test_mesh_construction(self):
        # Helper function
        def run(units, dims):
            bl     = BravaisLattice(units)
            bz     = BrillouinZone(bl)
            k_mesh = MeshBrZone(bz, dims)

            k1, k2, k3 = bz.units
            assert np.array_equal(k_mesh.closest_index(k1), [0,0,0])
            assert np.array_equal(k_mesh.closest_index(k2), [0,0,0])
            assert np.array_equal(k_mesh.closest_index(k3), [0,0,0])
            assert linalg.norm(dot(bl.units, bz.units.T) - eye(3)*2*pi) < 1e-14

        # ---- square lattice : 16 x 16 x 1
        units = np.array([[1.,0.,0.],[0.,1.,0.],[0.,0.,1.]])
        dims = [16, 16, 1]
        run(units, dims)

        # ---- triangular lattice : 6 x 6 x 1
        units = np.array([[1.,0.,0.],[0.5,np.sqrt(3)/2.,0.],[0.,0.,1.]])
        dims = [6, 6, 1]
        run(units, dims)

        # ---- random ONB and dims
        np.random.seed(seed=12345)
        from scipy.stats import ortho_group
        units = ortho_group.rvs(3) # Random orthonormal 3x3 matrix
        dims = np.random.randint(1, 10, size=(3,))
        run(units, dims)

    def test_interpolate(self):
        # ---- Construct Brillouin Zone Meshes for a Triangular Bravais Lattice -----

        n_orb = 3
        units = np.array([[1.,0.],[0.5,np.sqrt(3)/2.]])
        bl    = BravaisLattice(units=units,
                               orbital_positions=[(0., 0)]*n_orb)
        bz=BrillouinZone(bl)

        n_k = 40
        dims = [n_k, n_k, 1]
        k_mesh  = MeshBrZone(bz, dims)

        U = linalg.inv(bz.units)
        in_rec_basis = lambda k: dot(k.value, U)

        n_k_fine = 5 * n_k
        dims = [n_k_fine, n_k_fine, 1]
        k_fine_mesh  = MeshBrZone(bz, dims)

        # ----- Interpolate Smooth Function with given derivative -----

        f = lambda k: np.cos(2*pi * in_rec_basis(k)[0])
        dfdk = lambda k: -2*pi * np.sin(2*pi * in_rec_basis(k)[0])
        max_dfdk = max(abs(dfdk(k)) for k in k_mesh)

        f_k = Gf(mesh=k_mesh, target_shape=[])
        for k in k_mesh: f_k[k] = f(k)

        # Evaluate on finer mesh
        for k in k_fine_mesh:
            assert np.allclose(f_k(k.value), f(k), atol=max_dfdk/n_k)

        # ----- Interpolate Dispersion -----

        # Hopping[Displacement on the lattice]
        t = 1.0
        tb = TightBinding(bl, {  (1,0)  :  -t*np.diag([1,2,3]),
                                 (-1,0) :  -t*np.diag([1,2,3]),
                                 (0,1)  :  -t*np.diag([1,2,3]),
                                 (0,-1) :  -t*np.diag([1,2,3])})

        e_k = Gf(mesh=k_mesh, target_shape=(n_orb,n_orb))

        k_vec_rec = np.array([in_rec_basis(k) for k in k_mesh])
        e_k.data[:] = tb.fourier(k_vec_rec)[:]

        max_adj_diff = np.amax(abs(np.diff(e_k.data[:], axis=0)))

        # Evaluate on finer mesh
        for k in k_fine_mesh:
            e_k_exact = tb.fourier(in_rec_basis(k))
            assert np.allclose(e_k(k.value), e_k_exact, atol=max_adj_diff)

        # ----- Lattice Green function -----

        mu, beta, n_iw = 0.1, 10.0, 1000
        iw_mesh = MeshImFreq(beta, 'Fermion', n_iw)
        k_iw_mesh = MeshProduct(k_mesh, iw_mesh)
        G_k_iw = Gf(mesh=k_iw_mesh, target_shape=(n_orb,n_orb))

        iw_vec = np.array([iw.value * eye(n_orb) for iw in iw_mesh])
        mu_mat = mu * eye(n_orb)
        G_k_iw.data[:] = linalg.inv(iw_vec[None,...] + mu_mat[None,None,...] - e_k.data[::,None,...])

        # Evaluate on finer mesh
        for n in [0,10,100]: # Matsubara Idx
            G_cur = G_k_iw[::, Idx(n)]
            max_adj_diff = np.amax(abs(np.diff(G_cur.data[:], axis=0)))
            for k in k_fine_mesh:
                Gk_exact = linalg.inv(iw_mesh(n) * eye(n_orb) + mu_mat - tb.fourier(in_rec_basis(k)))
                assert np.allclose(G_cur(k.value), Gk_exact, atol=max_adj_diff)

if __name__ == '__main__':
    unittest.main()


import functools
import os
import subprocess
import sys
import tempfile
import uuid
from pathlib import Path
from typing import Any, Callable, List, Optional

import click
import openai

from skainet.data import CONFIG

def create_tempfile(ext: str) -> Path:
    temp_file = Path(tempfile.gettempdir()) / str(uuid.uuid4())
    temp_file = temp_file.with_suffix(ext)
    temp_file.touch()
    return temp_file

def handle_openai_error(error: openai.OpenAIError):
    click.echo(f"{error.__class__.__name__}: {error}", err=True)
    sys.exit(1)

class File(click.File):
    """
    Adding extra arguments to the click.File type to support file extension validation
    """

    def __init__(self, *args, exts: List[str], **kwargs):
        self.valid_ext = exts
        super().__init__(*args, **kwargs)

    def convert(self, value, param, ctx):
        file = super().convert(value, param, ctx)
        if self.valid_ext:
            extention = Path(file.name).suffix
            if extention not in self.valid_ext:
                self.fail(
                    f"{extention} is not a supported file type for this command",
                    param,
                    ctx,
                )
        return file

class Prompt(click.ParamType):
    name = "prompt"

    def convert(self, value: str, param, ctx):
        if not sys.stdin.isatty():
            if value:
                value = value + "\n"
            value += sys.stdin.read()

        if not value:
            value = click.edit()

        return value


#The goal of this script is to read fits files, locate stars, and return magnitudes for those stars
#Background sky level is calculated using random median sampling of square arrays
#A specific inset of the data array is taken if desired
#Pixel values are summed row-wise and column-wise and background level is used to determine which rows and columns contain stars
#A list of matched star coordinates is prepared
#Star magnitudes are obtained using square apertures after being background subtracted for the region specific to the star
#By Teresa Symons 2016

#from config import *

#Import math, plotting, extraneous functions, and fits file handling:
import numpy as np
import numpy.ma as ma
import random as rand
import os
from astropy.io import fits
from background import background
from binsum import binsum
from starlocate import starlocate
from starmed import starmed
from starphot import starphot
from astropy.table import Table
import matplotlib.patches as patches
import matplotlib.pylab as plt

parameters = {}
raw_params = open('photparty.param', 'r')
param_lines = raw_params.readlines()
for entry in param_lines:
    if entry[0] != '#' and entry[0] != '\n' and entry[0] != '\r':
        tempstring = entry.split(':')
        param_name = str(tempstring[0])
        param_value = str(tempstring[1].strip())
        parameters[param_name] = param_value
raw_params.close()

path = parameters['path']
exptimekword = parameters['exptimekword']
exptime = int(parameters['exptime'])
filterkword = parameters['filterkword']
filter = parameters['filter']
airmasskword = parameters['airmasskword']
airmass = int(parameters['airmass'])
gainkword = parameters['gainkword']
gain = int(parameters['gain'])
backsize = int(parameters['backsize'])
backnum = int(parameters['backnum'])
framearea = parameters['framearea']
xlow = int(parameters['xlow'])
ylow = int(parameters['ylow'])
xhigh = int(parameters['xhigh'])
yhigh = int(parameters['yhigh'])
uplim = int(parameters['uplim'])
lowsig = int(parameters['lowsig'])
sig = int(parameters['sig'])
plotdetect = parameters['plotdetect']
plotstars = parameters['plotstars']
boxhw = int(parameters['boxhw'])
defectcol = list(map(int, parameters['defectcol'].split()))
defectrow = list(map(int, parameters['defectrow'].split()))

#Create list of files to run based on defined path, ignoring all files that are not fit or fits
files = [f for f in os.listdir(path) if any([f.endswith('fit'), f.endswith('fits')]) if not f.startswith('.')]

#Alternatively, run list of files in a specified text file
#In this case files will output to the location of the main script
#files = [line.rstrip() for line in open('files.txt')]

#Run for all files in list
for i in files:
    #Define names for output files based on names of original files
    (name, ext) = os.path.splitext(i)
    newname = path+'/'+name+'info.txt'
    datname = path+'/'+name+'dat.txt'
    #Open output files
    f = open(newname,'w')
    df = open(datname,'w')
    #Open fits file
    filepath = path+'/'+i
    image = fits.open(filepath)

    #Retrieve data, exposure time, airmass, and filter from fits file:
    Data = image[0].data
    maskedData = Data
    if len(defectcol) > 0:
        maskarray = np.zeros_like(Data)
        maskarray[:, defectcol] = 1
        maskedData = ma.masked_array(Data, maskarray)
    if len(defectrow) > 0:
        maskarray = np.zeros_like(Data)
        maskarray[defectrow] = 1
        maskedData = ma.masked_array(Data, maskarray)

    if exptimekword == 'NONE':
        etime = int(exptime)
    else:
        etime = image[0].header[exptimekword]
    if filterkword == 'NONE':
        filter = filter
    else:
        filter = image[0].header[filterkword]
    if airmasskword == 'NONE':
        airmass = int(airmass)
    else:
        airmass = image[0].header[airmasskword]
    if gainkword == 'NONE':
        gain = int(gain)
    else:
        gain = image[0].header[gainkword]

    #Compute background sky level through random median sampling:
    #Inputs: data array, nxn size of random subarray to use for sampling, and number of desired sampling iterations
    back, skyvals = background(maskedData,backsize,backnum)

    #Create desired inset of total data array:
    if framearea == 'half':
        #Find midpoint of image data
        mid = len(Data)/2
        #Take an inset of data that is half of area
        inset = Data[round(mid/2):3*round(mid/2),round(mid/2):3*round(mid/2)]
        xlow = 0
        xhigh = 0
        ylow = 0
        yhigh = 0
    if framearea == 'whole':
        #Use entire data array as inset
        inset = Data
        mid = 0
        xlow = 0
        xhigh = 0
        ylow = 0
        yhigh = 0
    if framearea == 'custom':
        inset = Data[ylow-1:yhigh-1,xlow-1:xhigh-1]
        mid = 0
    # Replace defective columns and rows with local medians
    # The median is taken for 5 rows above and 5 below the defective row/col, and the std dev is calculated as well.
    # Each pixel of the defective row/col is replaced by this median +/- a multiple of the sigma
    # If defective pixel is near edge of frame, will look further in opposite direction when getting median etc.
    buffersize = 5
    lowwidth, upwidth = buffersize, buffersize
    if len(defectcol) > 0:
        for col in defectcol:
            if framearea == 'half':
                col -= 511
            elif framearea == 'custom':
                col -= (xlow -1)
            if col < 0 or col > len(inset):
                continue
            for i in range(buffersize):
                if col + upwidth > len(inset[0]):
                    upwidth -= 1
                    lowwidth += 1
                elif col - lowwidth < 0:
                    lowwidth -= 1
                    upwidth += 1
            under = inset[:, (col - lowwidth):col]
            over = inset[:, (col + 1):(col + 1 + upwidth)]
            tot = np.hstack((under, over))
            median = np.median(tot)
            std = np.std(tot)
            for i in range(len(inset)):
                inset[i][col] = (median + std * rand.uniform(-3, 3))
    if len(defectrow) > 0:
        for row in defectrow:
            if framearea == 'half':
                row -= 511
            elif framearea == 'custom':
                row -= (ylow -1)
            if row < 0 or row > len(inset[0]):
                continue
            for i in range(buffersize):
                if row + upwidth > len(inset):
                    upwidth -= 1
                    lowwidth += 1
                elif row - lowwidth < 0:
                    lowwidth -= 1
                    upwidth += 1
            under = inset[(row - lowwidth):row]
            over = inset[(row + 1):(row + 1 + upwidth)]
            tot = np.vstack((under, over))
            median = np.median(tot)
            std = np.std(tot)
            for i in range(len(inset[0])):
                inset[row][i] = (median + std * rand.uniform(-3, 3))

    #Blanket removal of bad pixels above 45000 and 3*standard deviation below 0:
    inset[inset>uplim] = 0
    std = np.std(inset)
    inset[inset<-lowsig*std] = 0

    #Calculate sky background for specific inset:
    #Inputs: inset data array, nxn size of random subarray used for sampling, number of desired sampling iterations
    insetback, insetskyvals = background(inset,backsize,backnum)
    #Compute summed row and column values for desired array by number of bins:
    #Inputs: inset data array, number of bins desired
    rowsum, colsum = binsum(inset,1)

    #Locate values in summed row and column vectors that are greater than desired sigma level above background:
    #Inputs: Data array, background level variable, desired sigma detection level, summed row vector, summed column vector
    starrow, starcol, backsum, std, sigma = starlocate(inset,insetback,sig,rowsum,colsum)
    if starrow == []:
        print('Error: No stars found in '+name+' by row - check threshold.')
    if starcol == []:
        print('Error: No stars found in '+name+' by column - check threshold.')

    # Plot summed row and column values with detection level marked:
    if plotdetect == 'on':
        plt.plot(rowsum)
        plt.plot((0, len(rowsum)), (backsum + sigma * std, backsum + sigma * std))
        plt.title('Summed Rows' + '-' + name)
        plt.xlabel('Row Index in Data Inset')
        plt.ylabel('Summed Row Value')
        plt.show()
        plt.plot(colsum)
        plt.plot((0, len(colsum)), (backsum + sigma * std, backsum + sigma * std))
        plt.title('Summed Columns' + '-' + name)
        plt.xlabel('Column Index in Data Inset')
        plt.ylabel('Summed Column Value')
        plt.show()

    #Take indices of detected star pixels and divide into sublists by individual star:
    #Return sublists of star indices, number of stars, and median pixel of each star
    #Pair star center row with star center column and return total number of pairs found
    #Inputs: vectors containing indices of detected star pixels for row and column and inset data array
    rowloc, colloc, numstarr, numstarc, rowmed, colmed, starpoints, adjstarpoints = starmed(starrow,starcol,inset,mid,xlow,ylow)

    #Take list of star coordinates and find summed pixel values within a square aperture of desired size:
    #Also find background values for each star and subtract them from star values
    #Convert background-subtracted star values into fluxes and then magnitudes
    #Inputs: half-width of nxn square aperture, inset data array, vector containing star coordinates, exposure time
    boxsum, starback, backsub, flux, mags, hw, magerr = starphot(boxhw, inset, starpoints, etime, gain, name)

    #Output data table to file:
    n = len(mags)
    tname = [i]*n
    tfilter = [filter]*n
    tairmass = [airmass]*n
    tetime = [etime]*n
    x = [x for [x,y] in adjstarpoints]
    y = [y for [x,y] in adjstarpoints]
    t = Table([tname, tfilter, tairmass, tetime, x, y, mags, magerr], names=('File_Name', 'Filter', 'Airmass', 'Exposure_Time', 'X', 'Y', 'Magnitude', 'Mag_Err'))
    t.write(df,format='ascii')

    #Plot fits image with square apertures for detected stars overlaid
    if plotstars == 'on':
        fig, ax = plt.subplots(1)
        ax.imshow(Data, cmap='Greys',vmin=0,vmax=10)
        for i in range(0,len(x)):
            rect = patches.Rectangle(((x[i]-1-hw),(y[i]-1-hw)), 2*hw, 2*hw, linewidth=1, edgecolor='r', facecolor='none')
            ax.add_patch(rect)
        if framearea == 'custom':
            rect = patches.Rectangle((xlow-1,ylow-1), xhigh-xlow, yhigh-ylow, linewidth=1, edgecolor='b', facecolor='none')
            ax.add_patch(rect)
        plt.title(name)
        plt.show()

    #Printing of values to check program function to file
    print('Exposure time:', file=f)
    print(etime, file=f)
    print('Filter:', file=f)
    print(filter, file=f)
    print('Airmass:', file=f)
    print(airmass, file=f)
    print('Sky background level:', file=f)
    print(back, file=f)
    print('Shape of inset array:', file=f)
    print(np.shape(inset), file=f)
    print('Inset background sky level:', file=f)
    print(insetback, file=f)
    print('Summed background value for one row/column:', file=f)
    print(backsum, file=f)
    print('Standard deviation of inset:', file=f)
    print(std, file=f)
    print('Detection level in sigma:', file=f)
    print(sigma, file=f)
    print('Indices of detected stars:', file=f)
    print(starrow, file=f)
    print(starcol, file=f)
    print('Indices of detected stars divided into sublist by star:', file=f)
    print(rowloc, file=f)
    print(colloc, file=f)
    print('Number of stars found by row/column:', file=f)
    print(numstarr, file=f)
    print(numstarc, file=f)
    print('Median pixel of each star by row/column:', file=f)
    print(rowmed, file=f)
    print(colmed, file=f)
    print('Paired indices of star centers:', file=f)
    print(starpoints, file=f)
    print('Total number of stars found:', file=f)
    print(len(starpoints), file=f)
    print('Coordinates of stars (x,y):', file=f)
    print(adjstarpoints, file=f)
    print('Width/Height of boxes:', file=f)
    print(hw * 2, file=f)
    print('Pixel sums for boxes around each star:', file=f)
    print(boxsum, file=f)
    print('Background values for each star:', file=f)
    print(starback, file=f)
    print('Background subtracted star values:', file=f)
    print(backsub, file=f)
    print('Flux of stars:', file=f)
    print(flux, file=f)
    print('Magnitudes for each star:', file=f)
    print(mags, file=f)


#!/usr/bin/python
# Time-stamp : Sunday, November 18, 2007 4:29:43 PM
from grapher  import *
from math import *
from random import *

def x(t): return t
def fx(t): return cos(t)

setViewBox(-0.3,-1.0,3.4,1.1)
openOutputFile("08Riemann-posandneg",240)

n=30
dx=3.0/n
xp = [i*dx for i in range(n+1)]
fxp = [fx(xx) for xx in xp]
c=[(uniform(xp[i],xp[i+1]) + xp[i] + xp[i+1])/3 for i in range(n)]
R=[rect(xp[i], xp[i+1], 0, fx(c[i])) for i in range(n)]

plot(x, fx, Viewxmin(), xp[0])
plot(x, fx, xp[n], Viewxmax())

#draw the box fills
for i in range(n):
    if fxp[i]<0 :
        polygonF(R[i], 'gray')

#draw the boundary of the region
setrgbcolor('blue')
linewidth(2)
plot(x, fx,  xp[0], xp[n])
for x in (xp[0], xp[n]):
    line([x,0], [x, fx(x)])
line([xp[0],0], [xp[n],0])
setrgbcolor('black')
x_axis(5)

#draw the boxes
linewidth(0.5)
for i in range(n):
    polygonC(R[i])

annotate([xp[0], 0], [-1, -12], "$a$")
annotate([xp[n], 0], [-2, 4], "$b$")

closeOutputFile()


# coding: utf8
# python

from get_save import HtmlParser, FromHtmlToCsv
import csv, argparse, os.path

def set_args():
	parser = argparse.ArgumentParser()
	parser.add_argument("-d", "--directory", type=str, help="Directory of the CSV file (default: csv/)", default="csv/")
	parser.add_argument("-o", "--csv_filename", type=str, help="Name you want to give to the CSV file (default: ing_checkaccount_YYYYMM.csv)", default="ing_checkaccount_YYYYMM.csv")
	parser.add_argument("-i", "--html_file", type=str, help="HTML file you want to import data from (default: html/ing.html)", default="html/ing.html")
	args = parser.parse_args()
	directory = args.directory
	csv_filename = args.csv_filename
	html_file = args.html_file

	check_args(directory, csv_filename, html_file)

	return directory, csv_filename, html_file

def check_args(directory, csv_filename, html_file):
	# Check if directory exists
	if os.path.isdir(directory) != True:
		print(u"[Error]: Directory not found")
		exit(0)
	# Check if CSV filename ends with .csv and don't already exists
	if csv_filename[-4:] != ".csv":
		print(u"[Error]: CSV file name must end with .csv")
		exit(0)
	if os.path.exists(directory + csv_filename):
		print(u"[Error]: CSV file already exists")
		exit(0)
	# Check if html filename ends with .html
	if html_file[-5:] != ".html":
		print(u"[Error]: HTML file name must end with .html")
		exit(0)
	# Check if html file exists
	if os.path.exists(html_file) != True:
		print(u"[Error]: HTML file not found")
		exit(0)

if __name__ == "__main__":
	directory, csv_filename, html_file = set_args()
	html_parser = HtmlParser(html_file)
	html_data, html_encoding = html_parser.parse()
	html_to_csv = FromHtmlToCsv(directory, csv_filename, html_data, html_encoding)
	try:
		html_to_csv.insert()
		print(u"[Success]: Data successfully imported")
	except Exception:
		print(u"[Error]: Something went wrong during data import")
		raise


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

from django.shortcuts import render, HttpResponse, redirect
from datetime import datetime

# Create your views here.

def index(request):

    ## session variable initialize
    if "error_message" not in request.session.keys():
        request.session["error_message"] = ""
    if "color" not in request.session.keys():
        request.session["color"] = ""
    if "font_big" not in request.session.keys():
        request.session["font_big"] = ""
    if "word_list" not in request.session.keys():
        request.session["word_list"] = []
    context = {
        "error_message" : request.session["error_message"],
        "word_list" : request.session["word_list"],
    }
    return render(request, "session_words_app/index.html", context)

def process(request):

    ## form validator
    # Case : not enter the word
    if len(request.POST["word"]) < 1:
        request.session["error_message"] = "Enter your word(s)"
        return redirect("/session_words")

    # Case : not click color radio
    elif "color" not in request.POST.keys():
        request.session["error_message"] = "Click your font color"
        return redirect("/session_words")

    # Case : form is valid
    else:

        # remove error message
        request.session["error_message"] = ""

        # store individual words and related info saves in dictionary
        temp_dict = {}
        temp_dict["words"] = request.POST["word"]

        # color setting
        if "color" not in request.POST.keys():
            temp_dict["color"] = ""
        else:
            if request.POST["color"] == "red":
                temp_dict["color"] = "redfont"
            elif request.POST["color"] == "green":
                temp_dict["color"] = "greenfont"
            elif request.POST["color"] == "blue":
                temp_dict["color"] = "bluefont"

        # font setting
        if "font_big" in request.POST.keys():
            temp_dict["color"] += " font_big"

        # get current time
        current_time = datetime.now().strftime("%H:%M:%S%p, %b-%d-%Y")
        temp_dict["add_time"] = "- added on " + str(current_time)

        # insert dictionary in front of list (descending order)
        request.session["word_list"].insert(0, temp_dict)

        return redirect("/session_words")

# reset route ( every keys in session deletes)
def reset(request):
    for key in request.session.keys():
        del request.session[key]
    return redirect("/session_words")


"""
Distributed under the MIT License. See LICENSE.txt for more info.
"""

import astropy.units as u
import pickle
import os
import re
import numpy as np

from astropy.coordinates import SkyCoord
from bokeh.embed import components
from bokeh.models import ColumnDataSource
from bokeh.util.hex import hexbin
from bokeh.palettes import Spectral6
from bokeh.plotting import figure
from bokeh.resources import CDN
from bokeh.transform import factor_cmap, linear_cmap
from django.conf import settings

from zooniverse_web.models import (
    Galaxy, Response, QuestionResponse,
    QuestionDrawnResponse)
from zooniverse_web.utility.constants import (
    display_plot_size_x, display_plot_size_y,
    sky_projection_plot_x, sky_projection_plot_y,
    scatterplot_x, scatterplot_y,
    ra_pickle_name, dec_pickle_name,
    fpeak_fint_pickle_name, log_snr_pickle_name
)

import matplotlib

# this must be used like the following, as there are some crashing issues in second request to the page
# setting up the matplotlib backend as 'Agg'
matplotlib.use('Agg')
# now importing the pyplot
import matplotlib.pyplot as plt

def generate_sky_projection(request):
    """Generate sky projection plot using matplotlib

    Parameters
    ----------
    request:
         Post request

    Returns
    -------
    image_url :
         Image location (settings.MEDIA_URL + image)
    """

    # getting pickle files location
    ra_pickle = settings.MEDIA_ROOT + ra_pickle_name
    dec_pickle = settings.MEDIA_ROOT + dec_pickle_name

    # checking pickle exists? if yes, loading from the file
    if os.path.isfile(ra_pickle) and os.path.isfile(dec_pickle):
        with open(ra_pickle, 'rb') as ra_pickle_in:
            ra_rad = pickle.load(ra_pickle_in)

        with open(dec_pickle, 'rb') as dec_pickle_in:
            dec_rad = pickle.load(dec_pickle_in)

    else:  # otherwise reading from database and saving in the pickle files
        # cleaning up pickle files if exists (can only happen if one is missing)
        if os.path.isfile(ra_pickle):
            os.remove(ra_pickle)

        if os.path.isfile(dec_pickle):
            os.remove(dec_pickle)

        galaxies = Galaxy.objects.all()

        ra = []
        dec = []

        for galaxy in galaxies:
            ra.append(galaxy.ra)
            dec.append(galaxy.dec)

        c = SkyCoord(ra=ra, dec=dec, frame='icrs', unit=(u.hourangle, u.degree))
        ra_rad = c.ra.wrap_at(180 * u.deg).radian
        dec_rad = c.dec.radian

        with open(ra_pickle, "wb") as ra_pickle_out:
            pickle.dump(ra_rad, ra_pickle_out)

        with open(dec_pickle, "wb") as dec_pickle_out:
            pickle.dump(dec_rad, dec_pickle_out)

    plt.figure(figsize=(8, 4.2))
    plt.subplot(111, projection="aitoff")
    # plt.title("Sky Projection")
    plt.grid(True)
    plt.plot(ra_rad, dec_rad, 'o', markersize=2, alpha=0.3)

    try:
        response = Response.objects.get(survey=request.session['survey_id'],
                                        user=request.user)
        question_responses = QuestionResponse.objects.filter(response=response)

        ra = []
        dec = []
        for response in question_responses:
            ra.append(response.survey_question.survey_element.galaxy.ra)
            dec.append(response.survey_question.survey_element.galaxy.dec)

        c = SkyCoord(ra=ra, dec=dec, frame='icrs', unit=(u.hourangle, u.degree))
        ra_rad2 = c.ra.wrap_at(180 * u.deg).radian
        dec_rad2 = c.dec.radian

        plt.plot(ra_rad2, dec_rad2, '*', markersize=7, alpha=1, color='red')
    except Response.DoesNotExist:  # No response yet
        pass

    # plt.plot(ra_rad, dec_rad, 'o', markersize=2, alpha=0.3)
    plt.subplots_adjust(top=0.95, bottom=0.0)
    image = 'sky_projection_{}.png'.format(request.user.username)
    plt.savefig(settings.MEDIA_ROOT + image)
    plt.close()
    return settings.MEDIA_URL + image

def get_global_fpeak_fint_over_log_snr():
    """Get global survey data for fpeak/fint vs log(snr) plot.

    This function computes bokeh.util.hex.hexbins for all galaxies in the catalog,
    where the x axis is galaxies.f_peak/galaxies.f_int, and the y axis is log10(snr),
    with snr=(galaxies.fpeak - 0.25)/galaxies.rms

    Returns
    -------
    hexbins:
        bins to be plotted by bokeh.
    """
    # getting pickle files location
    fpeak_fint_pickle = settings.MEDIA_ROOT + fpeak_fint_pickle_name
    log_snr_pickle = settings.MEDIA_ROOT + log_snr_pickle_name

    # checking pickle exists? if yes, loading from the file
    if os.path.isfile(fpeak_fint_pickle) and os.path.isfile(log_snr_pickle):
        with open(fpeak_fint_pickle, 'rb') as fpeak_fint_pickle_in:
            fpeak_fint = pickle.load(fpeak_fint_pickle_in)

        with open(log_snr_pickle, 'rb') as log_snr_pickle_in:
            log_snr = pickle.load(log_snr_pickle_in)

    else:  # otherwise reading from database and saving in the pickle files
        # cleaning up pickle files if exists (can only happen if one is missing)
        if os.path.isfile(fpeak_fint_pickle):
            os.remove(fpeak_fint_pickle)

        if os.path.isfile(log_snr_pickle):
            os.remove(log_snr_pickle)

        galaxies = Galaxy.objects.all()

        fpeak_fint = []
        log_snr = []

        for galaxy in galaxies:
            fpeak_fint.append(galaxy.fpeak / galaxy.fint)
            log_snr.append(np.log10((galaxy.fpeak - 0.25)/galaxy.rms))

        with open(fpeak_fint_pickle, "wb") as fpeak_fint_pickle_out:
            pickle.dump(fpeak_fint, fpeak_fint_pickle_out)

        with open(log_snr_pickle, "wb") as log_snr_pickle_out:
            pickle.dump(log_snr, log_snr_pickle_out)

    return hexbin(np.array(log_snr), np.array(fpeak_fint), 0.1)

def compute_request_fpeak_fint_over_log_snr(request):
    """Compute request f_peak/f_int vs log(snr).

    This function computes points for a scatter plot for currently labeled galaxies.
    The x axis is labeled_galaxies.f_peak/labeled_galaxies.f_int, and the y axis is
    log10(snr), with snr=(labeled_galaxies.fpeak - 0.25)/labeled_galaxies.rms

    Parameters
    ----------
    request:
        POST request

    Returns
    -------
    log_snr:
        numpy array used for the x axis of the scatter plot
    fpeak_fint:
        numpy array used for the y axis of the scatter plot
    """
    fpeak_fint = []
    log_snr = []

    try:
        response = Response.objects.get(survey=request.session['survey_id'],
                                        user=request.user)
        question_responses = QuestionResponse.objects.filter(response=response)

        for response in question_responses:
            galaxy = response.survey_question.survey_element.galaxy
            fpeak_fint.append(galaxy.fpeak / galaxy.fint)
            log_snr.append(np.log10((galaxy.fpeak - 0.25) / galaxy.rms))

    except Response.DoesNotExist:  # No response yet
        pass

    return log_snr, fpeak_fint

def compute_request_n_components_over_log_snr(request):
    """Compute request n-components vs log(snr).

    Similar to compute_request_fpeak_fint_over_log_snr, with the exception that the y axis is
    the number of components recorded by users during labelling.

    Parameters
    ----------
    request:
        POST request

    Returns
    -------
    x_axis:
        numpy array used for the x axis of the scatter plot
    y_axis:
        numpy array used for the y axis of the scatter plot
    """
    y_axis = []
    x_axis = []

    try:
        response = Response.objects.get(survey=request.session['survey_id'],
                                        user=request.user)

        question_responses = QuestionDrawnResponse.objects.filter(response=response)

        for question_response in question_responses:
            galaxy = question_response.survey_question.survey_element.galaxy
            y_axis.append(len(re.findall('NaN', question_response.x_coordinates)))
            x_axis.append(np.log10((galaxy.fpeak - 0.25) / galaxy.rms))

    except Response.DoesNotExist:  # No response yet
        pass

    return x_axis, y_axis

class Plot:
    """Class representing a plot.
    """
    label = ''
    script = None
    div = None

    def __init__(self, label):
        """Initialise the class.

        Parameters
        ----------
        label:
            plot label

        """
        self.label = label

        self.script, self.div = components(self._set_plot(), CDN)

    def _set_plot(self):
        """Set the bokeh plot.

        Returns
        -------
        plot:
            a bokeh figure.
        """
        fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
        counts = [5, 3, 4, 2, 4, 6]

        source = ColumnDataSource(data=dict(fruits=fruits, counts=counts))

        plot = figure(x_range=fruits, y_range=(2, 8), width=display_plot_size_x, height=display_plot_size_y)
        plot.vbar(x='fruits', top='counts', width=0.9, source=source, legend="fruits",
                  line_color='white', fill_color=factor_cmap('fruits', palette=Spectral6, factors=fruits))
        plot.axis.visible = False
        plot.background_fill_color = "#FFFFFF"
        plot.background_fill_alpha = 0.8
        plot.grid.grid_line_color = None

        return plot

class NComponentsSnrPlot(Plot):
    """Class representing the N-Components vs log(SNR) plot.
    """
    request = None

    def __init__(self, request):
        """Initialise the class

        Paramters
        ---------
        request:
            Post request
        """
        self.request = request
        super(NComponentsSnrPlot, self).__init__(label='NComponentsSnr')

    def _set_plot(self):
        """Set the plot.

        Returns
        -------
        plot :
            A bokeh.plotting.figure
        """
        plot = figure(
            width=scatterplot_x,
            height=scatterplot_y,
            logo=None,
            tools=['box_zoom,wheel_zoom,reset,pan'],
        )

        x, y = compute_request_n_components_over_log_snr(self.request)

        plot.scatter(x, y,
                     marker='asterisk',
                     line_color="#ca0020",
                     fill_color="#ca0020",
                     fill_alpha=1,
                     size=12,
                     )

        plot.xaxis.axis_label = 'log10(SNR)'
        plot.yaxis.axis_label = 'n components'

        return plot

class FluxSnrPlot(Plot):
    """Class representing the f_peak/f_int vs log(SNR) plot
    """
    request = None

    def __init__(self, request):
        """Initialise the class.

        Parameters
        ----------
        request:
            POST request
        """
        self.request = request
        super(FluxSnrPlot, self).__init__(label='FluxSnr')
        # self._set_plot()

    def _set_plot(self):
        """Set the plot.

        Returns
        -------
        plot :
            A bokeh.plotting.figure
        """
        plot = figure(
            width=scatterplot_x,
            height=scatterplot_y,
            logo=None,
            tools=['box_zoom,wheel_zoom,reset,pan'],
        )

        # Plot overall points.
        bins = get_global_fpeak_fint_over_log_snr()

        plot.hex_tile(q="q", r="r", size=0.1, line_color=None, source=bins,
                      fill_color=linear_cmap('counts', 'Blues8', 0, max(bins.counts)))

        x, y = compute_request_fpeak_fint_over_log_snr(self.request)

        plot.scatter(x, y,
                     marker='asterisk',
                     line_color="#ca0020",
                     fill_color="#ca0020",
                     fill_alpha=1,
                     size=12,
                     )

        plot.xaxis.axis_label = 'log10(SNR)'
        plot.yaxis.axis_label = 'f_peak / f_int'

        return plot

class SkyProjectionPlot(Plot):
    """Class representing the sky projection plot
    """
    request = None

    def __init__(self, request):
        """Initialise the class.

        Parameters
        ----------
        request:
            POST request.
        """
        self.request = request
        super(SkyProjectionPlot, self).__init__(label='SkyProjection')

    def _set_plot(self):
        """Set the plot.

        Returns
        -------
        plot :
            A bokeh.plotting.figure
        """
        url = generate_sky_projection(self.request)

        # constructing bokeh figure
        plot = figure(
            x_range=(0, 1),
            y_range=(0, 1),
            width=sky_projection_plot_x,
            height=sky_projection_plot_y,
            logo=None,
            tools=['box_zoom,wheel_zoom,reset,pan'],
        )

        # adding image to the figure
        plot.image_url(
            url=[url], x=0, y=0, w=1, h=1, anchor="bottom_left",
        )

        plot.axis.visible = False
        plot.background_fill_color = "#000000"
        plot.background_fill_alpha = 0.8
        plot.grid.grid_line_color = None
        return plot

def get_plots(request):
    """Get the different plots to be rendered on the page.

    Parameters
    ----------
    request:
        POST request

    Returns
    -------
    plots:
        list of bokeh.plotting.figure
    """
    return [SkyProjectionPlot(request=request), FluxSnrPlot(request=request), NComponentsSnrPlot(request=request), ]


# Starter code for the Coursera SDC Course 2 final project.
#
# Author: Trevor Ablett and Jonathan Kelly
# University of Toronto Institute for Aerospace Studies
import pickle
import numpy as np
import numpy.linalg as la
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from rotations import angle_normalize, rpy_jacobian_axis_angle, skew_symmetric, Quaternion

with open('data/pt1_data.pkl', 'rb') as file:
    data = pickle.load(file)

################################################################################################
gt = data['gt']
imu_f = data['imu_f']
imu_w = data['imu_w']
gnss = data['gnss']
lidar = data['lidar']

################################################################################################
gt_fig = plt.figure()
ax = gt_fig.add_subplot(111, projection='3d')
ax.plot(gt.p[:,0], gt.p[:,1], gt.p[:,2])
ax.set_xlabel('x [m]')
ax.set_ylabel('y [m]')
ax.set_zlabel('z [m]')
ax.set_title('Ground Truth trajectory')
ax.set_zlim(-1, 5)
#plt.show()

################################################################################################
# Correct calibration rotation matrix, corresponding to Euler RPY angles (0.05, 0.05, 0.1).
C_li = np.array([
   [ 0.99376, -0.09722,  0.05466],
   [ 0.09971,  0.99401, -0.04475],
   [-0.04998,  0.04992,  0.9975 ]
])

# Incorrect calibration rotation matrix, corresponding to Euler RPY angles (0.05, 0.05, 0.05).
# C_li = np.array([
#      [ 0.9975 , -0.04742,  0.05235],
#      [ 0.04992,  0.99763, -0.04742],
#      [-0.04998,  0.04992,  0.9975 ]
# ])

t_i_li = np.array([0.5, 0.1, 0.5])

# Transform from the LIDAR frame to the vehicle (IMU) frame.
lidar.data = (C_li @ lidar.data.T).T + t_i_li

#### 2. Constants ##############################################################################

var_imu_f = 0.010
var_imu_w = 0.010
var_gnss  = 0.80
var_lidar = 1.00

################################################################################################
g = np.array([0, 0, -9.81])  # gravity
l_jac = np.zeros([9, 6])
l_jac[3:, :] = np.eye(6)  # motion model noise jacobian
h_jac = np.zeros([3, 9])
h_jac[:, :3] = np.eye(3)  # measurement model jacobian

#### 3. Initial Values #########################################################################

################################################################################################
# Let's set up some initial values for our ES-EKF solver.
################################################################################################
p_est = np.zeros([imu_f.data.shape[0], 3])  # position estimates
v_est = np.zeros([imu_f.data.shape[0], 3])  # velocity estimates
q_est = np.zeros([imu_f.data.shape[0], 4])  # orientation estimates as quaternions
p_cov = np.zeros([imu_f.data.shape[0], 9, 9])  # covariance matrices at each timestep

# Set initial values.
p_est[0] = gt.p[0]
v_est[0] = gt.v[0]
q_est[0] = Quaternion(euler=gt.r[0]).to_numpy()
p_cov[0] = np.zeros(9)  # covariance of estimate
gnss_i  = 0
lidar_i = 0

#### 4. Measurement Update #####################################################################

################################################################################################
# Since we'll need a measurement update for both the GNSS and the LIDAR data, let's make
# a function for it.
################################################################################################
def measurement_update(sensor_var, p_cov_check, y_k, p_check, v_check, q_check):
    # 3.1 Compute Kalman Gain
    R_cov = sensor_var * np.eye(3)
    K = p_cov_check.dot(h_jac.T.dot(la.inv(h_jac.dot(p_cov_check.dot(h_jac.T)) + R_cov )))
    # 3.2 Compute error state
    delta_x = K.dot(y_k - p_check)

    # 3.3 Correct predicted state
    p_hat = p_check + delta_x[:3]
    v_hat = v_check + delta_x[3:6]
    q_hat = Quaternion(axis_angle=delta_x[6:]).quat_mult_left(q_check)

    # 3.4 Compute corrected covariance
    p_cov_hat = (np.eye(9) - K.dot(h_jac) ).dot(p_cov_check)

    return p_hat, v_hat, q_hat, p_cov_hat

#### 5. Main Filter Loop #######################################################################

################################################################################################
# Now that everything is set up, we can start taking in the sensor data and creating estimates
# for our state in a loop.
################################################################################################

for k in range(1, imu_f.data.shape[0]):  # start at 1 b/c we have initial prediction from gt
    delta_t = imu_f.t[k] - imu_f.t[k - 1]

    # 1. Update state with IMU inputs
    c_ns = Quaternion(*q_est[k-1]).to_mat()
    c_ns_dot_f_km = np.dot(c_ns, imu_f.data[k-1])
    p_est[k] = p_est[k-1] + delta_t * v_est[k-1] + 0.5 * (delta_t**2) * (c_ns_dot_f_km + g )

    v_est[k] = v_est[k-1] + delta_t * (c_ns_dot_f_km + g )

    q_est[k] = Quaternion(euler= (delta_t*imu_w.data[k-1])).quat_mult_right(q_est[k-1])

    # 1.1 Linearize the motion model and compute Jacobians
    F = np.eye(9)
    #imu_f_3x1 = imu_f.data[k-1].reshape((3,1))
    F[0:3,3:6] = delta_t * np.eye(3)
    F[3:6, 6:9] = -skew_symmetric(c_ns_dot_f_km) * delta_t

    Q = np.eye(6)
    Q[:3, :3] = var_imu_f * np.eye(3)
    Q[3:, 3:] = var_imu_w * np.eye(3)
    Q = (delta_t**2) * Q

    # 2. Propagate uncertainty
    p_cov[k] = F.dot(p_cov[k-1]).dot(F.T) + l_jac.dot(Q).dot(l_jac.T)

    #3. Check availability of GNSS and LIDAR measurements
    # for i in range(len(gnss.t)):
    #     if abs (gnss.t[i] - imu_f.t[k]) < 0.01 :
    #         p_est[k], v_est[k], q_est[k], p_cov[k] = measurement_update(var_gnss, p_cov[k], gnss.data[i], p_est[k], v_est[k], q_est[k])

    # for j in range(len(lidar.t)):
    #     if abs(lidar.t[j] - imu_f.t[k]) < 0.01 :
    #         p_est[k], v_est[k], q_est[k], p_cov[k] = measurement_update(var_lidar, p_cov[k], lidar.data[j], p_est[k], v_est[k], q_est[k])

    # Update states (save)

#### 6. Results and Analysis ###################################################################

################################################################################################
# Now that we have state estimates for all of our sensor data, let's plot the results. This plot
# will show the ground truth and the estimated trajectories on the same plot. Notice that the
# estimated trajectory continues past the ground truth. This is because we will be evaluating
# your estimated poses from the part of the trajectory where you don't have ground truth!
################################################################################################
est_traj_fig = plt.figure()
ax = est_traj_fig.add_subplot(111, projection='3d')
ax.plot(p_est[:,0], p_est[:,1], p_est[:,2], label='Estimated')
ax.plot(gt.p[:,0], gt.p[:,1], gt.p[:,2], label='Ground Truth')
ax.set_xlabel('Easting [m]')
ax.set_ylabel('Northing [m]')
ax.set_zlabel('Up [m]')
ax.set_title('Ground Truth and Estimated Trajectory')
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)
ax.set_zlim(-2, 2)
ax.set_xticks([0, 50, 100, 150, 200])
ax.set_yticks([0, 50, 100, 150, 200])
ax.set_zticks([-2, -1, 0, 1, 2])
ax.legend(loc=(0.62,0.77))
ax.view_init(elev=45, azim=-50)
plt.show()

################################################################################################
# We can also plot the error for each of the 6 DOF, with estimates for our uncertainty
# included. The error estimates are in blue, and the uncertainty bounds are red and dashed.
# The uncertainty bounds are +/- 3 standard deviations based on our uncertainty (covariance).
################################################################################################
error_fig, ax = plt.subplots(2, 3)
error_fig.suptitle('Error Plots')
num_gt = gt.p.shape[0]
p_est_euler = []
p_cov_euler_std = []

# Convert estimated quaternions to euler angles
for i in range(len(q_est)):
    qc = Quaternion(*q_est[i, :])
    p_est_euler.append(qc.to_euler())

    # First-order approximation of RPY covariance
    J = rpy_jacobian_axis_angle(qc.to_axis_angle())
    p_cov_euler_std.append(np.sqrt(np.diagonal(J @ p_cov[i, 6:, 6:] @ J.T)))

p_est_euler = np.array(p_est_euler)
p_cov_euler_std = np.array(p_cov_euler_std)

# Get uncertainty estimates from P matrix
p_cov_std = np.sqrt(np.diagonal(p_cov[:, :6, :6], axis1=1, axis2=2))

titles = ['Easting', 'Northing', 'Up', 'Roll', 'Pitch', 'Yaw']
for i in range(3):
    ax[0, i].plot(range(num_gt), gt.p[:, i] - p_est[:num_gt, i])
    ax[0, i].plot(range(num_gt),  3 * p_cov_std[:num_gt, i], 'r--')
    ax[0, i].plot(range(num_gt), -3 * p_cov_std[:num_gt, i], 'r--')
    ax[0, i].set_title(titles[i])
ax[0,0].set_ylabel('Meters')

for i in range(3):
    ax[1, i].plot(range(num_gt), \
        angle_normalize(gt.r[:, i] - p_est_euler[:num_gt, i]))
    ax[1, i].plot(range(num_gt),  3 * p_cov_euler_std[:num_gt, i], 'r--')
    ax[1, i].plot(range(num_gt), -3 * p_cov_euler_std[:num_gt, i], 'r--')
    ax[1, i].set_title(titles[i+3])
ax[1,0].set_ylabel('Radians')
plt.show()

#### 7. Submission #############################################################################

################################################################################################
# Now we can prepare your results for submission to the Coursera platform. Uncomment the
# corresponding lines to prepare a file that will save your position estimates in a format
# that corresponds to what we're expecting on Coursera.
################################################################################################

# Pt. 1 submission
# p1_indices = [9000, 9400, 9800, 10200, 10600]
# p1_str = ''
# for val in p1_indices:
#     for i in range(3):
#         p1_str += '%.3f ' % (p_est[val, i])
# with open('pt1_submission.txt', 'w') as file:
#     file.write(p1_str)

#Pt. 2 submission
# p2_indices = [9000, 9400, 9800, 10200, 10600]
# p2_str = ''
# for val in p2_indices:
#     for i in range(3):
#         p2_str += '%.3f ' % (p_est[val, i])
# with open('pt2_submission.txt', 'w') as file:
#     file.write(p2_str)

# Pt. 3 submission
# p3_indices = [6800, 7600, 8400, 9200, 10000]
# p3_str = ''
# for val in p3_indices:
#     for i in range(3):
#         p3_str += '%.3f ' % (p_est[val, i])
# with open('pt3_submission.txt', 'w') as file:
#     file.write(p3_str)


#!/usr/bin/env python3

"""Command line entry point."""

from hdyndns import logger
from hdyndns.config import (
    create_home,
    get_user,
    read_config,
    validate_api_secrets,
    validate_dns_providers,
)
from hdyndns.providers import GandiDynDNS
from hdyndns.settings import EXIT_CODE_0_OK

def cli_entrypoint() -> None:
    """The command line entrypoint."""
    user = get_user()
    create_home(user)

    config = read_config(user)
    sections = [section for section in config.keys() if section != 'DEFAULT']

    validate_dns_providers(config, sections)
    validate_api_secrets(config, sections)

    for section in sections:
        logger.info('Section {}'.format(section))

        if 'gandi' == config[section]['provider']:
            logger.info('Processing {} with provider Gandi'.format(section))
            GandiDynDNS(config[section]).update_dns()
        else:
            logger.critical('No supported provider found')

    exit(EXIT_CODE_0_OK)


#! /usr/bin/env python
"""

This module contains miscellaneous GPIB functions:

 - scanGpib

"""

from __future__ import print_function, unicode_literals

import platform
import warnings

if platform.system() == "Linux":
    try:
        import gpib

        has_gpib = True
    except Exception:
        print("Warning: Linux-GPIB Python bindings not found")
        has_gpib = False
else:
    has_gpib = False

def scanGpib(board):
    if not has_gpib:
        warnings.warn(
            "Linux-GPIB is not available. ScanGpib with VISA not implemented at the moment.",
            RuntimeWarning,
            stacklevel=2,
        )
    else:
        for pad in range(1, 31):
            listen = gpib.listener(board, pad)
            # print(board, pad, listen)
            if listen:
                print("GPIB" + str(board) + "::" + str(pad))
                try:
                    ud = gpib.dev(board, pad, 0, 10, 1, 0)
                    if ud > 0:
                        gpib.write(ud, "*CLS;*IDN?")
                        description = gpib.read(ud, 256)
                        print(description.strip().decode("ascii"))
                except Exception:
                    pass


"""
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/
"""

from typing import List

from test_helper import TreeNode

class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        def do(start: int, end: int) -> TreeNode:
            if start > end:
                return None

            if start == end:
                return TreeNode(preorder[start])

            rootVal = preorder[start]
            left = start + 1
            while left <= end and preorder[left] < rootVal:
                left += 1

            root = TreeNode(rootVal)
            root.left = do(start + 1, left - 1)
            root.right = do(left, end)
            return root

        return do(0, len(preorder) - 1)


#python program for sum of first n natural number.

#INPUT:
def sumofsquares(n):
    if n<0:
     pass
    sum = n*(n+1)*(2*n+1) //6
    return int(sum)

n = int(input("Enter n:"))
sum = sumofsquares(n)
print(sumofsquares(n))

#OUTPUT:
'''Enter n:2
5'''

#OR

#INPUT:
n=int(input("enter number:"))
sum=0
for i in range(1,n+1):
    sum+=i**2
    print(sum)

#OUTPUT:
'''enter number:2
1
5'''

#OR

#INPUT:
def squaresum(n):
    return(n*(n+1)*(2*n+1)) //6
n = int(input("Enter number:"))
print(squaresum(n))

#OUTPUT:
'''Enter number:2
5'''

#OR

#INPUT:
def squaresum(n):
    sum=0
    for i in range(1,n+1):
        sum=sum+(i**2)
    return sum
n = int(input("Enter number:"))
print(squaresum(n))

#OUTPUT:
'''Enter number:2
5'''