"""
Converts a pnml file to a graphml graph file. See example.pnml for an example of the pnml format.
This script converts a pnml petrinet with places, transitions, and arcs into our target graph format.
(The nomenclature: in pnml 'places' and 'transitions' are like graph nodes, and 'arcs' are edges.)
We want the ground-truth sequential model of the process, which has no places, only edges between transitions (activities).
So only the arc and transition data is useful; the 'place' data and other pnml data is irrelevant or just provides
structural info. 'Places' are essentially resolved: if P is a place, and given the edge set {A->P, P->B}, this
simplifies to {A->B}.

The output of this script is a graphml-formatted graph for which the nodes represent activities, the edges represent sequential
transitions between activities, and the graph has a START and END node representing the entry/exit points of the overall model.

TODO: May need to provide a visual for the presumed mapping between pnml data and our target graphml structure, for
documentation and research purposes.

So far the idea is to have the data generator generate traces, which are then defined in XES, parsed by an external
process discovery tool whose output is a pnml file defining the ground-truth model given by the traces, according to that
algorithm. This pnml must be converted to graphml so we can read in the graph and walk it, to generate the mini-graphs
as input to SUBDUE.
"""

from __future__ import print_function
import igraph
import platform
import sys
import xml.etree.ElementTree as ET
import os

"""
Given a list of arcs in the form (src<int>, dest<int>) and a vertexDict of <int,string>,
and a filter string, this removes all edges connected to vertices containing the filter string (eg, 'PLACE_').
The resolution procedure then sutures all input edges and output edges from the removed nodes. So logically
is A,B,C have in-links to D, and D has outlinks to E,F,G, and if the filter-string is 'D', then D will be removed
and replaced by direct links from A,B,C to E,F,G.

def _resolveEdges(arcs, vertexDict, filterString):
	placeIds = [pId for pId in vertexDict if filterString in vertexDict[pId]]
	for pId in placeIds:
		#get all outlinked nodes from this place
		outLinkNodes = [arc[1] for arc in arcs if arc[0] == pId]
		#get all inlinked nodes to this place
		inLinkNodes = [arc[0] for arc in arcs if arc[1] == pId]
		#remove all the arcs containing this pId as src or dst
		arcs = [arc for arc in arcs if (pId != arc[0] and pId != arc[1])]
		#add the in-out nodes back in
		for outNode in outLinkNodes:
			for inNode in inLinkNodes:
				arcs.append((inNode,outNode))
	return arcs
"""
"""
OBSOLETE: converted to bfs, below, for more safety

A recursive utility for getting all activities attached to a given set of outlinks.

An outlink leads to a place, tau-split, or an activity node. So think of an outlink as a graph
edge that can split at multiple points, like branches to flowers. The flowers are the activities.
Hence this retrieves all activities at the end of some branch, also detecting cycles (should not happen).

Cycles should not occur, since our process-graph definition does not allow self-loops, and this only
goes to the first set of nodes.

@outLinks: The immediate outlinks of a node
@arcs: List of tuples representing node ids
@vertexDict: the dict of id keys and string vertex names
@d: current call depth, for bounding search if cycling

Returns: The ids of the activities at the terminal points of these outlinks

def _getSuccessorActivityIds(outLinks,arcs,vertexDict,d=0):
	activities = []
	bound = 40

	#recursion depth check: probably cycling
	if d > bound:
		print("WARNING Recursive depth-bound of "+str(bound)+" struck in _getSuccessorActivityIds() of Pnml2Graphml.py!")
		return []

	#get all activities at the terminal points of these outlinks
	for outLink in outLinks:
		#if this link leads to a place or a tau node, get the outlinks from that node and recurse on them
		if "TAU_" in vertexDict[outLink[1]] or "PLACE_" in vertexDict[outLink[1]]:
			#get all the outlinks of this successor, and recurse on them
			successorLinks = [arc for arc in arcs if arc[0] == outLink[1]]
			activities += _getSuccessorActivityIds(successorLinks, arcs, vertexDict,d+1)
		#else the success is just a regular place, so add it to list
		else:
			activities.append(outLink[1])

	return activities
"""
"""
BFS version of prior function, which is much safer/clearer vs recursion.
This relies on distinguishing activity nodes from places/transitions, which is done
by checking for 'TAU' or "PLACE" in the node name.

Returns: The activity names of all activities immediately reachable from some node, given its outLinks. Graphs
are cyclic, so note that 'reachable' may include upstream nodes. This function basically just dissolves the place/transition
junk in between activities.

@outLinks: The outlinks of a given node
@arcs: The full set of links given by the pnml model
@vertexDict: the dict of id keys and string vertex names
"""
def _getSuccessorActivityIdsBFS(outLinks, arcs, vertexDict):

	successorIds = set()
	frontier = [arc[1] for arc in outLinks]
	visitedIds = set()

	while len(frontier) > 0:
		#pop front
		curId = frontier[0]
		frontier = frontier[1:]

		nodeName = vertexDict[curId]
		#if this id represents a place or tau construct, add dest ids of its outlinks to q, if not visited
		if "TAU_" in nodeName or "PLACE_" in nodeName:
			#get all dest ids of this node's outlinks
			outLinkIds = [arc[1] for arc in arcs if arc[0] == curId]
			#filter visited id's
			outLinkIds = [id for id in outLinkIds if id not in visitedIds]
			#add any ids to frontier
			if len(outLinkIds) > 0:
				frontier = frontier + outLinkIds
		else: #else this is a base successor (activity node), so add the id to activities, and ignore its successors
			successorIds.add(curId)

		#add this id to visited set
		visitedIds.add(curId)

	return successorIds

"""
Utility for converting pnml format file into a graphml structure for easier transmission and storage.

See pnml.jpg in this directory for an example visual of the relationship between taus, places, transitions, etc,
upon which this code is based.

@pnmlPath: Path to a pnml file
@opath: Path to the output location for the graphml representation of the pnml
"""
def Convert(pnmlPath):
	print("Converting graph. Be aware this script only resolves transitions separated by a single place, non-recursively.")
	print("It does not currently resolve consecutive places, if that is a valid construct given in some input petri net.")

	#The following algorithm
	#read the pnml data
	root = ET.parse(pnmlPath).getroot()
	netName = root.find("./net/name/text").text
	vertexDict = {} #vertices are stored temporarily as {id : text}
	places = {} #places are stored as vertices; they are only stored for the purposes of factoring them out of the final graph
	arcs = [] #pnml arcs are stored as a list of tuples, (sourceId<string>, targetId<string>)
	edges = [] #the output edge list for the igraph object

	#store the transitions, which will be a mix of 'tau' constructs and actual activities (eg, "register patient", "discharge patient", etc)
	for t in root.findall('./net/page/transition'):
		vId = t.get('id')
		vName = t.find('./name/text').text
		if 'tau' in vName.lower():
			vName = 'TAU_' + vName #mark tau nodes for detection later
		vertexDict[vId] = vName

	#add places to the vertex set, labelling them as "PLACE" for later identification
	for p in root.findall('./net/page/place'):
		pId = p.get('id')
		pName = 'PLACE_'+p.find('./name/text').text
		vertexDict[pId] = pName

	#parse the edge data from the petrinet
	for e in root.findall('./net/page/arc'):
		source = e.get('source') #these are the text-based node-ids, corresponding with the keys in the vertex dict
		target = e.get('target')
		arcs.append((source,target))

	#get the start node id (a source: vertex with no in-links)
	""" #This method fails
	startIds = []
	inlinks = [arc[1] for arc in arcs]
	for vId in vertexDict:
		if vId not in inlinks:
			startIds.append(vId)
	if len(startIds) != 1:
		#detect if more than one start node, which is a structurally defective graph/pnml, and should never happen
		print("WARNING len(startIds) != 1, is "+str(len(startIds))+" in Pnml2Graphml. See code. "+str(startIds))

		This warning is a result of a defect with the pnml format, or rather with my relying on it (is there another graph format we could use as output of the process miner?)
		Pnml files have provide no topological description of the start node in a process; they only have a visually 'leftmost' node.
		As a result, the graphs (especially if noise is added to a log) must always contain a defined start/end node.
		Consider multiple paths to resolve:
			1) pnml parsing logic (not clear how, since the pnml format doesn't provide a definition of start/end node)
			2) change to a different process output file type (dont know which exist)

	#get the end node ids (a sink: vertex with no outlinks)
	endIds = []
	outlinks = [arc[0] for arc in arcs]
	for vId in vertexDict:
		if vId not in outlinks:
			endIds.append(vId)
	if len(endIds) != 1:
		#detect if more than one start node, which is a structurally defective graph/pnml, and should never happend
		print("WARNING len(endIds) != 1, is "+str(len(endIds))+" in Pnml2Graphml. See code.")
	endNodeId = endIds[0]
	"""
	#gets the start node a priori, from the <initialMarking> pnml tag, of which I'm assuming there is always just one for my models
	startIds = []
	for p in root.findall('./net/page/place'):
		imChild = p.find("./initialMarking/text")
		if imChild is not None and "1" in imChild.text:
			#print("FOUND INITIAL MARKER NODE: "+p.attrib["id"])
			startIds.append(p.attrib["id"])
	if len(startIds) != 1:
		print("ERROR len startIds != 1 in  Pnml2Graphml: "+str(len(startIds))+" ids: "+str(startIds))
	startNodeId = startIds[0]

	#warn of unexpected structure: if detected, this is serious, and at least needs to be evaluated by looking at the pnml file and understanding why there is more than one finalmarkings tag
	markingCt = len(root.findall('./net/finalmarkings'))
	if markingCt > 1:
		print("WARNING: finalmarkings len "+str(markingCt))

	#get the end node id from the finalMarkings collection
	endIds = []
	for p in root.findall('./net/finalmarkings/marking/place'):
		imChild = p.find("./text")
		if imChild is not None and "1" in imChild.text:
			#print("FOUND FINAL MARKER NODE: "+p.attrib["idref"])
			endIds.append(p.attrib["idref"])
	if len(endIds) != 1:
		#detect if more than one start node, which is a structurally defective graph/pnml, and should never happend
		print("WARNING len(endIds) != 1, is "+str(len(endIds))+" in Pnml2Graphml. See code.  Ids: "+str(endIds))
	endNodeId = endIds[0]

	#re-mark the end and start node text; currently they are TAU_ or PLACE_ typed
	#start with a critical error check; this algorithm REQUIRES the final node detected above is not an activity, hence only a transition or a place.
	if "TAU_" not in vertexDict[startNodeId] and "PLACE_" not in vertexDict[startNodeId]:
		print("ERROR start node not TAU or PLACE see code")
	if "TAU_" not in vertexDict[endNodeId] and "PLACE_" not in vertexDict[endNodeId]:
		print("ERROR end node not TAU or PLACE see code")
	vertexDict[startNodeId] = "START"
	vertexDict[endNodeId] = "END"

	#get all activities (all non-Tau transitions)
	activities = [vertexDict[vId] for vId in vertexDict if "PLACE_" not in vertexDict[vId] and "TAU_" not in vertexDict[vId]]
	#print("Activities: "+str(activities))
	#print("Vertex dict: "+str(vertexDict))

	#bfs from START node: build an edge list (srcName,dstName) of all edges, such that the edges are between valid activities (non-Tau pnml-transitions)
	edgeList = []
	visited = []
	frontier = [startNodeId]
	while len(frontier) > 0:
		#pop first node on frontier list
		curNodeId = frontier[0]
		frontier = frontier[1:]

		if curNodeId not in visited:
			#get all immediate outlinks from this node
			outLinks = [arc for arc in arcs if arc[0] == curNodeId]
			#recursively get all activity node ids to which these outlinks point (following all intermediate taus, places, etc)
			#successors = _getSuccessorActivityIdsBFS(outLinks,arcs,vertexDict, d=0)
			#bfs successor getter
			successors = _getSuccessorActivityIdsBFS(outLinks,arcs,vertexDict)
			#print(str(successors))

			for successor in successors:
				#expand frontier with unvisited nodes
				if successor not in visited:
					frontier.append(successor)  #note, frontier is only appended with activity ids
				#add link between nodes
				edgeList.append((vertexDict[curNodeId], vertexDict[successor]))

		#add current node to visited list
		visited.append(curNodeId)

	#activities += ["START","END"]
	#build the igraph graph object. Igraph is just used to serialize the graph to graphml.
	graph = igraph.Graph(directed=True)
	#finally, add the filtered graph structure vertices and edges to an igraph
	graph.add_vertices(activities)
	graph.add_edges(edgeList) #edges is a sequence of vertex name tuples (source,target). Conveniently, you can pass either name tuples of id tuples to add_edges
	#print("edges: "+str(edgeList))

	#store the activity as both the node name and 'label' attribute
	graph.vs["label"] = [v["name"] for v in graph.vs]

	#name the graph
	if len(netName) > 0:
		graph["name"] = netName
	else:
		graph["name"] = "mined-process"

	return graph

