import random
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import cross, circle, winline, neuralnetwork, fonts

check = True
axisrange = 9.0
board = [0, 0, 0, 0, 0, 0, 0, 0, 0]
flag = 1

def init():
    glClearColor(0.3, 0.69, 0.31, 1.0)
    gluOrtho2D(-5.0, 5.0, -5.0, 5.0)

# the tic tac toe board
def displayboard():
    x = 3
    y = 3
    global flag
    glClear(GL_COLOR_BUFFER_BIT)
    glColor(0.11, 0.37, 0.13)
    glBegin(GL_QUADS)
    glVertex(9.0, 0.25 + y)
    glVertex(-9.0, 0.25 + y)
    glVertex(-9.0, -0.25 + y)
    glVertex(9.0, -0.25 + y)

    glVertex(9.0, 0.25 - y)
    glVertex(-9.0, 0.25 - y)
    glVertex(-9.0, -0.25 - y)
    glVertex(9.0, -0.25 - y)

    glVertex(0.5 - 0.25 + x, 9.0)
    glVertex(-0.25 + x, 9.0)
    glVertex(-0.25 + x, -9.0)
    glVertex(0.5 - 0.25 + x, -9.0)

    glVertex(0.5 - 0.25 - x, 9.0)
    glVertex(-0.25 - x, 9.0)
    glVertex(-0.25 - x, -9.0)
    glVertex(0.5 - 0.25 - x, -9.0)
    glEnd()
    glFlush()
    if flag == 0:
        computer_vs_computer()
        flag = 1

def displayoption():
    glClear(GL_COLOR_BUFFER_BIT)
    glColor(0.11, 0.37, 0.13)
    glBegin(GL_QUADS)
    glVertex(-5.5, 3.5)
    glVertex(5.5, 3.5)
    glVertex(5.5, 5.5)
    glVertex(-5.5, 5.5)

    glVertex(-5.5, 0.5)
    glVertex(5.5, 0.5)
    glVertex(5.5, 2.5)
    glVertex(-5.5, 2.5)

    glVertex(-5.5, -2.5)
    glVertex(5.5, -2.5)
    glVertex(5.5, -0.5)
    glVertex(-5.5, -0.5)

    glVertex(-5.5, -5.5)
    glVertex(5.5, -5.5)
    glVertex(5.5, -3.5)
    glVertex(-5.5, -3.5)
    glEnd()
    glColor(1, 1, 1)
    glRasterPos(-3, 4.4)
    for i in 'h-human v/s computer':
        glutBitmapCharacter(fonts.GLUT_BITMAP_TIMES_ROMAN_24, ord(i))
    glRasterPos(-3.5, 1.3)
    for i in 'c-computer v/s computer':
        glutBitmapCharacter(fonts.GLUT_BITMAP_TIMES_ROMAN_24, ord(i))
    glRasterPos(-1, -1.5)
    for i in 'r-replay':
        glutBitmapCharacter(fonts.GLUT_BITMAP_TIMES_ROMAN_24, ord(i))
    glRasterPos(-0.75, -4.5)
    for i in 'q-quit':
        glutBitmapCharacter(fonts.GLUT_BITMAP_TIMES_ROMAN_24, ord(i))
    glFlush()

def compute():
    global board
    reward_for_3 = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6],
    ]

    j = 0
    for i in reward_for_3:
        j += 1
        if board[i[0]] == 1 and board[i[1]] == 1 and board[i[2]] == 1:
            winline.draw(j)
            return True

        if board[i[0]] == 2 and board[i[1]] == 2 and board[i[2]] == 2:
            winline.draw(j)
            return True

def init_keyboard(key, x, y):
    global flag, board
    key = key.decode('utf-8')
    if key == 'h':
        glutDisplayFunc(displayboard)
        glutKeyboardFunc(human_keyboard)
        glutPostRedisplay()
        flag = 1
    if key == 'c':
        glutDisplayFunc(displayboard)
        glutKeyboardFunc(init_keyboard)
        glutPostRedisplay()
        flag = 0
    if key == 'r':
        board = [0, 0, 0, 0, 0, 0, 0, 0, 0]
        glutDisplayFunc(displayoption)
        glutKeyboardFunc(init_keyboard)
        glutPostRedisplay()
        flag = 0
    if key == 'q':
        sys.exit(0)

def human_keyboard(key, x, y):
    global check, board
    won = False
    key = key.decode('utf-8')
    if key == 'r':
        board = [0, 0, 0, 0, 0, 0, 0, 0, 0]
        glutDisplayFunc(displayoption)
        glutKeyboardFunc(init_keyboard)
        glutPostRedisplay()
    elif key == 'q':
        exit(0)
    else:
        if board[int(key) - 1] == 0:
            if not won:
                cross.input_given(key, board)
                won = compute()
            if not won:
                action = neuralnetwork.neuralnetwork(board)
                circle.input_given(str(action + 1), board)
                won = compute()

# def draw_board(board):
#     print(board[0], '|', board[1], '|', board[2])
#     print('---------')
#     print(board[3], '|', board[4], '|', board[5])
#     print('---------')
#     print(board[6], '|', board[7], '|', board[8])

def computer_vs_computer():
    won = False
    one = random.randint(0, 9)
    cross.input_given(str(one + 1), board)
    won = compute()
    a = 0
    while not won and a < 10:
        a += 1
        if not won:
            action1 = neuralnetwork.neuralnetwork(board)
            if board[action1] == 0:
                circle.input_given(str(action1 + 1), board)
                won = compute()
        if not won:
            action2 = neuralnetwork.neuralnetwork(board)
            if board[action2] == 0:
                cross.input_given(str(action2 + 1), board)
                won = compute()
        # draw_board(board)

def reshape(w, h):
    if h == 0:
        h = 1

    glViewport(0, 0, w, h)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()

    if w <= h:
        gluOrtho2D(-axisrange, axisrange, -axisrange * h / w, axisrange * h / w)
    else:
        gluOrtho2D(-axisrange * w / h, axisrange * w / h, -axisrange, axisrange)

    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

def main():
    neuralnetwork.train()
    glutInit()
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
    glutInitWindowSize(500, 500)
    glutInitWindowPosition(0, 0)
    glutCreateWindow('TIC-TAC-TOE'.encode())
    glutFullScreen()
    glutDisplayFunc(displayoption)
    glutReshapeFunc(reshape)
    glutKeyboardFunc(init_keyboard)
    init()
    glutMainLoop()

if __name__ == '__main__':
    main()


import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import math

def Ez(z):
    return np.sqrt(Om*(1.+z)**3+(1.-Om))

def integrand_dtbydz(z):
    return -1./(H0*(1.+z)*Ez(z))

global Om, H0
Om = 0.3; H0 = 70.e5/3.086e24
num = 500
z = np.linspace(0., 8., num)
MspercV = np.zeros((num,2))
for i in range(num):
    MspercV[i,:] = integrate.quad(integrand_dtbydz,10000.,z[i])

tanal = np.zeros(num)
for i in range(num):
    tanal[i] = (2./3./H0/np.sqrt(1.-Om))*math.asinh(np.sqrt((1.-Om)/(Om*(1.+z[i])**3)))

plt.plot(z,MspercV[:,0]/np.pi/1.e16,z,tanal/np.pi/1.e16)
#plt.plot(z,tanal/np.pi/1.e16)
#plt.plot(z[1:num],-np.diff(MspercV[:,0]))
#plt.xlim([0.,8])
#plt.xscale('log')
#plt.yscale('log')
plt.xlabel('z')
plt.ylabel('cosmic time (Gyr)')
plt.title(r'$\Omega_m=0.3, \Omega_\Lambda=0.6$')
plt.grid('on')
plt.show()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2021 Huawei Device Co., Ltd.
# 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 codecs
import sys
import os
import re
import time

files = []
trace_regex = "\s*(.*?)-(\d+?)\s+\(\s*(\d+?)\)\s+\[\d+\]\s+(.*?)\s+(.*?):\s+"
all_traces_dict = {} # {"deviceName": [(timestamp, line) ...]}
all_real_time_dict = {}
default_real_time = 7983849599000 # 2222-12-31 23:59:59

def compare_timestamp(time1, time2):
    return float(time1) < float(time2)

def read_files(file, devices_name):
    traces = []
    with codecs.open(file, 'r', encoding='utf-8') as fp:
        for line in fp:
            if line.find("binder_transaction") > -1 \
                or line.find("tracing_mark_write") > -1:
                line = line.replace("\n", "")
                trace_match = re.match(trace_regex, line)
                if trace_match:
                    traces.append((float(trace_match.group(5)), line))
                if line.find("realtime_ts") > -1:
                    time_regex = trace_regex + \
                        "tracing_mark_write:\s+trace_event_clock_sync: realtime_ts=(.*)"
                    time_match = re.match(time_regex, line)
                    all_real_time_dict[devices_name] = { \
                        "realtime_ts": int(time_match.group(6)), \
                        "timestamp": float(time_match.group(5))}
    if (not all_real_time_dict.__contains__(devices_name)) and traces:
        line = traces[-1][1]
        trace_match = re.match(trace_regex, line)
        all_real_time_dict[devices_name] = { \
            "realtime_ts": default_real_time, \
            "timestamp": float(trace_match.group(5))}
    return traces

def handle_option():
    if len(sys.argv) < 2:
        print("eg: python bytrace_multi.py file1.ftrace file2.ftrace ...")
        exit(0)
    for i in range(len(sys.argv)):
        if i == 0:
            continue
        if sys.argv[i] == "-h" or sys.argv[i] == "--help":
            print("eg: python bytrace_multi.py file1.ftrace file2.ftrace ...")
            exit(0)
        elif not os.path.exists(sys.argv[i]):
            print("Warning: {} is not found.".format(sys.argv[i]))
        else:
            files.append(sys.argv[i])

