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

from rpython.rlib.debug import debug_print
from rpython.rlib.jit import dont_look_inside

from typhon.atoms import getAtom
from typhon.autohelp import autohelp
from typhon.errors import Refused, userError
from typhon.objects.collections.maps import ConstMap, monteMap, unwrapMap
from typhon.objects.constants import NullObject
from typhon.objects.data import StrObject, unwrapStr
from typhon.objects.guards import anyGuard
from typhon.objects.root import Object, audited
from typhon.objects.slots import finalBinding
from typhon.objects.tests import UnitTest
from typhon.prelude import getGlobal
from typhon.importing import evaluateRaise, instantiateModule, obtainModule

RUN_1 = getAtom(u"run", 1)
RUN_2 = getAtom(u"run", 2)
SCRIPT_1 = getAtom(u"script", 1)
SCRIPT_2 = getAtom(u"script", 2)

@autohelp
@audited.DF
class Import(Object):
    """
    An importer of foreign objects from faraway modules.

    The imported module automatically is granted a safe scope.
    """

    def __init__(self, path, scope, recorder, testCollector):
        self.path = path
        self.scope = scope
        self.recorder = recorder
        self.testCollector = testCollector

    @dont_look_inside
    def performModule(self, path, importList=None):
        p = path.encode("utf-8")

        term = obtainModule(self.path, p, self.recorder)

        # Get module.
        module, _ = evaluateRaise([term], self.scope)

        scope = monteMap()
        DFb = getGlobal(u"DeepFrozen")
        if DFb is None:
            g = anyGuard
        else:
            g = DFb.getValue()
        scope[StrObject(u"import")] = finalBinding(self, g)

        scope[StrObject(u"unittest")] = finalBinding(
            UnitTest(path, self.testCollector), anyGuard)
        if importList is not None:
            assert isinstance(importList, ConstMap)
            scope.update(importList.objectMap)

        # Instantiate the module.
        mapping = instantiateModule(module, ConstMap(scope))

        if mapping is None:
            debug_print("Result was None :c")
            return NullObject
        return mapping

    @dont_look_inside
    def performScript(self, path, extraScope=None):
        p = path.encode("utf-8")

        # Transitive imports.
        scope = addImportToScope(self.path, self.scope, self.recorder,
                                 self.testCollector)
        if extraScope is not None:
            scope.update(extraScope)

        scope[u'unittest'] = finalBinding(
            UnitTest(path, self.testCollector), anyGuard)
        # Attempt the import.
        term = obtainModule(self.path, p, self.recorder)

        # Get results.
        result, _ = evaluateRaise([term], scope)
        return result

    def recv(self, atom, args):
        if atom is RUN_1:
            path = unwrapStr(args[0])
            return self.performModule(path)

        if atom is RUN_2:
            path = unwrapStr(args[0])
            return self.performModule(path, importList=args[1])

        if atom is SCRIPT_1:
            path = unwrapStr(args[0])
            return self.performScript(path, None)

        if atom is SCRIPT_2:
            path = unwrapStr(args[0])
            scope = unwrapMap(args[1])

            d = {}
            for k, v in scope.items():
                s = unwrapStr(k)
                if not s.startswith("&&"):
                    raise userError(u"import.script scope map must be of the "
                                    "form '[\"&&name\" => binding]'")
                d[s[2:]] = scope[k]

            return self.performScript(path, d)

        raise Refused(self, atom, args)

def addImportToScope(path, scope, recorder, testCollector):
    scope = scope.copy()
    DFb = getGlobal(u"DeepFrozen")
    if DFb is None:
        g = anyGuard
    else:
        g = DFb.getValue()
    scope[u"import"] = finalBinding(
        Import(path, scope, recorder, testCollector), g)
    return scope


filehandle = open("day7.txt")

contents = filehandle.readlines()
b = [x for x in range(2000)]
b = set(b)
dictionary = {}

i = 0
for i in range(0, contents.__len__()): #contents.__len__() - 1
    contents[i] = contents[i].replace("<-> ", '')
    contents[i] = contents[i].replace(",", '').split(" ")
    for j in range(0, len(contents[i])):
        contents[i][j] = int(contents[i][j])

for i in range(0, contents.__len__()):
    dictionary[i] = contents[i][1::]

#http://code.activestate.com/recipes/576723-dfs-and-bfs-graph-traversal/
def recursive_dfs(graph, start, path=[]):
  '''recursive depth first search from start'''
  path=path+[start]
  for node in graph[start]:
    if not node in path:
      path=recursive_dfs(graph, node, path)
  return path

def iterative_dfs(graph, start, path=[]):
  '''iterative depth first search from start'''
  q=[start]
  while q:
    v=q.pop(0)
    if v not in path:
      path=path+[v]
      q=graph[v]+q
  return path

print(len(dictionary), dictionary)

#a = sorted(iterative_dfs(dictionary, 0))

i = 0

#b = b - set(a)
print(len(b))
print(list(b)[0])

while b:
    #print("i =", i)
    #print("Len of b=", len(b), "\nList b[0]=", list(b)[0], b)
    #print("len(iterative_dfs(dictionary, list(b)[0])) =", len(iterative_dfs(dictionary, list(b)[0])))
    temp = iterative_dfs(dictionary, list(b)[0])
    print("temp =", temp)
    print(b.__len__(), b)
    if len(temp) > 1:
        b = set(sorted(list(b - set(sorted(temp)))))
        i += 1
    else:
        i += 1
        print(iterative_dfs(dictionary, list(b)[0]), "b.remove = ", list(b)[0])
        b.remove(list(b)[0])

print("i =", i)


from flask import Blueprint, request
from server import mysql
import jwt

follow = Blueprint("follow", __name__)

def fetch_user_id(auth_header):
    encoded_token = auth_header.split(" ")[1]
    decoded_data = jwt.decode(encoded_token, "masai02@", algorithm=["HS256"])
    return decoded_data["id"]

def user_exists_check(email):
    cursor = mysql.connection.cursor()
    cursor.execute("""SELECT id from users WHERE email = %s""", (email,))

    results = cursor.fetchall()
    items = []

    for item in results:
        items.append(item)

    mysql.connection.commit()
    cursor.close()

    if len(items) > 0:
        return True
    else:
        return False

def fetch_follows_user_id(email):
    cursor = mysql.connection.cursor()
    cursor.execute("""SELECT id from users WHERE email = %s""", (email,))

    results = cursor.fetchall()
    user_id = ""

    for item in results:
        user_id = item["id"]

    mysql.connection.commit()
    cursor.close()

    return user_id

def user_already_followed(follows_user_id):
    print(follows_user_id)
    cursor = mysql.connection.cursor()
    cursor.execute("""SELECT user_id from following WHERE follows_user_id = %s""", (follows_user_id,))

    results = cursor.fetchall()
    items = []

    for item in results:
        items.append(item)
    print(items)

    mysql.connection.commit()
    cursor.close()

    if len(items) > 0:
        return True
    else:
        return False

@follow.route("", methods=["POST"])
def follow_user():
    follows_user_email = request.json["email"]

    if user_exists_check(follows_user_email):
        follows_user_id = fetch_follows_user_id(follows_user_email)

        if (user_already_followed(follows_user_id)):
            return {"status": 400, "message": "User already followed"}
        else:
            current_user_id = fetch_user_id(request.headers.get("Authorization"))

            cursor = mysql.connection.cursor()

            cursor.execute(
                """INSERT INTO following (user_id, follows_user_id) VALUES (%s, %s)""",
                (current_user_id, follows_user_id))

            mysql.connection.commit()
            cursor.close()

            return {"status": 200, "message": "User following successful"}

    else:
        return {"status": 400, "message": "User does not exist"}


import json
import os
from pprint import pprint

from fastapi import File, UploadFile, APIRouter, Form
from fastapi.responses import FileResponse

from db.paper import db_upload_paper, db_query_papers, db_submit_paper
from settings import DATA_DIR

api_paper = APIRouter(tags=["paper"])

def get_file_path(id: str):
    return os.path.join(DATA_DIR, id)

def download_file(file: UploadFile, file_path: str):
    f1 = file.file.read()
    with open(file_path, "wb") as f2:
        f2.write(f1)

@api_paper.post("/upload/", summary="上传论文")
async def create_upload_paper(
        file: UploadFile = File(...),
        data: str = Form(...)
):
    upload_temp_file_data = json.loads(data)
    user_openid = upload_temp_file_data["user_openid"]
    file_data = upload_temp_file_data["file"]
    name = file_data["name"]
    time = file_data["time"]
    path = file_data["path"]
    size = file_data["size"]
    id = f"{time}-{name}"

    # 下载文件
    download_file(file, get_file_path(id))

    # 返回数据
    data = {
        "id": id,
        "user_openid": user_openid,
        "file_name": name,
        "file_size": size,
        "file_path": path,
        "time": time,
        "status": "uploaded",
    }
    db_upload_paper(data)
    pprint(data)
    return data

@api_paper.get("/submit/")
async def submit_paper(id: str):
    res = db_submit_paper(id)
    return res

@api_paper.get("/query/", summary="获取论文列表")
async def query_papers(user_openid: str = "test"):
    return db_query_papers(user_openid)

@api_paper.get("/download/", summary="下载报告")
async def download_paper(id: str = "test.json"):
    return FileResponse(get_file_path(id))


from flask import Flask
from app.register import register
from settings import Config

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    register_extensions(app)
    register(app)
    return app

def register_extensions(app):
    from app.extensions import db, migrate
    db.init_app(app)
    migrate.init_app(app, db)

app = create_app()


import os
import struct
import numpy as np
import cv2
import pandas as pd
from sklearn.model_selection import train_test_split
from skimage.transform import resize
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt

os.chdir("/run/user/1000/gvfs/sftp:host=192.168.84.212/KALpydev/icr_pickle_files/CNN_Data")

#Emnist data
train_img = 'emnist-byclass-train-images-idx3-ubyte'
train_lbl = 'emnist-byclass-train-labels-idx1-ubyte'
test_img = 'emnist-byclass-test-images-idx3-ubyte'
test_lbl = 'emnist-byclass-test-labels-idx1-ubyte'

with open(train_lbl, 'rb') as flbl:
        magic, num = struct.unpack(">II", flbl.read(8))
        train_lbl = np.fromfile(flbl, dtype=np.int8)

with open(train_img, 'rb') as fimg:
	magic, num, rows, cols = struct.unpack(">IIII", fimg.read(16))
	train_img = np.fromfile(fimg, dtype=np.uint8).reshape(len(train_lbl), rows, cols)

with open(test_lbl, 'rb') as flbl:
        magic, num = struct.unpack(">II", flbl.read(8))
        test_lbl = np.fromfile(flbl, dtype=np.int8)

with open(test_img, 'rb') as fimg:
	magic, num, rows, cols = struct.unpack(">IIII", fimg.read(16))
	test_img = np.fromfile(fimg, dtype=np.uint8).reshape(len(test_lbl), rows, cols)

#Change Background color

train_img=np.array(list(map(lambda x:255-np.transpose(x),train_img)))
test_img=np.array(list(map(lambda x:255-np.transpose(x),test_img)))

#0-9 class are numericals

train_img=train_img[train_lbl<=9]
train_lbl=train_lbl[train_lbl<=9]

test_img=test_img[test_lbl<=9]
test_lbl=test_lbl[test_lbl<=9]

def fg1(x):
	x[x>np.mean(x)]=1
	return(x)

size = 3

# generating the kernel
kernel_motion_blur = np.zeros((size, size))
kernel_motion_blur[int((size-1)/2), :] = np.ones(size)
kernel_motion_blur = kernel_motion_blur / size

# applying the kernel to the input image

x_train = np.array(list(map(lambda v:cv2.filter2D(v, -1, kernel_motion_blur),train_img)))
x_test = np.array(list(map(lambda v:cv2.filter2D(v, -1, kernel_motion_blur),test_img)))

