<commit_before>//============================================================================
// Name        : main.cpp
// Author      : Sammok Kabasi
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

/**
 * Check for TODO before submitting
 *
 * TODO remove unwanted couts and printfs
 *
 */
#include <iostream>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <unistd.h>

using namespace std;

#define STDIN 0
#define MAXIMUM_TIMEOUTS 3

int numberOfNodes;

int numberOfNeighbours;

int hostServerId = -1;

char weights[10][3];

char* ip_address;

void print_nodes_table() ;

/*
 http://stackoverflow.com/questions/4139405/how-to-know-ip-address-for-interfaces-in-c

 Retrieve the IP address of the process.
 */
int getIP() {
	struct ifaddrs *ifap, *ifa;
	struct sockaddr_in *sa;
	char * ip_address_temp;

	getifaddrs(&ifap);
	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
		if (ifa->ifa_addr->sa_family == AF_INET) {
			sa = (struct sockaddr_in *) ifa->ifa_addr;
			ip_address_temp = inet_ntoa(sa->sin_addr);
			//Make sure it's not the default localhost address that you are using.
			if ((strcmp(ip_address_temp, "127.0.0.1") != 0)
					&& (strcmp(ip_address_temp, "0.0.0.0") != 0)) {
				//  				cout<<"Setting the IP address as " <<ip_address_temp<<"   ";
				ip_address = ip_address_temp;
//				cout << ip_address;
				break;
			}
		}
	}

	cout<<endl<<"The IP address is "<<ip_address<<endl;

	freeifaddrs(ifap);
	return 0;
}

int readTopologyFile(char* filePath);

char* portNumber; //port number of current process

/**
 * Startup function.
 *TODO: do something here
 */
int startServer() {
return 0;
}

//HELPER METHODS
/**
 * TODO: kuch badal isme
 * Checks if the array pointed to by input holds a valid number.
 * Source: PA2 template
 * @param  input char* to the array holding the value.
 * @return TRUE or FALSE
 */
int isNumber(char *input)
{
    while (*input){
        if (!isdigit(*input))
            return 0;
        else
            input += 1;
    }

    return 1;
}

int timeout = -1;

struct nodes_table_info {
	uint32_t serverIp;
	uint16_t serverPort;
	uint16_t serverId;
	int numberOfTimeouts;
	int isNeighbour;
	uint16_t linkCost;
	int isDisabled;
	int nextHopId;
	char server_name[20];
	nodes_table_info() {
		serverId = 0;
		serverPort = 0;
		serverIp = 0;
		numberOfTimeouts = 0;
		isNeighbour = -1;
		isDisabled = -1;
		linkCost = 0xffff;
		nextHopId = -1;
	}
};

struct nodes_table_info nodes[5];

struct serverInfo {
	uint32_t serverIp;
	uint16_t port;
	uint16_t serverId;
	uint16_t cost;
};

//This is the format of the message packet.

struct routing_packet{
	uint16_t numberOfUpdateFields;
	uint16_t serverPort;
	uint32_t serverIp;
	struct serverInfo updateFields[100];
};

/** TODO : change
 * converts string array ip address to a uint32_t object
 */
uint32_t parse_ipaddress_string_to_uint32_t(char* ipAddress) {
	struct in_addr ip_addr;
	inet_pton(AF_INET, ipAddress, &ip_addr);
	return (uint32_t)ntohl(ip_addr.s_addr);

}

/*TODO : change
 *
 * Convert uint32_t to String IP address
*/
char* print_uint32_ip(uint32_t ip)
{
	 char *ipAddress = (char*)malloc(INET_ADDRSTRLEN);
	 struct in_addr ip_addr;
	 ip_addr.s_addr = htonl(ip);
	 inet_ntop(AF_INET, &ip_addr, ipAddress, INET_ADDRSTRLEN);
	 return ipAddress;
}

/*
 * Function to print the nodes table
*/
void print_nodes_table() {
	printf("%-15s|%-15s|%-15s|%-15s|%-15s|%-15s|%-15s|%-15s|\n", "serverId",
			"noOfTimeouts", "isNeighbour", "linkCost", "nextHopId",
			"isDisabled", "serverIp", "server_port");
	for (int i = 0; i < numberOfNodes; i++) {
		printf("%-15d|%-15d|%-15d|%-15d|%-15d|%-15d|%-15s|%-15d|\n",
				nodes[i].serverId, nodes[i].numberOfTimeouts,
				nodes[i].isNeighbour, nodes[i].linkCost, nodes[i].nextHopId,
				nodes[i].isDisabled, print_uint32_ip(nodes[i].serverIp),
				nodes[i].serverPort);
	}
}

/**
 *
 */
int createSocket(int listeningPort) {
	int listen_sock_fd = -1;
		//REQUIRED STRUCTS
		struct addrinfo listen_sock_details, *ai, *p;

		memset(&listen_sock_details,0, sizeof (listen_sock_details));
		listen_sock_details.ai_family = AF_INET;
		listen_sock_details.ai_socktype = SOCK_DGRAM;
		listen_sock_details.ai_flags = AI_PASSIVE | AI_ADDRCONFIG ;
		listen_sock_details.ai_protocol = 0;
		if(listeningPort != -1){
		char portString[6];
		memset(&portString, '\0', 6);
		sprintf(portString, "%d", listeningPort);
		int retval = getaddrinfo(NULL, portString, &listen_sock_details, &ai);
		if (retval!=0){
			fprintf(stderr, "UDP_socket creation selectserver: %s\n", gai_strerror(retval));
		        return(-1);
		}
		}else{
		int retval = getaddrinfo(NULL, "22134", &listen_sock_details, &ai);
		if (retval!=0){
			fprintf(stderr, "sending_socket creation selectserver: %s\n", gai_strerror(retval));
		        return (-1);
		}
		}
		for(p = ai;p != NULL; p = p->ai_next){
			listen_sock_fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
			if(listen_sock_fd < 0)
				continue;

			int y=1;
			setsockopt(listen_sock_fd, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(int));

			if(bind(listen_sock_fd, p->ai_addr, p->ai_addrlen) < 0){
				close(listen_sock_fd);
				continue;
			}
			break;
		}

		if(p==NULL){
			fprintf(stderr, "listen_socket selectserver: failed to bind\n");
	        	return(-2);
		}

		freeaddrinfo(ai);
		return listen_sock_fd;
}

/**
 * Reads the topology file, parses the values and populates the nodes_table_info struct object "nodes"
 */
int readTopologyFile(char* filePath) {

	FILE *fp;
	char buf[255];
	fp = fopen(filePath, "r");

	if (NULL == fp) {
		printf("Error opening file");
		return -1;
	}

	//Line 1 is number of nodes
	fscanf(fp, "%s", buf);

	numberOfNodes = atoi(buf);
	printf("number of nodes -->%d\n" , numberOfNodes);

	//Line 2 is numberOfNeighbours
	fscanf(fp, "%s", buf);
	numberOfNeighbours = atoi(buf);
	printf("number of connections -->%d\n" , numberOfNeighbours);

	//Next numberOfNodes lines is weight information
	for (int i = 0; i < numberOfNodes; i++) {
		fscanf(fp, "%s", buf);
		cout<<buf<<endl;
		nodes[i].serverId = atoi(buf);
//		cout<<"nodes[i].serverIp : "<<nodes[i].serverIp;
		fscanf(fp, "%s", buf);
		cout<<buf<<endl;
		nodes[i].serverIp = parse_ipaddress_string_to_uint32_t(buf);
		char *ip_str;
		uint32_t ip_int = parse_ipaddress_string_to_uint32_t(buf);
		ip_str = print_uint32_ip(ip_int);
		fscanf(fp, "%s", buf);
		cout<<buf<<endl;
		nodes[i].serverPort = atoi(buf);
	}
	//Parsed nodes should be in order in table
	struct nodes_table_info temp_node;
	for (int i = 0; i < numberOfNodes; i++) {
		for (int j = 0; j < numberOfNodes; j++) {
			if (nodes[j].serverId == (i + 1)) {
				temp_node = nodes[i];
				nodes[i] = nodes[j];
				nodes[j] = temp_node;
				break;
			}
		}
	}
	cout<<"Read Topology File"<<endl;
//	print_nodes_table();

	//Next numberOfNeighbours lines is
	for(int i=0;i<numberOfNeighbours;i++){
		fscanf(fp,"%s",buf);
		if(hostServerId == -1){
			hostServerId = atoi(buf);
		}else{
			if(hostServerId != atoi(buf)){
				cout<<"Invalid topology file. More than one host ?"<<endl;
			}
		}
		fscanf(fp,"%s",buf);
		int neighbour = atoi(buf);
		int j;
		for(j=0;j<numberOfNodes;j++){
			if(neighbour == nodes[j].serverId){
				break;
			}
		}
		nodes[j].isNeighbour = 1;
		fscanf(fp,"%s",buf);
		nodes[j].linkCost = atoi(buf);
		nodes[j].nextHopId = neighbour;//nodes[i].server_id;
	}
	for(int i=0;i<numberOfNodes;i++){
		if(hostServerId == nodes[i].serverId){
			nodes[i].linkCost = 0;
			nodes[i].nextHopId = hostServerId;
			break;
		}
	}
	fclose(fp);
	return 0;
}
int main(int nNumberofArgs, char* args[]) {

	int c;

	char* filePath;

	//Get the ip address and port number and store it in the local variables
		getIP();

	printf("Printing nodes table..\n");

	/*TODO change!
 	 * Parse the arguments
	 * http://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html
	*/
	while ((c = getopt(nNumberofArgs, args, "t:i:")) != -1) {
		switch (c) {
		case 't':
			cout << "Filename:" << optarg << endl;
			strcpy(filePath, optarg);
			break;

		case 'i':
			//argument should be an integer number (seconds)
			if (!isNumber(optarg)) {
				fprintf(stderr, "Invalid value for -i\n");
				cout << "Invalid value for -i\n";
				return -1;
			}
			timeout = atoi(optarg);
			break;

		case '?':
			break;

		default:
			cout
					<< "Usage: %s  -t <topology-file-name> -i <routing-update-interval-in-seconds>", args[0];

			return -1;
		}
	}

	//read the local topology file
	int r  = readTopologyFile(filePath);
	printf("%d", r);

//	print_nodes_table();

	cout << endl << "sock number : " << createSocket(59999);

	return 0;
}

<commit_msg>Added printRoutingTable<commit_after>//============================================================================
// Name        : main.cpp
// Author      : Sammok Kabasi
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

/**
 * Check for TODO before submitting
 *
 * TODO remove unwanted couts and printfs
 *
 */
#include <iostream>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <unistd.h>

using namespace std;

#define STDIN 0
#define MAXIMUM_TIMEOUTS 3

int numberOfNodes;

int numberOfNeighbours;

int hostServerId = -1;

char weights[10][3];

char* ip_address;

void print_nodes_table() ;

//void print_routing_table3();

/*
 http://stackoverflow.com/questions/4139405/how-to-know-ip-address-for-interfaces-in-c

 Retrieve the IP address of the process.
 */
int getIP() {
	struct ifaddrs *ifap, *ifa;
	struct sockaddr_in *sa;
	char * ip_address_temp;

	getifaddrs(&ifap);
	for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
		if (ifa->ifa_addr->sa_family == AF_INET) {
			sa = (struct sockaddr_in *) ifa->ifa_addr;
			ip_address_temp = inet_ntoa(sa->sin_addr);
			//Make sure it's not the default localhost address that you are using.
			if ((strcmp(ip_address_temp, "127.0.0.1") != 0)
					&& (strcmp(ip_address_temp, "0.0.0.0") != 0)) {
				//  				cout<<"Setting the IP address as " <<ip_address_temp<<"   ";
				ip_address = ip_address_temp;
//				cout << ip_address;
				break;
			}
		}
	}

	cout<<endl<<"The IP address is "<<ip_address<<endl;

	freeifaddrs(ifap);
	return 0;
}

int readTopologyFile(char* filePath);

char* portNumber; //port number of current process

/**
 * Startup function.
 *TODO: do something here
 */
int startServer() {
return 0;
}

//HELPER METHODS
/**
 * TODO: kuch badal isme
 * Checks if the array pointed to by input holds a valid number.
 * Source: PA2 template
 * @param  input char* to the array holding the value.
 * @return TRUE or FALSE
 */
int isNumber(char *input)
{
    while (*input){
        if (!isdigit(*input))
            return 0;
        else
            input += 1;
    }

    return 1;
}

int timeout = -1;

void printRoutingTable();

struct nodes_table_info {
	uint32_t serverIp;
	uint16_t serverPort;
	uint16_t serverId;
	int numberOfTimeouts;
	int isNeighbour;
	uint16_t linkCost;
	int isDisabled;
	int nextHopId;
	char server_name[20];
	nodes_table_info() {
		serverId = 0;
		serverPort = 0;
		serverIp = 0;
		numberOfTimeouts = 0;
		isNeighbour = -1;
		isDisabled = -1;
		linkCost = 0xffff;
		nextHopId = -1;
	}
};