def change_trace_time(all_trace_list, \
                      base_real_time, \
                      base_time_stamp, \
                      target_device):
    target_real_time = all_real_time_dict[target_device]["realtime_ts"]
    target_time_stamp = all_real_time_dict[target_device]["timestamp"]
    if not target_real_time == default_real_time:
        diff_real_time = float(target_real_time - base_real_time) / 1000
        target_time_stamp_ = base_time_stamp + diff_real_time
        diff_time = target_time_stamp - target_time_stamp_
    else:
        # If the file does not have realtime, the difference is 0.5s.
        diff_real_time = 0.5
        target_time_stamp_ = base_time_stamp + diff_real_time
        diff_time = target_time_stamp - target_time_stamp_
    traces = all_traces_dict[target_device]
    for mtuple in traces:
        timestamp = float(mtuple[0])
        line = mtuple[1]
        timestamp_ = "{:.6f}".format(timestamp - diff_time)
        line_ = target_device + \
            line.replace("{:.6f}".format(timestamp), str(timestamp_))
        all_trace_list.append((timestamp_, line_))

def write_to_file(data, file_name):
    with codecs.open(file_name, 'w+', encoding='utf-8') as fp:
        fp.write("# tracer: nop\n")
        fp.write("#\n")
        fp.write("#                                      _-----=> irqs-off\n")
        fp.write("#                                     / _----=> need-resched\n")
        fp.write("#                                    | / _---=> hardirq/softirq\n")
        fp.write("#                                    || / _--=> preempt-depth\n")
        fp.write("#                                    ||| /     delay\n")
        fp.write("#           TASK-PID    TGID   CPU#  ||||    TIMESTAMP  FUNCTION\n")
        fp.write("#              | |        |      |   ||||       |         |\n")
        for mtuple in data:
            fp.write(mtuple[1])
            fp.write("\n")

def main():
    handle_option()
    if len(files) == 0:
        exit(-1)

    for i, val in enumerate(files):
        device_name = "[device_{}]".format(str(i))
        all_traces_dict[device_name] = read_files(val, device_name)

    all_time_sorted_list = sorted(all_real_time_dict.items(), key=lambda \
        all_real_time_dict: all_real_time_dict[1]["realtime_ts"])
    base_real_time = all_time_sorted_list[0][1]["realtime_ts"]
    base_time_stamp = all_time_sorted_list[0][1]["timestamp"]
    all_trace_list = [] # [(timestamp, line)]
    for mtuple in all_time_sorted_list:
        target_device = mtuple[0]
        change_trace_time(all_trace_list, \
                          base_real_time, \
                          base_time_stamp, \
                          target_device)
    # Sort by timestamp from small to large
    all_trace_sorted_list = sorted(all_trace_list, key=lambda x: x[0])
    curtime = time.strftime("%Y%m%d_%H%M%S", time.localtime())
    write_to_file(all_trace_sorted_list, "multi_trace_"+str(curtime)+".ftrace")

if __name__ == '__main__':
    main()


import bpy, time
from mn_utils import *

normalNetworks = []
subNetworks = {}
invalidNetworks = []
useProfiling = False

def getAllNetworkCodeStrings():
	global subNetworks, invalidNetworks, useProfiling
	useProfiling = bpy.context.scene.mn_settings.developer.executionProfiling
	networkStrings = []
	clearSocketConnections()
	cleanupNodeTrees()
	nodeNetworks = getNodeNetworks()
	sortNetworks(nodeNetworks)
	if len(invalidNetworks) > 0:
		print("invalid node tree")
		return []
	for network in normalNetworks:
		codeGenerator = NetworkCodeGenerator(network)
		networkStrings.append(codeGenerator.getCode())
	clearSocketConnections()
	return networkStrings

def sortNetworks(nodeNetworks):
	global normalNetworks, subNetworks, invalidNetworks, idCounter
	normalNetworks = []
	subNetworks = {}
	invalidNetworks = []
	idCounter = 0
	for network in nodeNetworks:
		setUniqueCodeIndexToEveryNode(network)
		networkType = getNetworkType(network)
		if networkType == "Normal": normalNetworks.append(network)
		elif networkType == "Loop":
			startNode = getSubProgramStartNode(network)
			subNetworks[getNodeIdentifier(startNode)] = network
		elif networkType == "Invalid": invalidNetworks.append(network)

def getNetworkType(network):
	loopStarterAmount = 0
	for node in network:
		if node.bl_idname == "mn_LoopStartNode" or node.bl_idname == "mn_EnumerateObjectsStartNode":
			loopStarterAmount += 1
	if loopStarterAmount == 0: return "Normal"
	elif loopStarterAmount == 1: return "Loop"
	return "Invalid"
def getSubProgramStartNode(network):
	for node in network:
		if node.bl_idname == "mn_LoopStartNode" or node.bl_idname == "mn_EnumerateObjectsStartNode":
			return node

idCounter = 0
bpy.types.Node.codeIndex = bpy.props.IntProperty()
def setUniqueCodeIndexToEveryNode(nodes):
	global idCounter
	for node in nodes:
		node.codeIndex = idCounter
		idCounter += 1

# get node networks (groups of connected nodes)
###############################################

def getNodeNetworks():
	nodeNetworks = []
	nodeTrees = getAnimationNodeTrees()
	for nodeTree in nodeTrees:
		nodeNetworks.extend(getNodeNetworksFromTree(nodeTree))
	return nodeNetworks

def getAnimationNodeTrees():
	nodeTrees = []
	for nodeTree in bpy.data.node_groups:
		if hasattr(nodeTree, "isAnimationNodeTree"):
			nodeTrees.append(nodeTree)
			nodeTree.use_fake_user = True
	return nodeTrees

def getNodeNetworksFromTree(nodeTree):
	nodes = nodeTree.nodes
	resetNodeFoundAttributes(nodes)

	networks = []
	for node in nodes:
		if not node.isFound:
			networks.append(getNodeNetworkFromNode(node))
	return networks

def getNodeNetworkFromNode(node):
	nodesToCheck = [node]
	network = [node]
	node.isFound = True
	while len(nodesToCheck) > 0:
		linkedNodes = []
		for node in nodesToCheck:
			linkedNodes.extend(getLinkedButNotFoundNodes(node))
		network.extend(linkedNodes)
		setNodesAsFound(linkedNodes)
		nodesToCheck = linkedNodes
	return network

def setNodesAsFound(nodes):
	for node in nodes: node.isFound = True

def getLinkedButNotFoundNodes(node):
	nodes = []
	nodes.extend(getNotFoundInputNodes(node))
	nodes.extend(getNotFoundOutputNodes(node))
	return nodes
def getNotFoundInputNodes(node):
	nodes = []
	for socket in node.inputs:
		originSocket = getDataOriginSocket(socket)
		if originSocket is not None:
			fromNode = originSocket.node
			if not fromNode.isFound:
				nodes.append(fromNode)
				fromNode.isFound = True
	return nodes
def getNotFoundOutputNodes(node):
	nodes = []
	for socket in node.outputs:
		connectedSockets = getSocketsFromOutputSocket(socket)
		for toSocket in connectedSockets:
			toNode = toSocket.node
			if not toNode.isFound:
				nodes.append(toNode)
				toNode.isFound = True
	return nodes

bpy.types.Node.isFound = bpy.props.BoolProperty(default = False)
def resetNodeFoundAttributes(nodes):
	for node in nodes: node.isFound = False

# network code generator class
########################################