y_train=train_lbl
y_test=test_lbl

#Normalization
x_train = np.array(list(map(lambda v:(v-v.min())/(v.max()-v.min()),x_train)))
x_test = np.array(list(map(lambda v:(v-v.min())/(v.max()-v.min()),x_test)))

p=np.array(pd.Series(np.arange(x_train.shape[0])).sample(x_train.shape[0]))
x=x_train[p]
y=y_train[p]

#Choose certain numbers of images for making the set balanced
x1=list()
y1=list()
v=5200
for i in range(10):
	x2=x[y==i]

	if x2.shape[0]>v:
		y2=np.repeat(i,v)
		y1.extend(y2)
		x2=x2[0:v]
	else:

		y2=np.repeat(i,x2.shape[0])
		y1.extend(y2)

	x1.extend(x2)

x1=np.array(x1)
y1=np.array(y1)

x1=np.array(list(map(lambda v:fg1(v),x1)))

x_train,x_test,y_train,y_test = train_test_split(x1,y1, test_size = 0.20, stratify=y1)

#Data Augmentation functon

datagen=ImageDataGenerator(
    rotation_range=1,
    width_shift_range=0.10,
    height_shift_range=0.10,
    fill_mode='reflect')

#One side grid function
def line1(e,c):

	c = cv2.filter2D(c, -1, kernel_motion_blur)
	arr = np.linspace(70,150,48).reshape((24,2))
	u=np.random.shuffle(arr)
	a=np.int(28*e/100)
	c[2:26,a:(a+2)]=arr
	return(c)

#both sides grids function
def line2(c):

	c = cv2.filter2D(c, -1, kernel_motion_blur)
	arr = np.linspace(70,150,48).reshape((24,2))
	u=np.random.shuffle(arr)
	a=np.int(28*15/100)
	c[2:26,a:(a+2)]=arr
	u=np.random.shuffle(arr)
	a=np.int(28*85/100)
	c[2:26,a:(a+2)]=arr
	return(c)

#Data augmentation and grids in the images

def data_aug_line(x,y,v):
	x_test2=list()
	y_test2=list()

	#Grids location in the image
	g=np.array([15,30,45,60,75,85])

	for k in range(10):

		x1=x[y==k]
		y1=y[y==k]
		x_test1=list()
		y_test1=list()
		i = 0
		n_s=int(v*10/100)

		#Data augmentation
		for x_batch,y_batch in datagen.flow(np.reshape(x1,[x1.shape[0],28,28,1]),y1, batch_size=1):
			i += 1
			x_batch=x_batch.reshape(28,28)
			x_test1.append(x_batch)
			y_test1.extend(y_batch)
			if i > np.int(v*50/100)-1:
				break

		x2=x1.copy()
		x3=list()
		#one grid
		kl= list(map(lambda w:x3.extend(list(map(lambda v:line1(w,v),x2[np.array(pd.Series(np.arange(len(x2))).sample(n_s))]))),g))

		#two grids
		kl= x3.extend(list(map(lambda v:line2(v),x2[np.array(pd.Series(np.arange(len(x2))).sample(n_s))])))

		x_test1=np.array(x_test1)
		y_test1=np.array(y_test1)

		#Add Motion blur noise
		x_test1 = np.array(list(map(lambda v:cv2.filter2D(v, -1, kernel_motion_blur),x_test1)))

		x3=np.array(x3)
		y3=np.repeat(k,(len(g)+1)*n_s)

		x1=np.concatenate((x_test1,x3))
		y1=np.concatenate((y_test1,y3))

		#Normalization
		x1=np.array(list(map(lambda v:(v-v.min())/(v.max()-v.min()),x1)))
		x1=np.array(list(map(lambda v:fg1(v),x1)))

		x_test2.extend(x1)
		y_test2.extend(y1)

	x_test2=np.array(x_test2)
	y_test2=np.array(y_test2)

	return(x_test2,y_test2)

#Calling function and Creating train-test set

x_test2,y_test2=data_aug_line(train_img,train_lbl,4160)
x_test3,y_test3=data_aug_line(train_img,train_lbl,1040)

len(x_test2)
plt.imshow(x_test2[49908])
plt.show()
plt.imshow(x_test2[2100])

x_train=np.concatenate((x_train,x_test2))
y_train=np.concatenate((y_train,y_test2))

x_test=np.concatenate((x_test,x_test3))
y_test=np.concatenate((y_test,y_test3))

p=np.array(pd.Series(np.arange(x_train.shape[0])).sample(x_train.shape[0]))

x_train=x_train[p]
y_train=y_train[p]

p=np.array(pd.Series(np.arange(x_test.shape[0])).sample(x_test.shape[0]))

x_test=x_test[p]
y_test=y_test[p]

np.savez("m2.npz",x_train,y_train,x_test,y_test)


import math #importing module for math to calculate the square root
print("Enter the first point: ")

#entering the first point coordinates
x1=float(input())
y1=float(input())

#entering the second point coordinates
print("Enter the second point: ")
x2=float(input())
y2=float(input())

#formula for computing the distance between the two points
dist=math.sqrt((x2-x1)**2+(y2-y1)**2)

print("The distance from (",x1,",",y1,") to (",x2,",",y2,") is", dist)


import utilities
import vastool
import re

class vasProduct:

    def __init__(self, remoteShell):
        self.remoteShell = remoteShell

    def _getVersionNumber(self, versionNumber):
        versionNumber = versionNumber.split(".")
        versionNumber.pop()
        versionNumber = ".".join(versionNumber)
        return versionNumber

    def _getBuildNumber(self, versionNumber):
        buildNumber = versionNumber.split(".")
        buildNumber = buildNumber.pop()
        return buildNumber

    def _formatBuildNumber35(self, versionNumber):
        versionNumber = versionNumber.replace(".", "_")
        return versionNumber

    def _getBuildPath(self, version, buildNumber):
        release = "{}.{}".format(version, buildNumber)
        if version == "3.5.2":
            release = self._formatBuildNumber35(release)
            path = "/mnt/vas/dev-builds/Build-vas_vgp-VAS_{}".format(release)
        else:
            path = "/mnt/vas/dev-builds/QAS-{}".format(release)

        return path

    def copyInstallFiles(self, buildVersion, osPackageName, directory="/tmp/client", timeout=311):
        self.remoteShell.run('rm -rf {}'.format(directory))
        self.remoteShell.run('mkdir {}'.format(directory))

        version = self._getVersionNumber(buildVersion)
        buildNumber = self._getBuildNumber(buildVersion)
        path = self._getBuildPath(version, buildNumber)

        self.remoteShell.run('cp {}/install.sh /tmp'.format(path), timeout=timeout)
        self.remoteShell.run('cp -r {}/client/install-sh-data /tmp/client'.format(path))
        self.remoteShell.run('cp -r {}/client/{} /tmp/client'.format(path, osPackageName), timeout=timeout)

    def install(self, version, os, osversion, arch, packages="", location="", timeout=600):
        versionNumber = self._getVersionNumber(version)
        buildNumber = self._getBuildNumber(version)

        if packages == "":
            packages = self.getInstallPackages(os, version)

        if os == "HP-UX" and osversion > '11.23':
            hpPackage = self.hpuxInstallPackages(osversion, arch)
            self.copyInstallFiles(version, hpPackage)
            if location == "":
                path = "/tmp"

        else:
            path = self._getBuildPath(versionNumber, buildNumber)

        result = self.remoteShell.run('{}/install.sh -q {}'.format(path, packages), timeout=timeout)
        return utilities.getBooleanResult(result)

    def upgrade(self, version, os, osversion, previousBuild, packages="", location=""):
        # install previous build first
        result = self.install(previousBuild, packages, location)
        if result:
            # upgrade
            return self.install(version, os, osversion, packages, location)
        else:
            return result

    def uninstall(self, version="", packages=""):
        if version == "":
            version = self.getVasVersion()

        versionNumber = self._getVersionNumber(version)
        buildNumber = self._getBuildNumber(version)

        path = self._getBuildPath(versionNumber, buildNumber)

        result = self.remoteShell.run('{}/install.sh remove {}'.format(path, packages), timeout=1200)
        return utilities.getBooleanResult(result)

    def uninstallCheck(self, os):
        files = ["/etc/opt/quest/vas/access.d",
                 "/etc/opt/quest/vas/group-override.sample",
                 "/etc/opt/quest/vas/user-override.sample",
                 "/etc/opt/quest/vas/users.allow.sample",
                 "/etc/opt/quest/vas/users.deny.sample"]

        directories = ["/var/opt/quest/vas", "/var/opt/quest/vgp", "/opt/quest"]
        if os == "HP-UX":
            directories = ["/var/opt/quest/vas", "/var/opt/quest/vgp"]

        result = True
        for directory in directories:
            if self.remoteShell.run("test -d {}".format(directory)) == 0:
                self.remoteShell.run("ls -R {}".format(directory))
                result = False

        for vasFile in files:
            if self.remoteShell.run("test -f {}".format(vasFile)) == 0:
                result = False

        return result

    def hpuxInstallPackages(self, osversion, arch):
        if osversion == '11.11':
            return "hpux-pa-11v1"#THIS CHANGED IN 4.1 from hpux-pa
        elif osversion == '11.23':
            return "hpux-pa-11v1"
        elif osversion == '11.31' and arch == 'ia64':
            return "hpux-ia64"
        else:
            return "hpux-pa-11v1"

    def getInstallPackages(self, os, version):
        packages = "vasclnt vasgp"
        # if it's not mac, add vasyp and vasproxy
        if os.find('mac') == -1:
            packages += " vasyp vasproxy"
        # if it's an older build, include vasutil
        if version < "4.0.2.0":
            packages += " vasutil"

        return packages

    def removeVasutil(self, version, packages):
        self.uninstall(version, "vasutil")

    def getVasVersion(self):
        version, rCode = self.remoteShell.run("/opt/quest/bin/vastool -v", returnOutput=True)
        version = version.splitlines()
        version = version[0]
        versionRE = re.search("\w+: .+([0-9]\.[0-9]\.[0-9]\.[0-9]+)", version)
        if versionRE != None:
            return versionRE.group(1)
        else:
            return False


from itertools import combinations
def solve(ll):
	ll2=combinations(ll,4)
	count=0
	for i in ll2:
		if sum(i)==0:
			count+=1
	return count

def main():
	ll=list(map(int,input().split()))
	ans=solve(ll)
	print(ans)
if __name__ == '__main__':
	main()


import os
import os.path

import imageio
import pyglet

def create_gif(gif_name, path, duration):
    frames = []
    pngFiles = os.listdir(path)
    image_list = [os.path.join(path, f) for f in pngFiles]
    for image_name in image_list:
        # 读取 png 图像文件
        frames.append(imageio.imread(image_name))
    # 保存为 gif
    imageio.mimsave(gif_name, frames, 'GIF', duration=duration)

    ag_file = "2.gif"
    animation = pyglet.resource.animation(ag_file)
    sprite = pyglet.sprite.Sprite(animation)

    # 创建一个窗口并将其设置为图像大小
    win = pyglet.window.Window(width=sprite.width, height=sprite.height)

    # 设置窗口背景颜色 = r, g, b, alpha
    # 每个值从 0.0 到 1.0
    green = 0, 1, 0, 1
    pyglet.gl.glClearColor(*green)

    @win.event
    def on_draw():
        win.clear()
        sprite.draw()

    pyglet.app.run()

    return

def main():
    gif_name = '1.gif'
    path = 'D:\project\PycharmProject\TestApplication\image'  # 指定图片文件路径
    duration = 0.5
    create_gif(gif_name, path, duration)

if __name__ == "__main__":
    main()