struct nodes_table_info nodes[10];

struct serverInfo {
	uint32_t serverIp;
	uint16_t port;
	uint16_t serverId;
	uint16_t cost;
};

//This is the format of the message packet.

struct RoutingPacket{
	uint16_t numberOfUpdateFields;
	uint16_t serverPort;
	uint32_t serverIp;
	struct serverInfo updateFields[10];
};

struct RoutingTableEntry{
	uint16_t srcServerId;
	uint16_t destServerId;
	int nextHopId;
	uint16_t linkCost;

	RoutingTableEntry(){
		srcServerId = -1;
		destServerId = -1;
		nextHopId = -1;
		linkCost = 0xffff;
	}
};
struct RoutingTableEntry routingTable[10][10];

/** TODO : change
 * converts string array ip address to a uint32_t object
 */
uint32_t parse_ipaddress_string_to_uint32_t(char* ipAddress) {
	struct in_addr ip_addr;
	inet_pton(AF_INET, ipAddress, &ip_addr);
	return (uint32_t)ntohl(ip_addr.s_addr);

}

/*TODO : change
 *
 * Convert uint32_t to String IP address
*/
char* print_uint32_ip(uint32_t ip)
{
	 char *ipAddress = (char*)malloc(INET_ADDRSTRLEN);
	 struct in_addr ip_addr;
	 ip_addr.s_addr = htonl(ip);
	 inet_ntop(AF_INET, &ip_addr, ipAddress, INET_ADDRSTRLEN);
	 return ipAddress;
}

/*
 * Function to print the nodes table
*/
void print_nodes_table() {
	printf("%-15s|%-15s|%-15s|%-15s|%-15s|%-15s|%-15s|%-15s|\n", "serverId",
			"noOfTimeouts", "isNeighbour", "linkCost", "nextHopId",
			"isDisabled", "serverIp", "server_port");
	for (int i = 0; i < numberOfNodes; i++) {
		printf("%-15d|%-15d|%-15d|%-15d|%-15d|%-15d|%-15s|%-15d|\n",
				nodes[i].serverId, nodes[i].numberOfTimeouts,
				nodes[i].isNeighbour, nodes[i].linkCost, nodes[i].nextHopId,
				nodes[i].isDisabled, print_uint32_ip(nodes[i].serverIp),
				nodes[i].serverPort);
	}
}

/**TODO: change!
 *
 */
int createSocket(int listeningPort) {
	int listen_sock_fd = -1;
	//REQUIRED STRUCTS
	struct addrinfo listen_sock_details, *ai, *p;

	memset(&listen_sock_details, 0, sizeof(listen_sock_details));
	listen_sock_details.ai_family = AF_INET;
	listen_sock_details.ai_socktype = SOCK_DGRAM;
	listen_sock_details.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
	listen_sock_details.ai_protocol = 0;
	if (listeningPort != -1) {
		char portString[6];
		memset(&portString, '\0', 6);
		sprintf(portString, "%d", listeningPort);
		int retval = getaddrinfo(NULL, portString, &listen_sock_details, &ai);
		if (retval != 0) {
			fprintf(stderr, "UDP_socket creation selectserver: %s\n",
					gai_strerror(retval));
			return (-1);
		}
	} else {
		int retval = getaddrinfo(NULL, "22134", &listen_sock_details, &ai);
		if (retval != 0) {
			fprintf(stderr, "sending_socket creation selectserver: %s\n",
					gai_strerror(retval));
			return (-1);
		}
	}
	for (p = ai; p != NULL; p = p->ai_next) {
		listen_sock_fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
		if (listen_sock_fd < 0)
			continue;

		int y = 1;
		setsockopt(listen_sock_fd, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(int));

		if (bind(listen_sock_fd, p->ai_addr, p->ai_addrlen) < 0) {
			close(listen_sock_fd);
			continue;
		}
		break;
	}

	if (p == NULL) {
		fprintf(stderr, "listen_socket selectserver: failed to bind\n");
		return (-2);
	}

	freeaddrinfo(ai);
	return listen_sock_fd;
}

/**
 * Reads the topology file, parses the values and populates the nodes_table_info struct object "nodes"
 */
int readTopologyFile(char* filePath) {

	cout<<"inside readTopologyFile";

	FILE *fp;
	char buf[255];
	fp = fopen(filePath, "r");

	if (NULL == fp) {
		printf("Error opening file");
		return -1;
	}

	//Line 1 is number of nodes
	fscanf(fp, "%s", buf);

	numberOfNodes = atoi(buf);
	printf("number of nodes -->%d\n" , numberOfNodes);

	//Line 2 is numberOfNeighbours
	fscanf(fp, "%s", buf);
	numberOfNeighbours = atoi(buf);
	printf("number of connections -->%d\n" , numberOfNeighbours);

	//Next numberOfNodes lines is weight information
	for (int i = 0; i < numberOfNodes; i++) {
		fscanf(fp, "%s", buf);
		cout<<buf<<endl;
		nodes[i].serverId = atoi(buf);
//		cout<<"nodes[i].serverIp : "<<nodes[i].serverIp;
		fscanf(fp, "%s", buf);
		cout<<buf<<endl;
		nodes[i].serverIp = parse_ipaddress_string_to_uint32_t(buf);
		char *ip_str;
		uint32_t ip_int = parse_ipaddress_string_to_uint32_t(buf);
		ip_str = print_uint32_ip(ip_int);
		fscanf(fp, "%s", buf);
		cout<<buf<<endl;
		nodes[i].serverPort = atoi(buf);
	}
	//Parsed nodes should be in order in table
	struct nodes_table_info temp_node;
	for (int i = 0; i < numberOfNodes; i++) {
		for (int j = 0; j < numberOfNodes; j++) {
			if (nodes[j].serverId == (i + 1)) {
				temp_node = nodes[i];
				nodes[i] = nodes[j];
				nodes[j] = temp_node;
				break;
			}
		}
	}
	cout<<"Read Topology File"<<endl;
//	print_nodes_table();

	//Next numberOfNeighbours lines is
	for(int i=0;i<numberOfNeighbours;i++){
		fscanf(fp,"%s",buf);
		if(hostServerId == -1){
			hostServerId = atoi(buf);
		}else{
			if(hostServerId != atoi(buf)){
				cout<<"Invalid topology file. More than one host ?"<<endl;
			}
		}
		fscanf(fp,"%s",buf);
		int neighbour = atoi(buf);
		int j;
		for(j=0;j<numberOfNodes;j++){
			if(neighbour == nodes[j].serverId){
				break;
			}
		}
		nodes[j].isNeighbour = 1;
		fscanf(fp,"%s",buf);
		nodes[j].linkCost = atoi(buf);
		nodes[j].nextHopId = neighbour;//nodes[i].server_id;
	}
	for(int i=0;i<numberOfNodes;i++){
		if(hostServerId == nodes[i].serverId){
			nodes[i].linkCost = 0;
			nodes[i].nextHopId = hostServerId;
			break;
		}
	}
	fclose(fp);
	return 0;
}
int main(int nNumberofArgs, char* args[]) {

	int c;

	if (nNumberofArgs < 2) {
		fprintf(stderr, "Missing arguments\n");
		cout
				<< "Usage:   -t <topology-file-name> -i <routing-update-interval-in-seconds>";
		return -1;
	}

	char* filePath = (char*) malloc (200);

	//Get the ip address and port number and store it in the local variables
	getIP();

	/*TODO change!
 	 * Parse the arguments
	 * http://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html
	*/
	while ((c = getopt(nNumberofArgs, args, "t:i:")) != -1) {
		switch (c) {
		case 't':
			cout << "Topology file name:" << optarg << endl;
			strcpy(filePath, optarg);
			cout<<"break";
			break;

		case 'i':
			cout<<"case i : " <<optarg;

			//argument should be an integer number (seconds)
			if (!isNumber(optarg)) {
				fprintf(stderr, "Invalid value for -i\n");
				cout << "Invalid value for -i\n";
				return -1;
			}
			timeout = atoi(optarg);
			break;

		case '?':
			break;

		default:
			cout << "Usage: " << args[0]
					<< "  -t <topology-file-name> -i <routing-update-interval-in-seconds>";

			return -1;
		}
	}

	cout << "Reading the topology file...";
	//read the local topology file, exit if invalid.
	if (readTopologyFile(filePath) == -1) {
		cout << "Topology file is invalid. Exiting...";
		exit(1);
	}

	cout<<"Topology file read successfully";

	//Initializing the local routing table...

	//copy local nodes info table (populated from tpoology file) to routing table, so as to initialize it.

	for (int i = 0; i < numberOfNodes; i++) {
		for (int j = 0; j < numberOfNodes; j++) {
			routingTable[i][j].srcServerId = nodes[i].serverId;
			routingTable[i][j].destServerId = nodes[j].serverId;

			//If the node's server id is the current hostId, update the values for that table
			if (nodes[i].serverId == hostServerId) {
				routingTable[i][j].linkCost = nodes[j].linkCost;
				routingTable[j][i].linkCost = nodes[j].linkCost;
				routingTable[i][j].nextHopId = nodes[j].nextHopId;
			}
		}
	}

//	printRoutingTable();

//	print_nodes_table();

	printRoutingTable();

	cout << endl << "sock number : " << createSocket(59999);

	return 0;
}

//void printRoutingTable() {
//	cout << endl << "Routing table : " << endl;
//
//	cout<<"\t";
//	for (int i = 0; i < numberOfNodes; i++) {
//		cout << "|Node " <<i << "\t";
//	}
//	cout<<endl;
//	for (int i = 0; i < numberOfNodes; i++) {
//		cout<<"Node "<<i;
//		for (int j = 0; j < numberOfNodes; j++) {
//			cout <<"\t|" << routingTable[i][j].linkCost;
//		}
//		cout << endl;
//	}
//}