class NetworkCodeGenerator:
	def __init__(self, network):
		self.network = network
		self.modules = set(["bpy", "time"])
		self.functions = {}
		self.neededSocketReferences = []
		self.allNodesInTree = []
		self.executeNodes = []
		self.outputUseNodes = []

	def getCode(self):
		mainCode = self.getMainCode()

		codeParts = []
		codeParts.append("import " + ", ".join(self.modules))
		codeParts.append("nodes = bpy.data.node_groups['" + self.network[0].id_data.name + "'].nodes")
		codeParts.append(self.getNodeReferencingCode())
		codeParts.append(self.getNodeExecuteReferencingCode())
		codeParts.append(self.getSocketReferencingCode())
		codeParts.append(self.getOutputUseDeclarationCode())
		codeParts.append(self.getTimerDefinitions())
		codeParts.append(self.getFunctionsCode())
		codeParts.append(mainCode)
		codeParts.append(self.getCodeToPrintProfilingResult())
		return "\n".join(codeParts)

	def getMainCode(self):
		self.allNodesInTree.extend(self.network)
		self.orderedNodes = orderNodes(self.network)
		codeLines = []
		for node in self.orderedNodes:
			codeLines.extend(self.getNodeCodeLines(node))
		return "\n".join(codeLines)

	def makeFunctionCode(self, functionNetwork):
		startNode = getSubProgramStartNode(functionNetwork)
		if getNodeIdentifier(startNode) not in self.functions:
			self.functions[getNodeIdentifier(startNode)] = self.getFunctionCode(functionNetwork, startNode)
	def getFunctionCode(self, functionNetwork, startNode):
		self.allNodesInTree.extend(functionNetwork)
		self.orderedNodes = orderNodes(functionNetwork)
		mainLines = []
		mainLines.append("def " + getNodeFunctionName(startNode) + "(" + getNodeOutputName(startNode) + "):")
		mainLines.append("    global nodes")
		mainLines.append("    " + self.getTimerGlobalList(functionNetwork))
		for node in self.orderedNodes:
			if node != startNode:
				codeLines = self.getNodeCodeLines(node)
				self.setIndentationOnEveryLine(codeLines)
				mainLines.extend(codeLines)
		if useProfiling: mainLines.append("    globals().update(locals())")
		functionString = "\n".join(mainLines)
		return functionString
	def setIndentationOnEveryLine(self, codeLines):
		for i, line in enumerate(codeLines):
			codeLines[i] = "    " + line

	def getFunctionsCode(self):
		return "\n\n".join(self.functions.values())

	def getNodeCodeLines(self, node):
		codeLines = []
		if isExecuteableNode(node) or isInLineNode(node):
			codeLines.extend(self.getExecutableNodeCode(node))
		elif isLoopNode(node):
			codeLines.extend(self.getLoopNodeCode(node))
		elif isEnumerateObjectsNode(node):
			codeLines.extend(self.getEnumerateObjectsNodeCode(node))
		return codeLines

	def getExecutableNodeCode(self, node):
		codeLines = []
		if useProfiling: codeLines.append(getNodeTimerStartName(node) + " = time.clock()")
		codeLines.extend(self.getNodeExecutionLines(node))
		if useProfiling: codeLines.append(getNodeTimerName(node) + " += time.clock() - " + getNodeTimerStartName(node))
		return codeLines
	def getLoopNodeCode(self, node):
		codeLines = []
		codeLines.append(getNodeInputName(node) + " = " + self.generateInputListString(node))
		startNode = getCorrespondingStartNode(node)
		if startNode is not None:
			codeLines.append("for i in range(" + getNodeInputName(node) + "['Amount']):")
			codeLines.append("    " + getNodeInputName(node) + "['Index'] = i")
			codeLines.append("    " + getNodeFunctionName(startNode) + "(" + getNodeInputName(node) + ")")
			self.makeFunctionCode(subNetworks[getNodeIdentifier(startNode)])
		codeLines.append(getNodeOutputName(node) + " = " + getNodeInputName(node))
		return codeLines
	def getEnumerateObjectsNodeCode(self, node):
		codeLines = []
		inputName = getNodeInputName(node)
		codeLines.append(inputName + " = " + self.generateInputListString(node))
		codeLines.append(inputName + "['List Length'] = len("+ inputName + "['Objects'])")
		startNode = getCorrespondingStartNode(node)
		if startNode is not None:
			codeLines.append("if " + getNodeVariableName(node) + ".executeLoop:")
			codeLines.append("    for i, object in enumerate(" + inputName + "['Objects']):")
			codeLines.append("        " + inputName + "['Index'] = i")
			codeLines.append("        " + inputName + "['Object'] = object")
			codeLines.append("        " + getNodeFunctionName(startNode) + "(" + inputName + ")")
			self.makeFunctionCode(subNetworks[getNodeIdentifier(startNode)])
		codeLines.append(getNodeOutputName(node) + " = " + inputName)
		return codeLines

	def getTimerDefinitions(self):
		if useProfiling:
			codeLines = []
			for node in self.allNodesInTree:
				codeLines.append(getNodeTimerName(node) + " = 0")
			return "\n" + "\n".join(codeLines) + "\n"
		return ""
	def getTimerGlobalList(self, network):
		if useProfiling:
			nodeTimerNames = []
			for node in network:
				nodeTimerNames.append(getNodeTimerName(node))
			return "global " + ", ".join(nodeTimerNames)
		return ""

	def getCodeToPrintProfilingResult(self):
		if useProfiling:
			codeLines = []
			codeLines.append("print('----------  Profiling  ----------')")
			for node in self.allNodesInTree:
				codeLines.append("print('" + node.name + "')")
				codeLines.append("print('  ' + str(round(" + getNodeTimerName(node) + ", 5)) + ' s')")
			return "\n" + "\n".join(codeLines)
		return ""

	def getNodeReferencingCode(self):
		codeLines = []
		for node in self.allNodesInTree:
			codeLines.append(self.getNodeDeclarationString(node))
		return "\n".join(codeLines)

	def getNodeExecuteReferencingCode(self):
		codeLines = []
		for node in self.executeNodes:
			codeLines.append(self.getNodeFunctionDeclarationString(node))
		return "\n".join(codeLines)

	def getSocketReferencingCode(self):
		codeLines = []
		for socket in self.neededSocketReferences:
			codeLines.append(self.getSocketDeclarationString(socket))
		return "\n".join(codeLines)

	def getOutputUseDeclarationCode(self):
		codeLines = []
		for node in self.outputUseNodes:
			codeLines.append(getNodeOutputUseName(node) + " = " + getOutputUseDictionaryCode(node))
		return "\n".join(codeLines)

	def generateInputListString(self, node):
		inputParts = []
		useFastMethod = usesFastCall(node)
		inputSocketNames = None
		if useFastMethod: inputSocketNames = node.getInputSocketNames()
		for socket in node.inputs:
			originSocket = getDataOriginSocket(socket)
			if originSocket is not None:
				inputParts.append(self.getInputPartFromOtherNode(socket, originSocket, useFastMethod, inputSocketNames))
			else:
				self.neededSocketReferences.append(socket)
				inputParts.append(self.getInputPartFromSameNode(socket, useFastMethod, inputSocketNames))
		if usesOutputUseParameter(node):
			self.outputUseNodes.append(node)
			return node.outputUseParameterName + " = " + getNodeOutputUseName(node) + ", " + self.joinInputParts(inputParts, useFastMethod)
		else:
			return self.joinInputParts(inputParts, useFastMethod)

	def joinInputParts(self, inputParts, useFastMethod):
		if useFastMethod:
			return ", ".join(inputParts)
		else:
			return "{ " + ", ".join(inputParts) + " }"
	def getInputPartFromSameNode(self, socket, useFastMethod, inputSocketNames):
		if useFastMethod:
			return inputSocketNames[socket.identifier] + " = " + getInputValueVariable(socket)
		else:
			return "'" + socket.identifier + "' : " + getInputValueVariable(socket)
	def getInputPartFromOtherNode(self, socket, originSocket, useFastMethod, inputSocketNames):
		return self.getInputPartStart(socket, useFastMethod, inputSocketNames) + getInputValueVariable(socket)
	def getInputPartStart(self, socket, useFastMethod, inputSocketNames):
		if useFastMethod:
			return inputSocketNames[socket.identifier] + " = "
		else:
			return "'" + socket.identifier + "' : "

	def getNodeDeclarationString(self, node):
		return getNodeVariableName(node) + " = nodes['"+node.name+"']"
	def getNodeFunctionDeclarationString(self, node):
		return getNodeExecutionName(node) + " = " + getNodeVariableName(node) + ".execute"
	def getSocketDeclarationString(self, socket):
		return getInputSocketVariableName(socket) + " = " + getNodeVariableName(socket.node) + ".inputs['" + socket.name + "'].getValue()"
	def getNodeExecutionLines(self, node):
		useInLineExecution = False
		if hasattr(node, "useInLineExecution"):
			useInLineExecution = node.useInLineExecution()
		if useInLineExecution:
			if hasattr(node, "getModuleList"):
				self.modules.update(node.getModuleList())
			inLineString = node.getInLineExecutionString(getOutputUseDictionary(node))
			inputSocketNames = node.getInputSocketNames()
			outputSocketNames = node.getOutputSocketNames()
			for identifier, name in inputSocketNames.items():
				socket = node.inputs[identifier]
				inLineString = inLineString.replace("%" + name + "%", getInputValueVariable(socket))
				if not hasOtherDataOrigin(socket):
					self.neededSocketReferences.append(socket)
			for identifier, name in outputSocketNames.items():
				inLineString = inLineString.replace("$" + name + "$", getOutputValueVariable(node.outputs[identifier]))
			return inLineString.split("\n")
		else:
			self.executeNodes.append(node)
			return [getNodeOutputString(node) + " = " + getNodeExecutionName(node) + "(" + self.generateInputListString(node) + ")"]

def getNodeOutputString(node):
	if usesFastCall(node):
		outputSocketNames = node.getOutputSocketNames()
		if len(outputSocketNames) != len(node.outputs): raise Exception()
		if len(node.outputs) != 0:
			outputParts = []
			for socket in node.outputs:
				outputParts.append(getOutputValueVariable(socket))
			return ", ".join(outputParts)
	return getNodeOutputName(node)

def getOutputUseDictionaryCode(node):
	codeParts = []
	for socket in node.outputs:
		codeParts.append('"' + socket.identifier + '" : ' + str(isOutputSocketUsed(socket)))
	return "{" + ", ".join(codeParts) + "}"
def getOutputUseDictionary(node):
	outputUse = {}
	for socket in node.outputs:
		outputUse[socket.identifier] = isOutputSocketUsed(socket)
	return outputUse

def getCorrespondingStartNode(node):
	return node.getStartNode()

def isExecuteableNode(node):
	return hasattr(node, "execute")
def isInLineNode(node):
	return hasattr(node, "getInLineExecutionString")
def isLoopNode(node):
	return node.bl_idname == "mn_LoopNode"
def isEnumerateObjectsNode(node):
	return node.bl_idname == "mn_EnumerateObjectsNode"

def usesFastCall(node):
	if hasattr(node, "getInputSocketNames"):
		if hasattr(node, "getOutputSocketNames"): return True
		else: raise Exception()
	if hasattr(node, "getOutputSocketNames"): raise Exception()
	return False
def usesOutputUseParameter(node):
	return hasattr(node, "outputUseParameterName")

def getInputValueVariable(socket):
	originSocket = getDataOriginSocket(socket)
	if originSocket is not None:
		return getOutputValueVariable(originSocket)
	else:
		return getInputSocketVariableName(socket)
def getOutputValueVariable(socket):
	if usesFastCall(socket.node):
		outputSocketNames = socket.node.getOutputSocketNames()
		return getNodeOutputName(socket.node) + "_" + outputSocketNames[socket.identifier]
	else:
		return getNodeOutputName(socket.node) + "['" + socket.identifier + "']"

def getNodeVariableName(node):
	return "node_" + str(node.codeIndex)
def getNodeInputName(node):
	return "input_" + str(node.codeIndex)
def getNodeOutputName(node):
	return "output_" + str(node.codeIndex)
def getNodeOutputUseName(node):
	return getNodeVariableName(node) + "_output_use"
def getNodeFunctionName(node):
	return getNodeVariableName(node) + "_" + "Function"
def getNodeExecutionName(node):
	return getNodeVariableName(node) + "_" + "execute"