import copy
import os
import drawSvg as draw
from random import uniform
import numpy as np
from start_project.discriminator.discriminator import Discriminator
from start_project.paint_tool.image_processor import image_to_binary

class PaintEnvParameters(object):
    PREDICTION_REWARD_THRESHOLD = 0.5
    MAX_NO_STEP_PER_EPISODE = 2
    CANVAS_HEIGHT = 100
    CANVAS_WIDTH = 100
    STROKE_WIDTH = 1
    STROKE_COLOR = 'black'
    ACTION_LEN = 2

class PaintEnv(object):

    def __init__(self):
        self.canvas = None
        self.discriminator = Discriminator((28, 28, 1))
        self.current_no_steps = 0
        self.max_no_steps_per_episode = PaintEnvParameters.MAX_NO_STEP_PER_EPISODE

    def reset(self):
        self.canvas = draw.Drawing(PaintEnvParameters.CANVAS_WIDTH, PaintEnvParameters.CANVAS_HEIGHT)
        self.path = draw.Path(stroke_width=PaintEnvParameters.STROKE_WIDTH, stroke=PaintEnvParameters.STROKE_COLOR,
                              fill='none')
        self.path.M(0, 0)

    def step(self, action):
        '''
        action = [intermediate_point, final_point]
        '''
        if len(action) != PaintEnvParameters.ACTION_LEN:
            return
        self.path.Q(*(action[0] + action[1]))
        reward = 0
        self.current_no_steps += 1
        done = self.current_no_steps >= self.max_no_steps_per_episode
        if done:
            self.save_png()
            binary_img = image_to_binary(os.path.dirname(os.path.realpath(__file__)) + '/temp_paint.png')
            prediction = self.discriminator.model.predict(binary_img)[0]
            print(round(prediction[0],4),  round(prediction[1],4))
            if np.argmax(prediction) == 1 and prediction[1] - prediction[0] > PaintEnvParameters.PREDICTION_REWARD_THRESHOLD: #save as constant
                reward = 1 + prediction[1] - prediction[0]
            self.discriminator.train(binary_img)

        return self.path.args['d'], reward, done, {}

    def get_random_action(self):
        return [
            [round(uniform(0, PaintEnvParameters.CANVAS_WIDTH), 2),
             round(uniform(0, PaintEnvParameters.CANVAS_HEIGHT), 2)]
            for _ in range(2)
        ]

    def render(self):
        self.canvas.append(self.path)
        self.canvas.setRenderSize(PaintEnvParameters.CANVAS_WIDTH, PaintEnvParameters.CANVAS_HEIGHT)
        self.canvas.saveSvg('example.svg')

    def save_png(self):
        temp_canvas = copy.deepcopy(self.canvas)
        temp_canvas.append(self.path)
        temp_canvas.setRenderSize(28, 28)
        temp_canvas.savePng('temp_paint.png')


import sys, os
import pandas as pd

sys.path.append("../")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "atlas.settings")

import django
django.setup()

from councilman.models import Councilman, Donation

def save_from_row(row):
    d = Donation(**row)
    d.save()

if __name__ == "__main__":
    if len(sys.argv) == 2:
        f = str(sys.argv[1])

        print("Reading file " + f)

        councilman = pd.DataFrame().from_records(
            Councilman.objects.all().values('id', 'sequential_id')
        ).rename(columns={'id': 'councilman_id'})

        df = pd.read_csv(f)
        df['from_file'] = f.split("/")[-1]
        df = pd.merge(df, councilman, on='sequential_id')
        df.apply(save_from_row, axis=1)

    else:
        print("Please, provide the file path")


# fig_ggn_hyperpolarization.py ---
# Author: Subhasis  Ray
# Created: Tue Feb 12 14:53:34 2019 (-0500)
# Last-Updated: Tue Feb 12 15:37:32 2019 (-0500)
#           By: Subhasis  Ray
# Version: $Id$

# Code:
"""Supplementary figures showing GGN hyperpolarization when PN->KC
connection is not clustered"""

from __future__ import print_function
import sys
if sys.platform == 'win32':
    sys.path.append('D:/subhasis_ggn/model/analysis')
else:
    sys.path += ['/home/rays3/projects/ggn/analysis',
                 '/home/rays3/projects/ggn/morphutils',
                 '/home/rays3/projects/ggn/nrn']
import os
import h5py as h5
import numpy as np
import random
from matplotlib import pyplot as plt

import network_data_analysis as nda
import pn_kc_ggn_plot_mpl as myplot

datadir = '/data/rays3/ggn/olfactory_network'

#jid = '20161955'
# jid = '20162331'
jid = '20162116'
fname = nda.find_h5_file(jid, datadir)
fig, ax = plt.subplots()
with h5.File(fname, 'r') as fd:
    spike_counts = [ds.shape[0] for ds in fd['/data/event/kc/kc_spiketime'].values()]
    spiking = len(np.flatnonzero(spike_counts))
    print('spiking kcs:{}'.format(spiking))
    myplot.plot_ggn_vm(
        ax, fd,
        fd['/data/uniform/ggn_basal/GGN_basal_Vm'], 'dend_b', 1)
    ax.set_xlabel('Time (ms)')
    ax.set_ylabel('GGN Vm (mV)')
    ax.tick_params(right=False, top=False)
    ax.set_xlim(500, 2500)
fig.set_frameon(False)
fig.set_size_inches(20/2.54, 10/2.54)
fig.savefig('supp_4_ggn_ig_hyperpolarization.svg')

# 50.0,1.4,2.7,20162064
jid = '20162064'
fname = nda.find_h5_file(jid, datadir)
fig, ax = plt.subplots()
with h5.File(fname, 'r') as fd:
    spike_counts = [ds.shape[0] for ds in fd['/data/event/kc/kc_spiketime'].values()]
    spiking = len(np.flatnonzero(spike_counts))
    print('spiking kcs:{}'.format(spiking))
    myplot.plot_ggn_vm(ax, fd,
                       fd['/data/uniform/ggn_basal/GGN_basal_Vm'], 'dend_b', 1)
    ax.set_xlabel('Time (ms)')
    ax.set_ylabel('GGN Vm (mV)')
    ax.set_xlim(500, 2500)
    ax.tick_params(right=False, top=False)
fig.set_frameon(False)
fig.set_size_inches(20/2.54, 10/2.54)
fig.savefig('supp_5_ggn_ig_de_hyperpolarization.svg')

#
# fig_ggn_hyperpolarization.py ends here


# -*- coding: utf-8 -*-
########################################################################
#
#       License: BSD 3-clause
#       Created: September 22, 2010
#       Author:  Francesc Alted - faltet@gmail.com
#
########################################################################

# flake8: noqa

from __future__ import print_function

import os
import platform
import re
import sys
import io

from setuptools import Extension
from setuptools import setup
from glob import glob
from distutils.version import LooseVersion
from distutils.command.build_ext import build_ext
from distutils.errors import CompileError
from textwrap import dedent

class BloscExtension(Extension):
    """Allows extension to carry architecture-capable flag options.

    Attributes:
        avx2_def (Dict[str]: List[str]):
            AVX2 support dictionary mapping Extension properties to a
            list of values. If compiler is AVX2 capable, then these will
            be appended onto the end of the Extension properties.
    """

    def __init__(self, *args, **kwargs):
        self.avx2_defs = kwargs.pop("avx2_defs", {})
        Extension.__init__(self, *args, **kwargs)

class build_ext_posix_avx2(build_ext):
    """build_ext customized to test for AVX2 support in posix compiler.

    This is because until distutils has actually started the build
    process, we can't be certain what compiler is being used.

    If compiler supports, then the avx2_defs dictionary on any given
    Extension will be used to extend the other Extension attributes.
    """

    def _test_compiler_flags(self, name, flags):
        # type: (List[str]) -> Bool
        """Test that a sample program can compile with given flags.

        Attr:
            flags (List[str]): the flags to test
            name (str): An identifier-like name to cache the results as

        Returns:
            (bool): Whether the compiler accepted the flags(s)
        """
        # Look to see if we have a written file to cache the result
        success_file = os.path.join(self.build_temp, "_{}_present".format(name))
        fail_file = os.path.join(self.build_temp, "_{}_failed".format(name))
        if os.path.isfile(success_file):
            return True
        elif os.path.isfile(fail_file):
            return False
        # No cache file, try to run the compile
        try:
            # Write an empty test file
            test_file = os.path.join(self.build_temp, "test_{}_empty.c".format(name))
            if not os.path.isfile(test_file):
                open(test_file, "w").close()
            objects = self.compiler.compile(
                [test_file], output_dir=self.build_temp, extra_postargs=flags
            )
            # Write a success marker so we don't need to compile again
            open(success_file, 'w').close()
            return True
        except CompileError:
            # Write a failure marker so we don't need to compile again
            open(fail_file, 'w').close()
            return False
        finally:
            pass

    def build_extensions(self):
        # Verify that the compiler supports requested extra flags
        if self._test_compiler_flags("avx2", ["-mavx2"]):
            # Apply the AVX2 properties to each extension
            for extension in self.extensions:
                if hasattr(extension, "avx2_defs"):
                    # Extend an existing attribute with the stored values
                    for attr, defs in extension.avx2_defs.items():
                        getattr(extension, attr).extend(defs)
        else:
            print("AVX2 Unsupported by compiler")

        # Call up to the superclass to do the actual build
        build_ext.build_extensions(self)