void printRoutingTableWithProperFormat() {
		cout << endl << "Routing table : " << endl;

		cout<<"\t";
		for (int i = 0; i < numberOfNodes; i++) {
			cout << "|Node " <<i << "\t";
		}
		cout<<endl;
		for (int i = 0; i < numberOfNodes; i++) {
			cout<<"Node "<<i;
			for (int j = 0; j < numberOfNodes; j++) {
				cout <<"\t|" << routingTable[i][j].linkCost;
			}
			cout << endl;
	}
}
/*
 * Print routing table
*/
void printRoutingTable(){
cout<<"\nserverId\t|nextHopId\t|linkCost\n";
	for (int i = 0; i < numberOfNodes; i++) {
		cout<<nodes[i].serverId<<"\t";
		for (int j = 0; j < numberOfNodes; j++) {
			cout << "c(" << routingTable[i][j].srcServerId << ","
					<< routingTable[i][j].destServerId << ") = "
					<< routingTable[i][j].linkCost << ", ";
			cout << "NH(" << routingTable[i][j].srcServerId << ","
					<< routingTable[i][j].destServerId << ") = "
					<< routingTable[i][j].nextHopId << "\t|";
		}
		printf("\n");
	}
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qqmlextensionplugin.h"

QT_BEGIN_NAMESPACE

/*!
    \since 4.7
    \class QQmlExtensionPlugin
    \brief The QQmlExtensionPlugin class provides an abstract base for custom QML extension plugins.

    \ingroup plugins

    QQmlExtensionPlugin is a plugin interface that makes it possible to
    create QML extensions that can be loaded dynamically into QML applications.
    These extensions allow custom QML types to be made available to the QML engine.

    To write a QML extension plugin:

    \list
    \li Subclass QQmlExtensionPlugin, implement registerTypes() method
    to register types using qmlRegisterType(), and export the class using the Q_EXPORT_PLUGIN2() macro
    \li Write an appropriate project file for the plugin
    \li Create a \l{Writing a qmldir file}{qmldir file} to describe the plugin
    \endlist

    QML extension plugins can be used to provide either application-specific or
    library-like plugins. Library plugins should limit themselves to registering types,
    as any manipulation of the engine's root context may cause conflicts
    or other issues in the library user's code.

    \section1 An example

    Suppose there is a new \c TimeModel C++ class that should be made available
    as a new QML element. It provides the current time through \c hour and \c minute
    properties, like this:

    \snippet examples/declarative/cppextensions/plugins/plugin.cpp 0
    \dots

    To make this class available as a QML type, create a plugin that registers
    this type with a specific \l {QML Modules}{module} using qmlRegisterType(). For this example the plugin
    module will be named \c com.nokia.TimeExample (as defined in the project
    file further below).

    \snippet examples/declarative/cppextensions/plugins/plugin.cpp plugin
    \codeline
    \snippet examples/declarative/cppextensions/plugins/plugin.cpp export

    This registers the \c TimeModel class with the 1.0 version of this
    plugin library, as a QML type called \c Time. The Q_ASSERT statement
    ensures the module is imported correctly by any QML components that use this plugin.

    The project file defines the project as a plugin library and specifies
    it should be built into the \c com/nokia/TimeExample directory:

    \code
    TEMPLATE = lib
    CONFIG += qt plugin
    QT += declarative

    DESTDIR = com/nokia/TimeExample
    TARGET = qmlqtimeexampleplugin
    ...
    \endcode

    Finally, a \l{Writing a qmldir file}{qmldir file} is required in the \c com/nokia/TimeExample directory
    that describes the plugin. This directory includes a \c Clock.qml file that
    should be bundled with the plugin, so it needs to be specified in the \c qmldir
    file:

    \quotefile examples/declarative/cppextensions/plugins/com/nokia/TimeExample/qmldir

    Once the project is built and installed, the new \c Time element can be
    used by any QML component that imports the \c com.nokia.TimeExample module:

    \snippet examples/declarative/cppextensions/plugins/plugins.qml 0

    The full source code is available in the \l {declarative/cppextensions/plugins}{plugins example}.

    The \l {Tutorial: Writing QML extensions with C++} also contains a chapter
    on creating QML plugins.

    \sa QQmlEngine::importPlugin(), {How to Create Qt Plugins}
*/

/*!
    \fn void QQmlExtensionPlugin::registerTypes(const char *uri)

    Registers the QML types in the given \a uri. Subclasses should implement
    this to call qmlRegisterType() for all types which are provided by the extension
    plugin.

    The \a uri is an identifier for the plugin generated by the QML engine
    based on the name and path of the extension's plugin library.
*/

/*!
    Constructs a QML extension plugin with the given \a parent.

    Note that this constructor is invoked automatically by the
    Q_EXPORT_PLUGIN2() macro, so there is no need for calling it
    explicitly.
*/
QQmlExtensionPlugin::QQmlExtensionPlugin(QObject *parent)
    : QObject(parent)
{
}

/*!
  \internal
 */
QQmlExtensionPlugin::~QQmlExtensionPlugin()
{
}

/*!
    \fn void QQmlExtensionPlugin::initializeEngine(QQmlEngine *engine, const char *uri)

    Initializes the extension from the \a uri using the \a engine. Here an application
    plugin might, for example, expose some data or objects to QML,
    as context properties on the engine's root context.
*/

void QQmlExtensionPlugin::initializeEngine(QQmlEngine *engine, const char *uri)
{
    Q_UNUSED(engine);
    Q_UNUSED(uri);
}

QT_END_NAMESPACE
<commit_msg>Remove refence to declarative in the docs<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qqmlextensionplugin.h"

QT_BEGIN_NAMESPACE

/*!
    \since 4.7
    \class QQmlExtensionPlugin
    \brief The QQmlExtensionPlugin class provides an abstract base for custom QML extension plugins.

    \ingroup plugins

    QQmlExtensionPlugin is a plugin interface that makes it possible to
    create QML extensions that can be loaded dynamically into QML applications.
    These extensions allow custom QML types to be made available to the QML engine.

    To write a QML extension plugin:

    \list
    \li Subclass QQmlExtensionPlugin, implement registerTypes() method
    to register types using qmlRegisterType(), and export the class using the Q_EXPORT_PLUGIN2() macro
    \li Write an appropriate project file for the plugin
    \li Create a \l{Writing a qmldir file}{qmldir file} to describe the plugin
    \endlist

    QML extension plugins can be used to provide either application-specific or
    library-like plugins. Library plugins should limit themselves to registering types,
    as any manipulation of the engine's root context may cause conflicts
    or other issues in the library user's code.

    \section1 An example

    Suppose there is a new \c TimeModel C++ class that should be made available
    as a new QML element. It provides the current time through \c hour and \c minute
    properties, like this:

    \snippet examples/declarative/cppextensions/plugins/plugin.cpp 0
    \dots

    To make this class available as a QML type, create a plugin that registers
    this type with a specific \l {QML Modules}{module} using qmlRegisterType(). For this example the plugin
    module will be named \c com.nokia.TimeExample (as defined in the project
    file further below).

    \snippet examples/declarative/cppextensions/plugins/plugin.cpp plugin
    \codeline
    \snippet examples/declarative/cppextensions/plugins/plugin.cpp export

    This registers the \c TimeModel class with the 1.0 version of this
    plugin library, as a QML type called \c Time. The Q_ASSERT statement
    ensures the module is imported correctly by any QML components that use this plugin.

    The project file defines the project as a plugin library and specifies
    it should be built into the \c com/nokia/TimeExample directory:

    \code
    TEMPLATE = lib
    CONFIG += qt plugin
    QT += qml

    DESTDIR = com/nokia/TimeExample
    TARGET = qmlqtimeexampleplugin
    ...
    \endcode

    Finally, a \l{Writing a qmldir file}{qmldir file} is required in the \c com/nokia/TimeExample directory
    that describes the plugin. This directory includes a \c Clock.qml file that
    should be bundled with the plugin, so it needs to be specified in the \c qmldir
    file:

    \quotefile examples/declarative/cppextensions/plugins/com/nokia/TimeExample/qmldir

    Once the project is built and installed, the new \c Time element can be
    used by any QML component that imports the \c com.nokia.TimeExample module:

    \snippet examples/declarative/cppextensions/plugins/plugins.qml 0

    The full source code is available in the \l {declarative/cppextensions/plugins}{plugins example}.

    The \l {Tutorial: Writing QML extensions with C++} also contains a chapter
    on creating QML plugins.

    \sa QQmlEngine::importPlugin(), {How to Create Qt Plugins}
*/

/*!
    \fn void QQmlExtensionPlugin::registerTypes(const char *uri)

    Registers the QML types in the given \a uri. Subclasses should implement
    this to call qmlRegisterType() for all types which are provided by the extension
    plugin.

    The \a uri is an identifier for the plugin generated by the QML engine
    based on the name and path of the extension's plugin library.
*/

/*!
    Constructs a QML extension plugin with the given \a parent.

    Note that this constructor is invoked automatically by the
    Q_EXPORT_PLUGIN2() macro, so there is no need for calling it
    explicitly.
*/
QQmlExtensionPlugin::QQmlExtensionPlugin(QObject *parent)
    : QObject(parent)
{
}

/*!
  \internal
 */
QQmlExtensionPlugin::~QQmlExtensionPlugin()
{
}

/*!
    \fn void QQmlExtensionPlugin::initializeEngine(QQmlEngine *engine, const char *uri)

    Initializes the extension from the \a uri using the \a engine. Here an application
    plugin might, for example, expose some data or objects to QML,
    as context properties on the engine's root context.
*/

void QQmlExtensionPlugin::initializeEngine(QQmlEngine *engine, const char *uri)
{
    Q_UNUSED(engine);
    Q_UNUSED(uri);
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>// Copyright (c) 2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "qt/pivx/sendcustomfeedialog.h"
#include "qt/pivx/forms/ui_sendcustomfeedialog.h"
#include "qt/pivx/qtutils.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include <QListView>
#include <QComboBox>

SendCustomFeeDialog::SendCustomFeeDialog(PIVXGUI* parent, WalletModel* model) :
    QDialog(parent),
    ui(new Ui::SendCustomFeeDialog),
    walletModel(model)
{
    if (!walletModel)
        throw std::runtime_error(strprintf("%s: No wallet model set", __func__));
    ui->setupUi(this);

    // Stylesheet
    this->setStyleSheet(parent->styleSheet());
    setCssProperty(ui->frame, "container-dialog");

    // Text
    ui->labelTitle->setText(tr("Customize Fee"));
    ui->labelMessage->setText(tr("Customize the transaction fee, depending on the fee value your transaction might be included faster in the blockchain."));
    setCssProperty(ui->labelTitle, "text-title-dialog");
    setCssProperty(ui->labelMessage, "text-main-grey");

    // Recommended
    setCssProperty(ui->labelFee, "text-main-grey-big");
    setCssProperty(ui->comboBoxRecommended, "btn-combo-dialog");
    ui->comboBoxRecommended->setView(new QListView());
    ui->comboBoxRecommended->addItem(tr("Normal"), 5);
    ui->comboBoxRecommended->addItem(tr("Slow"), 20);
    ui->comboBoxRecommended->addItem(tr("Fast"), 1);

    // Custom
    setCssProperty(ui->labelCustomFee, "label-subtitle-dialog");
    ui->lineEditCustomFee->setPlaceholderText("0.000001");
    initCssEditLine(ui->lineEditCustomFee, true);
    GUIUtil::setupAmountWidget(ui->lineEditCustomFee, this);

    // Buttons
    setCssProperty(ui->btnEsc, "ic-close");
    setCssProperty(ui->btnCancel, "btn-dialog-cancel");
    ui->btnSave->setText(tr("SAVE"));
    setCssBtnPrimary(ui->btnSave);

    connect(ui->btnEsc, &QPushButton::clicked, this, &SendCustomFeeDialog::close);
    connect(ui->btnCancel, &QPushButton::clicked, this, &SendCustomFeeDialog::close);
    connect(ui->btnSave, &QPushButton::clicked, this, &SendCustomFeeDialog::accept);
    connect(ui->checkBoxCustom, &QCheckBox::clicked, this, &SendCustomFeeDialog::onCustomChecked);
    connect(ui->checkBoxRecommended, &QCheckBox::clicked, this, &SendCustomFeeDialog::onRecommendedChecked);
    connect(ui->comboBoxRecommended, static_cast<void (QComboBox::*)(const QString &)>(&QComboBox::currentIndexChanged),
        this, &SendCustomFeeDialog::updateFee);
    if (parent)
        connect(parent, &PIVXGUI::themeChanged, this, &SendCustomFeeDialog::onChangeTheme);
    ui->checkBoxRecommended->setChecked(true);
}

void SendCustomFeeDialog::showEvent(QShowEvent* event)
{
    updateFee();
    if (walletModel->hasWalletCustomFee()) {
        ui->checkBoxCustom->setChecked(true);
        onCustomChecked();
    } else {
        ui->checkBoxRecommended->setChecked(true);
        onRecommendedChecked();
    }
}

void SendCustomFeeDialog::onCustomChecked()
{
    bool isChecked = ui->checkBoxCustom->checkState() == Qt::Checked;
    ui->lineEditCustomFee->setEnabled(isChecked);
    ui->comboBoxRecommended->setEnabled(!isChecked);
    ui->checkBoxRecommended->setChecked(!isChecked);

    if (isChecked) {
        CAmount nFee;
        walletModel->getWalletCustomFee(nFee);
        ui->lineEditCustomFee->setText(BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), nFee));
    } else {
        ui->lineEditCustomFee->clear();
    }
}

void SendCustomFeeDialog::onRecommendedChecked()
{
    bool isChecked = ui->checkBoxRecommended->checkState() == Qt::Checked;
    ui->lineEditCustomFee->setEnabled(!isChecked);
    ui->comboBoxRecommended->setEnabled(isChecked);
    ui->checkBoxCustom->setChecked(!isChecked);
    if (isChecked) {
        ui->lineEditCustomFee->clear();
    }
}

// Fast = 1.
// Medium = 5
// Slow = 20
void SendCustomFeeDialog::updateFee()
{
    if (!walletModel->getOptionsModel()) return;

    QVariant num = ui->comboBoxRecommended->currentData();
    bool res = false;
    int nBlocksToConfirm = num.toInt(&res);
    if (res) {
        feeRate = mempool.estimateFee(nBlocksToConfirm);
        if (feeRate < CWallet::minTxFee) feeRate = CWallet::minTxFee;    // not enough data => minfee
        ui->labelFee->setText(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(),
                                                           feeRate.GetFeePerK()) + "/kB");
    }
}

void SendCustomFeeDialog::accept()
{
    const bool fUseCustomFee = ui->checkBoxCustom->checkState() == Qt::Checked;
    const CAmount customFee = getFeeRate().GetFeePerK();
    // Check insane fee
    const CAmount insaneFee = ::minRelayTxFee.GetFeePerK() * 10000;
    if (customFee >= insaneFee) {
        inform(tr("Fee too high. Must be below: %1").arg(
                BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), insaneFee)));
    } else if (customFee < CWallet::minTxFee.GetFeePerK()) {
        inform(tr("Fee too low. Must be above: %1").arg(
                BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), CWallet::minTxFee.GetFeePerK() * 1000)));
    } else {
        walletModel->setWalletCustomFee(fUseCustomFee, customFee);
        QDialog::accept();
    }
}

void SendCustomFeeDialog::clear()
{
    ui->comboBoxRecommended->setCurrentIndex(0);
}

CFeeRate SendCustomFeeDialog::getFeeRate()
{
    return ui->checkBoxRecommended->isChecked() ?
           feeRate : CFeeRate(GUIUtil::parseValue(ui->lineEditCustomFee->text(), walletModel->getOptionsModel()->getDisplayUnit()));
}

bool SendCustomFeeDialog::isCustomFeeChecked()
{
    return ui->checkBoxCustom->checkState() == Qt::Checked;
}

void SendCustomFeeDialog::onChangeTheme(bool isLightTheme, QString& theme)
{
    this->setStyleSheet(theme);
    updateStyle(this);
}