def getNodeTimerStartName(node):
	return "timer_start_" + str(node.codeIndex)
def getNodeTimerName(node):
	return "timer_" + str(node.codeIndex)
def getInputSocketVariableName(socket):
	node = socket.node
	return getNodeVariableName(node) + "_socketvalue_" + str(node.inputs.find(socket.name))

# order nodes (network) to possible execution sequence
######################################################

def orderNodes(nodes):
	preOrderedList = []
	for node in nodes:
		preOrderedList.extend(getAllNodeDependencies(node))
		preOrderedList.append(node)

	orderedList = []
	for node in preOrderedList:
		if node not in orderedList and node in nodes: orderedList.append(node)
	return orderedList

def getAllNodeDependencies(node):
	dependencies = []
	directDependencies = getDirectDependencies(node)
	for directDependency in directDependencies:
		dependencies.extend(getAllNodeDependencies(directDependency))
	dependencies.extend(directDependencies)
	return dependencies

def getDirectDependencies(node):
	directDependencies = []
	for socket in node.inputs:
		originSocket = getDataOriginSocket(socket)
		if originSocket is not None:
			node = originSocket.node
			directDependencies.append(node)
	return directDependencies

# cleanup of node trees
################################

convertRules = {}
convertRules[("Float", "Integer")] = "mn_ToIntegerConversion"
convertRules[("Generic", "Integer")] = "mn_ToIntegerConversion"
convertRules[("Float", "String")] = "mn_ToStringConversion"
convertRules[("Generic", "Float")] = "mn_ToFloatConversion"
convertRules[("Integer", "String")] = "mn_ToStringConversion"
convertRules[("Float", "Vector")] = "mn_CombineVector"
convertRules[("Integer", "Vector")] = "mn_CombineVector"
convertRules[("Vector", "Float")] = "mn_SeparateVector"
convertRules[("Vector", "Integer")] = "mn_SeparateVector"

def cleanupNodeTrees():
	nodeTrees = getAnimationNodeTrees()
	for nodeTree in nodeTrees:
		cleanupNodeTree(nodeTree)
def cleanupNodeTree(nodeTree):
	originalLinks = list(nodeTree.links)
	for link in originalLinks:
		toSocket = link.to_socket
		fromSocket = link.from_socket
		if toSocket.node.type == "REROUTE":
			continue
		if fromSocket.node.type == "REROUTE": originSocket = getOriginSocket(toSocket)
		else: originSocket = fromSocket
		if isOtherOriginSocket(toSocket, originSocket):
			if originSocket.dataType not in toSocket.allowedInputTypes and toSocket.allowedInputTypes[0] != "all":
				handleNotAllowedLink(nodeTree, link, fromSocket, toSocket, originSocket)
			else: setDataConnection(originSocket, toSocket)
def handleNotAllowedLink(nodeTree, link, fromSocket, toSocket, originSocket):
	fromType = originSocket.dataType
	toType = toSocket.dataType
	nodeTree.links.remove(link)
	convertNodeType = convertRules.get((fromType, toType))
	if convertNodeType is not None:
		insertConversionNode(nodeTree, convertNodeType, fromSocket, toSocket, originSocket)
def insertConversionNode(nodeTree, convertNodeType, fromSocket, toSocket, originSocket):
	node = nodeTree.nodes.new(convertNodeType)
	node.hide = True
	node.select = False
	x1, y1 = toSocket.node.location
	x2, y2 = list(fromSocket.node.location)
	node.location = [(x1+x2)/2+20, (y1+y2)/2-50]

	nodeTree.links.new(node.inputs[0], fromSocket)
	setDataConnection(originSocket, node.inputs[0])

	nodeTree.links.new(toSocket, node.outputs[0])
	setDataConnection(node.outputs[0], toSocket)

# find origin sockets
############################################

inputSockets = {}
outputSockets = {}

def handleLink(link):
	fromValid = isValidNode(link.from_node)
	toValid = isValidNode(link.to_node)
	if fromValid and toValid: setDataConnection(link.from_socket, link.to_socket)
	elif toValid:
		originSocket = getOriginSocket(link.to_socket)
		if isOtherOriginSocket(link.to_socket, originSocket):
			setDataConnection(originSocket, link.to_socket)

def clearSocketConnections():
	global inputSockets, outputSockets
	inputSockets = {}
	outputSockets = {}

def setDataConnection(fromSocket, toSocket):
	global inputSockets, outputSockets

	if fromSocket not in outputSockets:	outputSockets[fromSocket] = []

	inputSockets[toSocket] = fromSocket
	outputSockets[fromSocket].append(toSocket)

def isValidNode(node):
	return node.bl_idname[:3] == "mn_"

def hasOtherDataOrigin(socket):
	return inputSockets.get(socket) is not None
def getDataOriginSocket(socket):
	return inputSockets.get(socket)
def isOutputSocketUsed(socket):
	return socket in outputSockets
def getSocketsFromOutputSocket(socket):
	return outputSockets.get(socket, [])


import os
import sys
import pygame
# Add the parent directory to the path
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from Intcode.Intcode import Intcode

class Tile:
    def __init__(self, x, y, id):
        self.x = x
        self.y = y
        self.id = id

class BrickBreak(Intcode):
    def __init__(self, file):
        Intcode.__init__(self, file)
        self.__tiles = []
        self.__paddle = None
        self.__ball = None
        self.__score = 0

    def render(self, input=None):
        self.run(input)
        self.__tiles = []
        output = self.getOutput()
        i = 0
        while i < len(output):
            self.__tiles.append(Tile(output[i], output[i + 1], output[i + 2]))
            self.updateGame()
            i += 3

    def updateGame(self):
        for tile in self.__tiles:
            if tile.id == 3:
                self.__paddle = tile
            elif tile.id == 4:
                self.__ball = tile
            elif tile.x == -1:
                self.__score = tile.id

    def countBlocks(self):
        nBblocks = 0
        for tile in self.__tiles:
            if tile.id == 2:
                nBblocks += 1
        return nBblocks

    def playGame(self):
        while True:
            if self.__ball.x < self.__paddle.x:
                input = -1
            elif self.__ball.x > self.__paddle.x:
                input = 1
            else:
                input = 0

            self.render(input)

            if self.isStopped():
                break

        print(self.__score)

    def displayGame(self):
        pygame.init()
        font = pygame.font.Font(None, 36)
        # Set up the drawing window
        screen = pygame.display.set_mode([1320, 600])

        # Run until the user asks to quit
        running = True
        input = 0
        screen.fill((0, 0, 0))

        while running:
            # Did the user click the window close button?
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False

            for tile in self.__tiles:
                if tile.id == 0:
                    color = (0, 0, 0)
                elif tile.id == 2:
                    color = (245, 66, 99)
                else:
                    color = (255, 255, 255)

                pygame.draw.rect(screen, color, [tile.x*30, tile.y*30, 30, 30])

            if self.__ball.x < self.__paddle.x:
                input = -1
            elif self.__ball.x > self.__paddle.x:
                input = 1
            else:
                input = 0

            self.render(input)

            if brickBreak.isStopped():
                running = False

            # Flip the display
            pygame.display.flip()
            pygame.time.Clock().tick(60)

if __name__ == '__main__':
    brickBreak = BrickBreak("input.txt")
    brickBreak.render()
    print("Part 1:", brickBreak.countBlocks())
    brickBreak.playGame()


from django.core.files.storage import FileSystemStorage
from django.db.models.fields.files import FieldFile

class ForgeStorage(FileSystemStorage):

    def get_available_name(self, name):
        """
        Returns a filename that's free on the target storage system, and
        available for new content to be written to.
        """
        # Clobber existing files, or else will get filenames that won't
        # comply with the module naming format.
        if self.exists(name):
            self.delete(name)
        return name

def file_cleanup(sender, instance, *args, **kwargs):
    '''
        Deletes the file(s) associated with a :model instance. The model
        is not saved after deletion of the file(s) since this is meant
        to be used with the pre_delete signal.
    '''
    for field_name, _ in instance.__dict__.iteritems():
        field = getattr(instance, field_name)
        if issubclass(field.__class__, FieldFile) and field.name:
            field.delete(save=False)


# 时间复杂度：O(N)
# 解题思想：
# 本题可以利用比较巧妙的解法
# 1.例如样例所给的2 2 0 0 0 3 0 0 1 0
# 2.先用列表存放[1,1,5,5,5,8]
# 3.再将0插入到第一个1后面，即[1,0,0,1,5,5,5,8]
# 4.再将每一位用字符串连接起来
# 5.最终把字符串转为整型

Number = list(map(int, input().split()))  # 存放0-9的数字的个数
NumberList = list()  # 存放1-9的数字

for i in range(1, 10):
    NumberList += [i for j in range(Number[i])]  # 添加j个数字i，例如有3个2，则将3个2都添加到NumberList中

NumberList = NumberList[0:1] + [0 for i in range(Number[0])] + NumberList[1:]  # 列表拼接，如果有0，在第一个数后面添加0

Min = ''
for i in range(len(NumberList)):
    Min += str(NumberList[i])  # 字符串连接

print(int(Min))


#Used in PostUpdater.get_posted_message
EM_TRUE = "✅"
EM_FALSE = "⚫"
EM_FAIL = "❌"
EM_WEEKEND = "🔥"
USERS = "<b>Участники</b>"

# UTC time of posting
POST_WEEKDAY = 6
POST_HOUR = 21
POST_MINUTE = 1
JOB_DAYS_DURATION = 7

# Remind 3 hours before the end of the day from Mon to Fri.
REMINDER_DELTA = 3
REMINDER_DAYS = [0, 1, 2, 3, 4]


import csv
csvpath= 'PyBank/Resources/02-Homework_03-Python_Instructions_PyBank_Resources_budget_data.csv'
#Open CSV as Reader
with open(csvpath) as csv_file:
    csv_reader=csv.reader(csv_file, delimiter=",")
    csv_header=next(csv_file)
    print(f"Header:{csv_header}")