if __name__ == '__main__':

    with io.open('README.rst', encoding='utf-8') as f:
        long_description = f.read()

    try:
        import cpuinfo
        cpu_info = cpuinfo.get_cpu_info()
    except Exception:
        # newer cpuinfo versions fail to import on unsupported architectures
        cpu_info = None

    ########### Check versions ##########
    def exit_with_error(message):
        print('ERROR: %s' % message)
        sys.exit(1)

    # Check for Python
    if sys.version_info[0] == 2:
        if sys.version_info[1] < 7:
            exit_with_error("You need Python 2.7 or greater to install blosc!")
    elif sys.version_info[0] == 3:
        if sys.version_info[1] < 4:
            exit_with_error("You need Python 3.4 or greater to install blosc!")
    else:
        exit_with_error("You need Python 2.7/3.4 or greater to install blosc!")

    tests_require = ['numpy', 'psutil']

    ########### End of checks ##########

    # Read the long_description from README.rst
    with open('README.rst') as f:
        long_description = f.read()

    # Blosc version
    VERSION = open('VERSION').read().strip()
    # Create the version.py file
    open('blosc/version.py', 'w').write('__version__ = "%s"\n' % VERSION)

    # Global variables
    CFLAGS = os.environ.get('CFLAGS', '').split()
    LFLAGS = os.environ.get('LFLAGS', '').split()
    # Allow setting the Blosc dir if installed in the system
    BLOSC_DIR = os.environ.get('BLOSC_DIR', '')

    # Check for USE_CODEC environment variables
    try:
        INCLUDE_LZ4 = os.environ['INCLUDE_LZ4'] == '1'
    except KeyError:
        INCLUDE_LZ4 = True
    try:
        INCLUDE_SNAPPY = os.environ['INCLUDE_SNAPPY'] == '1'
    except KeyError:
        INCLUDE_SNAPPY = False  # Snappy is disabled by default
    try:
        INCLUDE_ZLIB = os.environ['INCLUDE_ZLIB'] == '1'
    except KeyError:
        INCLUDE_ZLIB = True
    try:
        INCLUDE_ZSTD = os.environ['INCLUDE_ZSTD'] == '1'
    except KeyError:
        INCLUDE_ZSTD = True

    # Handle --blosc=[PATH] --lflags=[FLAGS] --cflags=[FLAGS]
    args = sys.argv[:]
    for arg in args:
        if arg.find('--blosc=') == 0:
            BLOSC_DIR = os.path.expanduser(arg.split('=')[1])
            sys.argv.remove(arg)
        if arg.find('--lflags=') == 0:
            LFLAGS = arg.split('=')[1].split()
            sys.argv.remove(arg)
        if arg.find('--cflags=') == 0:
            CFLAGS = arg.split('=')[1].split()
            sys.argv.remove(arg)

    # Blosc sources and headers

    # To avoid potential namespace collisions use build_clib.py for each codec
    # instead of co-compiling all sources files in one setuptools.Extension object.
    clibs = [] # for build_clib, libraries TO BE BUILT

    # Below are parameters for the Extension object
    sources = ["blosc/blosc_extension.c"]
    inc_dirs = []
    lib_dirs = []
    libs = []  # Pre-built libraries ONLY, like python36.so
    def_macros = []
    builder_class = build_ext  # To swap out if we have AVX capability and posix
    avx2_defs = {}  # Definitions to build extension with if compiler supports AVX2

    if BLOSC_DIR != '':
        # Using the Blosc library
        lib_dirs += [os.path.join(BLOSC_DIR, 'lib')]
        inc_dirs += [os.path.join(BLOSC_DIR, 'include')]
        libs += ['blosc']
    else:

        # Configure the Extension
        # Compiling everything from included C-Blosc sources
        sources += [f for f in glob('c-blosc/blosc/*.c')
                    if 'avx2' not in f and 'sse2' not in f]

        inc_dirs += [os.path.join('c-blosc', 'blosc')]
        inc_dirs += glob('c-blosc/internal-complibs/*')

        # Codecs to be built with build_clib
        if INCLUDE_LZ4:
            clibs.append( ('lz4', {'sources': glob('c-blosc/internal-complibs/lz4*/*.c')} ) )
            inc_dirs += glob('c-blosc/internal-complibs/lz4*')
            def_macros += [('HAVE_LZ4',1)]

        # Tried and failed to compile Snappy with gcc using 'cflags' on posix
        # setuptools always uses gcc instead of g++, as it only checks for the
        # env var 'CC' and not 'CXX'.
        if INCLUDE_SNAPPY:
            clibs.append( ('snappy', {'sources': glob('c-blosc/internal-complibs/snappy*/*.cc'),
                                    'cflags': ['-std=c++11', '-lstdc++'] } ) )
            inc_dirs += glob('c-blosc/internal-complibs/snappy*')
            def_macros += [('HAVE_SNAPPY',1)]

        if INCLUDE_ZLIB:
            clibs.append( ('zlib', {'sources': glob('c-blosc/internal-complibs/zlib*/*.c')} ) )
            def_macros += [('HAVE_ZLIB',1)]

        if INCLUDE_ZSTD:
            clibs.append( ('zstd', {'sources': glob('c-blosc/internal-complibs/zstd*/*/*.c'),
                        'include_dirs': glob('c-blosc/internal-complibs/zstd*') + glob('c-blosc/internal-complibs/zstd*/common') } ) )
            inc_dirs += glob('c-blosc/internal-complibs/zstd*/common')
            inc_dirs += glob('c-blosc/internal-complibs/zstd*')
            def_macros += [('HAVE_ZSTD',1)]

        # Guess SSE2 or AVX2 capabilities
        # SSE2
        if 'DISABLE_BLOSC_SSE2' not in os.environ and cpu_info != None and 'sse2' in cpu_info.get('flags', {}):
            print('SSE2 detected')
            CFLAGS.append('-DSHUFFLE_SSE2_ENABLED')
            sources += [f for f in glob('c-blosc/blosc/*.c') if 'sse2' in f]
            if os.name == 'posix':
                CFLAGS.append('-msse2')
            elif os.name == 'nt':
                def_macros += [('__SSE2__', 1)]
        # AVX2
        if 'DISABLE_BLOSC_AVX2' not in os.environ and cpu_info != None and 'sse2' in cpu_info.get('flags', {}):
            if os.name == 'posix':
                print("AVX2 detected")
                avx2_defs = {
                    "extra_compile_args": ["-DSHUFFLE_AVX2_ENABLED", "-mavx2"],
                    "sources": [f for f in glob("c-blosc/blosc/*.c") if "avx2" in f]
                }
                # The CPU supports it but the compiler might not..
                builder_class = build_ext_posix_avx2
            elif(os.name == 'nt' and
                    LooseVersion(platform.python_version()) >= LooseVersion('3.5.0')):
                # Neither MSVC2008 for Python 2.7 or MSVC2010 for Python 3.4 have
                # sufficient AVX2 support
                # Since we don't rely on any special compiler capabilities,
                # we don't need to rely on testing the compiler
                print('AVX2 detected')
                CFLAGS.append('-DSHUFFLE_AVX2_ENABLED')
                sources += [f for f in glob('c-blosc/blosc/*.c') if 'avx2' in f]
                def_macros += [('__AVX2__', 1)]
        # TODO: AVX512

    classifiers = dedent("""\
    Development Status :: 5 - Production/Stable
    Intended Audience :: Developers
    Intended Audience :: Information Technology
    Intended Audience :: Science/Research
    License :: OSI Approved :: BSD License
    Programming Language :: Python
    Programming Language :: Python :: 2.7
    Programming Language :: Python :: 3.4
    Programming Language :: Python :: 3.5
    Programming Language :: Python :: 3.6
    Programming Language :: Python :: 3.7
    Topic :: Software Development :: Libraries :: Python Modules
    Topic :: System :: Archiving :: Compression
    Operating System :: Microsoft :: Windows
    Operating System :: Unix
    """)

    setup(name = "blosc",
        version = VERSION,
        description = 'Blosc data compressor',
        long_description = long_description,
        classifiers = [c for c in classifiers.split("\n") if c],
        author = 'Francesc Alted, Valentin Haenel',
        author_email = 'faltet@gmail.com, valentin@haenel.co',
        maintainer = 'Francesc Alted, Valentin Haenel',
        maintainer_email = 'faltet@gmail.com, valentin@haenel.co',
        url = 'http://github.com/blosc/python-blosc',
        license = 'https://opensource.org/licenses/BSD-3-Clause',
        platforms = ['any'],
        libraries = clibs,
        ext_modules = [
            BloscExtension( "blosc.blosc_extension",
                    include_dirs=inc_dirs,
                    define_macros=def_macros,
                    sources=sources,
                    library_dirs=lib_dirs,
                    libraries=libs,
                    extra_link_args=LFLAGS,
                    extra_compile_args=CFLAGS,
                    avx2_defs=avx2_defs
            ),
        ],
        tests_require=tests_require,
        zip_safe=False,
        packages = ['blosc'],
        cmdclass={'build_ext': builder_class},
        )
elif __name__ == '__mp_main__':
    # This occurs from `cpuinfo 4.0.0` using multiprocessing to interrogate the
    # CPUID flags
    # https://github.com/workhorsy/py-cpuinfo/issues/108
    pass


import Tic_Tac_Toe

class Tic_Tac_Toe_Controller:
    STATE_GAME_OVER = 2
    STATE_GAME_IN_COURSE = 1
    STATE_GAME_NO_STARTED = 0
    def __init__(self):
        self.gameData = Tic_Tac_Toe.Game()

    def  init_players_data(self, player1str:str, player2str:str = ""):
        player1 = Tic_Tac_Toe.Player()
        player2 = Tic_Tac_Toe.Player()
        player1.playerName = player1str
        if (player2str == ""):
            player2.playerName = "Computer"
            player2.isPc = True

        else:
            player2.playerName = player2str

        player1.playerShape = "X"
        player2.playerShape = "O"
        self.gameData.player1 = player1
        self.gameData.player2 = player2
        print (player1)

    def getPlayer1(self):
        return (self.gameData.player1.playerName)

    def getPlayer2(self):
        return (self.gameData.player2.playerName)

    def newMove(self, x, y, cell_size):
        ny = 0
        nx = 0
        for yi in range(1, 4):
            if y <= cell_size * yi:
                ny = yi - 1
                for xi in range(1, 4):
                    if x <= cell_size * xi:
                        nx = xi - 1
                        break
                break

        if (self.gameData.board.squares[nx][ny] == 0):
            self.gameData.board.squares[nx][ny] = 1
            coord = {"x": nx, "y": ny}
            playerMove = self.gameData.player1.newPlayerMove(coord)
            self.gameData.turns.append(playerMove)
            self.gameData.check_game_over()
            return playerMove

        return None

    def newMoveVsComputer(self,cell_size):
        resultMove = self.gameData.player2.newComputerGeneratedRandomMove(self.gameData.board.squares)
        if resultMove != None:
            self.gameData.turns.append(resultMove)
            self.gameData.board.squares[resultMove.movePlace["x"]][resultMove.movePlace["y"]] = 2
            grid_place =  resultMove.movePlace
            grid_place["x"] = (resultMove.movePlace["x"] + 1)* cell_size * .99
            grid_place["y"] = (resultMove.movePlace["y"] + 1) * cell_size * .99
            game_result = self.gameData.check_game_over()
            return grid_place
        return None


import multiprocessing
from pathlib import Path
import cv2
from visutils.vis_feed import VisFeed
import glob, os
import pandas as pd
import shutil
import pandas as pd
import visutils.vis as vis
from parse import parse
from collections import defaultdict