"""
Plotting, for visual analysis.
"""
def ShowGraph(graph,opath):
	#the sugiyama layout tends to have the best layout for a cyclic, left-to-right graph, if imperfect
	layout = graph.layout("sugiyama")
	layout = graph.layout("kk") #options: kk, fr, tree, rt
	#see: http://stackoverflow.com/questions/24597523/how-can-one-set-the-size-of-an-igraph-plot
	igraph.plot(graph, opath.replace(".graphml",".png"), layout = layout, bbox = (1000,1000), vertex_size=35, vertex_label_size=15)
	#igraph.plot(graph, layout = layout, bbox = (1000,1000), vertex_size=35, vertex_label_size=15)
	#igraph.plot(graph, bbox = (1000,1000), vertex_size=35, vertex_label_size=5,label="name")

def usage():
	print("Usage: python Pnml2Graphml.py [input file] [output path for graphml file] [optional: --show to show the graph]")

#print(str(sys.argv))
if len(sys.argv) < 3:
	print("ERROR incorrect number of arguments passed to Pnml2Graphml.py. Exiting.")
	usage()
	exit()

ipath = sys.argv[1]
opath= sys.argv[2]

print("Converting pnml at "+ipath+" to output graphml at "+opath+" from pwd "+os.getcwd())
transitionGraph = Convert(ipath)

if "--show" in sys.argv:
	ShowGraph(transitionGraph,opath)

#defensive programming on windows, for which write_graphml currently breaks (likely this is because of a precompiled exe install of igraph or its components)
if "windows" in platform.system().lower():
	try:
		transitionGraph.write_graphml(opath) #this crashes Python 3.5 under windows with igraph precompiled binaries
	except Exception as e: print(e)  #maybe this will save us? maybe not
else:
	transitionGraph.write_graphml(opath) #this crashes Python 3.5 under windows with igraph precompiled binaries
print("Pnml to graphml conversion complete.")
#print(str(transitionGraph))


# 2170 선 긋기(G5)
# https://www.acmicpc.net/problem/2170
# 정답

import sys

input = sys.stdin.readline
n = int(input())
lst = [[*map(int, input().split())] for _ in range(n)]
lst.sort()
pe = -1000000000
ans = 0
for s, e in lst:
    if e <= pe:
        continue
    small = pe if s < pe else s
    ans += e - small
    pe = max(pe, e)
print(ans)

# 앞쪽을 기준으로 정렬한다.
# 하나하나 살펴가면서 이전 선분과 현재 선분이 겹치는지 확인한다
# 겹치면 ? 겹친 부분만큼 정답에서 빼준다
# 안 겹치면 ? 정답에 그냥 다 더한다
# 이때 겹치는 게 완전히 포함하는 관계일 수도 있음을 유의한다

# 시간 초과가 잘 난다.
# 우선순위큐는 시간초과.


from engine.piece.piece import Piece as p

class King(p):

    def __init__(self, team):
        self.team = team
        self.is_rockable = True
        if(team == 1):
            self.pos = [3, 0]
        else:
            self.pos = [3, 7]

    def is_legal(self, board, pos):
        if(not super().is_legal(pos)): # If not in board
            return False
        board_list = board.get_board()
        for i in range (0, 8):
            for j in range (0, 8):
                if(board_list[i][j] != None and board_list[i][j].team != self.team):
                    attacking =  board_list[i][j].get_attacking_pos(board)
                    if(attacking):
                        for e in  attacking:
                            if(e[0] == pos[0] and e[1] == pos[1]):
                                return False
        return True

    # Get possible next move
    def get_playable_pos(self, board):
        pos_list = []
        for i in range (-1, 2):
            for j in range (-1, 2):
                if(self.is_legal(board, [self.pos[0] + i, self.pos[1] + j])):
                    pos_list.append([self.pos[0] + i, self.pos[1] + j])
                    print(i, j)
        return pos_list

    def is_promo(self, board, pos):
        return False

    def get_attacking_pos(self, board):
        pos_list = []
        board_list = board.get_board()
        for i in range (0, 3):
            for j in range (0, 3):
                if(self.is_legal(board, [self.pos[0] + i, self.pos[1] + j]) and board_list[i][j]):
                    pos_list.append([i, j])
                    print(i, j)
        return pos_list

    def is_check(self, board):
        print("King check is_check")
        board_list = board.get_board()
        for i in range (0, 8):
            for j in range (0, 8):
                if(board_list[i][j] != None and board_list[i][j].team != self.team):
                    if (board_list[i][j].get_attacking_pos(board) != None):
                        for e in  board_list[i][j].get_attacking_pos(board):
                            if(e[0] == self.pos[0] and e[1] == self.pos[1]):
                                return True
                    else:
                        if(e[0] == self.pos[0] and e[1] == self.pos[1]):
                                return True
        return False

    def is_playable(self, board, pos):
        playable_pos = self.get_playable_pos(board)
        for e in playable_pos:
            if(e == pos):
                return True
        return False

    def get_type(self):
        return "K"

    def play(self, board, pos):
        if (self.is_legal(board, pos)):
            self.pos = pos
            return True
        return False


import itertools

def combinationSum3(k: int, n: int) -> List[List[int]]:
    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    combos = itertools.combinations(nums, k)
    result = []
    for c in combos:
        if sum(c) == n:
            result.append(c)

    return result

def combinationSum3Bactrack(k, n):
    result = []
    def backtrack(remain, combo, next_start):
        if remain == 0 and len(combo) == k:
            result.append(list(combo))
            return
        elif remain < 0 or len(combo) == k:
            return
            # no match was found
        for i in range(next_start, 9):
            combo.append(i+1)
            backtrack(remain-i-1, combo, i+1)
            combo.pop()
    backtrack(n, [], 0)
    return result


from django import forms

from .methods import get_next_state, is_mediacms_editor
from .models import Media, Subtitle

class MultipleSelect(forms.CheckboxSelectMultiple):
    input_type = "checkbox"

class MediaForm(forms.ModelForm):
    new_tags = forms.CharField(label="Tags", help_text="a comma separated list of new tags.", required=False)

    class Meta:
        model = Media
        fields = (
            "title",
            "category",
            "new_tags",
            "add_date",
            "uploaded_poster",
            "description",
            "state",
            "enable_comments",
            "featured",
            "thumbnail_time",
            "reported_times",
            "is_reviewed",
            "allow_download",
        )
        widgets = {
            "tags": MultipleSelect(),
        }

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(MediaForm, self).__init__(*args, **kwargs)
        if self.instance.media_type != "video":
            self.fields.pop("thumbnail_time")
        if not is_mediacms_editor(user):
            self.fields.pop("featured")
            self.fields.pop("reported_times")
            self.fields.pop("is_reviewed")
        self.fields["new_tags"].initial = ", ".join([tag.title for tag in self.instance.tags.all()])

    def clean_uploaded_poster(self):
        image = self.cleaned_data.get("uploaded_poster", False)
        if image:
            if image.size > 5 * 1024 * 1024:
                raise forms.ValidationError("Image file too large ( > 5mb )")
            return image

    def save(self, *args, **kwargs):
        data = self.cleaned_data
        state = data.get("state")
        if state != self.initial["state"]:
            self.instance.state = get_next_state(self.user, self.initial["state"], self.instance.state)

        media = super(MediaForm, self).save(*args, **kwargs)
        return media

class SubtitleForm(forms.ModelForm):
    class Meta:
        model = Subtitle
        fields = ["language", "subtitle_file"]

    def __init__(self, media_item, *args, **kwargs):
        super(SubtitleForm, self).__init__(*args, **kwargs)
        self.instance.media = media_item

    def save(self, *args, **kwargs):
        self.instance.user = self.instance.media.user
        media = super(SubtitleForm, self).save(*args, **kwargs)
        return media