#Declare Variables
    monthcount=0
    total=0
    average_change=0
    date=[]
    profits=[]
    previous_profit=0
    difference=[]
    total_difference=0
    increase={"month": "", "profits": 0}
    decrease={"month": "", "losses": 0}

#The total number of months included in the dataset
    for row in csv_reader:
        monthcount +=1
        total += int(row[1])

#The net total amount of "Profit/Losses" over the entire period
        date.append(row[0])
        profit = int(row[1])
        profits.append(profit)

#Calculate the changes in "Profit/Losses" over the entire period,
        cd=0
        if previous_profit != 0:
            cd = profit - previous_profit
            difference.append(cd)
        previous_profit = profit

#The greatest increase in profits (date and amount) over the entire period
#The greatest decrease in losses (date and amount) over the entire period
        if cd > increase['profits']:
            increase['profits'] = cd
            increase['month'] = row[0]
        if cd < decrease['losses']:
            decrease['losses'] = cd
            decrease['month'] = row[0]
#then find the average of those changes
    average_change = sum(difference) / len(difference)

print(f"Financial Analysis")
print(f"----------------------------")
print(f"Total Months: {monthcount}")
print(f"Total: ${total}")
print(f"Average Change: ${average_change:.2f}")
print(f"Greatest Increase in Profits: {increase['month']} ${increase['profits']}")
print(f"Greatest Decrease in Profits: {decrease['month']} ${decrease['losses']}")

output = open("PyBank/Analysis/file.txt","w")
output.write(f"Financial Analysis\n")
output.write(f"----------------------------\n")
output.write(f"Total Months: {monthcount}\n")
output.write(f"Total: ${total}\n")
output.write(f"Average Change: ${average_change:.2f}\n")
output.write(f"Greatest Increase in Profits: {increase['month']} ${increase['profits']}\n")
output.write(f"Greatest Decrease in Profits: {decrease['month']} ${decrease['losses']}\n")


import os

import matplotlib.pyplot as plt
import numpy as np

from util import tum_jet
from util.inches import cm_to_inch

class RoiVsReferencePlotter:
    def __init__(self, folder_corrected, folder_uncorrected):
        self.fig, self.axes = self.__create_and_scale_figure_and_axes()
        self.folder_corrected = folder_corrected
        self.folder_uncorrected = folder_uncorrected
        self.corrected_data = self.__load_corrected_data()
        self.uncorrected_data = self.__load_uncorrected_data()

    def create_and_save_plot(self):
        self.__create_uncorrected_plot()
        self.__create_corrected_plot()
        plt.tight_layout()
        plt.savefig('corrected_vs_uncorrected.jpg', dpi=500)

    def __create_uncorrected_plot(self):
        self.__create_plot(self.__calc_uncorrected_taus(), 0, self.uncorrected_data)

    def __create_corrected_plot(self):
        self.__create_plot(self.__calc_corrected_taus(), 1, self.corrected_data)

    def __create_plot(self, taus, axis_index, data):
        axis = self.axes[axis_index]
        axis.plot(taus, data / data.max(), '.', color=tum_jet.tum_color(0))
        axis.set_xlabel('pulse duration (ns)')
        axis.set_ylabel('luminescence (norm.)')

    def __load_corrected_data(self):
        data = np.loadtxt(os.path.join(self.folder_corrected, 'result.txt'))
        return data - 3.8e10  # to increase contrast to level of NV 577

    def __load_uncorrected_data(self):
        filenames = os.listdir(self.folder_uncorrected)
        luminescences = np.zeros_like(filenames, dtype=np.float)
        for i, filename in enumerate(filenames):
            frame_data = np.loadtxt(os.path.join(self.folder_uncorrected, filename))[51:63, 91:103]
            luminescences[i] = np.average(frame_data)
        return luminescences

    def __create_and_scale_figure_and_axes(self):
        self.fig, self.axes = plt.subplots(nrows=1, ncols=2)
        self.fig.set_figheight(cm_to_inch(6))
        self.fig.set_figwidth(cm_to_inch(15))
        return self.fig, self.axes

    def __calc_uncorrected_taus(self):
        n_taus = len(os.listdir(self.folder_uncorrected))
        return np.linspace(20, 350, n_taus)

    def __calc_corrected_taus(self):
        n_taus = len(list(filter(lambda x: x.startswith('frame'), os.listdir(self.folder_corrected))))
        return np.linspace(2, 350, n_taus)

if __name__ == '__main__':
    folder_with_corrected_data = '//file/e24/Projects/ReinhardLab/data_setup_nv1/170502_01B_echo_after_annel/rabi_002'
    folder_with_uncorrected_data = '//file/e24/Projects/ReinhardLab/data_setup_nv1/161109_background_rabis/rabi_001'
    plotter = RoiVsReferencePlotter(folder_with_corrected_data, folder_with_uncorrected_data)
    plotter.create_and_save_plot()


from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from db.base_view import BaseVerifyView
from goods.models import GoodsSku

class AddCartView(View):
    def get(self, request):
        """
               1. 需要验证登陆
               2. 接收参数: 购物车加入数量(count),当前商品ID(sku_id)
               3. 验证数据
                   a. 都必须为整数
                   b. count 必须大于0
                   c. 商品必须存在
                   d. (可以有) 判断库存

               4. 添加商品到购物车中(通过redis实现)
                   存好处存 , 取好取
                   user_id  sku_id count
                   hash 对象: object = {"key1":value1,"key2":value2}
                       HSET key field value
                       HSET cart_key_user_id sku_id count

               5. 填写成功,返回
                   返回是否成功, 及 购物车中总的商品的数量

           """
        pass
    def post(self, request):
        #1. 需要验证登陆
        user_id = request.session.get("id")
        if user_id is None:
            #没有登录
            return JsonResponse({"code": 1, "errmsg": "没有登录"})
        # 接收参数: 购物车加入数量(count), 当前商品ID(sku_id)
        count = request.POST.get("count")
        sku_id = request.POST.get("sku_id")
        # 验证数据
        # a.都必须为整数
        try:
            count = int(count)
            sku_id = int(sku_id)
        except:
            return JsonResponse({"code": 2, "errmsg": "参数错误"})
        # b.count 必须大于0
        # if count <= 0:
        #     return JsonResponse({"code": 3, "errmsg": "参数错误"})
        # c.商品必须存在
        try:
            goodssku = GoodsSku.objects.get(pk=sku_id)
        except GoodsSku.DoesNotExist:
            return JsonResponse({"code": 4, "errmsg": "商品不存在"})
        # d.(可以有) 判断库存
        if count > goodssku.stock:
            return JsonResponse({"code": 5, "errmsg": "库存不足"})
        # 4.添加商品到购物车中(通过redis实现)
        r = get_redis_connection('default')
        cart_key = "cart_key_{}".format(user_id)
        res = r.hincrby(cart_key, sku_id, count)
        # 判断当前sku_id中的数量如果等于0说明 需要从redis中删除该sku_id对应的键
        if res == 0:
            r.hdel(cart_key, sku_id)
        # 获取购物车中总数量
        cart_count = 0
        vals = r.hvals(cart_key)
        for v in vals:
            cart_count += int(v)

        #成功返回
        return JsonResponse({"code": 0, "cart_count": cart_count})

#购物车页面
class ShopCartView(BaseVerifyView):
    def get(self, request):
        # 获取商品sku
        user_id = request.session.get("id")
        r = get_redis_connection('default')
        cart_key = "cart_key_{}".format(user_id)
        datas = r.hgetall(cart_key)  #二进制字典
        goodsskus = []
        for sku_id, count in datas.items():
            sku_id = int(sku_id)
            count = int(count)
            # 查询商品的完整信息
            goods = GoodsSku.objects.get(pk=sku_id)
            # 将count保存到 商品对象上(对象上添加一个自定义的属性)
            goods.count = count
            # 保存到列表
            goodsskus.append(goods)
        context = {
            "goodsskus": goodsskus,
        }
        return render(request, "cart/shopcart.html", context)
    def post(self, request):
        pass


import revnet
import os
import sys
import time

if __name__=='__main__':

	if len(sys.argv)!=3:

		print("USAGE: "+sys.argv[0]+" <host> <port>")

		exit()

	Host=sys.argv[1]
	Port=sys.argv[2]
	print("Binding "+Host+":"+Port)
	Conn=revnet.ServerConn(Host,int(Port))
	print("Connected: "+Conn.SocketAddr[0])

	CurrentDir=Conn.recvstring()

	while True:

		Command=input(CurrentDir+'>')

		if Command=='l_help':

			print("l_help - Print this help message.")
			print("lls - list contents of local directory")
			print("lcd - change local directory")
			print("lexec - execute local command")

		elif Command[0:3]=='lcd':

			os.chdir(Command[4:])

		elif Command[0:3]=='lls':

			for f in os.listdir():

				print(f)

		elif Command[0:5]=='lexec':

			os.system(Command[6:])

		elif Command[0:4]=='fget':

			Conn.sendstring(Command)
			Ack=Conn.recvstring()
			if Ack=='Bad':
				print('Error getting file')
			else:
				Conn.recvfile(Command[5:])
				print('File received!')
			CurrentDir=Conn.recvstring()

		elif Command[0:6]=='ftrans':

			Conn.sendstring(Command)
			try:

				f=open(Command[7:],'rb')
				f.close()
				Ack='Successful'

			except:

				Ack='Bad'
			Conn.sendstring(Ack)
			Ack=Conn.sendfile(Command[7:])
			if Ack=="Unable to open file":
				print(Ack)
			else:
				print('File sent!')
			CurrentDir=Conn.recvstring()

		elif Command[0:7]=='wc_snap':

			Conn.sendstring(Command)
			Ack=Conn.recvstring()
			if Ack=='Bad':
				print('Error getting file')
			else:
				print('Saving as '+Ack)
				Conn.recvfile(Ack)
				print('File received!')
			CurrentDir=Conn.recvstring()

		elif Command=='exit':

			Conn.sendstring(Command)
			Conn.close()
			exit()

		else:

			Conn.sendstring(Command)
			Ret=Conn.recvstring()
			CurrentDir=Conn.recvstring()
			print(Ret+'\n')