def to_sec(frame, fps=10):
    return str(int(frame) // fps) + "s"

def frame_to_time(imfile):
    frame_num = int(Path(imfile).stem.split("_")[-1])
    return frame_num

class IntegratorClass:
    def __init__(self, fps=10):
        self.bin_pax = {}
        self.tmp = []
        # to determine first used
        self.item_first_used = []
        self.fps = fps
        self.asso_info = defaultdict(lambda: defaultdict(dict))

        self.msg = set()

    def load_info(self, bin_file, pax_file, nu_file_cam):
        # load bin
        self.df_bin = self.load_bin(bin_file)

        # load pax info
        self.df_pax = self.refine_pax_df(pax_file)

        # get association info
        _ = self.get_association_info(nu_file_cam)

        print("loaded")

    def load_bin(self, bin_file):
        # load bin info
        df = pd.read_csv(str(bin_file), sep=",")
        df["x1"] = df["x1"] / 3
        df["y1"] = df["y1"] / 3
        df["x2"] = df["x2"] / 3
        df["y2"] = df["y2"] / 3
        df["camera"] = df["cam"]
        df['id'] = 'B' + df['id'].astype(str)
        # load location type
        # df_new = df[df["type"] == "loc"].copy()
        # df_comb = df_new

        # load change type
        # loc_cng = df["type"] == "chng"
        # df_comb.loc[loc_cng, "frame"] = df[loc_cng]["frame"] - 50
        # change detection offset
        df = df.sort_values("frame")
        return df

    def refine_pax_df(self, pax_file):
        # pax_names = [
        #     "frame", "cam", "timeoffset", "x1", "y1", "x2", "y2", "id",
        #     "firstused"
        # ]
        df = pd.read_csv(str(pax_file), sep=",", index_col=0)
        df["x1"] = df["x1"] / (1080. / 640)
        df["y1"] = df["y1"] / (720. / 360)
        df["x2"] = df["x2"] / (1080. / 640)
        df["y2"] = df["y2"] / (720. / 360)
        df["camera"] = df["cam"].apply(lambda x: f"cam{int(x):02d}")
        return df

    def get_association_info(self, nu_file):
        asso_msg = defaultdict(dict)

        # fid, cam, events
        df = pd.read_csv(nu_file, header=None, names=["frame", "cam", "des"])
        df['cam'] = df['cam'].apply(lambda x: f"cam{int(x[3:]):02d}")
        for _, row in df.iterrows():
            frame = row["frame"]
            des = row["des"]
            cam = row["cam"]
            des = parse("[{}]", des)
            if des is None:
                continue
            des = des[0]
            des_splits = des.split("', '")
            for i, each_split in enumerate(des_splits):
                each_split = each_split.strip().replace("'",
                                                        "").replace("'", "")

                if 'XFR' in each_split:
                    each_split = each_split.replace("owner-ID", "PAX-ID")
                    _msg = parse(("XFR: type: {} camera-num: {} frame: {} "
                                  "time-offset: {} BB: {} PAX-ID: {pax_id} "
                                  "DVI-ID: {bin_id} theft: {}"), each_split)
                    asso_msg[cam][frame] = [
                        'XFR', cam, frame, _msg["pax_id"], _msg["bin_id"],
                        each_split.replace("[", "").replace("]", "")
                    ]
                elif 'Association' in each_split:
                    # 1156,cam9,"['Association | P1 | owner of | Bin 3 |']"
                    pp = parse(
                        "{event_str}P{pax_id:d}{tmp}Bin {bin_id:d}{_end}",
                        each_split)
                    if pp is not None:
                        bin_id, pax_id = 'B' + str(pp['bin_id']), 'P' + str(
                            pp['pax_id'])
                        if "owner of" in pp['tmp']:
                            # association
                            self.asso_info[cam][bin_id][frame] = pax_id
        self._asso_msg = asso_msg

    def get_info_from_frame(self, frame, cam="cam09"):
        # get pax info
        logs = []
        df = self.df_pax
        msglist = []
        info = df[(df["frame"] == frame) & (df["camera"] == cam)]
        list_info_pax = []
        list_event_pax = []
        for _, row in info.iterrows():
            if not row.empty:
                row['id'] = str(row['id'])
                list_info_pax.append([
                    row["id"], "pax", row["x1"], row["y1"], row["x2"],
                    row["y2"]
                ])
                if "TSO" in row["id"]:
                    pax_type = "TSO"
                else:
                    pax_type = "PAX"
                log = (
                    f"LOC: type: {pax_type} camera-num: {cam[3:5]} frame: {frame} time-offset: {frame/self.fps:.2f} "
                    +
                    f"BB: {int(row['x1']*3)}, {int(row['y1']*3)}, {int(row['x2']*3)}, {int(row['y2']*3)} "
                    + f"ID: {row['id']}")
                logs.append(log)

        # get bin info.
        df = self.df_bin
        info = df[(df["frame"] == frame) & (df["camera"] == cam)]
        list_info_bin = []
        list_event_bin = []

        asso_info = self.asso_info[cam]  # association from camera 09
        for _, row in info.iterrows():
            if row["type"] == "loc":
                _id = str(row["id"])

                # get associated pax
                if _id in asso_info:
                    ffs = list(asso_info[_id])
                    for _f in ffs:
                        if frame >= _f:
                            self.bin_pax[_id] = str(asso_info[_id][_f])
                else:
                    pass

                # bin info for visualization
                list_info_bin.append([
                    _id,
                    "item",
                    row["x1"],
                    row["y1"],
                    row["x2"],
                    row["y2"],
                    self.bin_pax.get(_id, ""),
                ])

                # FIXME left-behind calculation
                left_behind = "FALSE"

                if self.bin_pax.get(_id, ""):
                    log = (
                        f"LOC: type: DVI camera-num: {cam[3:5]} frame: {frame} time-offset: {frame/self.fps:.2f} "
                        +
                        f"BB: {int(row['x1']*3)}, {int(row['y1']*3)}, {int(row['x2']*3)}, {int(row['y2']*3)} "
                        +
                        f"ID: {_id} PAX-ID: {self.bin_pax.get(_id, 'NA')} left-behind: {left_behind}"
                    )
                    logs.append(log)
            else:  # event type
                if (row["type"] == "enter" and cam == "cam09") or \
                     row["type"] == "chng" or (row["type"] == "empty" and cam != "cam09"):
                    # xfr event
                    _id = str(row["id"])
                    _type = "TO" if cam == "cam09" else "FROM"
                    log = (
                        f"XFR: type: {_type} camera-num: {cam[3:5]} frame: {frame} time-offset: {frame/self.fps:.2f} "
                        +
                        f"BB: {int(row['x1']*3)}, {int(row['y1']*3)}, {int(row['x2']*3)}, {int(row['y2']*3)} "
                        +
                        f"PAX-ID: {self.bin_pax.get(_id, 'NA')} DVI-ID: {_id} theft: FALSE"
                    )
                    logs.append(log)
                    continue
                # Which event to skip
                if row["type"] not in ("enter", "exit"):
                    pass  # skip event
                elif row["type"] == "enter" and cam == "cam09":
                    # skip bin 'enter' event for cam 09
                    pass
                else:
                    list_event_bin.append([row["type"], row["msg"]])
                    msglist.append([
                        row["camera"][-2:],
                        to_sec(row["frame"], fps=self.fps), row["msg"]
                    ])

            # add 'theft' message for visualization
            # if frame in self.asso_msg:
            #     rr = self.asso_msg[frame]
            #     if rr[0] == cam[3:5]:
            #         if (cam + rr[2]) not in self.tmp:
            #             msglist.append([rr[0], to_sec(rr[1]), rr[2]])
            #             self.tmp.append(cam + rr[2])

        if cam in self._asso_msg and frame in self._asso_msg[cam]:
            mtype, cam, frame, pax_id, bin_id, _msg = self._asso_msg[cam][
                frame]
            if mtype == 'XFR':
                # _type = "TO" if cam == "cam09" else "FROM"
                # log = (
                #     f"XFR: type: {_type} camera-num: {cam[3:5]} frame: {frame} time-offset: {frame/self.fps:.2f} "
                #     + f"BB: 0, 0, 0, 0 " +
                #     f"PAX-ID: {pax_id} DVI-ID: {bin_id} theft: FALSE")
                logs.append(_msg)

                if 'theft: true' in _msg.lower():
                    feed_msg = (cam, to_sec(frame, self.fps),
                                f'Potential theft: {pax_id} - {bin_id}')
                else:
                    feed_msg = (cam, to_sec(frame, self.fps),
                                f'XFR : {pax_id} - {bin_id}')
                if feed_msg not in self.msg:
                    msglist.append(feed_msg)
                    self.msg.add(feed_msg)

        return (list_info_bin, list_info_pax, list_event_bin, list_event_pax,
                msglist, logs)

    @staticmethod
    def draw_im(im, info_bin, info_pax, font_scale=0.5):
        for each_i in info_bin:
            bbox = [each_i[2], each_i[3], each_i[4], each_i[5]]
            im = vis.vis_bbox_with_str(
                im,
                bbox,
                each_i[0],
                each_i[-1],
                color=(33, 217, 14),
                thick=2,
                font_scale=font_scale,
                color_txt=(252, 3, 69),
            )

        for each_i in info_pax:
            bbox = [each_i[2], each_i[3], each_i[4], each_i[5]]
            im = vis.vis_bbox_with_str(
                im,
                bbox,
                each_i[0],
                None,
                color=(23, 23, 246),
                thick=2,
                font_scale=font_scale,
                color_txt=(252, 211, 3),
            )
        return im

class DrawClass():
    def __init__(self, conf=None, plot=True) -> None:
        self.vis_feed = VisFeed()
        self.Info = IntegratorClass(fps=conf.fps)
        self.plot = plot
        self.conf = conf

        # Output folder path of the feed
        self.feed_folder = Path(conf.folder_out_feed)
        # Path(conf.out_dir) / "run" / conf.file_num / "feed"
        if self.feed_folder.exists():
            shutil.rmtree(str(self.feed_folder))
        self.feed_folder.mkdir(exist_ok=True, parents=True)

        self.full_log = []

    def draw_batch(self, batch_frames, *csv_files):
        self.Info.load_info(*csv_files)
        all_out_args = []
        for out in batch_frames:
            _args = self._extract_info_for_draw_frame(*out)
            all_out_args.append(_args)

        if self.plot:
            self.plot_fn(all_out_args, self.feed_folder)

    def plot_fn(self, all_out_args, feed_folder):
        if self.conf.workers_plot > 1:
            with multiprocessing.Pool(
                    processes=self.conf.workers_plot) as pool:
                for each_step_arg in all_out_args:
                    # DrawClass.plot_fun_step(each_step_arg, feed_folder)
                    pool.apply_async(
                        DrawClass.plot_fun_step,
                        (each_step_arg, feed_folder),
                        #  callback=lambda x: print("#"),
                        error_callback=lambda e: print("error"))
                pool.close()
                pool.join()
        else:
            for each_step_arg in all_out_args:
                DrawClass.plot_fun_step(each_step_arg, feed_folder)

    @staticmethod
    def plot_fun_step(each_step_arg, feed_folder):
        ims = []
        vis_feed = VisFeed()
        for args in each_step_arg["args"]:
            im, info_bin, info_pax = args
            im = IntegratorClass.draw_im(im,
                                         info_bin,
                                         info_pax,
                                         font_scale=0.7)
            ims.append(im)
        # msglist.extend(mlist)
        if len(ims) < 2:
            ims.append(None)
        if len(ims) < 3:
            ims.append(None)

        frame_num = each_step_arg["frame"]
        msglist = each_step_arg["msg"]
        im_feed = vis_feed.draw(ims[0], ims[1], ims[2], frame_num, msglist)

        f_write = feed_folder / (str(frame_num).zfill(4) + ".jpg")
        cv2.imwrite(str(f_write), cv2.cvtColor(im_feed, cv2.COLOR_RGB2BGR))
        # print(f"save to {f_write}")

    def _extract_info_for_draw_frame(self, out1, out2=None, out3=None):

        out_args = []  # for multiprocess

        im1, imfile1, _ = out1
        im2 = None
        if out2 is not None:
            im2, imfile2, _ = out2
        im3 = None
        if out3 is not None:
            im3, imfile3, _ = out3

        frame_num = frame_to_time(imfile1)
        # Cam 09
        info_bin, info_pax, event_bin, event_pax, msglist, logs = self.Info.get_info_from_frame(
            frame_num, "cam09")
        self.full_log.extend(logs)
        if self.plot:
            # im1 = self.Info.draw_im(im1, info_bin, info_pax, font_scale=0.75)
            out_args.append((im1, info_bin, info_pax))

        # print("#draw:1", flush=True)
        # Cam 11
        if out2 is not None:
            info_bin, info_pax, event_bin, event_pax, mlist, logs = self.Info.get_info_from_frame(
                frame_num, "cam11")
            msglist.extend(mlist)
            self.full_log.extend(logs)
            if self.plot:
                # im2 = self.Info.draw_im(im2, info_bin, info_pax, font_scale=0.7)
                out_args.append((im2, info_bin, info_pax))

        if out3 is not None:
            frame_num3 = frame_to_time(imfile3)
            info_bin, info_pax, event_bin, event_pax, mlist, logs = self.Info.get_info_from_frame(
                frame_num3, "cam13")
            msglist.extend(mlist)
            self.full_log.extend(logs)
            if self.plot:
                # im3 = self.Info.draw_im(im3,
                #                         info_bin,
                #                         info_pax,
                #                         font_scale=0.7)
                out_args.append((im3, info_bin, info_pax))

        return {
            "args": out_args,
            "frame": frame_num,
            "msg": list(self.Info.msg)
        }

    def finish(self):
        # write ata output
        write_file = Path(self.conf.ata_output)
        write_file.parent.mkdir(exist_ok=True, parents=True)

        with open(str(write_file), "w") as fp:
            fp.write("\n".join(self.full_log))

        print(f"write to ", write_file)


# -*- encoding: utf-8 -*-
import sys
r_input = sys.stdin.readline

N = int(r_input())

if N % 2:
    print(0)
    exit()

total = 0

def dfs(num, save):
    global total

    if sum(save) > N:
        return

    if sum(save) == N:
        total += 3 ** save.count(2) * 2 ** (len(save) - save.count(2))

    else:
        for i in range(2, N + 1, 2):
            dfs(i, save + [i])

for i in range(2, N + 1, 2):
    dfs(i, [i])

print(total)


#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: bigfoolliu

"""
使用摄像头拍摄一段视频
"""

from builtins import WindowsError
import cv2

def capture_video():
    """
    捕获视频
    """
    cap = cv2.VideoCapture(0)  # 构建一个VideoCapture对象

    if not cap.isOpened():  # 判断摄像头是否打开，未打开使用cap.open()来打开摄像头
        raise WindowsError('camera is not opened')

    while True:
        ret, frame = cap.read()  # 一帧一帧的捕获图像
        if not ret:
            print('can not receive frame, existing...')
            break

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # 将捕获的图像转换为灰度图
        cv2.imshow("frame", gray)  # 展示灰度图,形成视频录制的效果

        # waitKey(1) 中的数字代表等待按键输入之前的无效时间，单位为毫秒，在这个时间段内按键 ‘q’ 不会被记录，在这之后按键才会被记录
        # 与操作是因为cv2.waitKey(1) 的返回值不止8位，但是只有后8位实际有效，为避免产干扰，通过 ‘与’ 操作将其余位置0
        if cv2.waitKey(5) & 0xFF == ord("q"):
            break

    # 展示获取的图像的宽度和高度
    print(f"width: {cap.get(3)}\nheight: {cap.get(4)}")

    # 重新设置图像的宽高
    # cap.set(3, 320)
    # cap.set(4, 240)

    # 当退出循环之后，释放对象，关闭所有窗口
    cap.release()
    cv2.destroyAllWindows()

def main():
    capture_video()

if __name__ == "__main__":
    main()


import functools
import time

def stopwatch(func):
    @functools.wraps(func)
    def wrapped(*args, **argv):
        print('`'+str(func.__name__)+'` started')
        time_start = time.perf_counter()
        result = func(*args, **argv)
        time_finish = time.perf_counter()
        time_watch = time_finish - time_start
        print('`'+str(func.__name__)+'` finished in '+str(round(time_watch,2))+'s')
        return result
    return wrapped


import sys
sys.path.append('../config')
from config.Config import Config
from subprocess import Popen
from subprocess import PIPE

class HandBrakeAdapter:

    @staticmethod
    def run(inputFile, outputFile):
        command = HandBrakeAdapter.__buildCommand(inputFile, outputFile)
        p = Popen(command, stdout=PIPE, stderr=PIPE)
        stdout, stderr = p.communicate()
        if p.returncode != 0:
            raise Exception(stderr)

    @staticmethod
    def __buildCommand(inputFile, outputFile):
        command = []
        command.append('HandBrakeCLI')
        command.append('-i')
        command.append(inputFile)
        command.append('-o')
        command.append(outputFile)
        command.append('-x')
        command.append(Config.get('handbrake.profile'))
        return command


import cv2
from matplotlib import pyplot as plt

# Reading the image and converting to grayscale
img = cv2.imread('pic.png')
image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# GLOBAL THRESHOLDING
retval, thresh1 = cv2.threshold(image, 110, 255, cv2.THRESH_BINARY)
retval1, thresh2 = cv2.threshold(image, 110, 255, cv2.THRESH_BINARY_INV)
retval2, thresh3 = cv2.threshold(image, 110, 255, cv2.THRESH_TRUNC)
retval3, thresh4 = cv2.threshold(image, 110, 255, cv2.THRESH_TOZERO)
retval4, thresh5 = cv2.threshold(image, 110, 255, cv2.THRESH_TOZERO_INV)

titles = ['Original image', 'Thresh binary', 'Thresh Binary_Inv', 'Trunc', 'Tozero', 'Tozero_Inv']
images = [image, thresh1, thresh2, thresh3, thresh4, thresh5]

for i in range(6):
    plt.subplot(2, 3, i + 1), plt.imshow(images[i], 'gray')
    plt.title(titles[i])
    plt.xticks([]), plt.yticks([])
plt.show()

# ADAPTIVE THRESHOLDING
adapt_thresh1 = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
adapt_thresh2 = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)