void SendCustomFeeDialog::inform(const QString& text)
{
    if (!snackBar) snackBar = new SnackBar(nullptr, this);
    snackBar->setText(text);
    snackBar->resize(this->width(), snackBar->height());
    openDialog(snackBar, this);
}

SendCustomFeeDialog::~SendCustomFeeDialog()
{
    delete ui;
}
<commit_msg>[Trivial] Fix wording: "must be above" to "must be at least"<commit_after>// Copyright (c) 2019 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "qt/pivx/sendcustomfeedialog.h"
#include "qt/pivx/forms/ui_sendcustomfeedialog.h"
#include "qt/pivx/qtutils.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include <QListView>
#include <QComboBox>

SendCustomFeeDialog::SendCustomFeeDialog(PIVXGUI* parent, WalletModel* model) :
    QDialog(parent),
    ui(new Ui::SendCustomFeeDialog),
    walletModel(model)
{
    if (!walletModel)
        throw std::runtime_error(strprintf("%s: No wallet model set", __func__));
    ui->setupUi(this);

    // Stylesheet
    this->setStyleSheet(parent->styleSheet());
    setCssProperty(ui->frame, "container-dialog");

    // Text
    ui->labelTitle->setText(tr("Customize Fee"));
    ui->labelMessage->setText(tr("Customize the transaction fee, depending on the fee value your transaction might be included faster in the blockchain."));
    setCssProperty(ui->labelTitle, "text-title-dialog");
    setCssProperty(ui->labelMessage, "text-main-grey");

    // Recommended
    setCssProperty(ui->labelFee, "text-main-grey-big");
    setCssProperty(ui->comboBoxRecommended, "btn-combo-dialog");
    ui->comboBoxRecommended->setView(new QListView());
    ui->comboBoxRecommended->addItem(tr("Normal"), 5);
    ui->comboBoxRecommended->addItem(tr("Slow"), 20);
    ui->comboBoxRecommended->addItem(tr("Fast"), 1);

    // Custom
    setCssProperty(ui->labelCustomFee, "label-subtitle-dialog");
    ui->lineEditCustomFee->setPlaceholderText("0.000001");
    initCssEditLine(ui->lineEditCustomFee, true);
    GUIUtil::setupAmountWidget(ui->lineEditCustomFee, this);

    // Buttons
    setCssProperty(ui->btnEsc, "ic-close");
    setCssProperty(ui->btnCancel, "btn-dialog-cancel");
    ui->btnSave->setText(tr("SAVE"));
    setCssBtnPrimary(ui->btnSave);

    connect(ui->btnEsc, &QPushButton::clicked, this, &SendCustomFeeDialog::close);
    connect(ui->btnCancel, &QPushButton::clicked, this, &SendCustomFeeDialog::close);
    connect(ui->btnSave, &QPushButton::clicked, this, &SendCustomFeeDialog::accept);
    connect(ui->checkBoxCustom, &QCheckBox::clicked, this, &SendCustomFeeDialog::onCustomChecked);
    connect(ui->checkBoxRecommended, &QCheckBox::clicked, this, &SendCustomFeeDialog::onRecommendedChecked);
    connect(ui->comboBoxRecommended, static_cast<void (QComboBox::*)(const QString &)>(&QComboBox::currentIndexChanged),
        this, &SendCustomFeeDialog::updateFee);
    if (parent)
        connect(parent, &PIVXGUI::themeChanged, this, &SendCustomFeeDialog::onChangeTheme);
    ui->checkBoxRecommended->setChecked(true);
}

void SendCustomFeeDialog::showEvent(QShowEvent* event)
{
    updateFee();
    if (walletModel->hasWalletCustomFee()) {
        ui->checkBoxCustom->setChecked(true);
        onCustomChecked();
    } else {
        ui->checkBoxRecommended->setChecked(true);
        onRecommendedChecked();
    }
}

void SendCustomFeeDialog::onCustomChecked()
{
    bool isChecked = ui->checkBoxCustom->checkState() == Qt::Checked;
    ui->lineEditCustomFee->setEnabled(isChecked);
    ui->comboBoxRecommended->setEnabled(!isChecked);
    ui->checkBoxRecommended->setChecked(!isChecked);

    if (isChecked) {
        CAmount nFee;
        walletModel->getWalletCustomFee(nFee);
        ui->lineEditCustomFee->setText(BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), nFee));
    } else {
        ui->lineEditCustomFee->clear();
    }
}

void SendCustomFeeDialog::onRecommendedChecked()
{
    bool isChecked = ui->checkBoxRecommended->checkState() == Qt::Checked;
    ui->lineEditCustomFee->setEnabled(!isChecked);
    ui->comboBoxRecommended->setEnabled(isChecked);
    ui->checkBoxCustom->setChecked(!isChecked);
    if (isChecked) {
        ui->lineEditCustomFee->clear();
    }
}

// Fast = 1.
// Medium = 5
// Slow = 20
void SendCustomFeeDialog::updateFee()
{
    if (!walletModel->getOptionsModel()) return;

    QVariant num = ui->comboBoxRecommended->currentData();
    bool res = false;
    int nBlocksToConfirm = num.toInt(&res);
    if (res) {
        feeRate = mempool.estimateFee(nBlocksToConfirm);
        if (feeRate < CWallet::minTxFee) feeRate = CWallet::minTxFee;    // not enough data => minfee
        ui->labelFee->setText(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(),
                                                           feeRate.GetFeePerK()) + "/kB");
    }
}

void SendCustomFeeDialog::accept()
{
    const bool fUseCustomFee = ui->checkBoxCustom->checkState() == Qt::Checked;
    const CAmount customFee = getFeeRate().GetFeePerK();
    // Check insane fee
    const CAmount insaneFee = ::minRelayTxFee.GetFeePerK() * 10000;
    if (customFee >= insaneFee) {
        inform(tr("Fee too high. Must be below: %1").arg(
                BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), insaneFee)));
    } else if (customFee < CWallet::minTxFee.GetFeePerK()) {
        inform(tr("Fee too low. Must be at least: %1").arg(
                BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), CWallet::minTxFee.GetFeePerK())));
    } else {
        walletModel->setWalletCustomFee(fUseCustomFee, customFee);
        QDialog::accept();
    }
}

void SendCustomFeeDialog::clear()
{
    ui->comboBoxRecommended->setCurrentIndex(0);
}

CFeeRate SendCustomFeeDialog::getFeeRate()
{
    return ui->checkBoxRecommended->isChecked() ?
           feeRate : CFeeRate(GUIUtil::parseValue(ui->lineEditCustomFee->text(), walletModel->getOptionsModel()->getDisplayUnit()));
}

bool SendCustomFeeDialog::isCustomFeeChecked()
{
    return ui->checkBoxCustom->checkState() == Qt::Checked;
}

void SendCustomFeeDialog::onChangeTheme(bool isLightTheme, QString& theme)
{
    this->setStyleSheet(theme);
    updateStyle(this);
}

void SendCustomFeeDialog::inform(const QString& text)
{
    if (!snackBar) snackBar = new SnackBar(nullptr, this);
    snackBar->setText(text);
    snackBar->resize(this->width(), snackBar->height());
    openDialog(snackBar, this);
}

SendCustomFeeDialog::~SendCustomFeeDialog()
{
    delete ui;
}
<|endoftext|>


<commit_before>/* Copyright (c) 2012, Antonie Jovanoski
 *
 * All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 *
 * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com>
 */

#include "qtweetstatusupdatewithmedia.h"
#include <QHttpMultiPart>
#include <QHttpPart>
#include <QFile>
#include <QNetworkReply>
#include <QNetworkRequest>
#include "json/qjsondocument.h"
#include "json/qjsonobject.h"
#include "qtweetconvert.h"
#include "qtweetstatus.h"

QTweetStatusUpdateWithMedia::QTweetStatusUpdateWithMedia(QObject *parent) :
    QTweetNetBase(parent), m_inReplyToStatusID(0), m_latitude(91.0f),
    m_longitude(181.0f), m_displayCoordinates(false)
{
}

QTweetStatusUpdateWithMedia::QTweetStatusUpdateWithMedia(OAuthTwitter *oauthTwitter, QObject *parent) :
    QTweetNetBase(oauthTwitter, parent), m_inReplyToStatusID(0), m_latitude(91.0f),
    m_longitude(181.0f), m_displayCoordinates(false)
{
}

void QTweetStatusUpdateWithMedia::post()
{
    if (!isAuthenticationEnabled()) {
        qCritical("Needs authentication to be enabled");
        return;
    }

    QUrl url("https://upload.twitter.com/1/statuses/update_with_media.json");

    QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::POST);

    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    QHttpPart statusPart;
    statusPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"status\""));
    statusPart.setBody(m_status.toUtf8());
    multiPart->append(statusPart);

    QHttpPart imagePart;
    imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"media[]\""));
    QFile *file = new QFile(m_imageFilename);
    file->open(QFile::ReadOnly);
    imagePart.setBodyDevice(file);
    file->setParent(multiPart);
    multiPart->append(imagePart);

    if (m_sensitive) {
        QHttpPart possiblySensitivePart;
        possiblySensitivePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"possibly_sensitive\""));
        possiblySensitivePart.setBody("true");
        multiPart->append(possiblySensitivePart);
    }

    if (m_inReplyToStatusID) {
        QHttpPart inReplyToStatusIDPart;
        inReplyToStatusIDPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"in_reply_to_status_id\""));
        inReplyToStatusIDPart.setBody(QString::number(m_inReplyToStatusID).toUtf8());
        multiPart->append(inReplyToStatusIDPart);
    }

    if (m_latitude < 90.0f && m_latitude > -90.0f) {
        QHttpPart latitudePart;
        latitudePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"lat\""));
        latitudePart.setBody(QString::number(m_latitude).toUtf8());
        multiPart->append(latitudePart);
    }

    if (m_longitude < 181.0f && m_longitude > -180.0f) {
        QHttpPart longitudePart;
        longitudePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"long\""));
        longitudePart.setBody(QString::number(m_longitude).toUtf8());
        multiPart->append(longitudePart);
    }

    if (!m_placeID.isEmpty()) {
        QHttpPart placeIDPart;
        placeIDPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"place_id\""));
        placeIDPart.setBody(m_placeID.toUtf8());
        multiPart->append(placeIDPart);
    }

    if (m_displayCoordinates) {
        QHttpPart displayCoordinatesPart;
        displayCoordinatesPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"display_coordinates\""));
        displayCoordinatesPart.setBody("true");
        multiPart->append(displayCoordinatesPart);
    }

    QNetworkRequest req(url);
    req.setRawHeader(AUTH_HEADER, oauthHeader);

    QNetworkReply *reply = oauthTwitter()->networkAccessManager()->post(req, multiPart);
    multiPart->setParent(reply);

    connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}

void QTweetStatusUpdateWithMedia::parseJsonFinished(const QJsonDocument &jsonDoc)
{
    if (jsonDoc.isObject()) {
        QTweetStatus status = QTweetConvert::jsonObjectToStatus(jsonDoc.object());

        emit postedUpdate(status);
    }
}
<commit_msg>Updated url for QTweetStatusUpdateWithMedia.<commit_after>/* Copyright (c) 2012, Antonie Jovanoski
 *
 * All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 *
 * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com>
 */

#include "qtweetstatusupdatewithmedia.h"
#include <QHttpMultiPart>
#include <QHttpPart>
#include <QFile>
#include <QNetworkReply>
#include <QNetworkRequest>
#include "json/qjsondocument.h"
#include "json/qjsonobject.h"
#include "qtweetconvert.h"
#include "qtweetstatus.h"

QTweetStatusUpdateWithMedia::QTweetStatusUpdateWithMedia(QObject *parent) :
    QTweetNetBase(parent), m_inReplyToStatusID(0), m_latitude(91.0f),
    m_longitude(181.0f), m_displayCoordinates(false)
{
}

QTweetStatusUpdateWithMedia::QTweetStatusUpdateWithMedia(OAuthTwitter *oauthTwitter, QObject *parent) :
    QTweetNetBase(oauthTwitter, parent), m_inReplyToStatusID(0), m_latitude(91.0f),
    m_longitude(181.0f), m_displayCoordinates(false)
{
}