import tkinter as tk
import math

#Default config to buttons
button_config = {
    "bg":"#242742",
    "fg":"#d1d2de",
    "font":("Consolas bold",12),
    "height": "2",
    "width": "7",
    "relief": "flat",
    "activebackground":"#313454"
}
#List of digits that need a special  function (only for verification).
digits = ["√","x²","C","n!","sin","cos","tan","sin-¹","cos-¹","tan-¹","DEG","RAD"]
#List of digits that will receive a custom bg
numbers = ["1","2","3","4","5","6","7","8","9","0",".","="]
#Constants that change if value is in radians or degrees
convert_deg = 1
convert_inverse_deg = 1
#Control variable (used in change of degrees to radians or radians to degrees)
cnt = 0

class Calculator:
    def __init__(self, master):

        self.master = master
        #Display frame
        self.displayFrame = tk.Frame(self.master)
        self.displayFrame.pack()
        #Frame which contains all the buttons on it
        self.buttonsFrame = tk.Frame(self.master)
        self.buttonsFrame.pack()
        #Display
        self.output = tk.Entry(self.displayFrame,
                               width=30, relief="sunken", bd=3, font=("Consolas bold",17),fg="#c9c9c5", bg="#242742")
        self.output.grid(row=0,column=0)
        #Button to change to degrees or radians
        self.change = tk.Button(self.displayFrame,
                                button_config, width=3, height=0, text="DEG", bg="#e35124",command=self.degreesRadian)
        self.change.grid(row=0,column=1)
        self.createButtons()

    def createButtons(self):
        #A matrix with all buttons, a sketch to the calculator
        self.buttons = [
            ["√", "x²", "**","(",")","/"],
            ["sin","cos","7","8","9","+"],
            ["sin-¹","cos-¹","4","5","6","-"],
            ["tan","tan-¹","1","2","3","*"],
            ["n!","π",".","0","=","C"]
                       ]

        #To implement buttons, create one for to lines, and another to columns
        for i in range(len(self.buttons)):
            for j in range(len(self.buttons[i])):
                text = self.buttons[i][j] #Get the text in specific line and column of matrix
                '''create a new button every iteration, with a different text, but same configuration
                   ->Lambda explanation: We define text = text to bind every function to correct button
                     without this, the only text it will be passed is C, that's last in the matrix,
                     so when clicking buttons, the only value that will appear on display it will be C.
                '''
                if text in numbers:
                    b = tk.Button(self.buttonsFrame,button_config,bg="#383c6b",
                    text=text, command = lambda text = text: self.buttonsAction(text))
                else:
                    b = tk.Button(self.buttonsFrame,button_config,text=text, command = lambda text = text: self.buttonsAction(text))
                b.grid(row = i, column = j)

    def buttonsAction(self, text):
        global convert_deg
        global convert_inverse_deg
        if text != "=":
            if text not in digits:
                self.output.insert('end',text)
            #special buttons
            else:
                if text == "√":
                    self.addValue(math.sqrt(float(self.output.get())))
                elif text == "n!":
                    self.addValue(math.factorial(float(self.output.get())))
                elif text == "x²":
                    self.addValue(float(self.output.get()) ** 2)
                elif text == "C":
                    self.addValue("")
                elif text == "π":
                    self.addValue(3.1415926535897932)
                elif text == "sin":
                    self.addValue(math.sin(float(self.output.get()) * convert_deg))
                elif text == "cos":
                    self.addValue(math.cos(float(self.output.get()) * convert_deg))
                elif text == "tan":
                    self.addValue(math.tan(float(self.output.get()) * convert_deg))
                elif text == "sin-¹":
                    self.addValue(math.asin(float(self.output.get())) * convert_inverse_deg)
                elif text == "cos-¹":
                    self.addValue(math.acos(float(self.output.get())) * convert_inverse_deg)
                elif text == "tan-¹":
                    self.addValue(math.atan(float(self.output.get())) * convert_inverse_deg)
        else:
            self.addValue(eval(self.output.get()))

    def addValue(self, value):
        self.output.delete(0, 'end')
        self.output.insert('end',value)

    def degreesRadian(self):
        global cnt
        global convert_deg
        global convert_inverse_deg

        if(cnt == 0): #If radians return to degrees
            convert_deg = math.pi / 180
            convert_inverse_deg = 180 / math.pi
            self.change['text'] = "RAD"
            cnt = 1
        else: #If in degrees, return to radian
            convert_deg = 1
            convert_inverse_deg = 1
            self.change['text'] = "DEG"
            cnt = 0

root = tk.Tk()
Calculator(root)
root.mainloop()


import numpy as np
import matplotlib.pyplot as plt
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from sklearn.decomposition import TruncatedSVD

class LSA:
    def __init__(self, stopwords):
        self.stopwords = stopwords
        self.lemmatizer = WordNetLemmatizer()
        self.token2idx = {}
        self.idx2token = {}
        self.documents = []
        self.token_idx = 0
        self.X = None
    # end constructor

    def fit(self, documents):
        for line in documents:
            line = line.decode('ascii', 'ignore') # this is done in py2, py3 needs to test again
            tokens = self.tokenize(line)
            self.documents.append(tokens)
            for token in tokens:
                if token not in self.token2idx: # tests the existence of a key in a dict
                    self.token2idx[token] = self.token_idx
                    self.idx2token[self.token_idx] = token
                    self.token_idx += 1
        assert len(self.idx2token) == len(self.token2idx), "The length of idx2token is unequal to token2idx"

        self.X = np.zeros((len(self.token2idx), len(self.documents))) # Term-Document Matrix
        for i, tokens in enumerate(self.documents):
            self.X[:, i] = self.tokens2vec(tokens)
    # end method fit

    def plot(self):
        model = TruncatedSVD()
        X_2d = model.fit_transform(self.X)
        plt.scatter(X_2d[:, 0], X_2d[:, 1])
        for i in range(len(self.idx2token)):
            plt.annotate(s=self.idx2token[i], xy=(X_2d[i, 0], X_2d[i, 1]))
        plt.show()
    # end method plot

    def tokenize(self, string):
        string = string.lower()
        tokens = word_tokenize(string) # more powerful split()
        tokens = [token for token in tokens if len(token)>2] # remove too short words
        tokens = [self.lemmatizer.lemmatize(token) for token in tokens] # words into base form
        tokens = [token for token in tokens if token not in self.stopwords] # remove stopwords
        tokens = [token for token in tokens if not any(c.isdigit() for c in token)] # remove any token that contains number
        return tokens
    # end method tokenize

    def tokens2vec(self, tokens):
        vec = np.zeros(len(self.token2idx))
        for token in tokens:
            idx = self.token2idx[token]
            vec[idx] = 1
        return vec
    # end method tokens2vec


# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------

from .sub_resource_py3 import SubResource

class InboundNatPool(SubResource):
    """Inbound NAT pool of the load balancer.

    All required parameters must be populated in order to send to Azure.

    :param id: Resource ID.
    :type id: str
    :param frontend_ip_configuration: A reference to frontend IP addresses.
    :type frontend_ip_configuration:
     ~azure.mgmt.network.v2018_04_01.models.SubResource
    :param protocol: Required. Possible values include: 'Udp', 'Tcp', 'All'
    :type protocol: str or
     ~azure.mgmt.network.v2018_04_01.models.TransportProtocol
    :param frontend_port_range_start: Required. The first port number in the
     range of external ports that will be used to provide Inbound Nat to NICs
     associated with a load balancer. Acceptable values range between 1 and
     65534.
    :type frontend_port_range_start: int
    :param frontend_port_range_end: Required. The last port number in the
     range of external ports that will be used to provide Inbound Nat to NICs
     associated with a load balancer. Acceptable values range between 1 and
     65535.
    :type frontend_port_range_end: int
    :param backend_port: Required. The port used for internal connections on
     the endpoint. Acceptable values are between 1 and 65535.
    :type backend_port: int
    :param idle_timeout_in_minutes: The timeout for the TCP idle connection.
     The value can be set between 4 and 30 minutes. The default value is 4
     minutes. This element is only used when the protocol is set to TCP.
    :type idle_timeout_in_minutes: int
    :param enable_floating_ip: Configures a virtual machine's endpoint for the
     floating IP capability required to configure a SQL AlwaysOn Availability
     Group. This setting is required when using the SQL AlwaysOn Availability
     Groups in SQL server. This setting can't be changed after you create the
     endpoint.
    :type enable_floating_ip: bool
    :param provisioning_state: Gets the provisioning state of the PublicIP
     resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
    :type provisioning_state: str
    :param name: The name of the resource that is unique within a resource
     group. This name can be used to access the resource.
    :type name: str
    :param etag: A unique read-only string that changes whenever the resource
     is updated.
    :type etag: str
    """

    _validation = {
        'protocol': {'required': True},
        'frontend_port_range_start': {'required': True},
        'frontend_port_range_end': {'required': True},
        'backend_port': {'required': True},
    }

    _attribute_map = {
        'id': {'key': 'id', 'type': 'str'},
        'frontend_ip_configuration': {'key': 'properties.frontendIPConfiguration', 'type': 'SubResource'},
        'protocol': {'key': 'properties.protocol', 'type': 'str'},
        'frontend_port_range_start': {'key': 'properties.frontendPortRangeStart', 'type': 'int'},
        'frontend_port_range_end': {'key': 'properties.frontendPortRangeEnd', 'type': 'int'},
        'backend_port': {'key': 'properties.backendPort', 'type': 'int'},
        'idle_timeout_in_minutes': {'key': 'properties.idleTimeoutInMinutes', 'type': 'int'},
        'enable_floating_ip': {'key': 'properties.enableFloatingIP', 'type': 'bool'},
        'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
        'name': {'key': 'name', 'type': 'str'},
        'etag': {'key': 'etag', 'type': 'str'},
    }

    def __init__(self, *, protocol, frontend_port_range_start: int, frontend_port_range_end: int, backend_port: int, id: str=None, frontend_ip_configuration=None, idle_timeout_in_minutes: int=None, enable_floating_ip: bool=None, provisioning_state: str=None, name: str=None, etag: str=None, **kwargs) -> None:
        super(InboundNatPool, self).__init__(id=id, **kwargs)
        self.frontend_ip_configuration = frontend_ip_configuration
        self.protocol = protocol
        self.frontend_port_range_start = frontend_port_range_start
        self.frontend_port_range_end = frontend_port_range_end
        self.backend_port = backend_port
        self.idle_timeout_in_minutes = idle_timeout_in_minutes
        self.enable_floating_ip = enable_floating_ip
        self.provisioning_state = provisioning_state
        self.name = name
        self.etag = etag