adapt_titles = ['original image', 'Thresh_binary', 'Adaptive_mean', 'Adaptive_gaussian']
adapt_images = [image, thresh1, adapt_thresh1, adapt_thresh2]

for i in range(4):
    plt.subplot(2, 2, i + 1), plt.imshow(adapt_images[i], 'gray')
    plt.title(adapt_titles[i])
    plt.xticks([]), plt.yticks([])
plt.show()

# Otsu's BINARIZATION
# Before Gaussian filtering
retval, otsu_thresh1 = cv2.threshold(image, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)

# After Gaussian filtering
blur = cv2.GaussianBlur(image, (5, 5), 0)
retval5, otsu_thresh2 = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

otsu_titles = ['original image', 'Histogram', 'Global thresholding',
               'original image', 'Histogram', "Otsu's thresholding",
               'Gaussian filtered image', 'Histogram', "Otsu's thresholding"]
otsu_images = [image, 0, thresh1,
               image, 0, otsu_thresh1,
               blur, 0, otsu_thresh2]

for i in range(3):
    plt.subplot(3, 3, i * 3 + 1), plt.imshow(otsu_images[i * 3], 'gray')
    plt.title(otsu_titles[i * 3 + 1]), plt.xticks([]), plt.yticks([])
    plt.subplot(3, 3, i * 3 + 2), plt.hist(otsu_images[3 * i].ravel(), 256)
    plt.title(otsu_titles[3 * i + 2]), plt.xticks([]), plt.yticks([])
    plt.subplot(3, 3, 3 * i + 3), plt.imshow(otsu_images[3 * i + 2], 'gray')
    plt.title(otsu_titles[3 * i + 2]), plt.xticks([]), plt.yticks([])
plt.show()


import csv
import math
with open ("data.csv", newline = "") as f:
    reader = csv.reader(f)
    file_data = list(reader)

    data = file_data[0]

def mean(data):
    n = len(data)
    total = 0
    for x in data:
        total += int(x)

    mean = total/n
    return(mean)

#squaring and getting the values
squared_list = []
for x in data:
    a = int(x) - mean(data)
    a = a**2
    squared_list.append(a)

# getting the sum
sum = 0
for x in squared_list:
    sum = sum + x

#dividing the sum by the total values
result = sum/ (len(data) - 1 )

# getting the deviation by taking the square root of the result
standard_deviation = math.sqrt(result)

print(standard_deviation, ".This is the standard deviation for the following data....")


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

import argparse
import os
import sys

from superflore.generate_installers import generate_installers
from superflore.generators.bitbake.gen_packages import regenerate_installer
from superflore.generators.bitbake.ros_meta import RosMeta
from superflore.TempfileManager import TempfileManager
from superflore.utils import err
from superflore.utils import info
from superflore.utils import ok
from superflore.utils import warn

# Modify if a new distro is added
active_distros = ['indigo', 'kinetic', 'lunar']
# just update packages, by default.
mode = 'update'
preserve_existing = True
overlay = None

def file_pr(overlay, delta, missing_deps):
    try:
        overlay.pull_request('{0}\n{1}'.format(delta, missing_deps))
    except Exception as e:
        err('Failed to file PR with allenh1/meta-ros repo!')
        err('  Exception: {0}'.format(e))
        sys.exit(1)

def main():
    global overlay
    global preserve_existing

    parser = argparse.ArgumentParser('Deploy ROS packages into Yocto Linux')
    parser.add_argument(
        '--ros-distro',
        help='regenerate packages for the specified distro',
        type=str
    )
    parser.add_argument(
        '--all',
        help='regenerate all packages in all distros',
        action="store_true"
    )
    parser.add_argument(
        '--output-repository-path',
        help='location of the Git repo',
        type=str
    )
    parser.add_argument(
        '--tar-archive-dir',
        help='location to store archived packages',
        type=str
    )
    selected_targets = active_distros
    args = parser.parse_args(sys.argv[1:])
    if args.all:
        warn('"All" mode detected... this may take a while!')
        preserve_existing = False
    elif args.ros_distro:
        warn('"{0}" distro detected...'.format(args.ros_distro))
        selected_targets = [args.ros_distro]
        preserve_existing = False
    with TempfileManager(args.output_repository_path) as _repo:
        if not args.output_repository_path:
            # give our group write permissions to the temp dir
            os.chmod(_repo, 17407)
        # clone if args.output-repository_path is None
        overlay = RosMeta(_repo, not args.output_repository_path)
        # generate installers
        total_installers = dict()
        total_broken = set()
        total_changes = dict()

        with TempfileManager(args.tar_archive_dir) as tar_dir:
            for distro in selected_targets:
                distro_installers, distro_broken, distro_changes =\
                    generate_installers(
                        distro,
                        overlay,
                        regenerate_installer,
                        preserve_existing,
                        tar_dir
                    )
                for key in distro_broken.keys():
                    for pkg in distro_broken[key]:
                        total_broken.add(pkg)

                total_changes[distro] = distro_changes
                total_installers[distro] = distro_installers

        num_changes = 0
        for distro_name in total_changes:
            num_changes += len(total_changes[distro_name])

        if num_changes == 0:
            info('ROS distro is up to date.')
            info('Exiting...')
            sys.exit(0)

        # remove duplicates
        inst_list = total_broken

        delta = "Changes:\n"
        delta += "========\n"

        if 'indigo' in total_changes and len(total_changes['indigo']) > 0:
            delta += "Indigo Changes:\n"
            delta += "---------------\n"

            for d in sorted(total_changes['indigo']):
                delta += '* {0}\n'.format(d)
            delta += "\n"

        if 'kinetic' in total_changes and len(total_changes['kinetic']) > 0:
            delta += "Kinetic Changes:\n"
            delta += "----------------\n"

            for d in sorted(total_changes['kinetic']):
                delta += '* {0}\n'.format(d)
            delta += "\n"

        if 'lunar' in total_changes and len(total_changes['lunar']) > 0:
            delta += "Lunar Changes:\n"
            delta += "--------------\n"

            for d in sorted(total_changes['lunar']):
                delta += '* {0}\n'.format(d)
            delta += "\n"

        missing_deps = ''

        if len(inst_list) > 0:
            missing_deps = "Missing Dependencies:\n"
            missing_deps += "=====================\n"
            for pkg in sorted(inst_list):
                missing_deps += " * [ ] {0}\n".format(pkg)

        # Commit changes and file pull request
        overlay.commit_changes(args.ros_distro)
        file_pr(overlay, delta, missing_deps)
        ok('Successfully synchronized repositories!')


# Authors: Adam Li <adam2392@gmail.com>
#          Alex Rockhill <aprockhill@mailbox.org>
# License: BSD Style.

from ...utils import verbose
from ..utils import _data_path_doc, _get_version, _version_doc, _download_mne_dataset

@verbose
def data_path(
    path=None, force_update=False, update_path=True, download=True, *, verbose=None
):  # noqa: D103
    return _download_mne_dataset(
        name="epilepsy_ecog",
        processor="untar",
        path=path,
        force_update=force_update,
        update_path=update_path,
        download=download,
    )

data_path.__doc__ = _data_path_doc.format(
    name="epilepsy_ecog", conf="MNE_DATASETS_EPILEPSY_ECOG_PATH"
)

def get_version():  # noqa: D103
    return _get_version("epilepsy_ecog")

get_version.__doc__ = _version_doc.format(name="epilepsy_ecog")


import os
import urllib.request
from flask import Flask, request, redirect, jsonify
from werkzeug.utils import secure_filename
from flask_cors import CORS, cross_origin

UPLOAD_FOLDER = 'uploads/files/'

app = Flask(__name__)

cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

ALLOWED_EXTENSIONS = set(['pdf'])

def allowed_file(filename):
	return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/hello', methods=['GET'])
@cross_origin()
def hello_world():
	return jsonify(hello='world')