class ContactForm(forms.Form):
    from_email = forms.EmailField(required=True)
    name = forms.CharField(required=False)
    message = forms.CharField(widget=forms.Textarea, required=True)

    def __init__(self, user, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        self.fields["name"].label = "Your name:"
        self.fields["from_email"].label = "Your email:"
        self.fields["message"].label = "Please add your message here and submit:"
        self.user = user
        if user.is_authenticated:
            self.fields.pop("name")
            self.fields.pop("from_email")


import requests
from bs4 import BeautifulSoup
query = input ("search for ... ")
url= "https://www.bing.com/search?q=" + query
print(url)
data= requests.get(url)
print(data)
soup= BeautifulSoup(data.content,"html.parser")
ResponseData=soup.find_all("li",{'class':'b_algo'})
#print(ResponseData[0].text)
for result in ResponseData :
	print(result.text)
	print(" ")


# Tools for working with TRANSP ion distributions.
# ------------------------------------------------------

import os

from netCDF4 import Dataset
import numpy as np
from scipy.interpolate import griddata, RectBivariateSpline, interp1d

import sampler

class Thermal:

    def __init__(self, transp_output, ion='D'):

        self.transp_output = transp_output
        self.step = transp_output.step
        self.ion = ion.upper()
        self.pop = 'BULK'      # type of population

        # Time window
        self.t0 = transp_output.t0
        self.t1 = transp_output.t1

        # Volume elements
        dV = transp_output.get_variable('DVOL')
        dV[1] = dV[1]/1e6     # m^-3

        self.dV = dV
        self.V = dV[1].sum()

        # Temperature and density profiles
        T = transp_output.get_variable('TI')

        if self.ion == 'D':
            n = transp_output.get_variable('ND')
        if self.ion == 'T':
            n = transp_output.get_variable('NT')
        if self.ion == '3HE':
            n = transp_output.get_variable('NHE3')

        T[1] = T[1] / 1e3    # keV
        n[1] = n[1] * 1e6    # m^-3

        self.n_max = n[1].max()

        self.T = T
        self.n = n

        self.n_interp = interp1d(n[0], n[1], fill_value='extrapolate')

        # Rotation
        omega = transp_output.get_variable('OMEGA')
        if omega != -1:
            self.omega = omega
        else:
            self.omega = None

        # Numer of particles in each volume element
        self.N_vol = self.n[1]*self.dV[1]
        self.N_vol_interp = interp1d(n[0], self.N_vol, fill_value='extrapolate')
        self.N_vol_max = self.N_vol.max()

        # Total number of particles in the distribution
        self.N = np.sum(self.N_vol)

    def __repr__(self):
        return 'TRANSP thermal {} dist from {}'.format(self.ion, self.transp_output.out_file)

    def get_density(self, R, Z):

        X = self.transp_output.get_rho(R, Z)

        #n = np.interp(X, self.n[0], self.n[1], right=0)
        n = self.n_interp(X)
        n[X>1.0] = 0

        return n

    def get_N_vol(self, R, Z):

        X = self.transp_output.get_rho(R, Z)

        N_vol = self.N_vol_interp(X)
        N_vol[X>1.0] = 0.0

        return N_vol

    def get_temperature(self, R, Z):

        X = self.transp_output.get_rho(R, Z)

        T = np.interp(X, self.T[0], self.T[1], right=0)

        return T

    def get_rotation(self, R, Z):

        if self.omega is None:
            vrot =  np.zeros_like(R)
        else:
            X = self.transp_output.get_rho(R, Z)

            omega = np.interp(X, self.omega[0], self.omega[1], right=0)     # rad/s
            vrot = omega * R       # m/s

        return vrot

    def sample(self, n_samples=None, R=None, Z=None):
        """
        Sample from the distribution. Must input either 'n_samples',
        (in which case the positions are sampled), or both 'R' and 'Z',
        (in which case energy and pitch are sampled at the correspoinding positions).
        """

        if (R is None) and (Z is None):
            sample_pos = True

            # Draw random positions
            Rmin = self.transp_output.R.min()
            Rmax = self.transp_output.R.max()
            Zmin = self.transp_output.Z.min()
            Zmax = self.transp_output.Z.max()
            lims = ([Rmin, Zmin], [Rmax, Zmax])

            s = sampler.sample_acc_rej(self.get_N_vol, lims, self.N_vol_max, n_samples)

            R = s[:,0]
            Z = s[:,1]
        else:
            sample_pos = False
            n_samples = len(R)

        # The (kinetic) energy is distributed as a chi2 variable with 3 degrees of freedom
        T = self.get_temperature(R, Z)
        E = np.random.chisquare(3, size=n_samples) * 0.5 * T

        # Pitch distribution is isotropic
        p = sampler.sample_uniform([-1,1], n_samples)

        if sample_pos:
            return R, Z, E, p
        else:
            return E, p

    def __call__(self, R, Z, E, p):
        """ Evaluate the distribution at the given point(s). """

        T = self.get_temperature(R,Z)
        n = self.get_density(R,Z)

        f = n*np.sqrt(E/np.pi)*T**(-1.5)*np.exp(-E/T)

        return f

class FBM:

    def __init__(self, transp_output, ion='D', pop='NBI', jdotb=None):

        self.transp_output = transp_output

        step = transp_output.step

        if step is None:
            raise ValueError('Invalid time step!')

        self.step = step

        self.ion = ion.upper()
        self.pop = pop.upper()

        suffix = self.ion + '_' + self.pop

        # Set default sampling method for EP distributions
        self.EP_sampling_method = 'acc_rej'

        # Open the FBM netCDF file
        fbm_cdf = transp_output._openfbm()

        # Time window
        self.t0 = transp_output.t0
        self.t1 = transp_output.t1

        # Extract the distribution data
        self.X  = fbm_cdf.variables['X2D'][:]
        self.TH = fbm_cdf.variables['TH2D'][:]
        self.R  = fbm_cdf.variables['R2D'][:] / 100
        self.Z  = fbm_cdf.variables['Z2D'][:] / 100

        self.index = np.arange(len(self.X))

        self.dV = fbm_cdf.variables['BMVOL'][:] / 1e6    # m^-3
        self.V = np.sum(self.dV)

        # Read fast ion distribution
        self.F = fbm_cdf.variables['F_{}'.format(suffix)][:] / 2.0 * 1000.0 * 1e6

        self.E  = fbm_cdf.variables['E_{}'.format(suffix)][:] / 1000.0
        self.A  = fbm_cdf.variables['A_{}'.format(suffix)][:]
        self.EB = fbm_cdf.variables['EB_{}'.format(suffix)][:] / 1000.0
        self.AB = fbm_cdf.variables['AB_{}'.format(suffix)][:]
        self.dE = np.diff(self.EB)
        self.dA = np.diff(self.AB)

        if jdotb is None:
            self.jdotb = int(fbm_cdf.variables['nsjdotb'][:])
        else:
            self.jdotb = int(jdotb)

        if self.jdotb == -1:
            # Negate and flip pitch axis in order to always have
            # pitch values given relative to the B-field.
            self.F = self.F[:, ::-1, :]
            self.A = -self.A[::-1]

        # Make interpolants for the (E,p) distributions in each spatial zone
        self.F_Ep = []
        self.F_Ep_max = np.zeros_like(self.X)

        for i in range(len(self.X)):
            F = RectBivariateSpline(self.E, self.A, self.F[i].T, kx=1, ky=1)
            self.F_Ep.append(F)

            # Also store maximum distribution value at each point,
            # in order to know suitable sampling regions later.
            self.F_Ep_max[i] = self.F[i].max()

        self.Emin = self.E[0]
        self.Emax = self.E[-1]
        self.pmin = -1
        self.pmax = 1

        # Calculate fast ion density at each grid point
        dE = self.dE
        dA = self.dA
        self.n = np.sum( np.sum(self.F*dE, axis=-1) *dA, axis=-1 )   # m^-3
        self.n_max = self.n.max()

        self.Rmin = self.R.min()
        self.Rmax = self.R.max()
        self.Zmin = self.Z.min()
        self.Zmax = self.Z.max()

        # Number of particles in each volume element
        self.N_vol = self.n * self.dV
        self.N_vol_max = self.N_vol.max()

        # Total number of particles in the distribution
        self.N = np.sum(self.n * self.dV)

        # Integrate distribution over RZ plane
        # (this factor can be handy for normalizing MC calculations)
        self.C_RZ = np.sum(self.n * self.dV/(2*np.pi*self.R))

        # Prepare for inverse CDF sampling
        dAdE = dA[None,:,None] * dE[None,None,:]          # phase space volume elements
        Ptab = self.F * dAdE
        self.Ptab = Ptab.reshape(len(self.X), len(self.E)*len(self.A))   # 1D tables of probabilities
        self.Ctab = np.cumsum(self.Ptab, axis=-1)

        Egrid, Agrid = np.meshgrid(self.E, self.A)
        self.Etab = Egrid.flatten()
        self.Atab = Agrid.flatten()

        self.i_tab = np.arange(len(self.Etab))

    def __repr__(self):
        return 'TRANSP FBM {} {} dist from {}'.format(self.ion, self.pop, self.transp_output.fbm_files[self.step-1])

    def get_density(self, R, Z):
        X = self.transp_output.get_rho(R, Z)
        n = griddata((self.R, self.Z), self.n, (R,Z), method='nearest', fill_value=0)
        return np.where(X<1.0, n, 0.0)

    def get_N_vol(self, R, Z):
        X = self.transp_output.get_rho(R, Z)
        N_vol = griddata((self.R, self.Z), self.N_vol, (R,Z), method='nearest', fill_value=0)
        return np.where(X<1.0, N_vol, 0.0)

    def get_F_Ep(self, i_vol, E, p):
        F = np.zeros_like(E, dtype='d')

        valid_E = (E < self.Emax) & (E > self.Emin)
        valid_p = (p < self.pmax) & (p > self.pmin)
        valid = valid_E & valid_p

        F[valid] = self.F_Ep[i_vol](E[valid], p[valid], grid=False)

        return F

    def get_spatial_index(self, R, Z):

        # Map each R,Z value to the closest spatial grid point.
        i_spatial = griddata((self.R, self.Z), self.index, (R,Z), method='nearest')

        # Points outside the plasma should not get a valid index
        X = self.transp_output.get_rho(R, Z)
        i_spatial[X>1] = self.index[-1] + 1

        # Map each spatial grid point to the corresponding R,Z values
        in_vol = np.empty(len(self.R), dtype='object')
        for i in range(len(in_vol)):
            in_vol[i] = []

        for i, i_s in enumerate(i_spatial):
            if i_s > self.index[-1]:
                continue   # don't include points outside the plasma
            else:
                in_vol[i_s].append(i)

        return i_spatial, in_vol

    def sample(self, n_samples=None, R=None, Z=None):
        """
        Sample from the distribution. Must input either 'n_samples',
        (in which case the positions are sampled), or both 'R' and 'Z',
        (in which case energy and pitch are sampled at the corresponding positions).
        """

        if (R is None) and (Z is None):
            print('Sampling positions...')
            sample_pos = True

            # Draw random positions
            def fun(R,Z): return self.get_density(R,Z)*R
            lims = ([self.Rmin,self.Zmin], [self.Rmax,self.Zmax])
            max_val = self.n_max * 3.2    # a bit of a hack...

            s = sampler.sample_acc_rej(fun, lims, max_val, n_samples)

            R = s[:,0]
            Z = s[:,1]

        else:
            R,Z = np.atleast_1d(R,Z)
            sample_pos = False
            n_samples = len(R)

        # Check in which volumes the sampled/requested positions reside,
        # and sample E and p from the appropriate distributions.
        print('Sampling energy and pitch...')

        i_spatial, in_vol = self.get_spatial_index(R, Z)

        E = np.zeros(n_samples)
        p = np.zeros(n_samples)

        for i,ip in enumerate(in_vol):

            if len(ip) == 0:
                continue    # no points here, moving on...

            # Draw samples
            if self.F_Ep_max[i] == 0.0:
                # If the distribution is zero in this volume element
                # we return samples with zero energy.
                E[ip] = 0.0
                p[ip] = 0.0
            else:
                if self.EP_sampling_method == 'acc_rej':
                    def fun(E,p): return self.get_F_Ep(i,E,p)   # function to sample from
                    lims = ([self.Emin, self.pmin], [self.Emax,self.pmax])  # sampling region

                    s = sampler.sample_acc_rej(fun, lims, self.F_Ep_max[i], len(ip))

                    E[ip] = s[:,0]
                    p[ip] = s[:,1]

                elif self.EP_sampling_method == 'inv_cdf':

                    # Make 1D table of probabilities
                    r = np.random.rand(len(ip)) * self.Ctab[i][-1]
                    s = np.interp(r, self.Ctab[i], self.i_tab)

                    E[ip] = np.interp(s, self.i_tab, self.Etab)
                    p[ip] = np.interp(s, self.i_tab, self.Atab)

        if self.EP_sampling_method == 'inv_cdf':
            # Add jitter to pitch samples
            dp = np.interp(p, self.A, self.dA) / 2.0
            p = np.random.uniform(low=p-dp, high=p+dp)

        print('Done!')

        if sample_pos:
            return R, Z, E, p
        else:
            return E, p

    def __call__(self, R, Z, E, p):
        """ Evaluate the distribution at the given point(s). """

        R, Z, E, p = np.atleast_1d(R, Z, E, p)

        F = np.zeros_like(R, dtype='d')

        # Only consider points inside the last closed flux surface
        X = self.transp_output.get_rho(R, Z)
        valid = X < 1

        R, Z, E, p = R[valid], Z[valid], E[valid], p[valid]
        F_valid = F[valid]

        # Find the closest spatial grid point
        i_spatial, in_vol = self.get_spatial_index(R, Z)

        # Loop over all volumes that contain requested points
        for i in np.unique(i_spatial):
            ip = in_vol[i]
            F_valid[ip] = self.get_F_Ep(i, E[ip], p[ip])

        F[valid] = F_valid

        return F


def quicksort(array, left, right):
    if(left>=right):
        return
    pivot = array[(left+right)//2]
    index = partition(array, pivot, left, right)
    quicksort(array,left,index-1)
    quicksort(array,index,right)
def partition(array, pivot, left, right):
    while(left<=right):
        while(array[left]<pivot):
            left = left+1
        while(array[right]>pivot):
            right = right-1
        if(left<=right):
            array[left],array[right]=array[right],array[left]
            left = left+1
            right = right-1
    return left
array = list(map(int,input().split()))
quicksort(array,0, len(array)-1)
print(array)


import argparse
import torch

parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
parser.add_argument('input_checkpoint', type=str)
parser.add_argument('output_model', type=str)
parser.add_argument('--state_dict_key', type=str, default='state_dict')

args = parser.parse_args()

checkpoint = torch.load(args.input_checkpoint)

state = dict()
for key, weight in checkpoint[args.state_dict_key].items():
	new_key = key.replace('module.','')
	print('{}->{}'.format(key,new_key))
	state[new_key] = weight

torch.save(state, args.output_model)


import numpy as np
import math
""" This module contains all the vector/math functions """

def unit_vector(p1, p2):
	""" Returns: the unit vector given points [p1] and [p2] """
	v =  np.array([p2[0]-p1[0], p2[1]-p1[1]])
	return v/np.linalg.norm(v)

def dist2(p1, p2):
	""" Returns: the square of the distance between [p1] and [p2] """
	return (np.square(p1[0]-p2[0]) + np.square(p1[1]-p2[1]))

def distance(p1, p2):
	""" Returns: the distance between points [p1] and [p2] """
	return np.sqrt(dist2(p1, p2))

def get_sign(v):
	""" Returns: the sign of the number [v] """
	if v == 0:
		return 0
	else:
		return v/np.abs(v)

def nearest_point_on_path(path, point):
	""" Returns: the nearest point on the [path] to the [point] """
	point1 = path[0]
	point2 = path[1]
	dist = distance(point1, point2)
	d2 = dist2(point1, point2)
	t = ((point[0] - point1[0])*(point2[0]-point1[0]) + (point[1] - point1[1]) * (point2[1] - point1[1]))/d2
	if (t < 0):
		return point1
	elif (t > 1):
		return point2
	else:
		x = point1[0] + t * (point2[0]-point1[0])
		y = point1[1] + t * (point2[1]-point1[1])
		return (x, y)

def angle_from_path(bike_direction, p1, p2):
	""" [angle_from_path] returns the angle that the bicycle has to turn to
	be perpendicular to the line defined by [p1] and [p2] as well as if
	it has to turn clockwise or counterclockwise """
	bike_vector = (math.cos(bike_direction), math.sin(bike_direction))
	path_vector = (p2[0]-p1[0], p2[1]-p1[1])
	dot_product = bike_vector[0]*path_vector[0] + bike_vector[1]*path_vector[1]
	angle = get_sign(dot_product)*math.acos(dot_product/distance(p1, p2))
	return angle

def distance_from_path(point, target_path):
	""" [distance_from_path] calculates the distance from [point] to [target_path] """
	# if target_path is None:
	# 	target_path = self.target_path
	p1 = np.array(target_path[0])
	v = unit_vector(target_path[0], target_path[1])
	if v[0] == 0:
		sign = get_sign(v[1])
		return  sign*(p1[0] - point[0])
	v_perp = np.array([v[1], -1*v[0]])
	bike_coords = np.array(point)
	r = p1 - bike_coords
	dist = np.sum(v_perp*r)
	return dist

def line_angle(line):
	""" Returns: angle of given path in global frame (radsss) """
	point1 = line[0]
	point2 = line[1]
	return np.arcsin((point2[1]-point1[1])/(point2[0]-point1[0]))

def line_slope(line):
	""" Returns: slope of [line] """
	return ((line[1][1]-line[0][1])/(line[1][0]-line[0][0]))


#import statements

#functions to go here

# checks that ticket name is not blank

def not_blank(question):
    valid = False

    while not valid:
        response = input(question)

        if response != "":
            return response
        else:
            print("Sorry, this can't be blank")

name = not_blank("Name: ")

#Set up dictionaries / lists needed to hold data

#Ask user if they have used the program before and show

#Loop to get ticket details

    #Get name (can't be blank)

    #Get age (between


from collections import UserDict, deque

class Term(object):
    def __init__(self, *args, value=None):
        self.args = args
        self.value = value

    def __eq__(self, other):
        return True if self.unify(other) else False

    def leq(self, other, sbs):
        if isinstance(other, Var):
            return other.leq(self, sbs)
        if type(self) != type(other) or len(self.args) != len(other.args) or \
                self.value != other.value:
            return False
        for a, b in zip(self.args, other.args):
            if not a.leq(b, sbs):
                return False
        return True

    def _unify(self, other, base, result):
        if isinstance(other, Var):
            return other._unify(self, base, result)
        if type(self) != type(other) or len(self.args) != len(other.args) or \
                self.value != other.value:
            return None
        for a, b in zip(self.args, other.args):
            result = a._unify(b, base, result)
            if not result:
                return None
        return result

    def _eq(self, other, sbs, temporary):
        if isinstance(other, Var):
            return other._eq(self, sbs, temporary)
        if type(self) != type(other) or len(self.args) != len(other.args) or \
                self.value != other.value:
            return None
        for a, b in zip(self.args, other.args):
            temporary = a._eq(b, sbs, temporary)
            if not temporary:
                return None
        return temporary

    def eq(self, other, sbs=None):
        r = self._eq(other, sbs, {})
        return Substitution(sbs, r) if r else None

    def unify(self, other, sbs=None):
        r = self._unify(other, sbs, {})
        return Substitution(sbs, r) if r else None

    def __str__(self):
        res = type(self).__name__ if self.value is None else str(self.value)
        if len(self.args) > 0:
            res = res + "(" + (",".join(str(x) for x in self.args)) + ")"
        return res

    def __call__(self, *args, **kwargs):
        if len(self.args) > 0:
            raise Exception("Cannot instantiate {}".format(self))
        return type(self)(*args, value=self.value)

    def substitute(self, sbs):
        args = [x.substitute(sbs) for x in self.args]
        result = type(self)(*args, value=self.value)
        return result

    def occur_check(self, var, sbs):
        for x in self.args:
            if x.occur_check(var, sbs):
                return True
        return False

class Var(object):
    count = 0

    def __init__(self):
        self.count = Var.count
        Var.count += 1

    def leq(self, other, sbs):
        if isinstance(other, Var)and other.count == self.count:
            return True
        if self.count in sbs:
            return other.leq(sbs[self.count], sbs)
        return False

    def _unify(self, other, base, result):
        if isinstance(other, Var) and other.count == self.count:
            return result
        if base is not None and self.count in base:
            return other._unify(base[self.count], base, result)
        if other.occur_check(self, base):
            return None
        result[self.count] = other
        return result

    def _eq(self, other, sbs, temporary):
        if isinstance(other, Var) and other.count == self.count:
            return temporary
        if sbs is not None and self.count in sbs:
            return other._eq(sbs[self.count], sbs, temporary)
        if not isinstance(other, Var):
            return None
        temporary[self.count] = other
        return temporary

    def __str__(self):
        return "x_%d"%self.count

    def substitute(self, sbs):
        res = sbs.get(self.count, None)
        if not res:
            res = Var()
            sbs[self.count] = res
        return res

    def occur_check(self, var, sbs):
        if self.count == var.count:
            return True
        if sbs and self.count in sbs:
            return sbs[self.count].occur_check(var, sbs)
        return False

class Predicate(Term):
    def __init__(self, name, *args):
        super(Predicate, self).__init__(*args, value=name)

    def negate(self):
        return Not(self)

    def substitute(self, sbs):
        args = [x.substitute(sbs) for x in self.args]
        result = type(self)(self.value, *args)
        return result

class Disjunct(Term):
    def __init__(self, *args):
        super(Disjunct, self).__init__(*args, value=" ∨ ")

    def __str__(self):
        return self.value.join(str(x) for x in self.args)

    def __add__(self, other):
        return Disjunct(args=self.args+other.args)

    def negate(self):
        c = Conjunct()
        c.args = [x.negate() for x in self.args]
        return c

    def substitute(self, sbs):
        args = [x.substitute(sbs) for x in self.args]
        result = type(self)(*args)
        return result

    def _resolve_predicate(self, predicate, sbs):
        result = []
        np = predicate.negate()
        for i, p in enumerate(self.args):
            unification = np.unify(p, sbs)
            if unification:
                x1 = self.args[:i] if i>0 else []
                x2 = self.args[i+1:] if i+1<len(self.args) else []
                x = Disjunct()
                x.args = list(x1) + list(x2)
                result.append(x.substitute(unification))
        #print(
        #    "result of _predicate resolving {} <<%%>> {} IS {}"
        #    .format(np, self, [str(x) for x in result])
        #)
        return result

    def resolve(self, disjunct, sbs):
        result = []
        for i, p in enumerate(disjunct.args):
            temp = self._resolve_predicate(p, sbs)
            if temp:
                x1 = disjunct.args[:i] if i>0 else []
                x2 = disjunct.args[i+1:] if i+1<len(disjunct.args) else []
                for z in temp:
                    z.args = list(z.args) + list(x1) + list(x2)
                result = result + temp
        return result

class Conjunct(Term):
    def __init__(self, *args):
        super(Conjunct, self).__init__(*args, value=" ∧\n")

    def __str__(self):
        return self.value.join(str(x) for x in self.args)

    def negate(self):
        c = Disjunct()
        c.args = [x.negate() for x in self.args]
        return c

    def substitute(self, sbs):
        args = [x.substitute(sbs) for x in self.args]
        result = type(self)(*args)
        return result

class Not(Predicate):
    def __init__(self, p):
        super(Not, self).__init__("¬", p)

    def negate(self):
        return self.args[0]

    def substitute(self, sbs):
        result = Not(self.args[0].substitute(sbs))
        return result

class Substitution(UserDict):
    def __init__(self, base, data=None):
        super(Substitution, self).__init__({} if data is None else data)
        self.base = base

    def __getitem__(self, item):
        result = self.data.get(item)
        if not result and self.base:
            result = self.base[item]
            self.data[item] = result
        return result

    def substitute(self, a, b):
        result = Substitution(self)
        result.data[a] = b
        return result

    def __str__(self):
        return "{" +\
               (",".join("{}:{}".format(x, y) for x, y in self.data.items())) +\
               "}"

class kb(object):
    def __init__(self):
        super(kb, self).__init__()
        self.known = deque()
        self.resolved = deque()

    def _include(self, s):
        for x in self.known:
            if x == s:
                return
        self.known.appendleft(s)
        print("________{}_______{}________".format(len(self.known),
                                                   len(self.resolved)))

    def tell(self, s):
        if isinstance(s, Disjunct):
            if not s.args:
                raise Exception("CONTRADICTION")
            print(">>>", s)
            self._include(s)
        elif isinstance(s, Conjunct):
            for x in s.args:
                self._include(x)
                print(">>>", x)

    def contradiction(self):
        sbs = Substitution(None)
        while len(self.known) != 0:
            x = self.known[-1]
            self.known.pop()
            for y in self.resolved:
                sentences = x.resolve(y, sbs)
                print(
                    "resolving {} <<X>> {} results {}"
                    .format(x, y, [str(x) for x in sentences])
                )
                for s in sentences:
                    self.tell(s)
            self.resolved.appendleft(x)


a = list(map(int,input().split()))
m = sum(a) / len(a)
q = m
s = 0
if m >= 4.5:
    print('ваш балл на 5 =', m)
    print('Its very good')
else:
    while q < 4.5:
        a.append(5)
        q = sum(a) / len(a)
        s += 1
    if s%10 == 1:
        print('Ваш балл ', round(m,2), 'вам нужно получить еще', s, 'пятерку чтоб ваш балл стал', q, 'на пятерку')
    elif s%10 == 2 or s%10 == 3 or s%10 == 4:
        print('Ваш балл ', round(m, 2), 'вам нужно получить еще', s, 'пятерки чтоб ваш балл стал', q, 'на пятерку')
    else:
        print('Ваш балл ', round(m, 2), 'вам нужно получить еще', s, 'пятерок чтоб ваш балл стал', q, 'на пятерку')
input('Press Enter to end')


from typing import List

class FindMinimumInRotatedSortedArray:
    """
        153. Find Minimum in Rotated Sorted Array

        Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:

        [4,5,6,7,0,1,2] if it was rotated 4 times.

        [0,1,2,4,5,6,7] if it was rotated 7 times.

        Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].

        Given the sorted rotated array nums of unique elements, return the minimum element of this array.

        You must write an algorithm that runs in O(log n) time.

        Constraints:

        n == nums.length

        1 <= n <= 5000

        -5000 <= nums[i] <= 5000

        All the integers of nums are unique.

        nums is sorted and rotated between 1 and n times.
    """
    def findMin(self, nums: List[int]) -> int:
        """
            O(log(n))

            We don't know how many times this array was rotated, so we start with a normal binary search

            However in each iteration we check if the number on the left is greater than the one on the right

            This means that we are in a sorted section, which means we can get the minimum from the left number

            Otherwise, we check if our middle number is greater than the left number, in-which case, it means the minimum

            section of the array is on the right, otherwise we search the left side
        """
        left = 0
        right = len(nums) - 1

        minimum = 5000
        while left <= right:
            if nums[left] < nums[right]:
                minimum = min(minimum, nums[left])
                break

            mid = left + (right - left) // 2
            minimum = min(minimum, nums[mid])
            if nums[mid] >= nums[left]:
                left = mid + 1
            else:
                right = mid - 1

        return minimum

if __name__ == '__main__':
    obj = FindMinimumInRotatedSortedArray()

    assert obj.findMin([3,4,5,1,2]) == 1
    assert obj.findMin([4,5,6,7,0,1,2]) == 0
    assert obj.findMin([11,13,15,17]) == 11
    assert obj.findMin([5,1,2,3,4]) == 1


"""
# Sample code to perform I/O:

name = input()                  # Reading input from STDIN
print('Hi, %s.' % name)         # Writing output to STDOUT

# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""

# Write your code here
t = int(input())
for _ in range(t):
    a, b, c, d, k = map(int, input().strip().split())
    low = 0
    high = 1000000  # 10^4
    while low < high:
        x = low + (high - low + 1) // 2
        fx = a * x * x * x + b * x * x + c * x + d  # ax^3 + bx^2 + cx + d
        if fx == k:
            print(k)
            break
        elif fx < k:
            low = x
        else:
            high = x - 1
    else:
        print(low)


from flask import Flask, request
from threading import Thread
import asyncio
import requests
import logging

from config import SERVER_IP, SERVER_PORT, CLIENT_ID, CLIENT_SECRET_PATH
from Modules.Register import RegisterModule
from SteamAPI import SteamAPI

DISCORD_API_BASE = 'https://discord.com/api/v7'
STEAMIO_BASE = 'https://steamid.io/'
STEAM_BASE = 'api.steampowered.com/IPlayerService/GetOwnedGames/v1/'

logger = logging.getLogger("FlaskServer")
logger.setLevel(logging.DEBUG)

class FlaskServer(Thread):
    app = Flask(__name__)
    client = None  # type: CPLBot
    steamApi = SteamAPI()
    with open(CLIENT_SECRET_PATH, 'r') as fd:
        _CLIENT_SECRET = fd.read()

    def __init__(self, client):
        Thread.__init__(self)
        FlaskServer.client = client

    @staticmethod
    @app.route('/', methods=['GET'])
    def register_route():
        client = FlaskServer.client
        code = request.args.get('code')
        if not code:
            return "Code not found in URL"

        state = request.args.get('state')
        if not state:
            return "Error
Please request a new link from Discord by using .register - this link does not contain your Discord UserID"

        ## Check Oauth2 Token
        oauth_response = requests.post(f'{DISCORD_API_BASE}/oauth2/token',
            data={'client_id': CLIENT_ID, 'grant_type': 'authorization_code', 'client_secret': FlaskServer._CLIENT_SECRET,
                  'code': code, 'scope': "identify connections", "redirect_uri": f"http://{SERVER_IP}:31612"}
        )
        oauth_json = oauth_response.json()
        if oauth_json.get("error"):
            return f"Error
{oauth_json.get('error')}: {oauth_json.get('error_description')}\nPlease contact a moderator"

        ## Get Discord Profile
        profile_response = requests.get(f'{DISCORD_API_BASE}/users/@me',
                                        headers={'authorization': f"Bearer {oauth_json['access_token']}"})
        profile_json = profile_response.json()
        if profile_json.get("code"):
            return f"Error
{profile_json.get('code')}"
        if profile_json.get('id') != request.args.get('state'):
            return "Error
You are logged into two different Discord accounts - one on the website and one in your app. Log out of the website and try again or try again from the website."

        ## Get Steam Connection
        connections_response = requests.get(f"{DISCORD_API_BASE}/users/@me/connections",
                                            headers={'authorization': f"Bearer {oauth_json['access_token']}"})
        connections_json = connections_response.json()
        if isinstance(connections_json, dict) and connections_json.get("code", None):
            return f"Error
{connections_json.get('code', None)}"

        i = [js['id'] for js in connections_json if js['type'] == 'steam']
        if not i or not i[0]:
            return f"Error
Your steam account does not seem to be linked to discord. Please close this window and step through the instructions again"
        discord_steam_id = i[0]
        # Steamid.io request
        steamio_response = requests.get(f"{STEAMIO_BASE}/lookup/{discord_steam_id}")
        steam_id = int(steamio_response.content.split(b'data-steamid64')[1].split(b'"')[1])
        logger.info(f"Get Steamid64: {steam_id}")
        # Check if ID is already in database
        player = client.database.get_player_by_steam_id(steam_id)
        if player:
            return "This Steam account is already registered"
        # Steam request
        minutes = asyncio.run(FlaskServer.steamApi.get_total_number_of_civ6_minutes_play(steam_id))
        logger.info(f"Player played {minutes} minutes at Civ6")
        if not minutes:
            return "Error:
You have your steam profile set to private, please make it public to allow the bot to verify you own the game and have at least 2 hours of playing."
        if minutes < 120:
            return "Error:
You either need more than 2 hours of Civ 6 play time or must change a Steam setting. Please close this page and return to Discord for further instructions."
        # Send to the discord Module
        registerModule = client.get_module(RegisterModule)
        client.loop.create_task(registerModule.register_player(profile_json['id'], steam_id))
        return "Your registration was complete, Welcome to Civ Player League.
You can now close this page"

    @staticmethod
    @app.route('/join/<string:game>/<string:player>/<string:session>', methods=['GET'])
    def join_route(game, player, session):
        return f""

    def run(self):
        self.app.run(SERVER_IP, SERVER_PORT, use_reloader=False)


# Problem: https://leetcode.com/problems/two-sum/submissions/875835984/

class Solution(object):
    def twoSum(self, nums, target):
        seen = {}
        for i, value in enumerate(nums):
            remaining = target - value
            if remaining in seen:
                return [i, seen[remaining]]
            seen[value] = i


import numpy as np
import gym
from collections import deque
from tqdm import trange
from DQN_agent import Agent
import torch

def running_average(x, N):
    """Function used to compute the running average
    of the last N elements of a vector x
    """
    if len(x) >= N:
        y = np.copy(x)
        y[N - 1 :] = np.convolve(x, np.ones((N,)) / N, mode="valid")
    else:
        y = np.zeros_like(x)
    return y

def dqn(
    N_episodes,
    discount_factor,
    n_ep_running_average,
    batch_size,
    buffer_size,
    alpha,
    epsilon_max,
    epsilon_min,
    seed,
    device
):

    # Import and initialize the discrete Lunar Laner Environment
    env = gym.make("LunarLander-v2")
    env.reset()

    # Parameters
    n_actions = env.action_space.n  # Number of available actions
    n_states = len(env.observation_space.high)  # State dimensionality

    # We will use these variables to compute the average episodic reward and the average number of steps per episode

    episode_reward_list = []  # this list contains the total reward per episode
    episode_number_of_steps = []  # this list contains the number of steps per episode
    episodes_avg = deque(maxlen=50)

    # Random agent initialization and count initialization

    agent = Agent(
        n_actions=n_actions,
        n_states=n_states,
        seed=seed,
        alpha=alpha,
        buffer_size=buffer_size,
        batch_size=batch_size,
        device=device
    )
    count = 1
    # Training

    EPISODES = trange(N_episodes, desc="Episode: ", leave=True, miniters=1)

    for i in EPISODES:

        # Update epsilon

        epsilon = agent.epsilon_t(
            episode_number=i,
            N_episodes=N_episodes,
            epsilon_max=epsilon_max,
            epsilon_min=epsilon_min,
        )

        # Reset enviroment data and initialize variables
        t = 1

        done = False
        state = torch.tensor(env.reset(), requires_grad=False, dtype=torch.float32)
        total_episode_reward = 0.0

        while not done:

            action = agent.action(state=state, epsilon=epsilon)
            next_state, reward, done, _ = env.step(action)
            agent.update(
                state=state,
                action=action,
                reward=reward,
                next_state=next_state,
                done=done,
                discount_factor=discount_factor,
                count=count,
            )
            state = torch.tensor(next_state, requires_grad=True, dtype=torch.float32)
            total_episode_reward += reward
            t += 1
            count += 1

        episode_reward_list.append(total_episode_reward)
        episodes_avg.append(total_episode_reward)
        episode_number_of_steps.append(t)

        # if np.mean(episodes_avg) >= 200.:
        #     print(
        #         "\nSolved in {:d} episodes with an \tAverage Score: {:.2f}".format(
        #             i, np.mean(episodes_avg)
        #         )
        #     )
        #     torch.save(agent.main_qnetwork, "neural-network-1.pth")

        # Updates the tqdm update bar with fresh information
        # (episode number, total reward of the last episode, total number of Steps
        # of the last episode, average reward, average number of steps)
        EPISODES.set_description(
            "Episode {} - Reward/Steps: {:.1f}/{} - Avg. Reward/Steps: {:.1f}/{}".format(
                i,
                total_episode_reward,
                t,
                np.mean(episodes_avg),
                np.mean(running_average(episode_number_of_steps, n_ep_running_average)),
            )
        )
    # Close environment
    env.close()
    return episode_reward_list, episode_number_of_steps


import random

import boto3

prefix = 'fcn-cfn-apollo-'
client = boto3.client('s3')
s3 = boto3.resource('s3')

def s3_create_bucket():
    random_number = random.randint(100, 999)
    bucket_name = prefix + str(random_number)
    bucket = s3.Bucket(bucket_name)

    response = bucket.create(
        ACL='private'
    )
    if response['ResponseMetadata']['HTTPStatusCode'] == 200:
        print("Successfully Created bucket {}".format(bucket_name))

def s3_delete_bucket(bucket_name):
    bucket = s3.Bucket(bucket_name)
    # object_versions_iterator = bucket.object_versions.all()
    # print(object_versions_iterator)
    bucket.object_versions.delete()
    bucket.delete()
    print("Successfully Deleted bucket {}".format(buckets))

def s3_list_buckets():
    response = client.list_buckets()
    all_buckets = []
    for bucket in response['Buckets']:
        if prefix in bucket['Name']:
            all_buckets.append(bucket['Name'])
    return all_buckets

def s3_put_objects(bucket_name):
    random_number = random.randint(100, 999)
    response = client.put_object(
        ACL='private',
        Bucket=bucket_name,
        Key="random_bucket_inside_bucket_" + str(random_number)
    )
    return response

if __name__ == '__main__':
    user_input = input("Would you like to create/delete bucket\nSelect 1 for create bucket \nSelect 2 for delete "
                       "bucket\nSelect 3 for put object\n")

    if user_input == '1':
        for _ in range(1):
            s3_create_bucket()
    elif user_input == '2':
        s3_bucket_name = s3_list_buckets()
        for buckets in s3_bucket_name:
            s3_delete_bucket(buckets)
    elif user_input == '3':
        print(s3_put_objects('fcn-cfn-apollo-495'))


# Import Libraries
import numpy as np
import tensorflow as tf
# from datetime import datetime
import matplotlib.pyplot as plt
import h5py
from tensorflow.keras.layers import Input, Dense, Conv2D, MaxPool2D, AveragePooling2D, UpSampling2D, concatenate, \
    BatchNormalization, Conv2DTranspose, Flatten, Reshape
from tensorflow.keras.optimizers import Adam

import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"

# -------------------------------------------------------------------------------------------------
# FILE SELECTION
Re = 20.0  # choose between Re= 20.0, 30.0, 40.0, 50.0, 60.0, 100.0, 180.0

# T has different values depending on Re
if Re == 20.0 or Re == 30.0 or Re == 40.0:
    T = 20000
else:
    T = 2000

path_folder = 'Final_Product/'  # path to folder in which flow data is situated
path = path_folder + f'Kolmogorov_Re{Re}_T{T}_DT01.h5'

# -------------------------------------------------------------------------------------------------
# PARAMETER SELECTION

dimensions = [8, 4, 2, 1]  # Specify the dimensions for each encoding layer (dim[3] = dimension of latent space)
# e.g. [16,8,4,2], [32,16,8,4], [64,32,16,8], [128,64,32,16], [256, 128, 64, 32]
# Decoding layer is mirror of encoding layer

activation_function = 'tanh'  # specify which activation function to use
learning_rate = 0.1  # change to 0.0001 if using a latent space dimension of 32 and 64
number_epochs = 10  # set high, early stopping function will stop iterations if it sees no visible change after 'patience_early_stopping' number of epochs
patience_early_stopping = 20  # how many epochs with no significant change before AE stops training
pooling = 'max'  # set to 'max' or 'average'
if pooling == 'max':
    pooling_function = MaxPool2D
else:
    pooling_function = AveragePooling2D

# -------------------------------------------------------------------------------------------------
# READ DATASET
hf = h5py.File(path, 'r')
Nx = 24
Nu = 1
t = np.array(hf.get('t'))
u_all = np.zeros((Nx, Nx, len(t), Nu))
u_all[:, :, :, 0] = np.array(hf.get('u_refined'))
# u_all[:,:,:,1] = np.array(hf.get('v_refined'))
u_all = np.transpose(u_all, [2, 0, 1, 3])
hf.close()
print(u_all.shape)
print('Read Dataset')

# normalize data
u_min = np.amin(u_all[:, :, :, 0])
u_max = np.amax(u_all[:, :, :, 0])
u_all[:, :, :, 0] = (u_all[:, :, :, 0] - u_min) / (u_max - u_min)
if Nu == 2:
    v_min = np.amin(u_all[:, :, :, 1])
    v_max = np.amax(u_all[:, :, :, 1])
    u_all[:, :, :, 1] = (u_all[:, :, :, 1] - v_min) / (v_max - v_min)
print('Normalized Data')

# visualization of the dataset
fig = plt.figure()
ax = fig.add_subplot(121)
ax.contourf(u_all[50, :, :, 0])
# ax2 = fig.add_subplot(122)
# ax2.contourf(u_all[0,:,:,1])
plt.show()
print('Showed data')

# -------------------------------------------------------------------------------------------------
# PREPARE DATASET
val_ratio = int(np.round(0.75 * len(u_all)))
test_ratio = int(np.round(0.95 * len(u_all)))

u_train = u_all[:val_ratio, :, :, :].astype('float32')
u_val = u_all[val_ratio:test_ratio, :, :, :].astype('float32')
u_test = u_all[test_ratio:, :, :, :].astype('float32')
print('Prepared Dataset')

# -------------------------------------------------------------------------------------------------
# CREATING NETWORK
input_img = Input(shape=(Nx, Nx, Nu))

nb_layer = 0

x = Conv2D(dimensions[0], (3, 3), padding='same', activation=activation_function)(input_img)
x = pooling_function((2, 2), padding='same')(x)
x = Conv2D(dimensions[1], (3, 3), padding='same', activation=activation_function)(x)
x = pooling_function((2, 2), padding='same')(x)
x = Conv2D(dimensions[2], (3, 3), padding='same', activation=activation_function)(x)
x = pooling_function((2, 2), padding='same')(x)
x = Conv2D(dimensions[3], (3, 3), padding='same', activation=activation_function)(x)
encoded = pooling_function((3, 3), padding='same')(x)

x = Conv2DTranspose(dimensions[3], (3, 3), padding='same', activation=activation_function)(encoded)
x = UpSampling2D((3, 3))(x)
x = Conv2DTranspose(dimensions[2], (3, 3), padding='same', activation=activation_function)(x)
x = UpSampling2D((2, 2))(x)
x = Conv2DTranspose(dimensions[1], (3, 3), padding='same', activation=activation_function)(x)
x = UpSampling2D((2, 2))(x)
x = Conv2DTranspose(dimensions[0], (3, 3), padding='same', activation=activation_function)(x)
x = UpSampling2D((2, 2))(x)
decoded = Conv2DTranspose(Nu, (3, 3), activation='linear', padding='same')(x)

autoencoder = tf.keras.models.Model(input_img, decoded)
encoder = tf.keras.models.Model(input_img, encoded)
print('Encoder Created')

# definition of the decoder
encoded_input = Input(shape=(1, 1, encoded.shape[3]))
deco = autoencoder.layers[-7](encoded_input)  # we re-use the same layers as the ones of the autoencoder
for i in range(6):
    deco = autoencoder.layers[-6 + i](deco)

decoder = tf.keras.models.Model(encoded_input, deco)

print('Decoder Created')
print(encoder.summary())
print(decoder.summary())
print(autoencoder.summary())

# -------------------------------------------------------------------------------------------------
# TRAINING NETWORK
autoencoder.compile(optimizer=Adam(learning_rate=learning_rate), loss='mse')
checkpoint_filepath = './checkpoint'
model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
    filepath=checkpoint_filepath,
    save_weights_only=True,
    monitor='val_loss',
    mode='min',
    save_best_only=True)
early_stop_callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=patience_early_stopping)

nb_epochs = number_epochs
batch_size = 20
hist = autoencoder.fit(u_train, u_train, epochs=nb_epochs, batch_size=batch_size,
                       shuffle=True, validation_data=(u_test, u_test),
                       verbose=1,
                       callbacks=[model_checkpoint_callback, early_stop_callback])

loss_history = hist.history['loss']
val_history = hist.history['val_loss']
plt.plot(loss_history, 'b')
plt.plot(val_history, 'r')
plt.title("Loss History")
plt.xlabel("Epoch")
plt.ylabel("Loss")

plt.show()
print('Trained Model')
# -------------------------------------------------------------------------------------------------
# VISUALIZATION OF PREDICTION
y_nn = autoencoder.predict(u_test[0:1, :, :, :])
print(y_nn.shape)

fig = plt.figure()
ax = fig.add_subplot(121)
ax.contourf(y_nn[0, :, :, 0])
ax = fig.add_subplot(122)
ax.contourf(u_test[0, :, :, 0])
plt.show()

print(f'AE error: {loss_history[-1]}')


# 4.60:  Quantify for an optional group.

# Pull out all the info about each person (Favorite Color may
# not be there).

import re

results = [ 'Name: Joe;  Favorite Color:  Blue;  Employee ID: 2395',
            'Name:  Marie;  Employee ID: 2321',
            'Name:  Teneski; Favorite Color: Green;  Employee ID:  1913' ]

for row in results:
    matchobj = re.search(r'', row)
    print(matchobj.groups())

# Expected Output:

# ('Joe', 'Favorite Color:  Blue;  ', 'Blue', '2395')
# ('Marie', None, None, '2321')
# ('Teneski', 'Favorite Color: Green;  ', 'Green', '1913')

# Note that if you see the message AttributeError: 'NoneType'
# object has no attribute 'group', this means that the search
# did not find a match and returned None, and the code
# attempted to call .group() on None.  Check the string and
# pattern to determine why it did not match.


from wordcloud import WordCloud
from collections import *
import pickle
import multiprocessing as mp
import os

def analysis (ners_dict, specifier, lan='en', font="G:\My Drive\Fall 2018\CAPP 30525\week3\simfang.ttf"):
    '''This function performs wordcloud analysis on the NER restuls.
    Specifier can be ['DATE', 'O', 'COUNTRY', 'TITLE', 'PERSON', 'ORGANIZATION', 'NUMBER', 'LOCATION', 'TIME', 'DEMONYM',
        'MONEY', 'STATE_OR_PROVINCE', 'GPE', 'MISC', 'ORDINAL', 'CITY', 'IDEOLOGY', 'PERCENT', 'CAUSE_OF_DEATH', 'FACILITY',
        'CRIMINAL_CHARGE', 'RELIGION', 'NATIONALITY']'''

    try:
        temp = Counter(ners_dict[specifier])
    except KeyError:
        print("Key incorrect!")
    ordered = temp.most_common()
    with open (f"output\{lan}_{specifier}.txt",'w', encoding="utf-8") as f:
        f.write(f"15 most common mentions in category {specifier} are:\n")
        for word, count in ordered[:15]:

            f.write(f"{word} with {count} mentions;\n")

    # create word cloud
    if lan == 'zh':
        wordcloud = WordCloud(collocations=False, font_path=font, width=5000, height=3000, margin=2)
    else:
        wordcloud = WordCloud(width=5000, height=3000, margin=2)

    wordcloud.generate_from_frequencies(frequencies=temp)
    # plt.figure()
    # plt.imshow(wordcloud, interpolation="bilinear")
    # plt.axis("off")
    # plt.show()
    # plt.close()
    wordcloud.to_file(f'output\{lan}_{specifier}.png')

if __name__ == '__main__':
    with open('ner_en.pickle', 'rb') as handle:
        ner_en = pickle.load(handle)
    with open('ner_ch.pickle', 'rb') as handle:
        ner_ch = pickle.load(handle)

    specifiers = ['COUNTRY', 'TITLE', 'PERSON', 'ORGANIZATION', 'LOCATION', 'STATE_OR_PROVINCE', 'CITY', 'IDEOLOGY',
                  'RELIGION']
    # with mp.Pool(os.cpu_count()) as p:
    #     p.apply(analysis, args=(ner_ch,specifiers,'zh'))
    #     p.apply(analysis, args=(ner_en, specifiers))
    for specifier in specifiers:
        analysis(ner_ch,specifier,'zh')
        analysis(ner_en,specifier)


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

def show_queue(tmp) :
    window = '현재 queue의 상태는 : '
    print_buffer = []
    for i in tmp :
        window += f'{str(i):>10}|'
    print_buffer.append(window)
    return list(map(print,print_buffer)) # 리턴값을 줄때, 실행문을 실행까지 시킬 수 있다.

def queue(list_x) :
    yield show_queue(list_x)

    for i in range(len(list_x)):
        dequeue = list_x[i]
        list_x[i] = '\000' * 10
        yield dequeue

input_list = list(range(100,1001,100))
queue1 = queue(input_list) # 제너레이터 객체 생성.

next(queue1); print(); #초기화

for i in queue1 : #내가 만든건 제너레이터이고, for문을 통해 하나씩 나오는 i는 각 yield값을 말한다.
    print(f'큐의 원소는 {i}')


from django.shortcuts import get_object_or_404

from rest_framework import serializers

from access.models import Grade, Student
from .grades import GradeSerializer

class StudentSerializer(serializers.ModelSerializer):

	grade = GradeSerializer()

	class Meta:
		model = Student
		fields = ['first_name', 'last_name_1', 'last_name_2', 'document', 'grade']

	def validate(self, data):
		""" Verify if Grade exists."""

		data = self.initial_data
		try:
			grade = Grade.objects.get(name=data['grade']['name'])
		except Grade.DoesNotExist:
			raise serializers.ValidationError('Grade does not exists.!!')

		data['grade'] = grade
		return data

	def create(self, validated_data):
		student = Student.objects.create(
			document=validated_data['document'],
			first_name=validated_data['first_name'],
			last_name_1=validated_data['last_name_1'],
			last_name_2=validated_data['last_name_2'],
			grade=validated_data['grade'])

		return student


# ITQ function (see ITQ paper)
import numpy as np
from numpy.linalg import svd, norm
from scipy.stats import ortho_group

def ITQ(V, n_iter=50, random_state=None):
    c = V.shape[1] # number of dimensions or bits
    R0 = ortho_group.rvs(c, random_state=random_state)
    Q_loss = np.zeros((n_iter,)) # quantization loss

    for it in range(n_iter):
        if it==0:
            VR=V@R0

        # compute quantization loss
        if it>0:
            VR = V@R
            # note that the following is Q_loss of previous iteration
            Q_loss[it-1] = (norm(B-VR))**2

        # fix R and update B
        B = np.sign(VR)

        # fix B and update R
        S, omega, Shat_transpose = svd(B.T@V)
        Shat = Shat_transpose.T
        R = Shat@S.T

        # compute the last quantization loss
        if it==(n_iter-1):
            VR = V@R
            Q_loss[it] = (norm(B-VR))**2

    return R,Q_loss/(c**2)


import numpy as np
import scipy.sparse as sp
import scipy.sparse.csgraph as cs

from qiskit.mapper import Layout
from qiskit.transpiler._basepasses import AnalysisPass
from qiskit.transpiler.exceptions import TranspilerError

class DenseLayout(AnalysisPass):
    """
    Chooses a Layout by finding the most connected subset of qubits.
    """

    def __init__(self, coupling_map):
        """
        Chooses a DenseLayout

        Args:
            coupling_map (Coupling): directed graph representing a coupling map.

        Raises:
            TranspilerError: if invalid options
        """
        super().__init__()
        self.coupling_map = coupling_map

    def run(self, dag):
        """
        Pick a convenient layout depending on the best matching
        qubit connectivity, and set the property `layout`.

        Args:
            dag (DAGCircuit): DAG to find layout for.

        Raises:
            TranspilerError: if dag wider than self.coupling_map
        """
        num_dag_qubits = sum([qreg.size for qreg in dag.qregs.values()])
        if num_dag_qubits > self.coupling_map.size():
            raise TranspilerError('Number of qubits greater than device.')
        best_sub = self._best_subset(num_dag_qubits)
        layout = Layout()
        map_iter = 0
        for qreg in dag.qregs.values():
            for i in range(qreg.size):
                layout[(qreg, i)] = int(best_sub[map_iter])
                map_iter += 1
        self.property_set['layout'] = layout

    def _best_subset(self, n_qubits):
        """Computes the qubit mapping with the best connectivity.

        Args:
            n_qubits (int): Number of subset qubits to consider.

        Returns:
            ndarray: Array of qubits to use for best connectivity mapping.
        """
        if n_qubits == 1:
            return np.array([0])

        device_qubits = self.coupling_map.size()

        cmap = np.asarray(self.coupling_map.get_edges())
        data = np.ones_like(cmap[:, 0])
        sp_cmap = sp.coo_matrix((data, (cmap[:, 0], cmap[:, 1])),
                                shape=(device_qubits, device_qubits)).tocsr()
        best = 0
        best_map = None
        # do bfs with each node as starting point
        for k in range(sp_cmap.shape[0]):
            bfs = cs.breadth_first_order(sp_cmap, i_start=k, directed=False,
                                         return_predecessors=False)

            connection_count = 0
            for i in range(n_qubits):
                node_idx = bfs[i]
                for j in range(sp_cmap.indptr[node_idx],
                               sp_cmap.indptr[node_idx + 1]):
                    node = sp_cmap.indices[j]
                    for counter in range(n_qubits):
                        if node == bfs[counter]:
                            connection_count += 1
                            break

            if connection_count > best:
                best = connection_count
                best_map = bfs[0:n_qubits]
        return best_map


import datetime
import logging

import webapp2

from google.appengine.ext import ndb

from infra_libs.ts_mon import shared
from infra_libs.ts_mon.common import interface

def find_gaps(num_iter):
  """Generate integers not present in an iterable of integers.

  Caution: this is an infinite generator.
  """
  next_num = -1
  for n in num_iter:
    next_num += 1
    while next_num < n:
      yield next_num
      next_num += 1
  while True:
    next_num += 1
    yield next_num

def _assign_task_num(time_fn=datetime.datetime.utcnow):
  expired_keys = []
  unassigned = []
  used_task_nums = []
  time_now = time_fn()
  expired_time = time_now - datetime.timedelta(
      seconds=shared.INSTANCE_EXPIRE_SEC)
  for entity in shared.Instance.query():
    # Don't reassign expired task_num right away to avoid races.
    if entity.task_num >= 0:
      used_task_nums.append(entity.task_num)
    # At the same time, don't assign task_num to expired entities.
    if entity.last_updated < expired_time:
      expired_keys.append(entity.key)
      shared.expired_counter.increment()
      logging.debug(
          'Expiring %s task_num %d, inactive for %s',
          entity.key.id(), entity.task_num,
          time_now - entity.last_updated)
    elif entity.task_num < 0:
      shared.started_counter.increment()
      unassigned.append(entity)

  logging.debug('Found %d expired and %d unassigned instances',
                len(expired_keys), len(unassigned))

  used_task_nums = sorted(used_task_nums)
  for entity, task_num in zip(unassigned, find_gaps(used_task_nums)):
    entity.task_num = task_num
    logging.debug('Assigned %s task_num %d', entity.key.id(), task_num)
  futures_unassigned = ndb.put_multi_async(unassigned)
  futures_expired = ndb.delete_multi_async(expired_keys)
  ndb.Future.wait_all(futures_unassigned + futures_expired)
  logging.debug('Committed all changes')

class SendHandler(webapp2.RequestHandler):
  def get(self):
    if self.request.headers.get('X-Appengine-Cron') != 'true':
      self.abort(403)

    with shared.instance_namespace_context():
      _assign_task_num()

    interface.invoke_global_callbacks()

app = webapp2.WSGIApplication([
    (r'/internal/cron/ts_mon/send', SendHandler),
], debug=True)


from binascii import crc32
import numpy as np
from scipy import sparse
from collections import Counter
from joblib import Parallel, delayed

def ngram_hash(text, n, num_buckets=10000):
    ''' Hash a string of text to a series of integer values
        based on its substrings modulo a number of 'buckets' '''
    rtn = []
    text_bytes = bytes(text, 'utf-8')
    for i in range( len(text_bytes) -n +1):
        fragment = text_bytes[i:(i+n)]
        rtn.append( crc32(fragment) % num_buckets )
    return rtn

def count_hashed_ngrams(text, n_range=[1,2,3,4,5,6], num_buckets=10000):
    ''' Return a map counting the frequency of hashed ngrams in a string of text
    '''
    rtn = {}
    for n in n_range:
        tmp = ngram_hash(text, n, num_buckets=num_buckets)
        for t in tmp:
            if t in rtn:
                rtn[t] += 1
            else:
                rtn[t] = 1
    return rtn

def get_dense_hash_count(texts, n_range=[1,2,3,4,5,6], num_buckets=10000):
    rtn = np.zeros( (len(texts), num_buckets) )
    for i, text in enumerate(texts):
        tmp  = count_hashed_ngrams(text,n_range=n_range, num_buckets=num_buckets)
        for idx, count in tmp.items():
            rtn[i,idx] = count
    return sparse.csr_matrix(rtn)

def char_ngrams(text_bytes, n_range):
    """Tokenize text_document into a sequence of character n-grams"""

    text_len = len(text_bytes)
    ngrams = []

    # bind method outside of loop to reduce overhead
    ngrams_append = ngrams.append

    for n in n_range:
        for i in range(text_len -n +1):
            ngrams_append(text_bytes[i: i + n])
    return ngrams

def light_hashed_ngram_count(texts, n_range=[5], num_buckets=10000):
    col_idx = []
    row_idx = []
    cr_counts = []
    # grams = [ char_ngrams(bytes(text,'utf-8'), n_range) for text in texts ]
    col_append = col_idx.append
    row_append = row_idx.append
    cr_append = cr_counts.append
    for i, text in enumerate(texts):
        grams = char_ngrams(bytes(text,'utf-8'), n_range)
        counter =  Counter( [ crc32(gram) % num_buckets for gram in grams ] )
        for col_el, col_count in list( counter.items() ):
            col_append(np.uint16(col_el))
            row_append(np.uint32(i))
            cr_append(np.uint16(col_count))
    return sparse.csr_matrix((cr_counts,(row_idx,col_idx)), shape = (len(texts), num_buckets), dtype=np.uint16)

def get_chunks(texts, num_chunks = 8):
    rtn = []
    chunk_size = ( len(texts) // num_chunks ) + 1
    for chunk in range(num_chunks):
        rtn.append(texts[chunk*chunk_size:(chunk+1)*chunk_size])
    return rtn

def par_count0(structured_input):
    texts = structured_input['texts']
    n_range = structured_input['n_range']
    num_buckets = structured_input['num_buckets']
    return light_hashed_ngram_count(texts, n_range=n_range, num_buckets=num_buckets)

def parallel_hashed_ngram_count(texts, n_range=[5], num_buckets=10000, num_chunks=8):
    chunks = get_chunks(texts, num_chunks=num_chunks)
    structured_chunks = [{'texts':chunk, 'n_range':n_range, 'num_buckets':num_buckets} for chunk in chunks]
    tmp = Parallel(n_jobs=num_chunks)(delayed(par_count0)(chunk) for chunk in structured_chunks)
    return sparse.vstack([t for t in tmp])


# s = input('* press enter to quit system')

P = []
O = []
N = []

while 1:
    s = input()
    if s == '':
        break

    try:
        num = int(s)
    except:
        continue

    if num < 0:
        N.append(s)
    elif num == 0: # s = 0 : binding , s == 0 : check number
        O.append(s)
    else:
        P.append(s)

output = N + O + P
print(output)


import serial
import sys
import time

port_dest = "/dev/cu.wchusbserial1420"
print("Starting port %s" % port_dest)
port = serial.Serial(port_dest, baudrate=1000000)

msg = ""

period = 0

while True:
    a = port.read(1)
    a = a.hex()

    if a == '55':
        b = port.read(1).hex()
        if b == 'a8':
            c = port.read(1).hex()
            if c == 'bb':
                #End Packet
                print(msg)
            msg = ""

    msg += a

while True:
    a = port.read(1)
    a = a.hex()

    if a == '55':
        b = port.read(1).hex()
        if b == 'a8':
            #End Packet
            asd = msg[2:]
            if asd[0:4] == '01a1':
                print(asd, time.time() - period)
            msg = ""
            period = time.time()
    msg += a

    #d = int(a.encode('hex'),16)
    #sys.stderr.write('{:#010b}({:02X}) '.format(d, d))
    #print('{:02X}'.format(d))
#sys.stderr.write('%s' % a.encode('hex'))


# В качестве входных данных программе подается шестизначное десятичное число. Выведите числа:
# 1. Составленное из цифр, стоящих на четных позициях в данном числе, записанных в обратном порядке.
# 2. Составленное из цифр, стоящих на нечетных позициях в данном числе.
# 3. Произведение двух вышеуказанных чисел.
#
# Все результирующие числа должны быть выведены на одной строке с символом “#” в качестве разделителя.
#
# Входные данные: одно целое положительное число, вводится с клавиатуры.
# Вывод программы: три числа в одной строке, разделенных символом “#”
#
# Пример
# Входные данные: 123456
# Вывод программы: 642#135#86670
#
# Примечание. В решении задачи запрещено использовать строки, циклы, списки и т.д.
# Используйте только целые числа и операции с ними.

num = int(input())

figure_1 = num % 1000000 // 100000
figure_2 = num % 100000 // 10000
figure_3 = num % 10000 // 1000
figure_4 = num % 1000 // 100
figure_5 = num % 100 // 10
figure_6 = num % 10

even_nums = figure_6 * 100 + figure_4 * 10 + figure_2
odd_nums = figure_1 * 100 + figure_3 * 10 + figure_5

print(even_nums, odd_nums, even_nums * odd_nums, sep='#')


import tkinter as tk

root = tk.Tk()

titleLabel = tk.Label(root, text = "Science formula Calculator", font= ("Helvetica", 30, ), foreground = "orange")
titleLabel.grid( row = 0, column = 0, columnspan = 2 )

output = tk.Text(root, height = 10, width = 50)
output.config(state = "disable")
output.grid(row = 1, column = 0, columnspan = 2)

word1Label = tk.Label(root, text = "Value 1", background = "Green", foreground = "yellow")
word1Label.grid(row =2, column = 0, sticky = "NESW")

word1Label = tk.Label(root, text = "Value 2", background = "Green", foreground = "yellow")
word1Label.grid(row =3, column = 0, sticky = "NESW")

word1Label = tk.Label(root, text = "Value 3", background = "Green", foreground = "yellow")
word1Label.grid(row =4, column = 0)

ent1 = tk.Entry(root)
ent1.grid(row = 2, column = 1)

ent2 = tk.Entry(root)
ent2.grid(row = 3, column = 1)

ent3 = tk.Entry(root)
ent3.grid(row = 7, column = 1)

btnGo = tk.Button(root, text = "Generate")
btnGo.grid(row = 8, column = 1)

import tkinter as tk

canvas = tk.Canvas(root,width =300, height = 100, background = "blue")
canvas.grid(row = 5, column = 0, columnspan = 2 )

canvas1 = tk.Canvas(root,width =300, height = 100, background = "red")
canvas1.grid(row = 6, column = 0, columnspan = 2)

root.mainloop()

root.mainloop() # starts the program


import pymongo

from pymongo import MongoClient
client = MongoClient()

db = client['testme']

print(db)

posts = db.myNewCollection
post_data = {
    'title': 'Python and MongoDB',
    'content': 'PyMongo is fun, you guys',
    'author': 'Scott'
}
result = posts.insert_one(post_data)

x = posts.find_one()
print(x)

Ben's Stuff (Pending Title)/DataCreator/pymongo1.py


# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand

from creacion_firma.models import User
from creacion_firma.utils import get_files_dir, pdfparser

import os
#path_pdfs = "/home/agmartinez/Timbrado INMEGEN/TIMBRADO 2016/QNA 05 2016/pdfs/"

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('--clave',
                default=None,
                help='clave presupuestal')
        parser.add_argument('--curp',
                default=None,
                help="")
        parser.add_argument('--path',
                default=None,
                help='path to files')

    def handle(self, *args, **options):
        clave = options.get('clave', "")
        path = options.get('path', "")
        if clave:
            self.find_clave(clave, path)
        else:
            curp = options.get('curp', "")
            self.find_curp(curp, path)

    def find_clave(self, clave, path):
        pdf_files = get_files_dir(path)
        data_path = pdfparser([os.path.join(path, f) for f in pdf_files])
        for data, path in data_path:
            if data.find(clave) != -1:
                print(clave, path)
                break

    def find_curp(self, curp, path):
        files = get_files_dir(path)
        for file_ in [os.path.join(path, f) for f in files]:
            with open(file_, 'r') as f:
                if f.read().find(curp) != -1:
                    print(curp, file_)
                    break


import sys
from PyQt5 import QtWidgets, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

# Global Variables for stack index
LOGIN_REGISTER = 0
HOME = 1

#comment

# To change between Pages - self.parent().setCurrentIndex(HOME)
#          Changes depending on what you want to switch to ^
class LoginRegisterWidget(QtWidgets.QWidget):  # Normal LoginPage
    def __init__(self, parent):
        QtWidgets.QWidget.__init__(self, parent)
        self.setup()

    def setup(self):
        # Our Layout
        self.box_layout = QtWidgets.QVBoxLayout()
        # Login Button
        self.login_button = QtWidgets.QPushButton("Login", self)
        self.login_button.clicked.connect(self.login_click)

        # Register Button
        self.register_button = QtWidgets.QPushButton("Register", self)
        self.register_button.clicked.connect(self.register_click)

        # Adding buttons to layout
        self.box_layout.addWidget(self.login_button)
        self.box_layout.addWidget(self.register_button)

        self.setLayout(self.box_layout)

    def login_click(self):
        self.login_dialog = QDialog()
        self.login_dialog.setWindowTitle("Login")
        self.login_dialog.exec_()

    def register_click(self):
        self.register_dialog = QDialog()
        self.register_dialog.setWindowTitle("Register")
        self.register_dialog.exec_()

class HomeWidget(QtWidgets.QWidget): # HomeWidget for joining, creating match
    def __init__(self, parent):
        QtWidgets.QWidget.__init__(self, parent)
        self.setup()

    def setup(self):
        # Our Layout
        self.box_layout = QtWidgets.QVBoxLayout()
        # Create Match Button
        self.create_button = QtWidgets.QPushButton("Create Match", self)
        self.create_button.clicked.connect(self.create_click)

        # Join Match Button
        self.join_button = QtWidgets.QPushButton("Join Match", self)
        self.join_button.clicked.connect(self.join_click)

        # Current Match Button
        self.current_button = QtWidgets.QPushButton("Current Match", self)
        self.current_button.clicked.connect(self.current_click)

        # Adding buttons to layout
        self.box_layout.addWidget(self.create_button)
        self.box_layout.addWidget(self.join_button)
        self.box_layout.addWidget(self.current_button)

        self.setLayout(self.box_layout)

    def create_click(self):
        self.garbage = 0

    def join_click(self):
        self.garbage = 0

    def current_click(self):
        self.garbage = 0

# INDEXES FOR STACK
# 0 - LoginRegisterWidget
# 1 - HomeWidget

class MainWindow(QtWidgets.QMainWindow):  # Main Window
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.setup()

    def setup(self):
        self.setGeometry(0, 0, 700, 700)
        self.setFixedSize(700, 700)  # eliminating resizing
        self.setWindowTitle("Fantasy Football")

        self.PageStack = QStackedWidget(self)

        # Creating our pages for the stack
        self.main_page = LoginRegisterWidget(self)
        self.home_page = HomeWidget(self)

        # Adding to stack; Pages indexed in order of addition
        self.PageStack.addWidget(self.main_page) # Index 0
        self.PageStack.addWidget(self.home_page) # Index 1

        self.setCentralWidget(self.PageStack)
        self.show()

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    app.exec_()