'''
Created on Nov 21, 2016

@author: jupark
originally from Robert
from http://mirobetm.blogspot.kr/2013/02/restricting-django-to-one-user.html
'''

from django.conf import settings
from django.core.cache import caches, get_cache
from django.utils.importlib import import_module

class UserRestrictMiddleware(object):
    def process_request(self, request):
        """
        Checks if different session exists for user and deletes it.
        """
        if request.user.is_authenticated():
            cache = get_cache('default')
            cache_timeout = 86400
            cache_key = "user_pk_%s_restrict" % request.user.pk
            cache_value = cache.get(cache_key)

            if cache_value is not None:
                if request.session.session_key != cache_value:
                    engine = import_module(settings.SESSION_ENGINE)
                    session = engine.SessionStore(session_key=cache_value)
                    session.delete()
                    cache.set(cache_key, request.session.session_key,
                              cache_timeout)
            else:
                cache.set(cache_key, request.session.session_key, cache_timeout)


"""The helpers are helping."""
from contextlib import asynccontextmanager
from typing import AsyncIterator, Optional

from jupiter.core.framework.base.entity_id import EntityId
from jupiter.core.framework.use_case import (
    ContextProgressReporter,
    EmptyContext,
    EntityProgressReporter,
    MarkProgressStatus,
    ProgressReporterFactory,
)
from jupiter.core.use_cases.infra.use_cases import AppGuestUseCaseContext

class NoOpEntityProgressReporter(EntityProgressReporter):
    """A progress reporter that does nothing."""

    async def mark_not_needed(self) -> "NoOpEntityProgressReporter":
        """Mark the fact that a particular modification isn't needed."""
        return self

    async def mark_known_entity_id(
        self,
        entity_id: EntityId,
    ) -> "NoOpEntityProgressReporter":
        """Mark the fact that we now know the entity id for the entity being processed."""
        return self

    async def mark_known_name(self, name: str) -> "NoOpEntityProgressReporter":
        """Mark the fact that we now know the entity name for the entity being processed."""
        return self

    async def mark_local_change(self) -> "NoOpEntityProgressReporter":
        """Mark the fact that the local change has succeeded."""
        return self

    async def mark_remote_change(
        self,
        success: MarkProgressStatus = MarkProgressStatus.OK,
    ) -> "NoOpEntityProgressReporter":
        """Mark the fact that the remote change has completed."""
        return self

    async def mark_other_progress(
        self,
        progress: str,
        success: MarkProgressStatus = MarkProgressStatus.OK,
    ) -> "NoOpEntityProgressReporter":
        """Mark some other type of progress."""
        return self

class NoOpContextProgressReporter(ContextProgressReporter):
    """A progress reporter that does nothing."""

    @asynccontextmanager
    async def section(self, title: str) -> AsyncIterator[None]:
        """Start a section or subsection."""
        yield None

    @asynccontextmanager
    async def start_creating_entity(
        self,
        entity_type: str,
        entity_name: str,
    ) -> AsyncIterator[NoOpEntityProgressReporter]:
        """Report that a particular entity is being created."""
        yield NoOpEntityProgressReporter()

    @asynccontextmanager
    async def start_updating_entity(
        self,
        entity_type: str,
        entity_id: Optional[EntityId] = None,
        entity_name: Optional[str] = None,
    ) -> AsyncIterator[NoOpEntityProgressReporter]:
        """Report that a particular entity is being updated."""
        yield NoOpEntityProgressReporter()

    @asynccontextmanager
    async def start_archiving_entity(
        self,
        entity_type: str,
        entity_id: Optional[EntityId] = None,
        entity_name: Optional[str] = None,
    ) -> AsyncIterator[NoOpEntityProgressReporter]:
        """Report that a particular entity is being archived."""
        yield NoOpEntityProgressReporter()

    @asynccontextmanager
    async def start_removing_entity(
        self,
        entity_type: str,
        entity_id: Optional[EntityId] = None,
        entity_name: Optional[str] = None,
    ) -> AsyncIterator[NoOpEntityProgressReporter]:
        """Report that a particular entity is being removed."""
        yield NoOpEntityProgressReporter()

    @asynccontextmanager
    async def start_complex_entity_work(
        self,
        entity_type: str,
        entity_id: EntityId,
        entity_name: str,
    ) -> AsyncIterator["NoOpContextProgressReporter"]:
        """Create a progress reporter with some scoping to operate with subentities of a main entity."""
        yield NoOpContextProgressReporter()

class NoOpProgressReporterFactory(ProgressReporterFactory[AppGuestUseCaseContext]):
    """A noop progress reporter factory."""

    def new_reporter(self, context: AppGuestUseCaseContext) -> ContextProgressReporter:
        """Construct a new progress reporter that does nothing."""
        return NoOpContextProgressReporter()

class EmptyProgressReporterFactory(ProgressReporterFactory[EmptyContext]):
    """A noop progress reporter factory."""

    def new_reporter(self, context: EmptyContext) -> ContextProgressReporter:
        """Construct a new progress reporter that does nothing."""
        return NoOpContextProgressReporter()


from tan_algo import apply_tan_algo
from sacred.observers import MongoObserver
from sacred import Experiment
from cnp_algo import apply_cnp_algo

# for c=4 case, directly simulate, (without accessing the cache)
algo_ex = Experiment()

if not algo_ex.observers:
    algo_ex.observers.append(MongoObserver(
        url="localhost:27017", db_name="c2_appendix_res"))

@algo_ex.config
def config():
    seed = 6
    type = 0  # 0-CNP, 1-Tan, 2-Perturb

    queue_rule = "FIFO"
    # queue_rule = "LO-Out"
    # queue_rule = "FO-Free"
    berth_num = 2
    line_num = 12
    set_no = 99
    stop_setting = (queue_rule, berth_num, line_num, set_no)

    # signal
    signal_setting = None

    # algorithm
    if type == 0:
        sample_num_of_each_region = 10
        max_depth = 4
        sim_budget = 160
        algo_setting = (sim_budget, max_depth, sample_num_of_each_region)
    elif type == 1:
        radius = 0.05 if berth_num == 2 else None
        # Note PAY ATTENTION TO berth_num^n
        region_num = 24 if berth_num == 2 else berth_num ** 4
        algo_setting = (radius, region_num)

@algo_ex.automain
def main(algo_setting, stop_setting, signal_setting):
    if config()["type"] == 0:
        history_min_delays = apply_cnp_algo(
            algo_setting, stop_setting, signal_setting)
    else:
        history_min_delays = apply_tan_algo(
            algo_setting, stop_setting, signal_setting)

    algo_ex.info["history_min_delays"] = history_min_delays
    print(history_min_delays)