void QTweetStatusUpdateWithMedia::post()
{
    if (!isAuthenticationEnabled()) {
        qCritical("Needs authentication to be enabled");
        return;
    }

    QUrl url("https://api.twitter.com/1.1/statuses/update_with_media.json");

    QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::POST);

    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    QHttpPart statusPart;
    statusPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"status\""));
    statusPart.setBody(m_status.toUtf8());
    multiPart->append(statusPart);

    QHttpPart imagePart;
    imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"media[]\""));
    QFile *file = new QFile(m_imageFilename);
    file->open(QFile::ReadOnly);
    imagePart.setBodyDevice(file);
    file->setParent(multiPart);
    multiPart->append(imagePart);

    if (m_sensitive) {
        QHttpPart possiblySensitivePart;
        possiblySensitivePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"possibly_sensitive\""));
        possiblySensitivePart.setBody("true");
        multiPart->append(possiblySensitivePart);
    }

    if (m_inReplyToStatusID) {
        QHttpPart inReplyToStatusIDPart;
        inReplyToStatusIDPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"in_reply_to_status_id\""));
        inReplyToStatusIDPart.setBody(QString::number(m_inReplyToStatusID).toUtf8());
        multiPart->append(inReplyToStatusIDPart);
    }

    if (m_latitude < 90.0f && m_latitude > -90.0f) {
        QHttpPart latitudePart;
        latitudePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"lat\""));
        latitudePart.setBody(QString::number(m_latitude).toUtf8());
        multiPart->append(latitudePart);
    }

    if (m_longitude < 181.0f && m_longitude > -180.0f) {
        QHttpPart longitudePart;
        longitudePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"long\""));
        longitudePart.setBody(QString::number(m_longitude).toUtf8());
        multiPart->append(longitudePart);
    }

    if (!m_placeID.isEmpty()) {
        QHttpPart placeIDPart;
        placeIDPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"place_id\""));
        placeIDPart.setBody(m_placeID.toUtf8());
        multiPart->append(placeIDPart);
    }

    if (m_displayCoordinates) {
        QHttpPart displayCoordinatesPart;
        displayCoordinatesPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"display_coordinates\""));
        displayCoordinatesPart.setBody("true");
        multiPart->append(displayCoordinatesPart);
    }

    QNetworkRequest req(url);
    req.setRawHeader(AUTH_HEADER, oauthHeader);

    QNetworkReply *reply = oauthTwitter()->networkAccessManager()->post(req, multiPart);
    multiPart->setParent(reply);

    connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}

