def _db_graph(self): """ Log results in the db and display the graph """ tree = self.info["TestTree"] connection = db_init() cursor = connection.cursor() db_create_if_need(cursor) db_insert(cursor, tree.success, tree.fail) try: import pygame except: print "Pygame module is not present on your computer" else: confirm = raw_input("Do you want to display the graph ? (y/n) ") if confirm == "y" or confirm == "Y": cat = {} for sub in tree.subcat: cat[sub.cat] = (sub.success, sub.fail) cat["all"] = (tree.success, tree.fail) graph(cat, cursor) connection.commit() connection.close()
def update_net(rrd): traffic = get_traf() for i in traffic.iteritems(): rrd_db = db_path + i[0] + '.' + rrd['net'] # Update rrd db rrdtool.update( rrd_db, 'N:%s:%s' % ( int(i[1]['in']), int(i[1]['out']) )) # Generate graph graph(rrd, 'net')
def getGraphDistance(f1, f2): start = time.clock() g1, g2 = graph(f1['basic_blocks']), graph(f2['basic_blocks']) distance = float(graph_edit_distance(g1, g2)) graph_similarity = 1 - ( distance / (g1.getGraphBlocks() + g1.getGraphEdges() + g1.getGraphSize() + g2.getGraphBlocks() + g2.getGraphEdges() + g2.getGraphSize())) return graph_similarity, time.clock() - start
def __init__(self, *args, **kwargs): x = getPrice() month = getChangeMonth("BCH") week = getChangeWeek("BCH") day = getChangeDay("BCH") Page.__init__(self, *args, **kwargs) label = tk.Label(self, text="The current price of Bitcoin Cash is $" + str(x["BCH"])) label.pack(side="top", pady=50) monthLabel = tk.Label( self, text="The monthly change is {0:.2f}%".format(month)) if month >= 0: monthLabel.config(fg="green") else: monthLabel.config(fg="red") monthLabel.pack(side="top") weekLabel = tk.Label(self, text="The weekly change is {0:.2f}%".format(week)) if week >= 0: weekLabel.config(fg="green") else: weekLabel.config(fg="red") weekLabel.pack(side="top") dayLabel = tk.Label(self, text="The daily change is {0:.2f}%".format(day)) if day >= 0: dayLabel.config(fg="green") else: dayLabel.config(fg="red") dayLabel.pack(side="top") button = tk.Button(self, text="Graph (1 Month)", bg="purple", fg="white", width=25, height=4, command=lambda: graph(currency("month", "BCH"))) button.pack(side="left", padx=130, pady=50) button = tk.Button(self, text="Graph (1 Week)", bg="purple", fg="white", width=25, height=4, command=lambda: graph(currency("week", "BCH"))) button.pack(side="left", padx=60, pady=50) button = tk.Button(self, text="Graph (1 Day)", bg="purple", fg="white", width=25, height=4, command=lambda: graph(currency("day", "BCH"))) button.pack(side="left", padx=130, pady=50)
async def profile(message): worth = 0.0 #get balance of user balance = float(wrapper_select_balance(message.author.id)) balance = round(balance, 2) #get all companies of user all_companies = wrapper_all_companies(message.author.id) companies = [None] * len(all_companies) for ii, company in enumerate(all_companies): companies[ii] = company + " ($" + str( float(round(wrapper_select_curr_val(message.author.id, company), 2))) + ")" worth += float(wrapper_select_curr_val(message.author.id, company)) #worth is current value of stocks + balance worth += balance worth = round(worth, 2) #get total profit of user profit = str(round(wrapper_select_profit(message.author.id), 2)) #check for negative if ('-' in profit): profit = profit.replace('-', '-$') else: profit = "$" + profit #format message embed = discord.Embed(title="Profile 👤", color=0xcc33ff) embed.add_field(name="Name", value=message.author.mention, inline=False) embed.add_field(name="Balance", value="$" + str(balance), inline=False) embed.add_field(name="Worth", value="$" + str(worth), inline=False) embed.add_field(name="Toal Profit", value=profit, inline=False) embed.add_field(name="Companies", value=companies, inline=False) #generates graph with matplotlib and saves to .png named after userId graph(message.author.id, message.author.name) #get .png graph filename = str(message.author.id) + '.png' #uploads to imgur from local im = pyimgur.Imgur(CLIENT_ID) #gets link of imgur upload image = im.upload_image(filename) #embeds message in discord embed.set_image(url=image.link) await message.channel.send(embed=embed)
def update_mem(rrd, db_type): rrd_db = db_path + rrd[db_type] #Get memmory data mem = get_mem() print mem # Debug # Update rrd db print('Updating mem DB') rrdtool.update( rrd_db, 'N:%s:%s:%s:%s:%s' % (int(mem['free'])*1000, int(mem['total'])*1000, int(mem['cached'])*1000,int(mem['buffers'])*1000, int(mem['used'])*1000 )) # Generate graph graph(rrd, db_type)
def getGraphDistance(f1, f2): g1 = graph(f1['basic_blocks']) g2 = graph(f2['basic_blocks']) distance = float(graph_edit_distance(g1, g2)) similarity = 1 - ( distance / (g1.getGraphBlocks() + g1.getGraphEdges() + g1.getGraphSize() + g2.getGraphBlocks() + g2.getGraphEdges() + g2.getGraphSize())) print 'g1 blocks ', g1.getGraphBlocks() print 'g2 blocks ', g2.getGraphBlocks() print 'g1 edges ', g1.getGraphEdges() print 'g2 edges ', g2.getGraphEdges() print 'graph similarity ', similarity return similarity
def readGraph(filename): ''' Reads CFG from specified file. Deprecated. @param filename: name of the file, from which to read from. ''' f = open(filename, 'r') s = f.readline() nodes = {} root = None while s != '': try: filt = lambda x: x != '' a = s.rstrip('\r\n').split(':') b = a[1].split(';') c = filter(filt, b[0].split(',')) d = filter(filt, b[1].split(',')) c = [x for x in c if x != ''] nodes[a[0]] = node(a[0], c, d) if root is None: root = a[0] except: pass s = f.readline() f.close() return graph(root, nodes)
def __init__(self): """ Initialize a hypergraph. """ self.node_links = {} # Pairing: Node -> Hyperedge self.edge_links = {} # Pairing: Hyperedge -> Node self.graph = graph() # Ordinary graph
def assignment(cost_matrix): n = len(cost_matrix) vertices = list(range(1, n + 1)) gr = graph(n, cost_matrix) for i in vertices: for j in vertices: #print(gr.has_edge(i, j)) if gr.has_edge(i, j): w = cost_matrix[i - 1][j - 1] gr.add_edge(i, j) start_time = float(round(time.time() * 1000, 5)) mst_prims = prims(gr) end_time = float(round(time.time() * 1000, 5)) end = end_time - start_time print('Prims algorithm MST(total cost: ' + str(cost(mst_prims)) + '; runtime:' + str(end) + 'ms)') print_graph(mst_prims) start_time = float(round(time.time() * 1000, 5)) mst_krus = kruskals(gr) end_time = float(round(time.time() * 1000, 5)) end = end_time - start_time print('Kruskals algorithm MST(total cost: ' + str(cost(mst_krus)) + '; runtime:' + str(end) + 'ms)') print_graph(mst_krus)
def pintaRecta(self): #print("hola la pendiente es: ",self.txtPendiente.get()) pendiente = self.txtPendiente.get() ordenada = self.txtOrdenada.get() pntInicial = self.txtpntInicial.get() periodo = self.txtPeriodo.get() sumas = self.txtSumas.get() valida = validaStrings() edo = 0 if (valida.validaCadena(pendiente) < 1): edo = 1 if (valida.validaCadena(ordenada) < 1): edo = 1 if (valida.validaCadena(pntInicial) < 1): edo = 1 if (valida.validaCadena(periodo) < 1): edo = 1 if (valida.validaCadena(sumas) < 1): edo = 1 if (edo == 0): carac = pntInicial.split("*") if (len(carac) > 1): npntI = float(carac[0]) * np.pi else: npntI = float(pntInicial) nper = valida.getValorCadena(periodo) npen = valida.getValorCadena(pendiente) nord = valida.getValorCadena(ordenada) pintar = graph(npntI, nper, int(sumas)) pintar.plotRecta(npen, nord)
def getRandomGraph (minNumNodes, maxNumNodes): g = graph () numNodes = randomint(minNumNodes, maxNumNodes) currNode = 0 i = numNodes while (i>0): weight = randomint(0, numNodes * 2) g.addNode ([], weight) i -= 1 while (currNode < numNodes): numNeighbors = randomint(0, numNodes - 1) neighbors = [] possible = [] j = numNodes - 1 while (j >= 0): if (not (j == currNode)): possible.append (j) j-=1 i = numNeighbors while (i > 0): index = randomint (0, len(possible) - 1) neighbor = possible.pop(index) neighbors.append (neighbor) l = g.getNeighbors(neighbor) if (not (currNode in l)): l.append (currNode) g.setNeighbors (neighbor, l) i-=1 l = g.getNeighbors (currNode) for node in neighbors: if (not(node in l)): l.append (node) g.setNeighbors (currNode, l) currNode += 1 return g
def djs_distance(m_map, x1, x2, y1, y2): m_graph = graph(m_map, 0) v = pos2idx(m_map, x1, y1) a = pos2idx(m_map, x2, y2) _, path = m_graph.dijkstra(v, a, m_map) dist = path[a] return dist
def testgetEdge(self): """Tests if it is possibel to get edge from the graph""" Test = graph() Test.add_vertices(10) Test.add_edge([2, 3]) e = edge([2, 3]) self.assert_(Test.get_edge(0).get_vertices() == [2, 3])
def conservative_alloc(fish_map, power_list, enemy_list, own_list): task_list = [] # start= time.time() for o in own_list: tmp_map = copy.deepcopy(fish_map) if len(enemy_list): for e in enemy_list: x1 = o.x y1 = o.y x2 = e.x y2 = e.y dist1 = abs(x1 - x2) dist2 = abs(y1 - y2) if dist1 <= constants.add_enemy_vision and dist2 <= constants.add_enemy_vision: tmp_map.add_enemy(e, o) m_graph = graph(tmp_map, 1) v = pos2idx(tmp_map, o.x, o.y) o.dijkstra(v, tmp_map, m_graph.matrix) # end= time.time() # print "!!!!!!!!!!!!!!!!",end-start,"s" #**********************************************# for p in power_list: value = p.point x = p.x y = p.y _task = task(x, y, value) _task.info = "power_task" _task.id = len(task_list) task_list.append(_task) # own_list----------task_list connection_list = [] for o in own_list: _task = fish_map.wander_task[o.id] _task.id = len(task_list) task_list.append(_task) _connection = connection(o, _task, own_list, tmp_map) connection_list.append(_connection) for t in task_list: if t.info == "wander_task": break else: _connection = connection(o, t, own_list, tmp_map) connection_list.append(_connection) # connection result_alloc = [] # print "the length of task list is ",len(task_list) # for t in task_list: # print "(",t.x,t.y,")", while to_be_alloc(own_list): _connection = choose_connection(connection_list) own_id = _connection.a task_id = _connection.b delete_own(own_id, own_list, connection_list) delete_task(task_id, task_list, connection_list) result_alloc.append(_connection) return result_alloc
def testSetGraphDegree(self): """This function sets the degree of vertex in the graph""" Test = graph() Test.add_vertices(4) Test.get_vertex(2).set_degree(3) self.assert_(Test.get_vertex(2).get_degree() == 3) self.assert_(Test.get_vertex(1).get_degree() == 0) self.assert_(Test.get_vertex(3).get_degree() == 0)
def testAddVertices(self): """Tests if it is possoble to add and get vertices from graph""" Test = graph() Test.add_vertices(4) self.assert_(Test.get_vertices_number() == 4) Test.add_vertices(8) self.assert_(Test.get_vertices_number() == 12) for i in range(0, 12): self.assert_(Test.get_vertex(i).get_number() == i)
def testGetEdgePosition(self): """Tests if it is possible to get edge position in the graph""" Test = graph() Test.add_vertices(10) e1 = Test.add_edge([2, 3]) e2 = Test.add_edge([5, 1]) pos1 = Test.get_edge_position(e1) pos2 = Test.get_edge_position(e2) self.assert_(e1 == Test.get_edge(pos1)) self.assert_(e2 == Test.get_edge(pos2))
def getVertices(self): return self.vertList.keys() g=graph() for i in range(3): g.addVertex(i) g.vertList g.addEdge(0,1,2) g.addEdge(1,0,2) g.addEdge(2,4,5) print()
def __init__(self, problem): self.problem = problem self.striking_shots = None self.index_lim = ((0, 0), (0, 0)) self.grid = None self.graph = graph() self.solution = [] self.step = self.problem.pos_step self.radius = self.problem.robot_radius self.min_dist = self.problem.min_dist if (self.min_dist is None): self.min_dist = 2 * self.problem.robot_radius
def update_cpu(rrd): physicals = cpus() cores = cpu_cores() load = cpu_load() print(load) # update all db_all = db_path + rrd['cpu'] load_all = load['all'] update_cpu_db(db_all, load_all) graph(rrd,'cpu') # Check hyper-threading if check_ht() == 1: cores = cores * 2 # update cores db count = 0 while count < cores: core_load = load[str(count)] core_db = db_path + str(count) + rrd['cpu'] update_cpu_db(core_db, core_load) count = count + 1 graph(rrd, 'cpu') graph(rrd, 'cpu_cores')
def conservative(fish_map, me, power_list, enemy_list, own_list): task_list = [] # make a task list, the target are power and enemy tmp_map = copy.deepcopy(fish_map) if len(enemy_list): for e in enemy_list: x1 = me.x y1 = me.y x2 = e.x y2 = e.y dist1 = abs(x1 - x2) dist2 = abs(y1 - y2) if dist1 <= constants.add_enemy_vision and dist2 <= constants.add_enemy_vision: tmp_map.add_enemy(e, me) m_graph = graph(tmp_map, 1) # add task # 0 idx = me.id fish_map.wander_task_check(me, 1) _task = fish_map.wander_task[idx] task_list.append(_task) # 1 for p in power_list: x1 = me.x y1 = me.y x2 = p.x y2 = p.y dist1 = abs(x1 - x2) dist2 = abs(y1 - y2) if dist1 <= constants.power_vision and dist2 <= constants.power_vision: if tmp_map.map[y2][x2] == 0: #bug!!!!!!!!!!! value = p.point / distance_(x1, y1, x2, y2) _task = task(x2, y2, value) _task.info = "power_task" task_list.append(_task) else: # print "!!!!!!!!!!!!! power is enemy" pass else: pass m_task = choose_task(task_list) if m_task.info == "power_task": tmp = power_list[:] for p in tmp: if p.x == m_task.x and p.y == m_task.y: power_list.remove(p) if p_round_info: print "id", me.id, "from(", me.x, me.y, ")", "to(", m_task.x, m_task.y, ")", m_task.info control = m_graph.move_direction(tmp_map, me.x, me.y, m_task.x, m_task.y) return control
def _make_usable_graph(self, g): if type(g).__module__ == 'numpy' and type(g).__name__ == 'ndarray': # check for the lowest dimensions v = min(g.shape) # make up graph object gg = graph(v) gg.set_graph(g) return gg elif type(g) is 'instance' and isinstance(g, graph) : return g return None
def readExGraph(filename): ''' Reads CFG from specified file. Deprecated. @param filename: name of the file, from which to read from. ''' p1 = re.compile(r'(\d+)\((.*?)\)') p2 = re.compile(r'(\d+)\[(.*?)\]') def procTF(arr): for x in range(len(arr)): m1 = p1.search(arr[x]) if m1 is not None: arr[x] = (m1.group(1), m1.group(2)) else: arr[x] = (arr[x], 'o') return arr def procB(s): m1 = p1.search(s) if m1 is not None: return (m1.group(1), m1.group(2), True) # conditional only m2 = p2.search(s) if m2 is not None: return (m2.group(1), m2.group(2), False) # complex node return (s, '', False) f = open(filename, 'r') s = f.readline() nodes = {} root = None while s != '': try: filt = lambda x: x != '' a = s.rstrip('\r\n').split(':') b = a[1].split(';') i = [] o = [] n = procB(a[0]) for x in filter(filt, b[0].split(',')): i.append(edge(x, n[0])) for (x, t) in procTF(filter(filt, b[1].split(','))): o.append(edge(n[0], x, t)) nodes[n[0]] = node(n[0], i, o, conditional=n[2], code=n[1]) if root is None: root = n[0] except: pass s = f.readline() f.close() return graph(root, nodes)
def submit(self): self.app.body.urls.save_set() self.vals = {} for col in self.inputs.keys(): self.vals[col] = self.inputs[col].text() print(f'{col}: "{self.vals[col]}"') self.inputs[col].setText("") # TODO multi process, call(url=self.vals['URL'], k=self.vals['K']) # check if file empty self.validate_file() self.app.body.init_urls(True) self.app.graph = graph(self.app, new=True) self.exit()
def testAddEdge(self): """Tests adding edge into the graph""" Test = graph() Test.add_vertices(4) Exc = False try: Test.add_edge([3, 2, 3, 8]) except OrderMismatch: Exc = True self.assert_(Exc) Test.add_edge([3, 2]) Exc = False try: Test.add_edge([3, 4]) except OutofRange: Exc = True self.assert_(Exc) self.assert_(Test.get_edge_number() == 1)
def createGraph(imgArray): # Creating a variable to track if we've # found the start of the Maze startFound = False # Next we find the number of dimensions in the array # (which should only be 2 in this case). This needs # to be stored, as nparray.shape is just a function # that returns a list each time it is called aDims = imgArray.shape # Next we instantiate an instance of the graph object # to store the eventual graph mazeGraph = graph() for y in range(aDims[0]): # First, we check if we're looking at the first row # in the Maze if y == 0: # If it is, we then scan the first line for the # start of the maze for x in range(aDims[1]): # We check for the one White pixel that signals # the start of the Maze if imgArray[y, x] == 1: # Once we find the start, we add it to the # graph labeled as "Start", then we can exit # out of the loop, as there will only ever be # one Start point on the top of the maze mazeGraph.add_vertex("Start") # After we find the start of the maze, we can loop over each # row of the maze to check if we've found for x in range(aDims[1]): # We check if the current pixel is white (part of the path) if imgArray[y, x] == 1: if imgArray if fLine == True: mazeGraph.add_edge("Start") startFound = True
def pintaExp(self): #print("hola la pendiente es: ",self.txtPendiente.get()) amplitud = self.txtAmplitud.get() frecuencia = self.txtFrecuencia.get() ordenada = self.txtOrdenada.get() pntInicial = self.txtpntInicial.get() periodo = self.txtPeriodo.get() sumas = self.txtSumas.get() #realizamos la validacion de las entradas del usuario valida = validaStrings() edo = 0 if(valida.validaCadena(amplitud)==0): edo = 1 if(valida.validaCadena(frecuencia)==0): edo = 1 if(valida.validaCadena(ordenada)==0): edo = 1 if(valida.validaCadena(pntInicial)==0): edo = 1 if(valida.validaCadena(periodo)==0): edo = 1 if(valida.validaCadena(sumas)==0): edo = 1 if(edo==0): carac = pntInicial.split("*") if(len(carac)>1): npntI = float(carac[0])*np.pi else: npntI = float(pntInicial) nper = valida.getValorCadena(periodo) namp = valida.getValorCadena(amplitud) nfrec = valida.getValorCadena(frecuencia) nord = valida.getValorCadena(ordenada) pintar = graph(npntI,nper,int(sumas)) pintar.plotExponencial(namp,nfrec,nord)
def prims(graph_G): vertices_no = graph_G.get_vertices() vertices_list = list(range(1, vertices_no + 1)) u = [vertices_list[0]] T = [] mst_cost_matrix = [[-1 for i in range(0, vertices_no)] for j in range(0, vertices_no)] cost = 0 while len(u) <= len(vertices_list): if len(u) == len(vertices_list): break else: max = 100 v = 0 start = 0 for vertex in u: temp_list = graph_G.cost_matrix[vertex - 1] for i in range(len(temp_list)): if temp_list[i] > 0 and temp_list[i] < max and ( i + 1) not in u: max = temp_list[i] v = (i + 1) start = vertex cost = cost + max u.append(v) mst_cost_matrix[start - 1][v - 1] = max mst_cost_matrix[v - 1][start - 1] = max T.append((start, v)) graph_R = graph(vertices_no, mst_cost_matrix) for key in T: graph_R.add_edge(key[0], key[1]) return graph_R
def result(input_): file_inp = open(input_, "r") vert_edge = file_inp.readline().split() n_vertices = int(vert_edge[0]) n_edges = int(vert_edge[1]) network = graph(n_vertices, n_edges) input_graph = [[n_edges, n_vertices]] for _ in range(n_edges): inp = file_inp.readline().split() from_edge = inp[0] to_edge = inp[1] weight = int(inp[2]) input_graph.append([inp[0], inp[1], inp[2]]) network.addEdge(from_edge, to_edge, weight) source_dest = file_inp.readline().split() source_router = source_dest[0] destination_router = source_dest[1] network.set_source_dest(source_router, destination_router) queue = priority_queue.priority_queue() dist, prev, steps = dijkstra(network, queue) return(steps, dist, prev, input_graph)
def _found_graph(self): """This is internal function. It generate random hypergraph according to the specification in the bdz class. It returns a queue of the edge and changes internal datastructure of BDZ class. Returned edges are ordered in such way, that they can be used for the construction of the PHF""" #First step is to initialize seed self.seed = dict() #Second step is to generate the random hash functions hashes = list() for i in range(0,self.function_number): x = jenkins_wrapper() x.generate_seed() # x = h3_hash() # x.set_bitsize(16) # x.set_input_size(len(self.key_set[0])) # x.generate_seed() hashes.append(x) self.seed["hashes"] = hashes #setting m self.m = int(math.ceil(self.ratio * len(self.key_set))) limit = int(math.ceil(float(self.m) /self.function_number)) self.m = 3*limit #print("XXXXXXXXXXXXXXX",limit, self.m) #Generation of hypergraph hyper = graph() hyper.set_order(self.function_number) hyper.add_vertices(self.m) #Generation of the edges of the hypergraph for x in self.key_set: values = list() for i in self.seed["hashes"]: #print("test",i.hash(x)%limit,limit*len(values)) vertex = (i.hash(x) % limit) + limit*len(values) values.append(vertex) #Add this edge into the hypergraph e = hyper.add_edge(values) # print(e.get_vertices()) #Add edge to the vertices for v in values: hyper.get_vertex(v).add_edge(e) #Generate queue for the edge evaluation queue_list = [] queue = deque() #Boolean vector of the used edges used = [False] * hyper.get_edge_number() #First remove edges that have at least one vertex with degree 1 for i in range(0,hyper.get_edge_number()): vert = hyper.get_edge(i).get_vertices() #print([hyper.get_vertex(x).get_degree() for x in vert]) Deg = [hyper.get_vertex(x).get_degree() == 1 for x in vert] if sum(Deg) > 0 and used[i] == False: #This edge has at least one vertex with degree 1 used[i] = True queue_list.append(i) queue.append(i) #Removing edges that have unique vertex (on the stack) #adding a new edges with unique vertex into stack while(len(queue)>0): edge = queue.popleft() #remove edge from the graph (only from vertex and decrease degree) for v in hyper.get_edge(edge).get_vertices(): hyper.get_vertex(v).get_edges().remove(hyper.get_edge(edge)) deg = hyper.get_vertex(v).get_degree() - 1 #print("KVIK",deg) hyper.get_vertex(v).set_degree(deg) #if degree decrease to 1, the remaining edge should be added #into the queue if(deg == 1): #Found the edge position e1 = hyper.get_vertex(v).get_edges()[0] position = hyper.get_edge_position(e1) #If it is not in the queue, put it there if used[position] == False: queue.append(position) queue_list.append(position) used[position] = True self.hyper = hyper return queue_list
from graph import * from traversal import * from path import * from TopOrdering import * from Dijkstra import * G = graph() G.addVertex(5) G.addEdge(0, 1, True, 1) G.addEdge(0, 2, True, 1) G.addEdge(0, 3, True, 1) G.addEdge(0, 4, True, 1) G.addEdge(1, 3, True, 1) G.addEdge(2, 1, True, 1) G.addEdge(2, 4, True, 1) G.addEdge(3, 4, True, 1) G.addEdge(3, 2, True, 1) print "Represenation of the Graph" G.printEdges() print print G.adj """ print "Remove Edge" G.removeEdge(3,2) G.printEdges() print print "Adjacency Matrix" AM = G.makeAdjMatrix() for r in AM: print r print
r1, sx1, sy1, fx1, fy1, stheta1, ftheta1 = get_all(method) r2, sx2, sy2, fx2, fy2, stheta2, ftheta2 = get_all(method) question = "" answer = "" distractor1 = "" distractor2 = "" distractor3 = "" if initial == "xy": if method == "coord": question = "Un vecteur $OM$ a pour coordonnées $(" + sx1[0] + "," + sy1[0] + ")$ et un vecteur $OM'$ a pour coordonnées $(" + sx2[0] + "," + sy2[0] + ")$. Que vaut le produit scalair entre ces deux vecteurs?" else: question = "Que vaut le produit scalair entre les deux vecteurs ci-dessous? \\\\ \n" + graph( sx1[0], sy1[0], fx1[0], fy1[0], r1[0], stheta1[0], ftheta1[0], initial) + " \n " + graph( sx2[0], sy2[0], fx2[0], fy2[0], r2[0], stheta2[0], ftheta2[0], initial, "O", "M'", "x'", "y'") answer = "$" + str(int(100*fx1[0]*fx2[0]+fy1[0]*fy2[0])/100) + "$" distractor1 = "$" + str(int(100*fx1[1]*fx2[1]+fy1[1]*fy2[1])/100) + "$" distractor2 = "$" + str(int(100*fx1[2]*fx2[2]+fy1[2]*fy2[2])/100) + "$" distractor3 = "$" + str(int(100*fx1[3]*fx2[3]+fy1[3]*fy2[3])/100) + "$" ####################################################################### if initial == "rtheta": if method == "coord": question = "Un vecteur $OM$ a pour rayon " + str(r1[0]) + " et pour angle $\\theta$ (entre le vecteur et l'axe des $x$) $" + stheta1[0] + "$. Un vecteur $OM'$ a pour rayon " + str(r2[0]) + " et pour angle $\\theta'$ (entre le vecteur et l'axe des $x$) $" + stheta2[0] + "$. Que vaut le produit scalair entre ces deux vecteurs?" else: question = "Que vaut le produit scalair entre les deux vecteurs ci-dessous? \\\\ \n" + graph( sx1[0], sy1[0], fx1[0], fy1[0], r1[0], stheta1[0], ftheta1[0], initial) + " \n " + graph( sx2[0], sy2[0], fx2[0], fy2[0], r2[0], stheta2[0], ftheta2[0], initial, "O","M'", "x'", "My'") answer = "$" + str(int(100*r1[0]*r2[0]*math.cos(ftheta1[0]-ftheta2[0]))/100) + "$" distractor1 = "$" + str(int(100*r1[1]*r2[1]*math.cos(ftheta1[1]-ftheta2[1]))/100) + "$" distractor2 = "$" + str(int(100*r1[2]*r2[2]*math.cos(ftheta1[2]-ftheta2[2]))/100) + "$"
import graph soundcloud_graph = graph()
if i == 2: figure() plot(grtc) plot(bsrtc) deviceArray = empty((len(grtc),4)) deviceArray[:,0]=grtc deviceArray[:,1]=bsrtc deviceArray[:,2]=lines deviceArray[:,3]=i allArray = append(allArray, deviceArray,axis=0) allArray = allArray[allArray[:,2].argsort()] graph(allArray[:,0], allArray[:,2], allArray[:,3]) show() data_array = empty((0,13)) for id in pc.IDs(): #if id not in [8,9,10,11,12,13]: print id if not SYNC: gyroTimestamps = pc.gyroRTC(id) accelTimestamps = pc.accelRTC(id) magTimestamps = pc.magRTC(id) else: gyroTimestamps = pc.synchronisedGyroRTC(id) accelTimestamps = pc.synchronisedAccelRTC(id)
return self.vertList[n] else: return None def getVertices(self): return self.vertList.keys() g=graph() for i in range(3): g.addVertex(i) g.vertList g.addEdge(0,1,2) g.addEdge(1,0,2) g.addEdge(2,4,5) print() #A program to implement Dict using Graph# import graph gr=graph() gr.add_nodes(['portugal','spain','France','a','b']) gr.add_nodes(['india','US','3','4']) gr.add_edge(['portugal','a']) gr.add_edge(['spain','b']) gr.add_edge(['indian','3']) print() #A program to implement tuples in Graph# tup1.add_node=('python','network security') tup2.add_node=(py,se) tup.add_edge('python':'programming lang') tup.add_edge('network security':'cse') print tup()
print("\nエンコードエラー", end="") print("\n") def gen_random_sentense(n, graph): print("ランダム文章生成:\n") # unbiased_init_terms = list(set(graph.init_terms)) unbiased_init_terms = [x for x in graph.G.nodes() if x[0] == "0Start"] [gen_random_sentense1(unbiased_init_terms, graph) for x in range(n)] if __name__ == "__main__": N = 1 txts = None graph = graph() if argc == 1: pass elif argc == 2: N = int(argvs[1]) elif argc > 2: N = int(argvs[1]) txts = argvs[2:] sentences = set_sentences(txts) [gen_n_markov_chain(s, N, graph) for s in sentences] # n階マルコフ連鎖 # graph.print_elem() ########################################################### ######################## Outputs #########################
def buildGraphs(Products): """ Construction d'un graph pour chaque produit. Le graph correspond aux chemins que prends ce produit dans le reseau. La structure du graph est toujours la meme: Le noeud de depart est le produit lui-meme. Une source est precedee du prefixe 'rx_'. Un client est precede du prefixe 'tx_'. les noeuds avec le prefixe 'to_' ne sont present que pour lier differentes parties du graph. Il sont par consequent transparent. Le retour de cette fonction est une liste de graphs """ alias = readAliasConf(); graphList = [] for p in Products: product = node("",p,"") g = graph(product) #Pour chaque cluster for i in range(len(Products[p])): cluster = Products[p][i][1] #Pour chaque source for source in Products[p][i][0]: newSource = g.addNode(node("rx_",source,cluster)) g.addLink(product,newSource) #Pour chaque client for client in Products[p][i][2]: newClient = g.addNode(node("tx_",client,cluster)) g.addLink(newSource,newClient) if(client in alias): toNode = g.addNode(node("to_",alias[client],cluster)) g.addLink(newClient,toNode) #Enlever les liens entre le root et un cluster interne listNode = [] for n in product.nextNodes: listNode.append(n) for inode in listNode: if(inode.name in alias): theNode = g.searchNode(node("to_",inode.cluster,alias[inode.name])) if(theNode): g.addLink(theNode,inode) g.removeLink(product,inode) #Sauter par dessus les 'to_' (Ce sont des noeuds transparent) listNode = [] for n in g.nodesList: listNode.append(n) for inode in listNode: listLink = [] for l in inode.nextNodes: listLink.append(l) for link in listLink: if(link.direction == "to_"): for n in link.nextNodes: g.addLink(inode,n) g.removeLink(inode,link) graphList.append(g) return graphList
from graph import * x = graph() x.addVertex(1) x.addVertex(1) x.addVertex(1) x.addVertex(1) x.addVertex(1) print(x.store) x.addEdge(0, 1, False, 1) x.addEdge(0, 2, False, 1) x.addEdge(0, 3, False, 1) x.addEdge(1, 2, False, 2) x.addEdge(1, 4, False, 2) x.addEdge(2, 3, True, 3) x.addEdge(3, 4, True, 4) x.addEdge(4, 5, True, 5) print(x.store) print("Depth") print(x.traverse(0, False)) print("Breadth") print(x.traverse(0, True)) print("Breadth; start=None") print(x.traverse(None, True))
def getGraphFromCodeBlocks(cb, debugDraw=False): ''' Builds CFG from codeblocks. @param cb: codeblocks (see L{CodeBlocks}). @param debugDraw: save intermediate CFGs as images while processing or not. ''' truthTable = { # TODO: recheck this truthTable 'for' : 'for', 'AF' : 'AF', 'loop' : 'loop', 'AL' : 'AL', 'DEAD' : 'DEAD', 'try' : 'try', 'except' : 'except', 'ASF' : 'ASF', 'finally' : 'finally', 'AE' : 'AE', 'JA' : 'JA', 'JF' : '', 'JIF' : 'f', 'NJIF' : 't', 'JIT' : 't', 'NJIT' : 'f' } cbs = sorted(cb.blocks.keys()) root = cb.root nodes = {} # TODO: recheck, optimize, sorted is not necessary?? for index in xrange(len(cbs)): toNode = cbs[index] if index < len(cbs) - 1: nodes[toNode] = node(toNode, [], [], conditional=False, code=str(toNode), offset=toNode, length=cbs[index+1]-toNode) else: nodes[toNode] = node(toNode, [], [], conditional=False, code=str(toNode), offset=toNode, length=0) for toNode in cbs: for ref in cb.blocks[toNode]: dbgprint(str(toNode) + ': ' + str(ref)) type = truthTable[ref.name] if type in ('t', 'f'): nodes[ref.blockxref].conditional = True elif type in ('loop', 'AL'): nodes[ref.blockxref].loop = True elif type in ('for', 'AF'): nodes[ref.blockxref].forloop = True elif type in ('try', 'except'): nodes[ref.blockxref].exceptNode = True elif type in ('finally', 'ASF'): nodes[ref.blockxref].finallyNode = True nodes[toNode].incoming.append(edge(ref.blockxref, toNode, type)) nodes[ref.blockxref].outgoing.append(edge(ref.blockxref, toNode, type)) for i in xrange(len(cbs)-1): if len(nodes[cbs[i]].outgoing) == 0: nodes[cbs[i]].outgoing.append(edge(cbs[i], cbs[i+1], '')) nodes[cbs[i+1]].incoming.append(edge(cbs[i], cbs[i+1], '')) return graph(root, nodes, debugDraw)
from graph import * def pdersets(gr): if len(gr.nds)!=len(gr.asets): gr.crasets(float(raw_input("Don't have subd, input please"))) for i in range(len(gr.nds)): print print gr.nds[i] print gr.asets[i] print gr.nbh[i] file=open('set.dat','r+') lines=file.readlines() els=[] for e in lines: els.append(node([float(x) for x in e.split()])) gr = graph(els) subd=float(raw_input()) gr.crasets(subd) gr.g_cl() #pdersets(gr)
from graph import * from signature import * threshold = 0.85; OLDDIR = os.getcwd() DIR = ".\\.." print "\n--------------------\ncompare_func_sig.py has been started\n" os.chdir(DIR) ea = ScreenEA() for function in Functions(SegStart(ea), SegEnd(ea)): func = get_func(function) fc = FlowChart(func) G = graph(fc) sig = signature(fc, G, True) similarities = sig.compare() similarities.sort() print '_____Results of function at %x (Threshold = %0.2f)_____' % (func.startEA, float(threshold * 100.0)) for item in similarities: if item.sim >= threshold: print 'Algorithm: %s, Compiler: %s, Optimization: %s' % (item.alg, item.cmp, item.opt) print 'Similarity: %0.2f\n' % (float(item.sim)) del G del sig
import matplotlib.pyplot as plt import pandas as pd import math import Selection_Algorithm import math # In[ ]: #TR_i = tr-ceyntrality i subgraph def graph(): import graph Graph = graph.H return Graph H = graph() # In[ ]: #equetion 2:TCi_constrain def TC_constrain_of(i): sdeg_i = (Selection_Algorithm.subgraph_of(i).number_of_nodes() - 1) sum_sdeg_i = (Selection_Algorithm.subgraph_of(i).number_of_edges() * 2) N_i = Selection_Algorithm.subgraph_of(i).number_of_nodes() NT_i = nx.triangles(H, i) #equetion 2:TCi_constrain TC_i_cons = (sdeg_i / sum_sdeg_i) - ((N_i - NT_i) / sum_sdeg_i) return TC_i_cons
from graph import * graph_dict = { 'a': ['d'], 'b': ['e'], 'd e': ['d', 'e', 'c'], 'c': [], 'd': [], 'e': [] } g = graph() g.set_graph(graph_dict) g.print_graph() # for key in g.graph_dict.keys(): # g.closure(key) # g.closure('a b') # g.closure('b c') # g.closure('a c') # g.closure('a b c') # dec = ['a','b','c'] # import itertools # p = itertools.combinations(dec,2) # p_list = list(p) # for item in p_list: # print '.'+(" ".join(item)).strip()+"." s = decomposed_graph() s.gen_decomposed_graph(g) s.print_graph()
from graph import * def printfunc(ver, arg): print(ver.name) gr = graph() gr.bidir = True gr.addvertex(vertex("vert1")) gr.addvertex(vertex("vert2")) gr.addvertex(vertex("vert3")) gr.addvertex(vertex("vert4")) gr.addedge(edge(gr.verts[0], gr.verts[1], value=10)) gr.addedge(edge(gr.verts[0], gr.verts[2], value=20)) gr.addedge(edge(gr.verts[0], gr.verts[3], value=30)) gr.addedge(edge(gr.verts[1], gr.verts[3], value=40)) gr.dotexportpng("autopng0.png") #gr.remvertex(gr.verts[0]) #gr.remedge(gr.edges[0]) #gr.rem2vertsedge(gr.verts[0], gr.verts[1]) #gr.addedge(edge(gr.verts[1], gr.verts[3])) gr.deikstrify2(start=gr.verts[2]) gr.dotexportpng("autopng1.png")
from graph import * graph_dict={ 'a':['d'], 'b':['e'], 'd e':['d','e','c'], 'c':[], 'd':[], 'e':[] } g = graph() g.set_graph(graph_dict) g.print_graph() # for key in g.graph_dict.keys(): # g.closure(key) # g.closure('a b') # g.closure('b c') # g.closure('a c') # g.closure('a b c') # dec = ['a','b','c'] # import itertools # p = itertools.combinations(dec,2) # p_list = list(p) # for item in p_list: # print '.'+(" ".join(item)).strip()+"." s = decomposed_graph() s.gen_decomposed_graph(g) s.print_graph()