from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(1080, 879)
        self.gridLayout = QtWidgets.QGridLayout(Form)
        self.gridLayout.setObjectName("gridLayout")
        spacerItem = QtWidgets.QSpacerItem(5, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
        self.gridLayout.addItem(spacerItem, 3, 0, 1, 1)
        spacerItem1 = QtWidgets.QSpacerItem(20, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
        self.gridLayout.addItem(spacerItem1, 4, 1, 1, 1)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.graphic_Viewer = QtWidgets.QGraphicsView(Form)
        self.graphic_Viewer.setObjectName("graphic_Viewer")
        self.horizontalLayout.addWidget(self.graphic_Viewer)
        spacerItem2 = QtWidgets.QSpacerItem(10, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem2)
        self.widget = QtWidgets.QWidget(Form)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(1)
        sizePolicy.setHeightForWidth(self.widget.sizePolicy().hasHeightForWidth())
        self.widget.setSizePolicy(sizePolicy)
        self.widget.setMinimumSize(QtCore.QSize(251, 531))
        self.widget.setMaximumSize(QtCore.QSize(251, 531))
        self.widget.setObjectName("widget")
        self.label_6 = QtWidgets.QLabel(self.widget)
        self.label_6.setGeometry(QtCore.QRect(0, 90, 101, 21))
        font = QtGui.QFont()
        font.setFamily("FZMiaoWu")
        font.setPointSize(18)
        font.setBold(False)
        font.setWeight(50)
        self.label_6.setFont(font)
        self.label_6.setObjectName("label_6")
        self.label_7 = QtWidgets.QLabel(self.widget)
        self.label_7.setGeometry(QtCore.QRect(0, 210, 251, 20))
        self.label_7.setText("")
        self.label_7.setPixmap(QtGui.QPixmap("Equation1.png"))
        self.label_7.setScaledContents(True)
        self.label_7.setObjectName("label_7")
        self.ln_shower = QtWidgets.QCheckBox(self.widget)
        self.ln_shower.setEnabled(True)
        self.ln_shower.setGeometry(QtCore.QRect(160, 450, 61, 21))
        font = QtGui.QFont()
        font.setFamily("FZMiaoWu")
        font.setPointSize(16)
        self.ln_shower.setFont(font)
        self.ln_shower.setObjectName("ln_shower")
        self.acceptButton = QtWidgets.QPushButton(self.widget)
        self.acceptButton.setGeometry(QtCore.QRect(0, 490, 101, 31))
        font = QtGui.QFont()
        font.setFamily("FZMiaoWu")
        font.setPointSize(20)
        self.acceptButton.setFont(font)
        self.acceptButton.setObjectName("acceptButton")
        self.times_Adder = QtWidgets.QPushButton(self.widget)
        self.times_Adder.setGeometry(QtCore.QRect(140, 250, 81, 21))
        font = QtGui.QFont()
        font.setFamily("FZMiaoWu")
        font.setPointSize(16)
        self.times_Adder.setFont(font)
        self.times_Adder.setObjectName("times_Adder")
        self.arg2_Inputer = QtWidgets.QLineEdit(self.widget)
        self.arg2_Inputer.setGeometry(QtCore.QRect(0, 130, 241, 21))
        font = QtGui.QFont()
        font.setFamily("Helvetica")
        self.arg2_Inputer.setFont(font)
        self.arg2_Inputer.setObjectName("arg2_Inputer")
        self.label_8 = QtWidgets.QLabel(self.widget)
        self.label_8.setGeometry(QtCore.QRect(0, 170, 131, 21))
        font = QtGui.QFont()
        font.setFamily("FZMiaoWu")
        font.setPointSize(18)
        font.setBold(False)
        font.setWeight(50)
        self.label_8.setFont(font)
        self.label_8.setObjectName("label_8")
        self.label_9 = QtWidgets.QLabel(self.widget)
        self.label_9.setGeometry(QtCore.QRect(0, 450, 141, 20))
        font = QtGui.QFont()
        font.setPointSize(9)
        self.label_9.setFont(font)
        self.label_9.setText("")
        self.label_9.setPixmap(QtGui.QPixmap("Equation2.png"))
        self.label_9.setScaledContents(True)
        self.label_9.setObjectName("label_9")
        self.exitButton = QtWidgets.QPushButton(self.widget)
        self.exitButton.setGeometry(QtCore.QRect(140, 490, 101, 31))
        font = QtGui.QFont()
        font.setFamily("FZMiaoWu")
        font.setPointSize(20)
        self.exitButton.setFont(font)
        self.exitButton.setObjectName("exitButton")
        self.times_selector = QtWidgets.QSpinBox(self.widget)
        self.times_selector.setGeometry(QtCore.QRect(20, 250, 81, 21))
        font = QtGui.QFont()
        font.setFamily("Helvetica")
        self.times_selector.setFont(font)
        self.times_selector.setObjectName("times_selector")
        self.arg1_Inputer = QtWidgets.QLineEdit(self.widget)
        self.arg1_Inputer.setGeometry(QtCore.QRect(0, 50, 241, 20))
        font = QtGui.QFont()
        font.setFamily("Helvetica")
        self.arg1_Inputer.setFont(font)
        self.arg1_Inputer.setObjectName("arg1_Inputer")
        self.label_10 = QtWidgets.QLabel(self.widget)
        self.label_10.setGeometry(QtCore.QRect(0, 10, 101, 21))
        font = QtGui.QFont()
        font.setFamily("FZMiaoWu")
        font.setPointSize(18)
        font.setBold(False)
        font.setWeight(50)
        self.label_10.setFont(font)
        self.label_10.setObjectName("label_10")
        self.scrollArea = QtWidgets.QScrollArea(self.widget)
        self.scrollArea.setGeometry(QtCore.QRect(0, 290, 241, 141))
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 239, 139))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.horizontalLayout.addWidget(self.widget)
        self.gridLayout.addLayout(self.horizontalLayout, 1, 1, 1, 1)
        self.logBrowser = QtWidgets.QTextBrowser(Form)
        font = QtGui.QFont()
        font.setFamily("FZMiaoWu")
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.logBrowser.setFont(font)
        self.logBrowser.setObjectName("logBrowser")
        self.gridLayout.addWidget(self.logBrowser, 3, 1, 1, 1)
        spacerItem3 = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
        self.gridLayout.addItem(spacerItem3, 2, 1, 1, 1)
        spacerItem4 = QtWidgets.QSpacerItem(20, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
        self.gridLayout.addItem(spacerItem4, 0, 1, 1, 1)
        spacerItem5 = QtWidgets.QSpacerItem(5, 20, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
        self.gridLayout.addItem(spacerItem5, 1, 2, 1, 1)

        self.retranslateUi(Form)
        self.exitButton.clicked.connect(Form.close)
        QtCore.QMetaObject.connectSlotsByName(Form)

        #handly add a layout in scrollArea, should be change in *.ui in the future.
        # self.scrollAreaLayout = QtWidgets.QGridLayout(self.scrollArea)

        #not use GridLayout
        self.scrollFiller = QtWidgets.QWidget(self.scrollArea)
        self.scrollFiller.setMinimumSize (1200, 1200 )

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label_6.setText(_translate("Form", "Input Arg2:"))
        self.ln_shower.setText(_translate("Form", "Show"))
        self.acceptButton.setText(_translate("Form", "Accept"))
        self.times_Adder.setText(_translate("Form", "Add"))
        self.arg2_Inputer.setText(_translate("Form", "0.89, 0.91, 0.94, 0.96, 0.99, 1.0, 1.03, 1.06, 1.08, 1.11, 1.14, 1.16, 1.18, 1.2"))
        self.label_8.setText(_translate("Form", "Fitting Type:"))
        self.exitButton.setText(_translate("Form", "Exit"))
        self.arg1_Inputer.setText(_translate("Form", "450, 500, 560, 630, 710, 800, 900, 1000, 1120, 1250, 1400, 1600, 1800, 2000"))
        self.label_10.setText(_translate("Form", "Input Arg1:"))
        self.logBrowser.setHtml(_translate("Form", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<meta name=\"qrichtext\" content=\"1\" />\n"
"

"))


import itertools
import numpy as np
import matplotlib.pyplot as plt

from sklearn import svm, datasets
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix

def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.PuRd):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if normalize:
        cm = cm.astype(int) / cm.sum(axis=1)[ :,np.newaxis]
        #cm = cm.astype(int) / cm.sum(axis=1)[ :, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')
    #print(cm);
    plt.imshow(100*cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    #pcl=plt.colorbar()
    #pcl.set_label('F1-score (%)', rotation=270)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=30,fontsize=25)
    plt.yticks(tick_marks, classes,fontsize=25)
    fmt = 'd' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format((100*cm[i, j]).astype(int), fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")
    plt.tight_layout()
    #plt.annotate('%', xy=(.5, .5))
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    #plt.rcParams["font.size"] = "18"


from django.views.generic import TemplateView
from recipe.models import Recipe

class IndexTemplateView(TemplateView):
    template_name = "index.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        try:
            context['recipe_top'] = Recipe.objects.order_by('?')[0]
        except IndexError:
            context['recipe_top'] = None

        context['recipe_list'] = Recipe.objects.order_by("-created")

        return context


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

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

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('blog', '0007_auto_20150715_1622'),
    ]

    operations = [
        migrations.CreateModel(
            name='Comments',
            fields=[
                ('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),
                ('comment', models.CharField(max_length=255, verbose_name='Комментарий')),
                ('created_at', models.DateTimeField(verbose_name='Создан', auto_now_add=True)),
                ('author', models.ForeignKey(verbose_name='Автор', to=settings.AUTH_USER_MODEL)),
                ('post', models.ForeignKey(verbose_name='Пост', to='blog.Post')),
            ],
            options={
                'verbose_name': 'Комментарий',
                'verbose_name_plural': 'Комментарии',
                'ordering': ['-created_at'],
            },
        ),
    ]


from pyspark import SparkContext, SparkConf
import collections
import re

def normalize_text(text):
    words = re.compile(r'\W+', re.UNICODE).split(text.lower())
    return words

conf = SparkConf().setMaster("local").setAppName("Word-Count-the-hard-but-right-way-using-spark")
sc = SparkContext(conf = conf)

rdd_lines = sc.textFile("file:/Users/pk/Documents/Studies/selflearn/gitspark/exercise4/Book.txt")
words = rdd_lines.flatMap(normalize_text)

# instead of using conntByValue() use map and reduceByKey to find frequency
temp = words.map(lambda x: (x, 1)).reduceByKey(lambda x,y: x + y)
#temp1 = temp.reduceByKey(lambda x,y: x + y)

# Now to easily browse the most frequent and least frequent words at a  glance

sorted_res = temp.map(lambda x: (x[1], x[0])).sortByKey()
results = sorted_res.collect()

for result in results:
    print(""+result[1] + " : " + str(result[0]))


import math
import urllib
from netaddr import IPSet, IPNetwork, cidr_merge
import requests
import urllib.request
country_code="TR"

download_url = "ftp://ftp.ripe.net/pub/stats/ripencc/delegated-ripencc-latest"
with urllib.request.urlopen(download_url) as r:
    data = r.readlines()

data_list=[]
for item in data:
	data_list.append(item.decode("utf-8"))

ip_list =[]
for line in data_list:
	if (('ipv4' in line) & (country_code in line)):
			s=line.split("|")
			net=s[3]
			cidr=float(s[4])
			ip = "%s/%d" % (net,(32-math.log(cidr,2)))
			ip_list.append(IPNetwork(ip))
cidr_merge(ip_list)
for ip_network in ip_list:
	print (str(ip_network))


def ini(num):
	a=[]
	for i in range(1,num+1):
		a.append(i)
	return a

def finale(list):
	empti = []
	if (len(list)) == 1:
		return list
	else:
		if (len(list)) % 2 == 0:
			del_bool = False
		else:
			del_bool = True

		for i in range(0,(len(list))):
			if (i % 2) == 1:
				empti.append(list[i])

		for q in empti:
			list.remove(q)
		if del_bool == True:
			del list[0]
	return finale(list)