def simple(V, E): ''' Returns a random simple graph containing V vertices and E edges. @param V the number of vertices @param E the number of edges @return a random simple graph on V vertices, containing a total of E edges @raises ValueError if no such simple graph exists ''' if E > V * (V - 1) / 2: raise ValueError("Too many edges") if E < 0: raise ValueError("Too few edges") # Modification question #5 if V <= 0: raise ValueError("A simple graph must have at least one vertex") G = Graph(V) edges = [] while G.E() < E: v = rand.randrange(V) w = rand.randrange(V) e = (v, w) if v != w and e not in edges: edges.append(e) G.add_edge(e) return G
def bipartite_with_probability(V1, V2, p): ''' Returns a random simple bipartite graph on V1 and V2 vertices, containing each possible edge with probability p. @param V1 the number of vertices in one partition @param V2 the number of vertices in the other partition @param p the probability that the graph contains an edge with one endpoint in either side @return a random simple bipartite graph on V1 and V2 vertices, containing each possible edge with probability p @raises ValueError if proba bility is not between 0 and 1 ''' if p < 0.0 or p > 1.0: raise ValueError('Probability must be between 0 and 1') # Modification question #5 if V1 < 0 or V2 < 0: raise ValueError("Vertex value cannot be less then 0") vertices = [i for i in range(V1 + V2)] rand.shuffle(vertices) G = Graph(V1 + V2) for i in range(V1): for j in range(V2): if utils.bernoulli(p): G.add_edge((vertices[i], vertices[V1 + j])) return G
def regular(V, k): ''' Returns a uniformly random k-regular graph on V vertices (not necessarily simple). The graph is simple with probability only about e^(-k^2/4), which is tiny when k = 14. @param V the number of vertices in the graph @param k degree of each vertex @return a uniformly random k-regular graph on V vertices. ''' if k >= V: raise ValueError("Too many edges") if k < 0: raise ValueError("number of edges must be positive") if V < 3: raise ValueError("number of vertices must be greater or equal to 3") if V*k % 2 != 0: raise ValueError("Number of vertices * k must be even") G = Graph(V) # create k copies of each vertex vertices = [0 for _ in range(V*k)] for v in range(V): for j in range(k): vertices[v + V*j] = v # pick a random perfect matching rand.shuffle(vertices) while(regularHasSameEdges(vertices)): rand.shuffle(vertices) for i in range(V*k//2): G.add_edge((vertices[2*i], vertices[2*i + 1])) return G
def regular(V, k): ''' Returns a uniformly random k-regular graph on V vertices (not necessarily simple). The graph is simple with probability only about e^(-k^2/4), which is tiny when k = 14. @param V the number of vertices in the graph @param k degree of each vertex @return a uniformly random k-regular graph on V vertices. ''' if V * k % 2 != 0: raise ValueError("Number of vertices * k must be even") # Modification question #5 if V <= 0: raise ValueError("A regular graph must have at least one vertex") G = Graph(V) # create k copies of each vertex vertices = [0 for _ in range(V * k)] for v in range(V): for j in range(k): vertices[v + V * j] = v # pick a random perfect matching rand.shuffle(vertices) for i in range(V * k // 2): G.add_edge((vertices[2 * i], vertices[2 * i + 1])) return G
def bipartite(V1, V2, E): ''' * Returns a random simple bipartite graph on V1 and V2 vertices * with E edges. * @param V1 the number of vertices in one partition * @param V2 the number of vertices in the other partition * @param E the number of edges * @return a random simple bipartite graph on V1 and V2 vertices, * containing a total of E edges * @raises ValueError if no such simple bipartite graph exists ''' if E > V1 * V2: raise ValueError('Too many edges') if E < 0: raise ValueError('Too few edges') # Modification question #5 if V1 < 0 or V2 < 0: raise ValueError("Vertex value cannot be less then 0") G = Graph(V1 + V2) vertices = [i for i in range(V1 + V2)] rand.shuffle(vertices) edges = [] while G.E() < E: i = rand.randrange(V1) j = V1 + rand.randrange(V2) e = (vertices[i], vertices[j]) if e not in edges: edges.append(e) G.add_edge(e) return G
def metric(metric_name=''): graph = Graph([ metric_name, ]) graph.day_graph_need_shift = True graph.auto_refresh = True body = template('templates/graph', **locals()) return render_page(body)
def generate_graph(self, key_name): avg = Graph(key_name = key_name, btc_currency = Currency_Label, btc_avg = [[0] for i in range(len(Currency_Label))], btc_hml = [[] for i in range(len(Currency_Label))], ltc_currency = Currency_Label_LTC, ltc_avg = [[0] for i in range(len(Currency_Label_LTC))], ltc_hml = [[] for i in range(len(Currency_Label_LTC))], timestamp = [datetime.datetime.now()]) avg.put()
def server(server = ''): global diamond graphs = [] for plugin in sorted(diamond[server].keys()): graph = Graph(diamond[server][plugin], title = server + ' ' + plugin) graph.detail_url = '/server/%s/%s' % (server, plugin) graph.detail_title = plugin graphs.append(graph) body = template('templates/graph-list', **locals()) return render_page(body)
def server(server=''): global diamond graphs = [] for plugin in sorted(diamond[server].keys()): graph = Graph(diamond[server][plugin], title=server + ' ' + plugin) graph.detail_url = '/server/%s/%s' % (server, plugin) graph.detail_title = plugin graphs.append(graph) body = template('templates/graph-list', **locals()) return render_page(body)
def path(V): ''' Returns a path graph on V vertices. @param V the number of vertices in the path @return a path graph on V vertices ''' G = Graph(V) vertices = [i for i in range(V)] rand.shuffle(vertices) for i in range(V - 1): G.add_edge((vertices[i], vertices[i + 1])) return G
def get(self): Pavg = Graph.get_by_key_name('price') for i in range(len(Pavg.btc_avg)): del Pavg.btc_avg[i][0] for i in range(len(Pavg.ltc_avg)): del Pavg.ltc_avg[i][0] Vavg = Graph.get_by_key_name('volume') for i in range(len(Vavg.btc_avg)): del Vavg.btc_avg[i][0] for i in range(len(Vavg.ltc_avg)): del Vavg.ltc_avg[i][0] Pavg.put() Vavg.put()
def testBlank(self): # test set up component = Graph(20,10) # test execution actual = component.render() # test verification self.assertEqual(actual, " \n" \ " \n" \ " \n" \ " \n" \ " \n" \ " \n" \ " \n" \ " \n" \ " \n" \ " ")
def ParseGraph(data, image): objects = [] object_map = {} relationships = [] attributes = [] # Create the Objects for obj in data['bounding_boxes']: names = [] synsets = [] for s in obj['boxed_objects']: names.append(s['name']) synsets.append(ParseSynset(s['object_canon'])) object_ = Object(obj['id'], obj['x'], obj['y'], obj['width'], obj['height'], names, synsets) object_map[obj['id']] = object_ objects.append(object_) # Create the Relationships for rel in data['relationships']: relationships.append(Relationship(rel['id'], object_map[rel['subject']], \ rel['predicate'], object_map[rel['object']], ParseSynset(rel['relationship_canon']))) # Create the Attributes for atr in data['attributes']: attributes.append(Attribute(atr['id'], object_map[atr['subject']], \ atr['attribute'], ParseSynset(atr['attribute_canon']))) return Graph(image, objects, relationships, attributes)
def ParseGraphVRD(d): image = Image(d['photo_id'], d['filename'], d['width'], d['height'], '', '') id2obj = {} objs = [] rels = [] atrs = [] for i, o in enumerate(d['objects']): b = o['bbox'] obj = Object(i, b['x'], b['y'], b['w'], b['h'], o['names'], []) id2obj[i] = obj objs.append(obj) for j, a in enumerate(o['attributes']): atrs.append(Attribute(j, obj, a['attribute'], [])) for i, r in enumerate(d['relationships']): s = id2obj[r['objects'][0]] o = id2obj[r['objects'][1]] v = r['relationship'] rels.append(Relationship(i, s, v, o, [])) return Graph(image, objs, rels, atrs)
def filter(): ## canciones[between]=0,20&sexo[equal]=mujer filters = parse_filters(request.args.items()) gph = Graph() people, friendships = friend.filter(filters) statistics = GraphStatistics(gph, people) for k, p in people.iteritems(): gph.add_node(p, 'usuario') for f in friendships: gph.add_edge([f['usuario_1'], f['usuario_2']], songs=f['canciones']) st = statistics.compute() return jsonify({ 'statistics': st, 'nodes': gph.nodes, 'edges': gph.edges })
def ParseGraphLocal(data, image, verbose=False): global count_skips objects = [] object_map = {} relationships = [] attributes = [] for obj in data['objects']: object_map, o_ = MapObject(object_map, obj) objects.append(o_) for rel in data['relationships']: if rel['subject_id'] in object_map and rel['object_id'] in object_map: object_map, s = MapObject(object_map, {'object_id': rel['subject_id']}) v = rel['predicate'] object_map, o = MapObject(object_map, {'object_id': rel['object_id']}) rid = rel['relationship_id'] relationships.append(Relationship(rid, s, v, o, rel['synsets'])) else: # Skip this relationship if we don't have the subject and object in # the object_map for this scene graph. Some data is missing in this way. count_skips[0] += 1 if 'attributes' in data: for attr in data['attributes']: a = attr['attribute'] if a['object_id'] in object_map: attributes.append( Attribute(attr['attribute_id'], a['object_id'], a['names'], a['synsets'])) else: count_skips[1] += 1 if verbose: print 'Skipped {} rels, {} attrs total'.format(*count_skips) return Graph(image, objects, relationships, attributes)
def star(V): ''' Returns a star graph on V vertices. @param V the number of vertices in the star @return a star graph on V vertices: a single vertex connected to every other vertex ''' if V <= 0: raise ValueError("Number of vertices must be at least 1") G = Graph(V) vertices = [i for i in range(V)] rand.shuffle(vertices) # connect vertices[0] to every other vertex for i in range(V): G.add_edge((vertices[0], vertices[i])) return G
def testBlank(self): # test set up component = Graph(20, 10) # test execution actual = component.render() # test verification self.assertEqual(actual, " \n" \ " \n" \ " \n" \ " \n" \ " \n" \ " \n" \ " \n" \ " \n" \ " \n" \ " ")
def get(self): if not (session and session.get('uid')): return jsonify({'error': 'Not logged in'}) user = User.objects.get(id=ObjectId(session.get('uid'))) graphs = Graph.objects(user=user) if len(graphs) == 0: return jsonify({'error': 'No graphs stored!'}) return jsonify(graphs[0].data)
def get_graph(self) -> Graph: script_path = Path(__file__).resolve().parent / 'build_graph.js' script = read_text_file(str(script_path)) self.driver.execute_script(script) graph = self.driver.execute_script('return graph;') graph = Graph(**graph) print(f'Constructed graph with {len(graph.nodes)} nodes.') return graph
def get(self): if not (session and session.get('uid')): return redirect('/login') user = User.objects.get(id=session.get('uid')) graphs = Graph.objects(user=user) if len(graphs) == 0: loaded=False else: loaded = True return render_template('my_graph.html',name=user.name, loaded=loaded)
def testHorizontal(self): # test set up component = Graph(20, 10) start = Coordinate(0, 4) end = Coordinate(19, 4) # test execution component.plot(start, end) actual = component.render() # test verification self.assertEqual(actual, " \n" \ " \n" \ " \n" \ " \n" \ "XXXXXXXXXXXXXXXXXXXX\n" \ " \n" \ " \n" \ " \n" \ " \n" \ " ")
def testVertical(self): # test set up component = Graph(20,10) start = Coordinate(1,1) end = Coordinate(1, 8) # test execution component.plot(start, end) actual = component.render() # test verification self.assertEqual(actual, " \n" \ " X \n" \ " X \n" \ " X \n" \ " X \n" \ " X \n" \ " X \n" \ " X \n" \ " X \n" \ " ")
def eulerianPath(V, E): ''' Returns an Eulerian path graph on V vertices. @param V the number of vertices in the path @param E the number of edges in the path @return a graph that is an Eulerian path on V vertices and E edges @raises ValueError if either V <= 0 or E < 0 ''' if E < 0: raise ValueError("negative number of edges") if V <= 0: raise ValueError("An Eulerian path must have at least one vertex") G = Graph(V) vertices = [] for i in range(E + 1): vertices[i] = rand.randrange(V) for i in range(E): G.add_edge((vertices[i], vertices[i + 1])) return G
def testHorizontal(self): # test set up component = Graph(20,10) start = Coordinate(0,4) end = Coordinate(19,4) # test execution component.plot(start, end) actual = component.render() # test verification self.assertEqual(actual, " \n" \ " \n" \ " \n" \ " \n" \ "XXXXXXXXXXXXXXXXXXXX\n" \ " \n" \ " \n" \ " \n" \ " \n" \ " ")
def get_alt_avg(name): data = memcache.get(name) if data is not None: return {'btc_avg': data.btc_avg,'ltc_avg':data.ltc_avg,'timestamp':data.timestamp, 'btc_hml':data.btc_hml,'ltc_hml':data.ltc_hml} else: data = Graph.get_by_key_name(name) memcache.add(name, data, 60*60*6) return {'btc_avg': data.btc_avg,'ltc_avg':data.ltc_avg,'timestamp':data.timestamp, 'btc_hml':data.btc_hml,'ltc_hml':data.ltc_hml}
def testDiagonal(self): # test set up component = Graph(20, 10) start = Coordinate(1, 1) end = Coordinate(8, 8) # test execution component.plot(start, end) actual = component.render() # test verification self.assertEqual(actual, " \n" \ " X \n" \ " X \n" \ " X \n" \ " X \n" \ " X \n" \ " X \n" \ " X \n" \ " X \n" \ " ")
def testBackDiagonal(self): # test set up component = Graph(20,10) start = Coordinate(4,9) end = Coordinate(14, 0) # test execution component.plot(start, end) actual = component.render() # test verification self.assertEqual(actual, " X \n" \ " X \n" \ " X \n" \ " X \n" \ " X \n" \ " X \n" \ " X \n" \ " X \n" \ " X \n" \ " X ")
def simple_with_probability(V, p): ''' Returns a random simple graph on V vertices, with an edge between any two vertices with probability p. This is sometimes referred to as the Erdos-Renyi random graph model. @param V the number of vertices @param p the probability of choosing an edge @return a random simple graph on V vertices, with an edge between any two vertices with probability p @raises ValueError if probability is not between 0 and 1 ''' if p < 0.0 or p > 1.0: raise ValueError('Probability must be between 0 and 1') G = Graph(V) for v in range(V): for w in range(v+1,V,1): if utils.bernoulli(p): G.add_edge((v , w)) return G
def update_distances(G: Graph, node1: Node, node2: Node): """ This function updates the distances between two nodes :param G: graph :param node1: start node :param node2: destination node :type G: Graph :type node1: Node :type node2: Node """ p = get_weight(G, node1, node2) print(G.distances) print('-' * 10) print(G.distances[node2]) print('-' * 10) print(G.distances[node1]) if G.distances[node2] > G.distances[node1] + p: G.distances[node2] = G.distances[node1] + p G.preds[node2] = node1
def _graph_projects(platform, prjsack): projects = set() prjids = set() for prj in prjsack: projects.add(prj.name) prjids.add(str(prj.id)) projects = sorted(projects) prjids = sorted(prjids) dotfilename = os.path.join(settings.MEDIA_ROOT, "graph", "%s_%s.dot" % (str(platform.id), "_".join(prjids))) graph = _get_or_none(Graph, dot=dotfilename) if not graph: graph = Graph(direction=0) dot = _get_projects_dot(prj.buildservice.apiurl, projects) graph.dot.save(dotfilename, ContentFile(str("\n".join(dot))), save=False) svg = _get_svg(dotfilename, prog="dot") graph.svg.save(dotfilename.replace(".dot",".svg"), File(open(svg)), save=False) graph.save() os.unlink(svg) return graph
def get(self): if BTCurrency.get_by_key_name('btcoin') is None: BTCurrency(key_name = 'btcoin', currency = ['Coinbase','MtGox'], price = [0.0,0.0], timestamp = datetime.datetime.now()).put() if AltCurrency.get_by_key_name('alt_btc') is None: self.generate_data(Currency_Label, 'alt_btc','/BTC') self.generate_data(Currency_Label_LTC, 'alt_ltc','/LTC') if Graph.get_by_key_name('price') is None: self.generate_graph('price') if Graph.get_by_key_name('volume') is None: self.generate_graph('volume') #check if we ened to update the graphs ### TODO CHECK IF THIS WORKS Pavg = util.adjust_avg_database(Graph.get_by_key_name('price'),Currency_Label,Currency_Label_LTC) Vavg = util.adjust_avg_database(Graph.get_by_key_name('volume'),Currency_Label,Currency_Label_LTC) params = {'price':Pavg.btc_avg, 'volume':Vavg.btc_avg, } memcache.set(key="counter", value=0) return self.render_template('about.html', **params)
def get(self): LtcAlt = util.get_alt_data('alt_ltc') BtcAlt = util.get_alt_data('alt_btc') avg = Graph.get_by_key_name('price') for i,v in enumerate(BtcAlt.price): avg.btc_avg[i].append(v) avg.btc_hml[i] = [max(avg.btc_avg[i][-4:]),sum(avg.btc_avg[i][-4:])/4.,min(avg.btc_avg[i][-4:])] for i,v in enumerate(LtcAlt.price): avg.ltc_avg[i].append(v) avg.ltc_hml[i] = [max(avg.ltc_avg[i][-4:]),sum(avg.ltc_avg[i][-4:])/4.,min(avg.ltc_avg[i][-4:])] avg.timestamp.append(LtcAlt.timestamp) avg.put()
def main(argv=None): # IGNORE:C0111 """Command line interface application %s """ % program_usage if argv is None: argv = sys.argv else: sys.argv.extend(argv) graph = Graph(20,10) if(len(sys.argv) > 1): pattern = re.compile("\(([0-9]+),([0-9]+)\) - \(([0-9]+),([0-9]+)\)") vectors = sys.argv[1].split(', ') for coordinates in vectors: result = pattern.match(coordinates) if result: start = Coordinate(int(result.group(1)), int(result.group(2))) end = Coordinate(int(result.group(3)), int(result.group(4))) graph.plot(start, end) print(graph.render())
def main(argv=None): # IGNORE:C0111 """Command line interface application %s """ % program_usage if argv is None: argv = sys.argv else: sys.argv.extend(argv) graph = Graph(20, 10) if (len(sys.argv) > 1): pattern = re.compile("\(([0-9]+),([0-9]+)\) - \(([0-9]+),([0-9]+)\)") vectors = sys.argv[1].split(', ') for coordinates in vectors: result = pattern.match(coordinates) if result: start = Coordinate(int(result.group(1)), int(result.group(2))) end = Coordinate(int(result.group(3)), int(result.group(4))) graph.plot(start, end) print(graph.render())
def graph(request): if request.method == "POST": graph = Graph() graph.title = request.POST["title"] graph.timetric_id = request.POST["id"] graph.user = request.user graph.save() # need this save to make sure there's an ID! token = RemoteToken.objects.filter(user=request.user)[0] source_uuid = add_new_timetric_source(token, graph.title, graph.id) graph.coda_source_id = source_uuid graph.save() return HttpResponseRedirect(urlresolvers.reverse("graph-view", args=[graph.pk,])) else: return HttpResponseNotAllowed(["POST",])
def ParseGraphLocal(data, image_id): global count_skips objects = [] object_map = {} relationships = [] attributes = [] for rel in data['relationships']: object_map, objects, s = MapObject(object_map, objects, rel['subject']) v = rel['predicate'] object_map, objects, o = MapObject(object_map, objects, rel['object']) rid = rel['relationship_id'] relationships.append(Relationship(rid, s, v, o, rel['synsets'])) return Graph(image_id, objects, relationships, attributes)
def _graph_projects(platform, prjsack): projects = set() prjids = set() for prj in prjsack: projects.add(prj.name) prjids.add(str(prj.id)) projects = sorted(projects) prjids = sorted(prjids) dotfilename = os.path.join( settings.MEDIA_ROOT, "graph", "%s_%s.dot" % (str(platform.id), "_".join(prjids))) graph = _get_or_none(Graph, dot=dotfilename) if not graph: graph = Graph(direction=0) dot = _get_projects_dot(prj.buildservice.apiurl, projects) graph.dot.save(dotfilename, ContentFile(str("\n".join(dot))), save=False) svg = _get_svg(dotfilename, prog="dot") graph.svg.save(dotfilename.replace(".dot", ".svg"), File(open(svg)), save=False) graph.save() os.unlink(svg) return graph
def test_graph_vertex_add(self): g = Graph() v1 = Vertex(Point(1, 2)) v2 = Vertex(Point(2, 1)) g.add_vertex(v1) g.add_vertex(v2) g.add_edge(v1, v2) g.add_edge(v2, v1) self.assertEqual(len(g.edges), 1)
def cycle(V): ''' Returns a cycle graph on V vertices. @param V the number of vertices in the cycle @return a cycle graph on V vertices ''' G = Graph(V) vertices = [i for i in range(V)] rand.shuffle(vertices) for i in range(V - 1): G.add_edge((vertices[i], vertices[i + 1])) G.add_edge((vertices[V - 1], vertices[0])) return G
def wheel(V): ''' Returns a wheel graph on V vertices. @param V the number of vertices in the wheel @return a wheel graph on V vertices: a single vertex connected to every vertex in a cycle on V-1 vertices ''' if V <= 1: raise ValueError("Number of vertices must be at least 2") G = Graph(V) vertices = [i for i in range(V)] rand.shuffle(vertices) # simple cycle on V-1 vertices for i in range(V - 1): G.add_edge((vertices[i], vertices[i + 1])) G.add_edge((vertices[V - 1], vertices[1])) # connect vertices[0] to every vertex on cycle for i in range(V): G.add_edge((vertices[0], vertices[i])) return G
def save_graph(): # Angular sends json data by default title = request.json.get("title") settings = request.json.get("settings") username = request.cookies.get("username") new_graph = Graph(settings) db.session.add(new_graph) db.session.commit() new_meta = Metadata(title, new_graph.id, username) new_meta.generate_hash() db.session.add(new_meta) db.session.commit() return jsonify({ "url": new_graph.meta.short_url, "result": "Success", })
def parse_graph(data, image): """ Helper to parse a Graph object from API data. """ objects = [] object_map = {} relationships = [] attributes = [] # Create the Objects for obj in data['bounding_boxes']: names = [] synsets = [] for bbx_obj in obj['boxed_objects']: names.append(bbx_obj['name']) synsets.append(parse_synset(bbx_obj['object_canon'])) object_ = Object(obj['id'], obj['x'], obj['y'], obj['width'], obj['height'], names, synsets) object_map[obj['id']] = object_ objects.append(object_) pass # Create the Relationships for rel in data['relationships']: relationships.append( Relationship(rel['id'], object_map[rel['subject']], rel['predicate'], object_map[rel['object']], parse_synset(rel['relationship_canon']))) pass # Create the Attributes for atr in data['attributes']: attributes.append( Attribute(atr['id'], object_map[atr['subject']], atr['attribute'], parse_synset(atr['attribute_canon']))) pass return Graph(image, objects, relationships, attributes)
def ParseGraphLocal(data, image): global count_hit global count_miss objects = [] object_map = {} relationships = [] for obj in data['objects']: object_map, o_ = MapObject(object_map, obj) objects.append(o_) for rel in data['relationships']: if rel['subject_id'] in object_map and rel['object_id'] in object_map: object_map, s = MapObject(object_map, {'object_id': rel['subject_id']}) v = rel['predicate'] object_map, o = MapObject(object_map, {'object_id': rel['object_id']}) rid = rel['relationship_id'] relationships.append(Relationship(rid, s, v, o, rel['synsets'])) else: count_miss += 1 if count_miss % 10000 == 1: print 'Misses: ', count_miss # print 'SKIPPING s: {}, v: {}, o: {}'.format(rel['subject_id'], rel['relationship_id'], rel['object_id']) return Graph(image, objects, relationships, [])
def eulerianCycle(V, E): ''' Returns an Eulerian cycle graph on V vertices. @param V the number of vertices in the cycle @param E the number of edges in the cycle @return a graph that is an Eulerian cycle on V vertices and E edges @raises ValueError if either V <= 0 or E <= 0 ''' if E <= 0: raise ValueError("An Eulerian cycle must have at least one edge") if V <= 0: raise ValueError("An Eulerian cycle must have at least one vertex") G = Graph(V) vertices = [rand.randrange(V) for i in range(E)] for i in range(E - 1): G.add_edge((vertices[i], vertices[i + 1])) G.add_edge((vertices[E - 1], vertices[0])) return G
def init(G: Graph, start_node: Node): for node in G.nodes: G.distances[node] = 999 G.distances[start_node] = 0
def metric(metric_name = ''): graph = Graph([metric_name, ]) graph.day_graph_need_shift = True graph.auto_refresh = True body = template('templates/graph', **locals()) return render_page(body)
def regex(): global metrics, diamond errors = [] if request.method == 'POST': search = request.forms.get('search') if not search.strip(): errors.append('can not be none') else: return redirect('/regex/?' + urlencode({'search' : search})) elif request.method == 'GET': # url will be like '/regex/?search=...' search = request.query.get('search', '') if search.strip() in ['.*', '.*?']: errors.append('are you kidding me?') elif ':' in search: # search is started with prefix if search.startswith('plugin:'): # search == 'plugin:<plugin>:<server_regex>' _, plugin, server_regex = search.strip().split(':', 2) graphs = [] data = do_plugin(diamond, plugin, server_regex) for server in sorted(data.keys()): graph = Graph(data[server], title = server + ' ' + plugin) graph.detail_url = '/server/%s/%s' % (server, plugin) graphs.append(graph) body = template('templates/graph-list', **locals()) elif search.startswith('merge:'): # search == 'merge:' _, regex = search.strip().split(':', 1) title = request.query.get('title') targets = search_metrics(metrics, regex) graph = Graph(targets, title = title or 'a merged graph') body = template('templates/graph', **locals()) elif search.startswith('sum:'): # search == 'merge:' _, regex = search.strip().split(':', 1) targets = search_metrics(metrics, regex) graph = Graph(['sumSeries(%s)' % (','.join(targets)), ], title = 'a sum-ed graph') body = template('templates/graph', **locals()) else: # search is common regex without any prefix match = groupby_re.match(search) if match: graphs = [] for group, targets in do_groupby(metrics, **match.groupdict()): graph = Graph(targets, title = group) graph.detail_url = '/regex/?search=merge:^(%s)$&title=%s' % ('|'.join(graph.targets), group) graph.detail_title = group graphs.append(graph) body = template('templates/graph-list', **locals()) else: data = search_metrics(metrics, search) if len(data) == 0: errors.append('no metric is matched') graphs = [] for metric in data: graph = Graph(targets = [metric, ], title = metric) graph.detail_url = '/metric/%s' % metric graph.detail_title = metric graph.auto_refresh = True graphs.append(graph) body = template('templates/graph-list', **locals()) if errors: body = template('templates/error', **locals()) return render_page(body, search = search)