@app.route('/upload', methods=['POST'])
@cross_origin()
def upload_file():
	# check if the post request has the file part
	if 'files[]' not in request.files:
		resp = jsonify({'message': 'No file part in the request'})
		resp.status_code = 400
		return resp

	files = request.files.getlist('files[]')

	errors = {}
	success = False

	for file in files:
		if file and allowed_file(file.filename):
			filename = secure_filename(file.filename)
			file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
			success = True
		else:
			errors[file.filename] = 'File type is not allowed'

	if success and errors:
		errors['message'] = 'File(s) successfully uploaded'
		resp = jsonify(errors)
		resp.status_code = 500
		return resp
	if success:
		resp = jsonify(
            {
                'summary': {
                    'positions': [
                        {
                            'stock': 'ITAUSA',
                            'averagePrice': 21.10,
                            'sellingPrice': 10.00,
                            'profitLoss': -11.10
                        },
                        {
                            'stock': 'ITAUSA',
                            'averagePrice': 21.10,
                            'sellingPrice': 30.00,
                            'profitLoss': 8.90
                        }
                    ],
                    'totalPL': -2.2,
                    'tax': 0
                }
            })
		resp.status_code = 201
		return resp
	else:
		resp = jsonify(errors)
		resp.status_code = 500
		return resp

if __name__ == "__main__":
    # create the uploads directory if it doesn't exist
    if not os.path.exists(UPLOAD_FOLDER):
        os.makedirs(UPLOAD_FOLDER)

    app.run(host='0.0.0.0', debug=True)


# -*- coding: utf-8 -*-
import sys, traceback, socket
from time import sleep
from json import dumps as jsonify

from MessageReceiver import MessageReceiver

class Client:
    """
    This is the chat client class
    """
    def __init__(self, host, server_port):
        """
        This method is run when creating a new Client object
        """
        # Set up the socket connection to the server
        self.host = host
        self.server_port = server_port
        self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect()
        self.messagereceiver = MessageReceiver("client", self.connection)
        self.messagereceiver.start()
        self.run()

    def run(self):
        while True:
            try:
                msg = self.prompt_user()
                self.send_request(msg)

            except Exception:
                print("Exception in client. Restarting client.")
                traceback.print_exc()
                return self
                #sys.exit()

    def connect(self):
        while True:
            errno = self.connection.connect_ex((self.host, self.server_port))
            if errno == 0:
                print("Connected to server.")
                return
            else:
                print("Connection failed. Retrying...")
                sleep(1)

    def disconnect(self):

        print("Disconnected. Try to reconnect? y/n")
        if input() == 'y':
            self.connect()
        else:
            sys.exit()

    def prompt_user(self):
        msg = {}
        print(">>", end='')
        inp = input()
        args = inp.split()
        msg['request'] = args[0]
        msg['content'] = ""
        if len(args)>1:
            msg['content'] = args[1]
        return msg

    def send_request(self, request):
        #bytes(jsonify(request), 'utf-8')
        self.connection.send(bytes("asdfasdf", "utf-8"))

if __name__ == '__main__':
    """
    This is the main method and is executed when you type "python Client.py"
    in your terminal.

    No alterations are necessary
    """
    while True:
        client = Client('localhost', 9997)


from __future__ import print_function, division

import numpy as np
from astropy.table import Table

CART_COL_NAMES = ['X', 'Y', 'Z', 'U', 'V', 'W',
                  'dX', 'dY', 'dZ', 'dU', 'dV', 'dW',
                  'c_XY', 'c_XZ', 'c_XU', 'c_XV', 'c_XW',
                  'c_YZ', 'c_YU', 'c_YV', 'c_YW',
                  'c_ZU', 'c_ZV', 'c_ZW',
                  'c_UV', 'c_UW',
                  'c_VW']

def buildMeanAndCovMatFromRow(row):
    """
    Build a covariance matrix from a row

    Paramters
    ---------
    row : astropy Table row
        Entries: {X, Y, Z, U, V, W, dX, dY, ..., cXY, cXZ, ...}

    Return
    ------
    cov_mat : [6,6] numpy array
        Diagonal elements are dX^2, dY^2, ...
        Off-diagonal elements are cXY*dX*dY, cXZ*dX*dZ, ...
    """
    dim = 6
    # CART_COL_NAMES = ['X', 'Y', 'Z', 'U', 'V', 'W',
    #                   'dX', 'dY',   'dZ',   'dU',   'dV',   'dW',
    #                         'c_XY', 'c_XZ', 'c_XU', 'c_XV', 'c_XW',
    #                                 'c_YZ', 'c_YU', 'c_YV', 'c_YW',
    #                                         'c_ZU', 'c_ZV', 'c_ZW',
    #                                                 'c_UV', 'c_UW',
    #                                                         'c_VW']
    mean = np.zeros(dim)
    for i, col_name in enumerate(CART_COL_NAMES[:6]):
        mean[i] = row[col_name]

    std_vec = np.zeros(dim)
    for i, col_name in enumerate(CART_COL_NAMES[6:12]):
        std_vec[i] = row[col_name]
    corr_tri = np.zeros((dim,dim))
    # Insert upper triangle (top right) correlations
    for i, col_name in enumerate(CART_COL_NAMES[12:]):
        corr_tri[np.triu_indices(dim,1)[0][i],np.triu_indices(dim,1)[1][i]]\
            =row[col_name]
    # Build correlation matrix
    corr_mat = np.eye(6) + corr_tri + corr_tri.T
    # Multiply through by standard deviations
    cov_mat = corr_mat * std_vec * std_vec.reshape(6,1)
    return mean, cov_mat

def insertCartesainData(gt_row, xyzuvw_mean, xyzuvw_cov):
    dim = 6
    # CART_COL_NAMES = ['X', 'Y', 'Z', 'U', 'V', 'W',
    #                   'dX', 'dY', 'dZ', 'dU', 'dV', 'dW',
    #                   'c_XY', 'c_XZ', 'c_XU', 'c_XV', 'c_XW',
    #                           'c_YZ', 'c_YU', 'c_YV', 'c_YW',
    #                                   'c_ZU', 'c_ZV', 'c_ZW',
    #                                           'c_UV', 'c_UW',
    #                                                   'c_VW']

    # fill in cartesian mean
    try:
        for col_ix, col_name in enumerate(CART_COL_NAMES[:6]):
            gt_row[col_name] = xyzuvw_mean[col_ix]
    except IndexError:
        import pdb; pdb.set_trace()

    # fill in standard deviations
    xyzuvw_stds = np.sqrt(xyzuvw_cov[np.diag_indices(dim)])
    for col_ix, col_name in enumerate(CART_COL_NAMES[6:12]):
        gt_row[col_name] = xyzuvw_stds[col_ix]

    correl_matrix = xyzuvw_cov / xyzuvw_stds / xyzuvw_stds.reshape(6, 1)
    # fill in correlations
    for col_ix, col_name in enumerate(CART_COL_NAMES[12:]):
        gt_row[col_name] = correl_matrix[
            np.triu_indices(dim, k=1)[0][col_ix],
            np.triu_indices(dim, k=1)[1][col_ix]
        ]

def eraseCartesianData(gt_row):
    """
    Replace all cartesian data with blanks (for erasing binary companions that
    have been incoroporated into host star's kinematics)
    """
    dim = 6

    for col_name in CART_COL_NAMES:
        gt_row[col_name] = np.nan

if __name__ == '__main__':
    gagne_filename = '../data/gagne_bonafide_full_kinematics_with_lit' \
                     '_and_best_radial_velocity.fits'
    gt = Table.read(gagne_filename)
    new_gagne_filename = '../data/gagne_bonafide_full_kinematics_with_lit' \
                     '_and_best_radial_velocity_comb_binars.fits'

    # companion_ixs = np.where(gt['Companion'] == 'True')
    # host_ixs = (companion_ixs[0]-1,)

    row_ix = 0
    while row_ix < len(gt['Companion']) - 1:
        # find next instance of host
        system_ixs = []
        while (row_ix+1 < len(gt['Companion']) and
               gt[row_ix+1]['Companion'] == 'False'):
            row_ix += 1
        # Check if we've reached end of table
        if row_ix == len(gt['Companion'])-1:
            break
        system_ixs.append(row_ix)

        # find subsequent associated companions
        row_ix += 1
        while row_ix < len(gt['Companion']) and gt[row_ix]['Companion'] == 'True':
            system_ixs.append(row_ix)
            row_ix += 1

        print(system_ixs)

        masses = []
        means = []
        cov_mats = []
        for row_ix in system_ixs:
            # Check 'U' (for e.g.) has been calculated
            # (requires both RV and parallax so good guide for 6D completeness)
            if np.isfinite(gt[row_ix]['U']):
                masses.append(gt[row_ix]['approx_mass'])
                mean, cov_mat = buildMeanAndCovMatFromRow(gt[row_ix])
                means.append(mean)
                cov_mats.append(cov_mat)

        masses = np.array(masses)
        means = np.array(means)
        cov_mats = np.array(cov_mats)

        nstars = len(means)
        if nstars != 0:
            # establish average of available masses
            av_present_mass = masses[np.where(np.isfinite(masses))].mean()
            # replace everything with 1 if there are no valid masses
            if np.isnan(av_present_mass):
                masses[:] = 1.0
            # replace any missing masses with average of available masses
            else:
                masses[np.where(np.isnan(masses))] = av_present_mass

            assert np.all(np.isfinite(masses))
            total_mass = np.sum(masses)

            aver_mean = (means.T * masses).sum(axis=-1) / total_mass
            aver_cov_mat = (cov_mats.T * masses).sum(axis=-1) / total_mass

            insertCartesainData(gt[system_ixs[0]], aver_mean, aver_cov_mat)

            for system_ix in system_ixs[1:]:
                eraseCartesianData(gt[system_ix])

    for pos_dim in CART_COL_NAMES[:3]:
        gt[pos_dim].unit = 'pc'
    for vel_dim in CART_COL_NAMES[3:6]:
        gt[vel_dim].unit = 'km/s'
    for pos_std in CART_COL_NAMES[6:9]:
        gt[pos_std].unit = 'pc'
    for vel_std in CART_COL_NAMES[9:12]:
        gt[vel_std].unit = 'km/s'
    gt['approx_mass'].unit = 'M_solar'

    gt.write(new_gagne_filename)


# -*- coding: utf-8 -*-
"""
Created on Tue Aug 31 08:38:10 2021

@author: Erlend Tøssebro
"""

import math

def areal_sirkel(radius):
    areal = math.pi*radius*radius
    return areal

def omkrets_sirkel(radius):
    return 2.0*math.pi*radius

radius_streng = input("Skriv inn radius til sirkelen: ")
radius_bruker = float(radius_streng)
areal_global = areal_sirkel(radius_bruker)
print(f"Arealet ble: {areal_global:8.2f}")
omkrets = omkrets_sirkel(radius_bruker)
print(f"Omkretsen ble: {omkrets:8.2f}")

9. Egendefinerte funksjoner (37-44)/areal_omkrets_sirkel.py


from django.urls import path

from . import views

app_name = 'encyclopedia'
urlpatterns = [
    path('', views.index, name='index'),
    path('wiki/<str:title>', views.entry, name='entry'),
    path('search', views.search, name='search'),
    path('new_page', views.new, name='new'),
    path('save', views.save, name='save'),
    path('random_page', views.random_page, name='random_page'),
    path('edit_page/<str:title>', views.edit_page, name='edit_page')
]


import json
import numpy as np
import os
from sklearn.model_selection import train_test_split
import cv2
import torch

TUSIMPLE_PATH='./train_set'