void QTweetStatusUpdateWithMedia::parseJsonFinished(const QJsonDocument &jsonDoc)
{
    if (jsonDoc.isObject()) {
        QTweetStatus status = QTweetConvert::jsonObjectToStatus(jsonDoc.object());

        emit postedUpdate(status);
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: forbiddencharacterstable.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:44:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _FORBIDDENCHARACTERSTABLE_HXX
#define _FORBIDDENCHARACTERSTABLE_HXX

#ifndef _TABLE_HXX //autogen
#include <tools/table.hxx>
#endif

#include <vos/refernce.hxx>

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif

#ifndef _COM_SUN_STAR_I18N_FORBIDDENCHARACTERS_HPP_
#include <com/sun/star/i18n/ForbiddenCharacters.hpp>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

namespace com {
namespace sun {
namespace star {
namespace lang {
    class XMultiServiceFactory;
}}}}

struct ForbiddenCharactersInfo
{
    com::sun::star::i18n::ForbiddenCharacters aForbiddenChars;
    BOOL bTemporary;
};

DECLARE_TABLE( SvxForbiddenCharactersTableImpl, ForbiddenCharactersInfo* )

class SVX_DLLPUBLIC SvxForbiddenCharactersTable : public SvxForbiddenCharactersTableImpl, public vos::OReference
{
private:
    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > mxMSF;

public:
            SvxForbiddenCharactersTable( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xMSF, USHORT nISize = 4, USHORT nGrow = 4 );
            ~SvxForbiddenCharactersTable();

    const com::sun::star::i18n::ForbiddenCharacters* GetForbiddenCharacters( USHORT nLanuage, BOOL bGetDefault ) const;
    void    SetForbiddenCharacters(  USHORT nLanuage , const com::sun::star::i18n::ForbiddenCharacters& );
    void    ClearForbiddenCharacters( USHORT nLanuage );
};

#endif // _FORBIDDENCHARACTERSTABLE_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.4.1256); FILE MERGED 2008/04/01 15:49:15 thb 1.4.1256.3: #i85898# Stripping all external header guards 2008/04/01 12:46:20 thb 1.4.1256.2: #i85898# Stripping all external header guards 2008/03/31 14:17:55 rt 1.4.1256.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: forbiddencharacterstable.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _FORBIDDENCHARACTERSTABLE_HXX
#define _FORBIDDENCHARACTERSTABLE_HXX

#ifndef _TABLE_HXX //autogen
#include <tools/table.hxx>
#endif

#include <vos/refernce.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/i18n/ForbiddenCharacters.hpp>
#include "svx/svxdllapi.h"

namespace com {
namespace sun {
namespace star {
namespace lang {
    class XMultiServiceFactory;
}}}}

struct ForbiddenCharactersInfo
{
    com::sun::star::i18n::ForbiddenCharacters aForbiddenChars;
    BOOL bTemporary;
};

DECLARE_TABLE( SvxForbiddenCharactersTableImpl, ForbiddenCharactersInfo* )

class SVX_DLLPUBLIC SvxForbiddenCharactersTable : public SvxForbiddenCharactersTableImpl, public vos::OReference
{
private:
    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > mxMSF;

public:
            SvxForbiddenCharactersTable( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xMSF, USHORT nISize = 4, USHORT nGrow = 4 );
            ~SvxForbiddenCharactersTable();

    const com::sun::star::i18n::ForbiddenCharacters* GetForbiddenCharacters( USHORT nLanuage, BOOL bGetDefault ) const;
    void    SetForbiddenCharacters(  USHORT nLanuage , const com::sun::star::i18n::ForbiddenCharacters& );
    void    ClearForbiddenCharacters( USHORT nLanuage );
};

#endif // _FORBIDDENCHARACTERSTABLE_HXX

<|endoftext|>


<commit_before>// Copyright (c) 2017-2018 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "cbtx.h"
#include "core_io.h"
#include "deterministicmns.h"
#include "simplifiedmns.h"
#include "specialtx.h"

#include "base58.h"
#include "chainparams.h"
#include "consensus/merkle.h"
#include "univalue.h"
#include "validation.h"

CSimplifiedMNListEntry::CSimplifiedMNListEntry(const CDeterministicMN& dmn) :
    proRegTxHash(dmn.proTxHash),
    confirmedHash(dmn.pdmnState->confirmedHash),
    service(dmn.pdmnState->addr),
    pubKeyOperator(dmn.pdmnState->pubKeyOperator),
    keyIDVoting(dmn.pdmnState->keyIDVoting),
    isValid(dmn.pdmnState->nPoSeBanHeight == -1)
{
}

uint256 CSimplifiedMNListEntry::CalcHash() const
{
    CHashWriter hw(SER_GETHASH, CLIENT_VERSION);
    hw << *this;
    return hw.GetHash();
}

std::string CSimplifiedMNListEntry::ToString() const
{
    return strprintf("CSimplifiedMNListEntry(proRegTxHash=%s, confirmedHash=%s, service=%s, pubKeyOperator=%s, votingAddress=%s, isValie=%d)",
        proRegTxHash.ToString(), confirmedHash.ToString(), service.ToString(false), pubKeyOperator.ToString(), CBitcoinAddress(keyIDVoting).ToString(), isValid);
}

void CSimplifiedMNListEntry::ToJson(UniValue& obj) const
{
    obj.clear();
    obj.setObject();
    obj.push_back(Pair("proRegTxHash", proRegTxHash.ToString()));
    obj.push_back(Pair("confirmedHash", confirmedHash.ToString()));
    obj.push_back(Pair("service", service.ToString(false)));
    obj.push_back(Pair("pubKeyOperator", pubKeyOperator.ToString()));
    obj.push_back(Pair("votingAddress", CBitcoinAddress(keyIDVoting).ToString()));
    obj.push_back(Pair("isValid", isValid));
}

CSimplifiedMNList::CSimplifiedMNList(const std::vector<CSimplifiedMNListEntry>& smlEntries)
{
    mnList = smlEntries;

    std::sort(mnList.begin(), mnList.end(), [&](const CSimplifiedMNListEntry& a, const CSimplifiedMNListEntry& b) {
        return a.proRegTxHash.Compare(b.proRegTxHash) < 0;
    });
}

CSimplifiedMNList::CSimplifiedMNList(const CDeterministicMNList& dmnList)
{
    mnList.reserve(dmnList.GetAllMNsCount());

    dmnList.ForEachMN(false, [this](const CDeterministicMNCPtr& dmn) {
        mnList.emplace_back(*dmn);
    });

    std::sort(mnList.begin(), mnList.end(), [&](const CSimplifiedMNListEntry& a, const CSimplifiedMNListEntry& b) {
        return a.proRegTxHash.Compare(b.proRegTxHash) < 0;
    });
}

uint256 CSimplifiedMNList::CalcMerkleRoot(bool* pmutated) const
{
    std::vector<uint256> leaves;
    leaves.reserve(mnList.size());
    for (const auto& e : mnList) {
        leaves.emplace_back(e.CalcHash());
    }
    return ComputeMerkleRoot(leaves, pmutated);
}

void CSimplifiedMNListDiff::ToJson(UniValue& obj) const
{
    obj.setObject();

    obj.push_back(Pair("baseBlockHash", baseBlockHash.ToString()));
    obj.push_back(Pair("blockHash", blockHash.ToString()));

    CDataStream ssCbTxMerkleTree(SER_NETWORK, PROTOCOL_VERSION);
    ssCbTxMerkleTree << cbTxMerkleTree;
    obj.push_back(Pair("cbTxMerkleTree", HexStr(ssCbTxMerkleTree.begin(), ssCbTxMerkleTree.end())));

    obj.push_back(Pair("cbTx", EncodeHexTx(*cbTx)));

    UniValue deletedMNsArr(UniValue::VARR);
    for (const auto& h : deletedMNs) {
        deletedMNsArr.push_back(h.ToString());
    }
    obj.push_back(Pair("deletedMNs", deletedMNsArr));

    UniValue mnListArr(UniValue::VARR);
    for (const auto& e : mnList) {
        UniValue eObj;
        e.ToJson(eObj);
        mnListArr.push_back(eObj);
    }
    obj.push_back(Pair("mnList", mnListArr));

    CCbTx cbTxPayload;
    if (GetTxPayload(*cbTx, cbTxPayload)) {
        obj.push_back(Pair("merkleRootMNList", cbTxPayload.merkleRootMNList.ToString()));
    }
}

bool BuildSimplifiedMNListDiff(const uint256& baseBlockHash, const uint256& blockHash, CSimplifiedMNListDiff& mnListDiffRet, std::string& errorRet)
{
    AssertLockHeld(cs_main);
    mnListDiffRet = CSimplifiedMNListDiff();

    BlockMap::iterator baseBlockIt = mapBlockIndex.begin();
    if (!baseBlockHash.IsNull()) {
        baseBlockIt = mapBlockIndex.find(baseBlockHash);
    }
    auto blockIt = mapBlockIndex.find(blockHash);
    if (baseBlockIt == mapBlockIndex.end()) {
        errorRet = strprintf("block %s not found", baseBlockHash.ToString());
        return false;
    }
    if (blockIt == mapBlockIndex.end()) {
        errorRet = strprintf("block %s not found", blockHash.ToString());
        return false;
    }

    if (!chainActive.Contains(baseBlockIt->second) || !chainActive.Contains(blockIt->second)) {
        errorRet = strprintf("block %s and %s are not in the same chain", baseBlockHash.ToString(), blockHash.ToString());
        return false;
    }
    if (baseBlockIt->second->nHeight > blockIt->second->nHeight) {
        errorRet = strprintf("base block %s is higher then block %s", baseBlockHash.ToString(), blockHash.ToString());
        return false;
    }

    LOCK(deterministicMNManager->cs);

    auto baseDmnList = deterministicMNManager->GetListForBlock(baseBlockHash);
    auto dmnList = deterministicMNManager->GetListForBlock(blockHash);
    mnListDiffRet = baseDmnList.BuildSimplifiedDiff(dmnList);

    // TODO store coinbase TX in CBlockIndex
    CBlock block;
    if (!ReadBlockFromDisk(block, blockIt->second, Params().GetConsensus())) {
        errorRet = strprintf("failed to read block %s from disk", blockHash.ToString());
        return false;
    }

    mnListDiffRet.cbTx = block.vtx[0];

    std::vector<uint256> vHashes;
    std::vector<bool> vMatch(block.vtx.size(), false);
    for (const auto& tx : block.vtx) {
        vHashes.emplace_back(tx->GetHash());
    }
    vMatch[0] = true; // only coinbase matches
    mnListDiffRet.cbTxMerkleTree = CPartialMerkleTree(vHashes, vMatch);

    return true;
}
<commit_msg>Fix incorrect usage of begin() when genesis block is requested in "protx diff" (#2699)<commit_after>// Copyright (c) 2017-2018 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "cbtx.h"
#include "core_io.h"
#include "deterministicmns.h"
#include "simplifiedmns.h"
#include "specialtx.h"

#include "base58.h"
#include "chainparams.h"
#include "consensus/merkle.h"
#include "univalue.h"
#include "validation.h"

CSimplifiedMNListEntry::CSimplifiedMNListEntry(const CDeterministicMN& dmn) :
    proRegTxHash(dmn.proTxHash),
    confirmedHash(dmn.pdmnState->confirmedHash),
    service(dmn.pdmnState->addr),
    pubKeyOperator(dmn.pdmnState->pubKeyOperator),
    keyIDVoting(dmn.pdmnState->keyIDVoting),
    isValid(dmn.pdmnState->nPoSeBanHeight == -1)
{
}

uint256 CSimplifiedMNListEntry::CalcHash() const
{
    CHashWriter hw(SER_GETHASH, CLIENT_VERSION);
    hw << *this;
    return hw.GetHash();
}

std::string CSimplifiedMNListEntry::ToString() const
{
    return strprintf("CSimplifiedMNListEntry(proRegTxHash=%s, confirmedHash=%s, service=%s, pubKeyOperator=%s, votingAddress=%s, isValie=%d)",
        proRegTxHash.ToString(), confirmedHash.ToString(), service.ToString(false), pubKeyOperator.ToString(), CBitcoinAddress(keyIDVoting).ToString(), isValid);
}

void CSimplifiedMNListEntry::ToJson(UniValue& obj) const
{
    obj.clear();
    obj.setObject();
    obj.push_back(Pair("proRegTxHash", proRegTxHash.ToString()));
    obj.push_back(Pair("confirmedHash", confirmedHash.ToString()));
    obj.push_back(Pair("service", service.ToString(false)));
    obj.push_back(Pair("pubKeyOperator", pubKeyOperator.ToString()));
    obj.push_back(Pair("votingAddress", CBitcoinAddress(keyIDVoting).ToString()));
    obj.push_back(Pair("isValid", isValid));
}

CSimplifiedMNList::CSimplifiedMNList(const std::vector<CSimplifiedMNListEntry>& smlEntries)
{
    mnList = smlEntries;

    std::sort(mnList.begin(), mnList.end(), [&](const CSimplifiedMNListEntry& a, const CSimplifiedMNListEntry& b) {
        return a.proRegTxHash.Compare(b.proRegTxHash) < 0;
    });
}

CSimplifiedMNList::CSimplifiedMNList(const CDeterministicMNList& dmnList)
{
    mnList.reserve(dmnList.GetAllMNsCount());

    dmnList.ForEachMN(false, [this](const CDeterministicMNCPtr& dmn) {
        mnList.emplace_back(*dmn);
    });

    std::sort(mnList.begin(), mnList.end(), [&](const CSimplifiedMNListEntry& a, const CSimplifiedMNListEntry& b) {
        return a.proRegTxHash.Compare(b.proRegTxHash) < 0;
    });
}

uint256 CSimplifiedMNList::CalcMerkleRoot(bool* pmutated) const
{
    std::vector<uint256> leaves;
    leaves.reserve(mnList.size());
    for (const auto& e : mnList) {
        leaves.emplace_back(e.CalcHash());
    }
    return ComputeMerkleRoot(leaves, pmutated);
}

void CSimplifiedMNListDiff::ToJson(UniValue& obj) const
{
    obj.setObject();

    obj.push_back(Pair("baseBlockHash", baseBlockHash.ToString()));
    obj.push_back(Pair("blockHash", blockHash.ToString()));

    CDataStream ssCbTxMerkleTree(SER_NETWORK, PROTOCOL_VERSION);
    ssCbTxMerkleTree << cbTxMerkleTree;
    obj.push_back(Pair("cbTxMerkleTree", HexStr(ssCbTxMerkleTree.begin(), ssCbTxMerkleTree.end())));

    obj.push_back(Pair("cbTx", EncodeHexTx(*cbTx)));

    UniValue deletedMNsArr(UniValue::VARR);
    for (const auto& h : deletedMNs) {
        deletedMNsArr.push_back(h.ToString());
    }
    obj.push_back(Pair("deletedMNs", deletedMNsArr));

    UniValue mnListArr(UniValue::VARR);
    for (const auto& e : mnList) {
        UniValue eObj;
        e.ToJson(eObj);
        mnListArr.push_back(eObj);
    }
    obj.push_back(Pair("mnList", mnListArr));

    CCbTx cbTxPayload;
    if (GetTxPayload(*cbTx, cbTxPayload)) {
        obj.push_back(Pair("merkleRootMNList", cbTxPayload.merkleRootMNList.ToString()));
    }
}

bool BuildSimplifiedMNListDiff(const uint256& baseBlockHash, const uint256& blockHash, CSimplifiedMNListDiff& mnListDiffRet, std::string& errorRet)
{
    AssertLockHeld(cs_main);
    mnListDiffRet = CSimplifiedMNListDiff();

    const CBlockIndex* baseBlockIndex = chainActive.Genesis();
    if (!baseBlockHash.IsNull()) {
        auto it = mapBlockIndex.find(baseBlockHash);
        if (it == mapBlockIndex.end()) {
            errorRet = strprintf("block %s not found", baseBlockHash.ToString());
            return false;
        }
        baseBlockIndex = it->second;
    }
    auto blockIt = mapBlockIndex.find(blockHash);
    if (blockIt == mapBlockIndex.end()) {
        errorRet = strprintf("block %s not found", blockHash.ToString());
        return false;
    }
    const CBlockIndex* blockIndex = blockIt->second;

    if (!chainActive.Contains(baseBlockIndex) || !chainActive.Contains(blockIndex)) {
        errorRet = strprintf("block %s and %s are not in the same chain", baseBlockHash.ToString(), blockHash.ToString());
        return false;
    }
    if (baseBlockIndex->nHeight > blockIndex->nHeight) {
        errorRet = strprintf("base block %s is higher then block %s", baseBlockHash.ToString(), blockHash.ToString());
        return false;
    }

    LOCK(deterministicMNManager->cs);

    auto baseDmnList = deterministicMNManager->GetListForBlock(baseBlockHash);
    auto dmnList = deterministicMNManager->GetListForBlock(blockHash);
    mnListDiffRet = baseDmnList.BuildSimplifiedDiff(dmnList);

    // TODO store coinbase TX in CBlockIndex
    CBlock block;
    if (!ReadBlockFromDisk(block, blockIndex, Params().GetConsensus())) {
        errorRet = strprintf("failed to read block %s from disk", blockHash.ToString());
        return false;
    }

    mnListDiffRet.cbTx = block.vtx[0];

    std::vector<uint256> vHashes;
    std::vector<bool> vMatch(block.vtx.size(), false);
    for (const auto& tx : block.vtx) {
        vHashes.emplace_back(tx->GetHash());
    }
    vMatch[0] = true; // only coinbase matches
    mnListDiffRet.cbTxMerkleTree = CPartialMerkleTree(vHashes, vMatch);

    return true;
}
<|endoftext|>


<commit_before>// ==========================================================================
// Image File Reading Support Functions
//  - requires the Magick++ development libraries: http://www.imagemagick.org
//
// Note: This file will not compile by itself! The snippets below are meant
// to be added to the template application distributed for Assignment #1.
// You may use this code (or not) however you see fit for your work.
//
// Author:  Sonny Chan, University of Calgary
// Date:    January 2016
// ==========================================================================

#include <Magick++.h>

// --------------------------------------------------------------------------
// Functions to set up OpenGL objects for storing image data

struct MyTexture
{
    // OpenGL names for array buffer objects, vertex array object
    GLuint  textureName;

    // dimensions of the image stored in this texture
    GLuint  width, height;

    // initialize object names to zero (OpenGL reserved value)
    MyTexture() : textureName(0), width(0), height(0)
    {}
};

// use the Magick++ library to load an image with a given file name into
// an OpenGL rectangle texture
bool InitializeTexture(MyTexture *texture, const string &imageFileName)
{
    Magick::Image myImage;

    // try to read the provided image file
    try {
        myImage.read(imageFileName);
    }
    catch (Magick::Error &error) {
        cout << "Magick++ failed to read image " << imageFileName << endl;
        cout << "ERROR: " << error.what() << endl;
        return false;
    }

    // store the image width and height into the texture structure
    texture->width = myImage.columns();
    texture->height = myImage.rows();

    // create a Magick++ pixel cache from the image for direct access to data
    Magick::Pixels pixelCache(myImage);
    Magick::PixelPacket *pixels;
    pixels = pixelCache.get(0, 0, texture->width, texture->height);

    // determine the number of stored bytes per pixel channel in the cache
    GLenum channelDataType;
    switch (sizeof(Magick::Quantum)) {
        case 4:     channelDataType = GL_UNSIGNED_INT;      break;
        case 2:     channelDataType = GL_UNSIGNED_SHORT;    break;
        default:    channelDataType = GL_UNSIGNED_BYTE;
    }

    // create a texture name to associate our image data with
    if (!texture->textureName)
        glGenTextures(1, &texture->textureName);

    // bind the texture as a "rectangle" to access using image pixel coordinates
    glBindTexture(GL_TEXTURE_RECTANGLE, texture->textureName);

    // send image pixel data to OpenGL texture memory
    glTexImage2D(GL_TEXTURE_RECTANGLE, 0, GL_RGB, texture->width, texture->height,
                 0, GL_BGRA, channelDataType, pixels);

    // unbind this texture
    glBindTexture(GL_TEXTURE_RECTANGLE, 0);

    return !CheckGLErrors();
}

<commit_msg>Removed ImageReader.cpp<commit_after><|endoftext|>


<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TF1.h>
#include <TFile.h>
#include <TH1F.h>
#include <TGraph.h>
#include <TStyle.h>
#include <TSystem.h>
#include <TString.h>
#include <TGrid.h>
#include <TCanvas.h>
#include <TLatex.h>
#include <TObjArray.h>
#include "AliCDBEntry.h"
#include "AliITSDriftSpeedArraySDD.h"
#include "AliITSDriftSpeedSDD.h"
#endif

// Macro to plot the calibration parameters from the OCDB file
// created from an INJECTOR run (OCDB/ITS/Calib/DriftSpeedSDD)
// Two methods ShowDriftSpeedSDD:
//  - the first takes the name of the file to be displayed
//  - the second builds the alien path+name from run number and file version
//
// Origin: F. Prino (prino@to.infn.it)

Bool_t kNoDraw = kFALSE; // set to kTRUE to eliminate module dependent plots

void ShowDriftSpeedSDD(Char_t filnam[150]="$ALICE_ROOT/ITS/Calib/DriftSpeedSDD/Run0_9999999_v0_s0.root", Int_t firstmod=0, Int_t lastmod=260,Int_t nrun=0){
  TFile *f= TFile::Open(filnam);
  AliCDBEntry *ent=(AliCDBEntry*)f->Get("AliCDBEntry");
  TObjArray *drspSDD = (TObjArray *)ent->GetObject();
  AliITSDriftSpeedArraySDD *vdriftarr0;
  AliITSDriftSpeedArraySDD *vdriftarr1;
  TGraph **gvdr0=new TGraph*[260];
  TGraph **gvdr1=new TGraph*[260];
  TCanvas *c0=NULL;
  if(!kNoDraw)c0=new TCanvas("c0","Module Drift Speed",1100,500);

  TGraph *vvsmod0=new TGraph(0);
  TGraph *vvsmod1=new TGraph(0);
  TGraph *poldegvsmod0=new TGraph(0);
  TGraph *poldegvsmod1=new TGraph(0);
  TGraph *anmaxvsmod0=new TGraph(0);
  TGraph *anmaxvsmod1=new TGraph(0);
  TGraph *dvcevsmod0=new TGraph(0);
  TGraph *dvcevsmod1=new TGraph(0);
  TGraph *dveevsmod0=new TGraph(0);
  TGraph *dveevsmod1=new TGraph(0);

  char tit0[100];
  sprintf(tit0,"Drift Speed vs. mod. number");
  if(nrun!=0)sprintf(tit0,"Drift Speed vs. mod. number - Run %d",nrun);
  vvsmod0->SetTitle(tit0);
  vvsmod1->SetTitle(tit0);

  sprintf(tit0,"Degree of poly fit vs. mod. number");
  if(nrun!=0)sprintf(tit0,"Degree of poly fit vs. mod. number - Run %d",nrun);
  poldegvsmod0->SetTitle(tit0);
  poldegvsmod1->SetTitle(tit0);

  sprintf(tit0,"Anode with max. vdrift vs. mod. number");
  if(nrun!=0)sprintf(tit0,"Anode with max. vdrift vs. mod. number - Run %d",nrun);
  anmaxvsmod0->SetTitle(tit0);
  anmaxvsmod1->SetTitle(tit0);

  sprintf(tit0,"Delta Vdrift 128-0 vs. mod. number");
  if(nrun!=0)sprintf(tit0,"Delta Vdrift 128-0 vs. mod. number - Run %d",nrun);
  dvcevsmod0->SetTitle(tit0);
  dvcevsmod1->SetTitle(tit0);

  sprintf(tit0,"Delta Vdrift 256-0 vs. mod. number");
  if(nrun!=0)sprintf(tit0,"Delta Vdrift 256-0 vs. mod. number - Run %d",nrun);
  dveevsmod0->SetTitle(tit0);
  dveevsmod1->SetTitle(tit0);

  TF1* fPoly=new TF1("fPoly","[0]+[1]*x+[2]*x*x+[3]*x*x*x",0.,256.);
  Char_t tit[100];
  Int_t iGoodInj=0;
  Int_t iAverSpeed=0;
  for(Int_t i=firstmod; i<lastmod; i++){
    Int_t iMod=i+240;
    if(!kNoDraw){
      c0->Clear();
      c0->Divide(2,1);
    }
    Int_t i0=2*i;
    Int_t i1=1+2*i;
    vdriftarr0=(AliITSDriftSpeedArraySDD*)drspSDD->At(i0);
    vdriftarr1=(AliITSDriftSpeedArraySDD*)drspSDD->At(i1);
    AliITSDriftSpeedSDD* vdrift0=0x0;
    if(vdriftarr0) vdrift0=vdriftarr0->GetDriftSpeedObject(0);
    AliITSDriftSpeedSDD* vdrift1=0x0;
    if(vdriftarr1) vdrift1=vdriftarr1->GetDriftSpeedObject(0);

    gvdr0[i]=new TGraph(0);
    gvdr1[i]=new TGraph(0);
    gvdr0[i]->SetMarkerStyle(7);
    gvdr1[i]->SetMarkerStyle(7);
    gvdr0[i]->SetMinimum(5.);
    gvdr1[i]->SetMinimum(5.);
    gvdr0[i]->SetMaximum(9.);
    gvdr1[i]->SetMaximum(9.);
    sprintf(tit,"Mod %d\n",iMod);
    gvdr0[i]->SetTitle(tit);
    gvdr1[i]->SetTitle(tit);

    for(Int_t iAn=0; iAn<256; iAn++){
      Float_t vel0=0;
      if(vdrift0) vel0=vdrift0->GetDriftSpeedAtAnode(iAn);
      Float_t vel1=0;
      if(vdrift1) vel1=vdrift1->GetDriftSpeedAtAnode(iAn);
      gvdr0[i]->SetPoint(iAn,(Float_t)iAn,vel0);
      gvdr1[i]->SetPoint(iAn,(Float_t)iAn,vel1);
    }
    if(vdriftarr0->GetInjectorStatus()>0) iGoodInj++;
    else iAverSpeed++;
    if(vdriftarr1->GetInjectorStatus()>0) iGoodInj++;
    else iAverSpeed++;

    printf(" Mod. %d \tStatusLR=%X %X \t v(an 128l)= %f",iMod,vdriftarr0->GetInjectorStatus(),vdriftarr1->GetInjectorStatus(),vdriftarr0->GetDriftSpeed(0,128));
    printf("        \t v(an 128r)= %f  Degree=%d %d\n",vdriftarr1->GetDriftSpeed(0,128),vdrift0->GetDegreeofPoly(),vdrift1->GetDegreeofPoly());

    if(!kNoDraw){
      c0->cd(1);
      gvdr0[i]->Draw("AP");
      gvdr0[i]->GetXaxis()->SetTitle("Anode");
      gvdr0[i]->GetYaxis()->SetTitle("Vdrift (#mum/ns)");
      c0->cd(2);
      gvdr1[i]->Draw("AP");
      gvdr1[i]->GetXaxis()->SetTitle("Anode");
      gvdr1[i]->GetYaxis()->SetTitle("Vdrift (#mum/ns)");
      c0->Update();
    }

    Float_t vel0=0;
    Float_t pd0=0;
    if(vdrift0){
      vel0=vdrift0->GetDriftSpeedAtAnode(128);
      pd0=vdrift0->GetDegreeofPoly();
    }
    Float_t vel1=0;
    Float_t pd1=0;
    if(vdrift1){
      vel1=vdrift1->GetDriftSpeedAtAnode(128);
      pd1=vdrift1->GetDegreeofPoly();
    }
    vvsmod0->SetPoint(vvsmod0->GetN(),(Float_t)iMod,vel0);
    vvsmod1->SetPoint(vvsmod1->GetN(),(Float_t)iMod,vel1);
    poldegvsmod0->SetPoint(poldegvsmod0->GetN(),(Float_t)iMod,pd0);
    poldegvsmod1->SetPoint(poldegvsmod1->GetN(),(Float_t)iMod,pd1);

    for(Int_t ipar=0; ipar<=vdrift0->GetDegreeofPoly(); ipar++){
      fPoly->SetParameter(ipar,vdrift0->GetDriftSpeedParameter(ipar));
    }
    if(vdrift0->GetDegreeofPoly()<3){
      for(Int_t ipar=vdrift0->GetDegreeofPoly()+1; ipar<=3; ipar++) fPoly->SetParameter(ipar,0.);
    }

    anmaxvsmod0->SetPoint(anmaxvsmod0->GetN(),(Float_t)iMod,fPoly->GetMaximumX(0.,256.));
    dvcevsmod0->SetPoint(dvcevsmod0->GetN(),(Float_t)iMod,fPoly->Eval(128)-fPoly->Eval(0));
    dveevsmod0->SetPoint(dveevsmod0->GetN(),(Float_t)iMod,fPoly->Eval(256)-fPoly->Eval(0));

    for(Int_t ipar=0; ipar<=vdrift1->GetDegreeofPoly(); ipar++){
      fPoly->SetParameter(ipar,vdrift1->GetDriftSpeedParameter(ipar));
    }
    if(vdrift1->GetDegreeofPoly()<3){
      for(Int_t ipar=vdrift1->GetDegreeofPoly()+1; ipar<=3; ipar++) fPoly->SetParameter(ipar,0.);
    }
    anmaxvsmod1->SetPoint(anmaxvsmod1->GetN(),(Float_t)iMod,fPoly->GetMaximumX(0.,256.));
    dvcevsmod1->SetPoint(dvcevsmod1->GetN(),(Float_t)iMod,fPoly->Eval(128)-fPoly->Eval(0));
    dveevsmod1->SetPoint(dveevsmod1->GetN(),(Float_t)iMod,fPoly->Eval(256)-fPoly->Eval(0));
    //    getchar();
  }

  printf("Number of half-modules with drift speed from injectors = %d\n",iGoodInj);
  printf("Number of half-modules with average drift speed        = %d\n",iAverSpeed);

  TCanvas* c2;
  c2=new TCanvas("c2","",1000,700);
  vvsmod0->SetMarkerStyle(20);
  vvsmod0->Draw("AP");
  vvsmod0->GetXaxis()->SetTitle("Module Number");
  vvsmod0->GetYaxis()->SetTitle("Vdrift (#mum/ns)");
  vvsmod1->SetMarkerStyle(21);
  vvsmod1->SetMarkerColor(2);
  vvsmod1->Draw("SAMEP");
  TLatex* tleft=new TLatex(0.2,0.82,"Side 0");
  tleft->SetNDC();
  tleft->SetTextColor(1);
  tleft->Draw();
  TLatex* tright=new TLatex(0.2,0.75,"Side 1");
  tright->SetNDC();
  tright->SetTextColor(2);
  tright->Draw();

  TCanvas* c3;
  c3=new TCanvas("c3","",900,900);
  c3->Divide(2,2);

  c3->cd(1);
  gPad->SetLeftMargin(0.14);
  poldegvsmod0->SetMarkerStyle(20);
  poldegvsmod0->Draw("AP");
  poldegvsmod0->GetXaxis()->SetTitle("Module Number");
  poldegvsmod0->GetYaxis()->SetTitle("Degree of Polynomial fit");
  poldegvsmod0->GetYaxis()->SetTitleOffset(1.4);
  poldegvsmod1->SetMarkerStyle(21);
  poldegvsmod1->SetMarkerColor(2);
  poldegvsmod1->Draw("SAMEP");
  tleft->Draw();
  tright->Draw();
  c3->cd(2);
  gPad->SetLeftMargin(0.14);
  anmaxvsmod0->SetMarkerStyle(20);
  anmaxvsmod0->Draw("AP");
  anmaxvsmod0->GetXaxis()->SetTitle("Module Number");
  anmaxvsmod0->GetYaxis()->SetTitle("Anode with max. drift speed");
  anmaxvsmod0->GetYaxis()->SetTitleOffset(1.4);
  anmaxvsmod1->SetMarkerStyle(21);
  anmaxvsmod1->SetMarkerColor(2);
  anmaxvsmod1->Draw("SAMEP");
  tleft->Draw();
  tright->Draw();
  c3->cd(3);
  gPad->SetLeftMargin(0.14);
  dvcevsmod0->SetMarkerStyle(20);
  dvcevsmod0->Draw("AP");
  dvcevsmod0->GetXaxis()->SetTitle("Module Number");
  dvcevsmod0->GetYaxis()->SetTitle("vdrift(anode128)-vdrift(anode0)");
  dvcevsmod0->GetYaxis()->SetTitleOffset(1.4);
  dvcevsmod1->SetMarkerStyle(21);
  dvcevsmod1->SetMarkerColor(2);
  dvcevsmod1->Draw("SAMEP");
  tleft->Draw();
  tright->Draw();
  c3->cd(4);
  gPad->SetLeftMargin(0.14);
  dveevsmod0->SetMarkerStyle(20);
  dveevsmod0->Draw("AP");
  dveevsmod0->GetYaxis()->SetTitleOffset(1.4);
  dveevsmod0->GetXaxis()->SetTitle("Module Number");
  dveevsmod0->GetYaxis()->SetTitle("vdrift(anode256)-vdrift(anode0)");
  dveevsmod1->SetMarkerStyle(21);
  dveevsmod1->SetMarkerColor(2);
  dveevsmod1->Draw("SAMEP");
  tleft->Draw();
  tright->Draw();

}

void ShowDriftSpeedSDD(Int_t nrun, Int_t year=2010){
  TGrid::Connect("alien:",0,0,"t");
  TString cmd=Form("gbbox find \"/alice/data/%d/OCDB/ITS/Calib/DriftSpeedSDD\" \"Run%d*.root\" > run.txt",year,nrun);
  gSystem->Exec(cmd.Data());

  Char_t filnam[200],filnamalien[200];
  FILE* runtxt=fopen("run.txt","r");
  fscanf(runtxt,"%s\n",filnam);
  if(!strstr(filnam,"/alice/data/")){
    printf("Bad run number\n");
    gSystem->Exec("rm run.txt");
    return;
  }
  sprintf(filnamalien,"alien://%s",filnam);

  printf("Open file: %s\n",filnamalien);
  ShowDriftSpeedSDD(filnamalien,0,260,nrun);
  fclose(runtxt);
  gSystem->Exec("rm run.txt");

}
<commit_msg>Updates in macro to monitor SDD drift speed values<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TF1.h>
#include <TFile.h>
#include <TH1F.h>
#include <TGraph.h>
#include <TStyle.h>
#include <TSystem.h>
#include <TString.h>
#include <TGrid.h>
#include <TCanvas.h>
#include <TLatex.h>
#include <TObjArray.h>
#include "AliCDBEntry.h"
#include "AliITSDriftSpeedArraySDD.h"
#include "AliITSDriftSpeedSDD.h"
#endif

// Macro to plot the calibration parameters from the OCDB file
// created from an INJECTOR run (OCDB/ITS/Calib/DriftSpeedSDD)
// Two methods ShowDriftSpeedSDD:
//  - the first takes the name of the file to be displayed
//  - the second builds the alien path+name from run number and file version
//
// Origin: F. Prino (prino@to.infn.it)

Bool_t kNoDraw = kFALSE; // set to kTRUE to eliminate module dependent plots

void ShowDriftSpeedSDD(Char_t filnam[150]="$ALICE_ROOT/ITS/Calib/DriftSpeedSDD/Run0_9999999_v0_s0.root", Int_t firstmod=0, Int_t lastmod=260,Int_t nrun=0){
  TFile *f= TFile::Open(filnam);
  AliCDBEntry *ent=(AliCDBEntry*)f->Get("AliCDBEntry");
  TObjArray *drspSDD = (TObjArray *)ent->GetObject();
  AliITSDriftSpeedArraySDD *vdriftarr0;
  AliITSDriftSpeedArraySDD *vdriftarr1;
  TGraph **gvdr0=new TGraph*[260];
  TGraph **gvdr1=new TGraph*[260];
  TCanvas *c0=0x0;
  if(!kNoDraw)c0=new TCanvas("c0","Module Drift Speed",700,1000);

  TGraph *vvsmod0=new TGraph(0);
  TGraph *vvsmod1=new TGraph(0);
  TGraph *poldegvsmod0=new TGraph(0);
  TGraph *poldegvsmod1=new TGraph(0);
  TGraph *anmaxvsmod0=new TGraph(0);
  TGraph *anmaxvsmod1=new TGraph(0);
  TGraph *dvcevsmod0=new TGraph(0);
  TGraph *dvcevsmod1=new TGraph(0);
  TGraph *dveevsmod0=new TGraph(0);
  TGraph *dveevsmod1=new TGraph(0);

  char tit0[100];
  sprintf(tit0,"Drift Speed vs. mod. number");
  if(nrun!=0)sprintf(tit0,"Drift Speed vs. mod. number - Run %d",nrun);
  vvsmod0->SetTitle(tit0);
  vvsmod1->SetTitle(tit0);

  sprintf(tit0,"Degree of poly fit vs. mod. number");
  if(nrun!=0)sprintf(tit0,"Degree of poly fit vs. mod. number - Run %d",nrun);
  poldegvsmod0->SetTitle(tit0);
  poldegvsmod1->SetTitle(tit0);

  sprintf(tit0,"Anode with max. vdrift vs. mod. number");
  if(nrun!=0)sprintf(tit0,"Anode with max. vdrift vs. mod. number - Run %d",nrun);
  anmaxvsmod0->SetTitle(tit0);
  anmaxvsmod1->SetTitle(tit0);

  sprintf(tit0,"Delta Vdrift 128-0 vs. mod. number");
  if(nrun!=0)sprintf(tit0,"Delta Vdrift 128-0 vs. mod. number - Run %d",nrun);
  dvcevsmod0->SetTitle(tit0);
  dvcevsmod1->SetTitle(tit0);

  sprintf(tit0,"Delta Vdrift 256-0 vs. mod. number");
  if(nrun!=0)sprintf(tit0,"Delta Vdrift 256-0 vs. mod. number - Run %d",nrun);
  dveevsmod0->SetTitle(tit0);
  dveevsmod1->SetTitle(tit0);

  TF1* fPoly=new TF1("fPoly","[0]+[1]*x+[2]*x*x+[3]*x*x*x",0.,256.);
  Char_t tit[100];
  TString psnm0 = "vdriftSDD.ps[";
  TString psnm1 = "vdriftSDD.ps";
  TString psnm2 = "vdriftSDD.ps]";
  if(!kNoDraw) c0->Print(psnm0.Data());
  Int_t cntpad = 0;
  Int_t iGoodInj=0;
  Int_t iAverSpeed=0;
  TLatex* tleft=new TLatex(0.2,0.82,"Side 0");
  tleft->SetNDC();
  tleft->SetTextColor(1);
  TLatex* tright=new TLatex(0.2,0.75,"Side 1");
  tright->SetNDC();
  tright->SetTextColor(2);

  for(Int_t i=firstmod; i<lastmod; i++){
    Int_t iMod=i+240;
    Int_t i0=2*i;
    Int_t i1=1+2*i;
    vdriftarr0=(AliITSDriftSpeedArraySDD*)drspSDD->At(i0);
    vdriftarr1=(AliITSDriftSpeedArraySDD*)drspSDD->At(i1);
    AliITSDriftSpeedSDD* vdrift0=0x0;
    if(vdriftarr0) vdrift0=vdriftarr0->GetDriftSpeedObject(0);
    AliITSDriftSpeedSDD* vdrift1=0x0;
    if(vdriftarr1) vdrift1=vdriftarr1->GetDriftSpeedObject(0);

    gvdr0[i]=new TGraph(0);
    gvdr1[i]=new TGraph(0);
    gvdr0[i]->SetMarkerStyle(7);
    gvdr1[i]->SetMarkerStyle(7);
    gvdr0[i]->SetMarkerColor(kBlack);
    gvdr0[i]->SetLineColor(kBlack);
    gvdr0[i]->SetMinimum(5.);
    gvdr1[i]->SetMinimum(5.);
    gvdr0[i]->SetMaximum(7.5);
    gvdr1[i]->SetMaximum(7.5);
    sprintf(tit,"Mod %d\n",iMod);
    gvdr0[i]->SetTitle(tit);
    gvdr1[i]->SetTitle(tit);
    gvdr1[i]->SetMarkerColor(kRed);
    gvdr1[i]->SetLineColor(kRed);

    for(Int_t iAn=0; iAn<256; iAn++){
      Float_t vel0=0;
      if(vdrift0) vel0=vdrift0->GetDriftSpeedAtAnode(iAn);
      Float_t vel1=0;
      if(vdrift1) vel1=vdrift1->GetDriftSpeedAtAnode(iAn);
      gvdr0[i]->SetPoint(iAn,(Float_t)iAn,vel0);
      gvdr1[i]->SetPoint(iAn,(Float_t)iAn,vel1);
    }
    if(vdriftarr0->GetInjectorStatus()>0) iGoodInj++;
    else iAverSpeed++;
    if(vdriftarr1->GetInjectorStatus()>0) iGoodInj++;
    else iAverSpeed++;

    printf(" Mod. %d \tStatusLR=%X %X \t v(an 128l)= %f",iMod,vdriftarr0->GetInjectorStatus(),vdriftarr1->GetInjectorStatus(),vdriftarr0->GetDriftSpeed(0,128));
    printf("        \t v(an 128r)= %f  Degree=%d %d\n",vdriftarr1->GetDriftSpeed(0,128),vdrift0->GetDegreeofPoly(),vdrift1->GetDegreeofPoly());

    if(!kNoDraw){
      if (i%12==0 ) {
	c0->cd();
	c0->Modified();
	c0->Update();
	if (i) c0->Print(psnm1.Data());
	c0->Clear();
	c0->Divide(3,4);
	cntpad = 0;
      }
      c0->cd(++cntpad);
      gvdr0[i]->Draw("AP");
      gvdr0[i]->GetXaxis()->SetTitle("Anode");
      gvdr0[i]->GetYaxis()->SetTitle("Vdrift (#mum/ns)");
      gvdr1[i]->Draw("P same");
      gvdr1[i]->GetXaxis()->SetTitle("Anode");
      gvdr1[i]->GetYaxis()->SetTitle("Vdrift (#mum/ns)");
      tleft->Draw();
      tright->Draw();
    }

    Float_t vel0=0;
    Float_t pd0=0;
    if(vdrift0){
      vel0=vdrift0->GetDriftSpeedAtAnode(128);
     pd0=vdrift0->GetDegreeofPoly();
    }
    Float_t vel1=0;
    Float_t pd1=0;
    if(vdrift1){
      vel1=vdrift1->GetDriftSpeedAtAnode(128);
      pd1=vdrift1->GetDegreeofPoly();
    }
    vvsmod0->SetPoint(vvsmod0->GetN(),(Float_t)iMod,vel0);
    vvsmod1->SetPoint(vvsmod1->GetN(),(Float_t)iMod,vel1);
    poldegvsmod0->SetPoint(poldegvsmod0->GetN(),(Float_t)iMod,pd0);
    poldegvsmod1->SetPoint(poldegvsmod1->GetN(),(Float_t)iMod,pd1);

    for(Int_t ipar=0; ipar<=vdrift0->GetDegreeofPoly(); ipar++){
      fPoly->SetParameter(ipar,vdrift0->GetDriftSpeedParameter(ipar));
    }
    if(vdrift0->GetDegreeofPoly()<3){
      for(Int_t ipar=vdrift0->GetDegreeofPoly()+1; ipar<=3; ipar++) fPoly->SetParameter(ipar,0.);
    }

    anmaxvsmod0->SetPoint(anmaxvsmod0->GetN(),(Float_t)iMod,fPoly->GetMaximumX(0.,256.));
    dvcevsmod0->SetPoint(dvcevsmod0->GetN(),(Float_t)iMod,fPoly->Eval(128)-fPoly->Eval(0));
    dveevsmod0->SetPoint(dveevsmod0->GetN(),(Float_t)iMod,fPoly->Eval(256)-fPoly->Eval(0));

    for(Int_t ipar=0; ipar<=vdrift1->GetDegreeofPoly(); ipar++){
      fPoly->SetParameter(ipar,vdrift1->GetDriftSpeedParameter(ipar));
    }
    if(vdrift1->GetDegreeofPoly()<3){
      for(Int_t ipar=vdrift1->GetDegreeofPoly()+1; ipar<=3; ipar++) fPoly->SetParameter(ipar,0.);
    }
    anmaxvsmod1->SetPoint(anmaxvsmod1->GetN(),(Float_t)iMod,fPoly->GetMaximumX(0.,256.));
    dvcevsmod1->SetPoint(dvcevsmod1->GetN(),(Float_t)iMod,fPoly->Eval(128)-fPoly->Eval(0));
    dveevsmod1->SetPoint(dveevsmod1->GetN(),(Float_t)iMod,fPoly->Eval(256)-fPoly->Eval(0));
    //    getchar();
  }

  if(!kNoDraw){
    c0->cd();
    c0->Modified();
    c0->Update();
    c0->Print(psnm2.Data());
  }
  printf("Number of half-modules with drift speed from injectors = %d\n",iGoodInj);
  printf("Number of half-modules with average drift speed        = %d\n",iAverSpeed);

  TCanvas* c2;
  c2=new TCanvas("c2","",1000,700);
  vvsmod0->SetMarkerStyle(20);
  vvsmod0->Draw("AP");
  vvsmod0->GetXaxis()->SetTitle("Module Number");
  vvsmod0->GetYaxis()->SetTitle("Vdrift (#mum/ns)");
  vvsmod1->SetMarkerStyle(21);
  vvsmod1->SetMarkerColor(2);
  vvsmod1->Draw("SAMEP");
  tleft->Draw();
  tright->Draw();

  TCanvas* c3;
  c3=new TCanvas("c3","",900,900);
  c3->Divide(2,2);

  c3->cd(1);
  gPad->SetLeftMargin(0.14);
  poldegvsmod0->SetMarkerStyle(20);
  poldegvsmod0->Draw("AP");
  poldegvsmod0->GetXaxis()->SetTitle("Module Number");
  poldegvsmod0->GetYaxis()->SetTitle("Degree of Polynomial fit");
  poldegvsmod0->GetYaxis()->SetTitleOffset(1.4);
  poldegvsmod1->SetMarkerStyle(21);
  poldegvsmod1->SetMarkerColor(2);
  poldegvsmod1->Draw("SAMEP");
  tleft->Draw();
  tright->Draw();
  c3->cd(2);
  gPad->SetLeftMargin(0.14);
  anmaxvsmod0->SetMarkerStyle(20);
  anmaxvsmod0->Draw("AP");
  anmaxvsmod0->GetXaxis()->SetTitle("Module Number");
  anmaxvsmod0->GetYaxis()->SetTitle("Anode with max. drift speed");
  anmaxvsmod0->GetYaxis()->SetTitleOffset(1.4);
  anmaxvsmod1->SetMarkerStyle(21);
  anmaxvsmod1->SetMarkerColor(2);
  anmaxvsmod1->Draw("SAMEP");
  tleft->Draw();
  tright->Draw();
  c3->cd(3);
  gPad->SetLeftMargin(0.14);
  dvcevsmod0->SetMarkerStyle(20);
  dvcevsmod0->Draw("AP");
  dvcevsmod0->GetXaxis()->SetTitle("Module Number");
  dvcevsmod0->GetYaxis()->SetTitle("vdrift(anode128)-vdrift(anode0)");
  dvcevsmod0->GetYaxis()->SetTitleOffset(1.4);
  dvcevsmod1->SetMarkerStyle(21);
  dvcevsmod1->SetMarkerColor(2);
  dvcevsmod1->Draw("SAMEP");
  tleft->Draw();
  tright->Draw();
  c3->cd(4);
  gPad->SetLeftMargin(0.14);
  dveevsmod0->SetMarkerStyle(20);
  dveevsmod0->Draw("AP");
  dveevsmod0->GetYaxis()->SetTitleOffset(1.4);
  dveevsmod0->GetXaxis()->SetTitle("Module Number");
  dveevsmod0->GetYaxis()->SetTitle("vdrift(anode256)-vdrift(anode0)");
  dveevsmod1->SetMarkerStyle(21);
  dveevsmod1->SetMarkerColor(2);
  dveevsmod1->Draw("SAMEP");
  tleft->Draw();
  tright->Draw();

}

void ShowDriftSpeedSDD(Int_t nrun, Int_t year=2010, Int_t nv=-1){
  TGrid::Connect("alien:",0,0,"t");
  TString cmd=Form("gbbox find \"/alice/data/%d/OCDB/ITS/Calib/DriftSpeedSDD\" \"Run%d*.root\" > run.txt",year,nrun);
  if(nv>0){
    cmd.Form("gbbox find \"/alice/data/%d/OCDB/ITS/Calib/DriftSpeedSDD\" \"Run%d_999999999_v%d_s0.root\" > run.txt",year,nrun,nv);
  }
  gSystem->Exec(cmd.Data());

  Char_t filnam[200],filnamalien[200];
  FILE* runtxt=fopen("run.txt","r");
  fscanf(runtxt,"%s\n",filnam);
  if(!strstr(filnam,"/alice/data/")){
    printf("Bad run number\n");
    gSystem->Exec("rm run.txt");
    return;
  }
  sprintf(filnamalien,"alien://%s",filnam);

  printf("Open file: %s\n",filnamalien);
  ShowDriftSpeedSDD(filnamalien,0,260,nrun);
  fclose(runtxt);
  gSystem->Exec("rm run.txt");

}
<|endoftext|>