##标注并结构化图森数据集
class CreateTusimpleData():

    def __init__(self,tusimple,line_width):

        self.tusimple=tusimple
        self.line_width=line_width

    def __call__(self):
        if not os.path.exists('./data/train_binary'):
            os.mkdir('./data/train_binary')
        if not os.path.exists('./data/cluster'):
            os.mkdir('./data/cluster')
        if not os.path.exists('./data/LaneImages'):
            os.mkdir('./data/LaneImages')
        jsons=[json for json in os.listdir(self.tusimple) if json.split('.')[-1]=='json']
        for j in jsons:
            data=[]
            with open(os.path.join(self.tusimple,j)) as f:
                for line in f.readlines():
                    data.append(json.loads(line))
            for entry in data:
                height=entry['h_samples']
                width=entry['lanes']
                for index,w in enumerate(width):
                    counter=list(set(w))
                    if counter[0]==-2 and len(counter)==1:
                        del width[index]
                clip=entry['raw_file']
                img=cv2.imread(os.path.join(self.tusimple,clip))
                cv2.imwrite(os.path.join('./data/LaneImages','_'.join(clip.split('/')[1:])),img)
                img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
                img_binary=np.zeros_like(img)
                img_cluster=np.zeros_like(img)
                for lane in range(len(width)):
                    queue=[]
                    for h,w in zip(height,width[lane]):
                        if w<0:
                            continue
                        else:
                            queue.insert(0,(w,h))
                            if len(queue)==2:
                                cv2.line(img_binary,queue[0],queue[1],255,self.line_width)
                                cv2.line(img_cluster,queue[0],queue[1],255-50*lane,self.line_width)
                            if len(queue)>1:
                                queue.pop()
                new_name='_'.join(clip.split('/')[1:])
                new_name='.'.join([new_name.split('.')[0],'png'])

                cv2.imwrite(os.path.join('./data/train_binary',new_name),img_binary)
                cv2.imwrite(os.path.join('./data/cluster',new_name),img_cluster)

if __name__=='__main__':

    creator=CreateTusimpleData(TUSIMPLE_PATH,5)
    creator()


from flask import Blueprint, request

from utils import tojson, hash_user
from db.connection import DBConnection
import db.config as db_config

users_bp = Blueprint('users_bp', __name__)
endpoint = 'users'

@users_bp.route(f'/{endpoint}', methods=['GET', 'POST'])
def users():
    with DBConnection() as conn:
        col = conn.db.get_collection(db_config.USER_COL)

        if request.method == 'GET':
            return tojson(list(col.find({})))

        # Post data
        data = dict(request.get_json())
        hash_user(data)
        response = conn.validate_unique(db_config.USER_COL, data)
        if not response['valid']:
            response = tojson(response)
            response.status_code = 401
            return response

        col.insert_one(data)
        return tojson(data)

@users_bp.route(f'/{endpoint}/<user_id>', methods=['GET', 'PUT', 'DELETE'])
def users_userid(user_id):
    with DBConnection() as conn:
        col = conn.db.get_collection(db_config.USER_COL)

        if request.method == 'GET':
            return tojson(col.find_one({'user_id': user_id}))

        elif request.method == 'DELETE':
            return tojson(col.delete_one({'user_id': user_id}))

        # Update data
        data = dict(request.get_json())
        hash_user(data)
        response = conn.validate_unique(db_config.USER_COL, data)
        if not response['valid']:
            response = tojson(response)
            response.status_code = 401
            return response

        col.update_one(
            {'user_id': user_id},
            {'$set': data}
        )
        return tojson(col.find_one({'user_id': user_id}))


import os
from random import randint

import pygame
import pickle

WINDOW_SIZE = WINDOW_WIDTH, WINDOW_HEIGHT = 800, 600
TIMER_EVENT_TYPE = 30
TIMER_END_GAME = 31
DATA_DIR = 'data'

class HighScore:
    def __init__(self):
        self.save_file_name = f'{DATA_DIR}/clickme.highscore.dat'
        self.size = 10
        self.visible = False
        self.table = self.load()

    def render(self, p_screen):
        if not self.visible:
            return
        font = pygame.font.Font(None, 40)
        text = font.render(f'High score:', 1, pygame.Color('green'))
        p_screen.blit(text, (20, 50))
        for i in range(len(self.table)):
            text = font.render(f'{i+1}', 1, pygame.Color('green'))
            p_screen.blit(text, (20, 100 + 30*i))
            text = font.render(f'{self.table[i]}', 1, pygame.Color('green'))
            p_screen.blit(text, (80, 100 + 30*i))

    def update(self, score):
        if score < min(self.table):
            return
        self.table.append(score)
        self.table.sort(reverse=True)
        self.table = self.table[:self.size]
        self.save()

    def save(self):
        with open(self.save_file_name, 'wb') as file:
            pickle.dump(self.table, file)

    def load(self):
        if not os.path.isfile(self.save_file_name):
            return [0 for _ in range(self.size)]
        with open(self.save_file_name, 'rb') as file:
            return pickle.load(file)

    def show(self):
        self.visible = True

    def hide(self):
        self.visible = False

class ClickMe:
    def __init__(self):
        self.width = 200
        self.height = 60
        self.x, self.y = self.random_xy()
        self.delay = 1000
        self.game_timer = 1000 * 10
        self.max_clicks = 25
        self.score = 0
        self.is_paused = False
        self.is_stopped = False
        self.save_file_name = f'{DATA_DIR}/clickme.save.dat'
        self.click_count = 0
        self.reset_btn_timer()
        self.update_caption()
        pygame.time.set_timer(TIMER_END_GAME, self.game_timer)

    def update_caption(self):
        pygame.display.set_caption(f'Clicks: {self.click_count}, Delay: {self.delay}, Game paused: {self.is_paused}, '
                                   f'Game over: {self.is_stopped}')

    def decrease_delay(self):
        self.delay = max(self.delay - 50, 50)
        # self.update_caption()

    def reset_btn_timer(self):
        pygame.time.set_timer(TIMER_EVENT_TYPE, self.delay)

    def random_xy(self):
        return randint(0, WINDOW_WIDTH - self.width), randint(0, WINDOW_HEIGHT - self.height)

    def pos(self):
        return self.x, self.y, self.width, self.height

    def render(self, p_screen):
        if self.is_stopped:
            font = pygame.font.Font(None, 80)
            text = font.render('Game Over!', 1, (232, 170, 160))
            p_screen.blit(text, ((WINDOW_WIDTH - text.get_width()) // 2, (WINDOW_HEIGHT - text.get_height()) // 2))
            return
        font = pygame.font.Font(None, 50)
        text = font.render('Click me!', 1, (50, 70, 0))
        pygame.draw.rect(p_screen, (200, 150, 50), self.pos())
        p_screen.blit(text, (self.x + (self.width - text.get_width()) // 2,
                             self.y + (self.height - text.get_height()) // 2))
        font = pygame.font.Font(None, 24)
        text = font.render(f'Hits: {self.score}', 1, (200, 200, 200))
        p_screen.blit(text, (20, 20))

    def move(self):
        self.x, self.y = self.random_xy()

    def on_lmb_click(self, pos):
        if self.is_paused or self.is_stopped:
            return
        self.click_count += 1
        self.check(pos)
        self.update_caption()
        self.check_max_click()

    def check(self, pos):
        x, y = pos
        if self.x <= x <= self.x + self.width and self.y <= y <= self.y + self.height:
            self.move()
            self.decrease_delay()
            self.reset_btn_timer()
            self.inc_score()

    def inc_score(self):
        self.score += (1000 - self.delay) // 10

    def switch_pause(self):
        if self.is_stopped:
            return
        self.is_paused = not self.is_paused
        pygame.time.set_timer(TIMER_EVENT_TYPE, 0 if self.is_paused else self.delay)

    def save(self):
        with open(self.save_file_name, 'wb') as file:
            pickle.dump(self, file)

    def load(self):
        if not os.path.isfile(self.save_file_name):
            return
        with open(self.save_file_name, 'rb') as file:
            return pickle.load(file)

    def end(self):
        self.is_stopped = True
        pygame.time.set_timer(TIMER_END_GAME, 0)
        pygame.time.set_timer(TIMER_EVENT_TYPE, 0)

    def check_max_click(self):
        if self.click_count >= self.max_clicks:
            self.is_stopped = True

def main():
    pygame.init()
    screen = pygame.display.set_mode(WINDOW_SIZE)
    bg = pygame.Color('black')

    clickme = ClickMe()
    highscore = HighScore()

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                break
            if event.type == TIMER_EVENT_TYPE:
                clickme.move()
            if event.type == TIMER_END_GAME or clickme.is_stopped:
                clickme.end()
                highscore.update(clickme.score)
                highscore.show()
            if event.type == pygame.MOUSEBUTTONDOWN:
                clickme.on_lmb_click(event.pos)
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_p:
                    clickme.switch_pause()
                if event.key == pygame.K_s:
                    clickme.save()
                if event.key == pygame.K_l:
                    clickme = clickme.load()

        if not running:
            break

        screen.fill(bg)
        clickme.render(screen)
        highscore.render(screen)
        pygame.display.flip()

    pygame.display.quit()

if __name__ == '__main__':
    main()


# based on the idea from
# https://github.com/andsens/bootstrap-vz/blob/5250f8233215f6f2e3a571be2f5cf3e09accd4b6/docs/transform_github_links.py
#
# Copyright 2013-2014 Anders Ingemann <anders@ingemann.de>
# Copyright 2016 Darragh Bailey <dbailey@hpe.com>

from docutils import nodes
import os.path

def transform_github_links(app, doctree, fromdocname):
    """Convert file references for github to correct target

    Scans the doctree for links directly referencing ReSTructured
    text documents within this repository. It converts these links
    to a suitable target for sphinx generated docs.

    Such references as <file>.rst are used by source code hosting
    sites such as GitHub when rendering documents directly from
    individual source files without parsing the entire doctree.

    However referencing the original <file>.rst is not useful for
    sphinx generated documentation as <file>.rst will not exist in
    the resulting documentation as it will also have been converted
    to the chosen format e.g. <file>.html

    Supporting automatic conversion ensures that GitHub/BitBucket
    and any other git hosting site performing rendering on a file
    by file basis allowing users to navigate through the documentation,
    while still ensuring the output from fully generated sphinx docs
    will point to the correct target.
    """

    try:
        target_format = app.builder.link_suffix
    except AttributeError:
        # if the builder has no link_suffix, then no need to modify
        # the current links.
        return

    source_suffix = app.config.source_suffix
    # Links are either absolute against the repository or relative to
    # the current document's directory. Note that this is not
    # necessarily app.srcdir, which is the documentation root
    # directory. Instead rely on 'source' attribute of doctree to
    # identify the path of the file providing the current doctree
    try:
        doc_path = doctree.attributes['source']
        doc_dir = os.path.dirname(doc_path)
    except KeyError:
        # some doctrees added by other libraries through dynamic
        # generation do not have a source file. Assume paths are
        # relative to the repo.
        doc_dir = ""

    for node in doctree.traverse(nodes.reference):
        if 'refuri' not in node:
            continue
        if node['refuri'].startswith('http'):
            continue

        try:
            link, anchor = node['refuri'].split('#', 1)
            anchor = '#' + anchor
        except ValueError:
            link = node['refuri']
            anchor = ''

        if link is None:
            continue

        # Replace the suffix with the correct target format file ending,
        # but only if the link ends with both the correct source suffix
        # and refers to a local file.
        for src_suffix in source_suffix:
            if link.endswith(src_suffix):
                # absolute paths are considered relative to repo
                if link.startswith("/"):
                    basepath = ""
                # relative paths are against the current doctree source path
                else:
                    basepath = doc_dir
                if os.path.exists(os.path.join(basepath, link)):
                    node['refuri'] = (link[:-len(source_suffix)] + target_format +
                                    anchor)

def setup(app):
    app.connect('doctree-resolved', transform_github_links)
    return {'version': '0.1'}