TreeNode *deserialize(string data) {
     if (data[0] == '#')
         return nullptr;
     int i = data.find(' ');
     TreeNode *root = new TreeNode(stoi(data.substr(0, i++)));
     queue<TreeNode *> path;
     path.push(root);
     while (i < data.size()) {
         TreeNode *p = path.front();
         path.pop();
         int j = data.find(' ', i);
         if (data[i] != '#') {
             p->left = new TreeNode(stoi(data.substr(i, j - i)));
             path.push(p->left);
         }
         i = ++j;
         j = data.find(' ', i);
         if (data[i] != '#') {
             p->right = new TreeNode(stoi(data.substr(i, j - i)));
             path.push(p->right);
         }
         i = ++j;
     }
     return root;
 }
Card load_single_card(CDocument& doc)
{
	using std::stoi;

	Card result;

	result.name = load_text(doc, "#ctl00_ctl00_ctl00_MainContent_SubContent_SubContent_nameRow .value");
	result.manaCost = load_mana_cost(doc, "#ctl00_ctl00_ctl00_MainContent_SubContent_SubContent_manaRow .value img");

	int i = stoi(load_text(doc, "#ctl00_ctl00_ctl00_MainContent_SubContent_SubContent_cmcRow .value"));
	clamp(result.convertedManaCost, i);

	result.types = load_text(doc, "#ctl00_ctl00_ctl00_MainContent_SubContent_SubContent_typeRow .value");
	result.text = load_rules_text(doc, "#ctl00_ctl00_ctl00_MainContent_SubContent_SubContent_textRow .value");

	result.flavour = load_text(doc, "#ctl00_ctl00_ctl00_MainContent_SubContent_SubContent_FlavorText .flavortextbox");

	result.powerThoughness = load_text(doc, "#ctl00_ctl00_ctl00_MainContent_SubContent_SubContent_ptRow .value");
	//result.expansion = load_text(doc, "#ctl00_ctl00_ctl00_MainContent_SubContent_SubContent_setRow .value");
	result.rarity = load_text(doc, "#ctl00_ctl00_ctl00_MainContent_SubContent_SubContent_rarityRow .value");

	i = stoi(load_text(doc, "#ctl00_ctl00_ctl00_MainContent_SubContent_SubContent_numberRow .value"));
	clamp(result.cardNumber, i);

	result.artist = load_text(doc, "#ctl00_ctl00_ctl00_MainContent_SubContent_SubContent_artistRow .value");

	return result;
}
Example #3
0
slab_config::slab_config(string file_name){

  ifstream in(file_name);
  
  string line;
  while(in>>line){
    auto pos = line.find(",");
    slab_settings.push_back(make_pair(stoi(line.substr(0,pos)) , stoi(line.substr(pos+1))));
  }
    
  in.close();
}
Example #4
0
int main(int argc, char *argv[])
{
	string input_file;

	// Check first argument if it exists for input file, otherwise ask user
	if (argc > 1)
	{
		input_file = argv[1];
	}
	else
	{
		cout << "Please enter the path to your input file: " << endl;
		cin >> input_file;
	}

	// Open input file and check if successfully opened
	ifstream ifs(input_file);
	if (!ifs)
	{
		cout << "Failed to open input file." << endl;
		return 1;
	}

	string line;
	while (getline(ifs, line))
	{
		unsigned int number_of_iterations = 0; 

		// If the length is one by default it's a palindrome
		if (line.length() == 1)
		{
			cout << number_of_iterations << " " << line << endl;
			continue;
		}

		while (!is_palindrome(line))
		{
			int original_number = stoi(line); // Convert line to an int
			reverse(line.begin(), line.end()); // Reverse the order of line
			int reversed_number = stoi(line); 
			int new_number = original_number + reversed_number; 
			line = to_string(new_number); 
			number_of_iterations++;
		}
		cout << number_of_iterations << " " << line << endl;
	}

	return 0;
}
Example #5
0
void add_task(int argc, char **args) {
	PGAdaptor pg;

	string task(args[0]);
	Options opts = default_options();
	if(argc > 1) {
		opts = get_options(argc - 1, &args[1]);
	}
	if(opts.error) {
		cerr << "An error occurred while parsing options. Aborting." << endl;
		exit(EXIT_FAILURE);
	}
	Task *p;

	if(opts.recurring) {
		if(isdigit(opts.recurrence.front())) {
			p = new Task(task, stoi(opts.recurrence), opts.persistent, opts.start_date);
		}
		else {
			p = new Task(task, opts.recurrence, opts.persistent, opts.start_date);
		}
	}
	else {
		p = new Task(task, opts.persistent, opts.start_date);
	}

	Task t = *p;
	delete p;

	bool success = pg.save_task(t);
	if(!success) {
		cerr << "An error occurred during task creation. See the log for more details. Aborting." << endl;
	}
}
Example #6
0
int main(int argc, char * argv[])
{
	if ((argc != 4) || (string(argv[1]) != "Astar") || (string(argv[2]) != "-h")) {
		std::cerr << "ERROR input should be in the format: Astar -h number" << endl;
		exit(1);
	}
	
	cout << "Please type in the initial state: ";
	
	char input[19];
	cin.getline(input,sizeof(input));
	
	vector<int> puzzleVector;
	puzzleVector.push_back(atoi(string(1,input[1]).c_str()));
	puzzleVector.push_back(atoi(string(1,input[3]).c_str()));
	puzzleVector.push_back(atoi(string(1,input[5]).c_str()));
	puzzleVector.push_back(atoi(string(1,input[7]).c_str()));
	puzzleVector.push_back(atoi(string(1,input[9]).c_str()));
	puzzleVector.push_back(atoi(string(1,input[11]).c_str()));
	puzzleVector.push_back(atoi(string(1,input[13]).c_str()));
	puzzleVector.push_back(atoi(string(1,input[15]).c_str()));
	puzzleVector.push_back(atoi(string(1,input[17]).c_str()));

	Tree puzzleTree(puzzleVector);

	puzzleTree.chooseMove(*puzzleTree.root, stoi(string(argv[3])));
	cout << "The total Number of Nodes Expanded: " << puzzleTree.numberOfExpandedNodes << endl;
	cout << "Initial State: ";
	puzzleTree.printVector(puzzleVector);
	for (int i = 0; i < puzzleTree.solutionSequence.size(); i++)
		cout << puzzleTree.solutionSequence[i] << endl;
	cout << "The total Number of Operators Applied: " << puzzleTree.numberOfOperators << endl;
	return 0;
	
}
Example #7
0
void TaigaConfigInt::load(ALLEGRO_CONFIG* config)
{
	const char* val = al_get_config_value(config, sectionname.data(), keyname.data());

	if(val)
		*setting = stoi(val);
}
Example #8
0
int main(int argc, char *argv[])
{
	string input_file;

	// Check first argument if it exists for input file, otherwise ask user
	if (argc > 1)
	{
		input_file = argv[1];
	}
	else
	{
		cout << "Please enter the path to your input file: " << endl;
		cin >> input_file;
	}

	// Open input file and check if successfully opened
	ifstream ifs(input_file);
	if (!ifs)
	{
		cout << "Failed to open input file." << endl;
		return 1;
	}

	string line;
	while (getline(ifs, line))
	{
		// Parse line and load values into x1,y1,x2 and y2 respectively
		istringstream iss_line(line);
		string temp;
		getline(iss_line, temp, ',');
		temp.erase(0, 1);
		int x1 = stoi(temp);
		getline(iss_line, temp, ')');
		temp.erase(0, 1);
		int y1 = stoi(temp);
		getline(iss_line, temp, ',');
		temp.erase(0, 2);
		int x2 = stoi(temp);
		getline(iss_line, temp, ')');
		temp.erase(0, 1);
		int y2 = stoi(temp);

		// Output distance
		cout << distance(x1,y1,x2,y2) << endl;
	}
	return 0;
}
vector<int> HuffmanTree::groupEncoded8bit(string encoded) {
    unsigned long inputSize = encoded.size();
    vector<int> numbers;
    for (unsigned long i = 0; i < inputSize; i += 8) {
        numbers.push_back(stoi(encoded.substr(i, 8), nullptr, 2));
    }

    return numbers;
}
int main(int argc, char* argv[]) {
  default_random_engine gen((random_device())());
  for (int times = 0; times < 10000; ++times) {
    int n;
    if (argc == 2) {
      n = stoi(argv[1]);
    } else {
      uniform_int_distribution<int> dis(1, 10000);
      n = dis(gen);
    }
    vector<int> A;
    uniform_int_distribution<int> A_dis(0, 999999);
    generate_n(back_inserter(A), n, [&] { return A_dis(gen); });
    sort(A.begin(), A.end());
    uniform_int_distribution<int> n_dis(0, n - 1);
    int shift = n_dis(gen);
    reverse(A.begin(), A.end());
    reverse(A.begin(), A.begin() + shift + 1);
    reverse(A.begin() + shift + 1, A.end());
    /*
    for (size_t i = 0; i < n; ++i) {
      cout << A[i] << ' ';
    }
    cout << endl;
    */
    assert((shift + 1) % n == SearchSmallest(A));
  }

  // hand-made tests
  vector<int> A;
  A.emplace_back(2);
  A.emplace_back(2);
  A.emplace_back(2);
  assert(0 == SearchSmallest(A));
  A.clear();
  A.emplace_back(100);
  A.emplace_back(2);
  A.emplace_back(5);
  A.emplace_back(5);
  assert(1 == SearchSmallest(A));
  A.clear();
  A.emplace_back(1);
  A.emplace_back(2);
  A.emplace_back(3);
  A.emplace_back(3);
  A.emplace_back(3);
  assert(0 == SearchSmallest(A));
  A.clear();
  A.emplace_back(5);
  A.emplace_back(2);
  A.emplace_back(3);
  A.emplace_back(3);
  A.emplace_back(3);
  assert(1 == SearchSmallest(A));
  return 0;
}
Example #11
0
int main(int argc, char *argv[])
{
	string input_file;

	// Check first argument if it exists for input file, otherwise ask user
	if (argc > 1)
	{
		input_file = argv[1];
	}
	else
	{
		cout << "Please enter the path to your input file: " << endl;
		cin >> input_file;
	}

	// Open input file and check if successfully opened
	ifstream ifs(input_file);
	if (!ifs)
	{
		cout << "Failed to open input file." << endl;
		return 1;
	}

	string line;
	while (getline(ifs, line))
	{
		istringstream iss(line);
		string a_number;
		getline(iss, a_number, ',');
		// Convert string to int
		int N = stoi(a_number);
		getline(iss, a_number, ',');
		int M = stoi(a_number);

		// N mod M
		while ((N - M) >= 0)
		{
			N -= M;
		}
		cout << N << endl;
	}
	return 0;
}
int main(int argc, char* argv[]) {
  default_random_engine gen((random_device())());
  vector<GraphVertex> G;
  int n;
  if (argc == 2) {
    n = stoi(argv[1]);
  } else {
    uniform_int_distribution<int> dis(1, 1000);
    n = dis(gen);
  }
  fill_n(back_inserter(G), n, GraphVertex());
  cout << G.size() << endl;
  uniform_int_distribution<int> dis(1, n * (n - 1) >> 1);
  int m = dis(gen);
  vector<deque<bool>> is_edge_exist(n, deque<bool>(n, false));
  /*
  // Make the graph become connected
  for (int i = 1; i < n; ++i) {
  G[i - 1].edges.emplace_back(i);
  G[i].edges.emplace_back(i - 1);
  is_edge_exist[i - 1][i] = is_edge_exist[i][i - 1] = true;
  }
   */

  // Generate edges randomly
  while (m-- > 0) {
    uniform_int_distribution<int> dis(0, n - 1);
    int a, b;
    do {
      a = dis(gen), b = dis(gen);
    } while (a == b || is_edge_exist[a][b] == true);
    is_edge_exist[a][b] = is_edge_exist[b][a] = true;
    G[a].edges.emplace_back(&G[b]);
    G[b].edges.emplace_back(&G[a]);
  }

  transitive_closure(&G);
  /*
  for (int i = 0; i < G.size(); ++i) {
    cout << i << endl << '\t';
    for (GraphVertex* &e : G[i].extended_contacts) {
      cout << e << ' ';
    }
    cout << endl;
  }
  for (int i = 0; i < G.size(); ++i) {
    cout << i << endl;
    for (int j = 0; j < G[i].edges.size(); ++j) {
      cout << ' ' << G[i].edges[j];
    }
    cout << endl;
  }
  */
  return 0;
}
int main(int argc, char* argv[]) {
    default_random_engine gen((random_device())());
    for (int times = 0; times < 1000; ++times) {
        int num, k;
        if (argc == 2) {
            num = stoi(argv[1]);
            uniform_int_distribution<int> dis(1, num);
            k = dis(gen);
        } else if (argc == 3) {
            num = stoi(argv[1]);
            k = stoi(argv[2]);
        } else {
            uniform_int_distribution<int> num_dis(1, 10000);
            num = num_dis(gen);
            uniform_int_distribution<int> k_dis(1, num);
            k = k_dis(gen);
        }
        vector<Star> stars;
        // Randomly generate num of stars.
        uniform_real_distribution<double> dis(0, 100000);
        for (int i = 0; i < num; ++i) {
            stars.emplace_back(Star{i, dis(gen), dis(gen), dis(gen)});
        }
        string s;
        for (int i = 0; i < num; ++i) {
            stringstream ss;
            ss << stars[i].ID_ << ',' << stars[i].x_ << ',' << stars[i].y_ << ','
               << stars[i].z_ << endl;
            s += ss.str();
            // cout << stars[i].ID_ << ' ' << stars[i].Distance() << endl;
        }
        istringstream sin(s);
        vector<Star> closest_stars(FindClosestKStars(k, &sin));
        vector<Star> selected_stars(SelectK(stars, k));
        sort(selected_stars.begin(), selected_stars.end());
        sort(stars.begin(), stars.end());
        cout << "k = " << k << endl;
        // assert(stars[k - 1].ID_ == closest_stars[0].ID_);
        assert(stars[k - 1].Distance() == selected_stars.back().Distance());
    }
    return 0;
}
Example #14
0
void Parser::parseWeblog(string line) {
    // Hoping pcre can save me here
    const string pattern =
        "(\\S+)\\s" // IP Address
        "(\\S+)\\s" // -
        "(\\S+)\\s" // -
        "\\[(\\d{2}/\\w+/\\d{4}\\:\\d{2}\\:\\d{2}\\:\\d{2}\\s+.+?)\\]\\s" // Date
        "\\\"(\\w+\\s\\S+\\s\\w+\\/\\d+\\.\\d+)\\\"\\s" // Request
        "(\\d+)\\s" // Code
        "(\\d+)\\s" // Size
        "\\\"(\\S+)\\\"\\s" // Referer
        "\\\"(.+)\\\"";  // Agent
    // Prep a Weblog object
    Weblog w;

    // Call upon the mighty powers of PCRE
    Pcre p(pattern);
    if (p.search(line) == true) {
        if (p.matches() == 9) {
            // Should get 9 matches out of an apache log
            w.ip_addr = p[0];
            w.date = p[3];
            w.request = p[4];
            w.code = stoi(p[5]);
            w.size = stoi(p[6]);
            w.referer = p[7];
            w.agent = p[8];
        }
        else {
            cout << "Input string didn't match properly." << endl;
        }
    }
    else {
        cout << "Input string didn't match pattern at all." << endl;
        return;
    }

    // Shove the Weblog into the private logs vector
    logs.push_back(w);

    // Done!
}
Example #15
0
void
parseSue(string sue)
{
  auto r = regex("Sue (\\d*): (\\w+): (\\d*), (\\w+): (\\d*), (\\w+): (\\d*)");
  std::smatch m;
  if(std::regex_match(sue,m,r)){
    int sueNo = stoi(m[1].str());
    string item1 = m[2].str();
    int item1tot = stoi(m[3]);
    string item2 = m[4].str();
    int item2tot = stoi(m[5]);
    string item3 = m[6].str();
    int item3tot = stoi(m[7]);
    if(passes(item1,item1tot)
      && passes(item2,item2tot)
      && passes(item3,item3tot)){
          std::cout << "Found Sue " << sueNo << "!" << std::endl;
      }
  }
}
		//逆波兰式实际上是对二叉树后序遍历的结果,这里采用栈实现
		int evalRPN(vector<string> &tokens)
		{
			if (tokens.empty())
			  return 0;
			stack<int> iStack;

			iStack.push(stoi(tokens[0]));
			for (vector<string>::iterator iter = tokens.begin()+1; iter != tokens.end(); ++iter)
			{
				if (!isdigit((*iter)[0]) && (*iter).size()==1)
				{
					int i = iStack.top();
					iStack.pop();
					int j = iStack.top();
					iStack.pop();
					iStack.push(myOperation(j, i, (*iter)[0]));
				}
				else
				  iStack.push(stoi(*iter));
			}
			return iStack.top();
		}
Example #17
0
void delete_tasks(int argc, char **args) {
	PGAdaptor pg;

	bool success = true;
	for(int i = 0; i < argc; i++) {
		int task_id = stoi(args[i]);
		bool s = pg.delete_task(task_id);
		success = success && s;
	}
	if(!success) {
		cerr << "An error occurred during task deletion. See the log for more details. Aborting." << endl;
	}
}
Example #18
0
File: send.cpp Project: rio-/pt22x2
int main(int argc, char* argv[]) {
    if (argc != 4) {
        cout << "usage: send <system_code> <channel>|all on|off" << endl;
        return -1;
    }

    GPIOPin pin(24);
    pin.setOutput();
    PT22x2::Encoder encoder(pin);

    unsigned int system_code = stoi(argv[1]);

    Command::State state;
    if (argv[3] == string("on")) {
        state = Command::State::On;
    }
    else if (argv[3] == string("off")) {
        state = Command::State::Off;
    }
    else {
        cout << "state has to be 'on' or 'off'" << endl;
        return -1;
    }

    if (argv[2] == string("all")) {
        send(encoder, system_code, 1, state);
        send(encoder, system_code, 2, state);
        send(encoder, system_code, 4, state);
        send(encoder, system_code, 8, state);
    }
    else {
        unsigned int channel = stoi(argv[2]);
        send(encoder, system_code, channel, state);
    }
    return 0;
}
Example #19
0
void incomplete_tasks(int argc, char **args) {
	PGAdaptor pg;

	bool success = true;
	for(int i = 0; i < argc; i++) {
		int task_id = stoi(args[i]);
		Task task = pg.retrieve_task(task_id);
		task.mark_incomplete();
		bool s = pg.save_task(task);
		success = success && s;
	}
	if(!success) {
		cerr << "An error occurred during task incompletion. See the log for more details. Aborting." << endl;
	}
}
Example #20
0
int main(int argc, char** argv) {

	// http://stackoverflow.com/questions/17015830/how-can-i-prevent-zombie-child-processes
	struct sigaction sigchld_action;
	sigchld_action.sa_handler = SIG_DFL;
	sigchld_action.sa_flags = SA_NOCLDWAIT;
	sigaction(SIGCHLD, &sigchld_action, nullptr);


	logger 		= make_shared<Util::Logger>(Util::Logger::Level::INFO, std::cout);

	if (argc < 5) {
		std::cout << "usage: controller <control-port> <working-dir> <initial-id> <initial-ssh-port>\n";
		return -1;
	}

	ssocket 	= make_shared<Net::ServerSocket>(std::stoi(argv[1]));
	controller 	= make_shared<Vm::Controller>(string(argv[2]), stoi(argv[3]), stoi(argv[4]), logger);

	logger->info("VM Controller started!");

	for (;;) {
		try {
			auto socket = ssocket->accept();
			auto handler = new CommandHandler(socket);
			handler->start();
		}
		catch(Util::Exception& ex) {
			logger->error(ex.what());
		}
	}

	ssocket->close();

	return 0;
}
Example #21
0
int main(int argc, char *argv[])
{
	string input_file;

	// Check first argument if it exists for input file, otherwise ask user
	if (argc > 1)
	{
		input_file = argv[1];
	}
	else
	{
		cout << "Please enter the path to your input file: " << endl;
		cin >> input_file;
	}

	// Open input file and check if successfully opened
	ifstream ifs(input_file);
	if (!ifs)
	{
		cout << "Failed to open input file." << endl;
		return 1;
	}

	string line;
	while (getline(ifs, line))
	{
		// Load the values of each line into a set
		istringstream iss(line);
		set<int> uniques;
		string temp;
		while (getline (iss, temp, ','))
		{
			int number = stoi(temp);
			uniques.insert(number);
		}

		// Print unique elements
		string result;
		for (auto i = uniques.begin(); i != uniques.end(); i++)
		{
			result += (to_string(*i) + ",");
		}
		result.pop_back(); // Remove unnecessary comma
		cout << result << endl;
	}

	return 0;
}
Example #22
0
int
main(int argc, char const *argv[]) {

  std::fstream f;
  f.open(argv[1], std::fstream::in);

  vector<int> sizes;
  for (std::string line; std::getline(f, line);){
    sizes.push_back(stoi(line));
    std::cout << line << std::endl;
  }

  vector<bool> used(sizes.size(),false);
  int combinations = 0;
  int minContainers = sizes.size()+1;
  const int combs = 2 << (sizes.size()-1);
  for(int bits=0;bits<combs;bits++){
    int total = 0;
    int containers = 0;
    //std::cout << "Comb[";
    for(int i=0;i<sizes.size();i++){
      if(bitSet(bits,i)){
        //std::cout << sizes[i] << ",";
        total += sizes[i];
        containers++;
      };
    }
    if(total == 150 && minContainers >= containers) {
      //std::cout << "=25";
      combinations = (minContainers>containers)? 1:combinations+1;
      minContainers = containers;
    }
    //std::cout << "]" << std::endl;
  }

  std::cout << "Size combs: " << combs << std::endl;
  std::cout << "Total combs: " << combinations << std::endl;

  return 0;
}
 int evalRPN(vector<string> &tokens) {
     stack<int> operand;
     for (auto p = tokens.begin(); p != tokens.end(); ++p) {
         if (p->size() > 1 || (*p)[0] >= '0' && (*p)[0] <= '9') {
             operand.push(stoi(*p));
         } else {
             int b = operand.top();
             operand.pop();
             int a = operand.top();
             operand.pop();
             int res = 0;
             switch ((*p)[0]) {
                 case '+' : res = a + b; break;
                 case '-' : res = a - b; break;
                 case '*' : res = a * b; break;
                 case '/' : res = a / b; break;
             }
             operand.push(res);
         }
     }
     return operand.top();
 }
vector<Star> FindClosestKStars(int k, istringstream *sin) {
    // Use max_heap to find the closest k stars.
    priority_queue<Star, vector<Star>> max_heap;
    string line;

    // Record the first k stars.
    while (getline(*sin, line)) {
        stringstream line_stream(line);
        string buf;
        getline(line_stream, buf, ',');
        int ID = stoi(buf);
        array<double, 3> data;  // stores x, y, and z.
        for (int i = 0; i < 3; ++i) {
            getline(line_stream, buf, ',');
            data[i] = stod(buf);
        }
        Star s{ID, data[0], data[1], data[2]};

        if (max_heap.size() == k) {
            // Compare the top of heap with the incoming star.
            Star far_star = max_heap.top();
            if (s < far_star) {
                max_heap.pop();
                max_heap.emplace(s);
            }
        } else {
            max_heap.emplace(s);
        }
    }

    // Store the closest k stars.
    vector<Star> closest_stars;
    while (!max_heap.empty()) {
        closest_stars.emplace_back(max_heap.top());
        max_heap.pop();
    }
    return closest_stars;
}
Example #25
0
int Expression::evaluatePostfixExpression()
{
	const string postfix = convertToPostfix();
	if (postfix == "Invalid expression")
	{
		cerr << postfix << endl;
		return 0;
	}
	unsigned i = 0;
	Stack <int> numbers;
	string value;
	while (i < postfix.length())
	{
		if (isNumber(postfix[i]))
		{
			value += postfix[i];
		}
		else
		{
			if (i && isNumber(postfix[i - 1]))
			{
				numbers.push(stoi(value));
				value.clear();
			}
			if (isPropOperation(postfix[i]))
			{
				int x, y;
				numbers.pop(x);
				numbers.pop(y);
				numbers.push(calculate(y, x, postfix[i]));
			}
		}
		i++;
	}
	int res;
	numbers.pop(res);
	return res;
}
Example #26
0
int main(int argc, char** argv) {
    if (argc != 2) {
        std::cerr << "usage: " << argv[0] << " <name>\n";
        return 1;
    }
    string name;
    if (!demangle(argv[1], name)) {
        std::cerr << name << '\n';
        return 1;
    }
    size_t pos{}, tmp{};
    int ind{};
    // functional stuff
    auto drop = [&](size_t i) { return name.substr(pos+i); };
    auto chr = [&](size_t i) { return pos+i < name.length() ? name[pos+i] : '\0'; };
    auto startswith = [&](string prefix) -> bool {
        return name.length()-pos >= prefix.length() &&
            std::equal(prefix.begin(), prefix.end(), name.begin()+pos);
    };
    auto word = [&](string word) -> bool {
        bool r = name.length()-pos >= word.length()
                ? startswith(word) && !isalpha(chr(0))
                : startswith(word);
        if (r) tmp = word.length();
        return r;
    };
    auto ln = [&]() {
        cout << '\n';
        for (int i=0; i<ind; ++i) cout << "  ";
    };
    string rm; // regex match
    auto match = [&](const Regex& re) {
        #ifdef USE_RE2
        re2::StringPiece p{name.c_str()+pos};
        return RE2::PartialMatch(p, re, &rm);
        #else
        std::smatch sm;
        bool res = std::regex_search(name.cbegin()+pos, name.cend(), sm, re);
        if (res) rm = sm[1];
        return res;
        #endif
    };
    string
        c_reset{"\033[0m"},
        c_char{"\033[36m"},
        c_digit{"\033[34m"},
        c_kw{"\033[35m"},
        c_lambda{"\033[32m"},
        c_ptr{"\033[31m"},
        c_ns{"\033[33m"};
    Regex kw{"^(int|char|std|unsigned|long|short)"};
    while (pos < name.length()) {
        if (startswith("(char)")) {
            pos += 6;
            cout << c_char << '\'' << static_cast<char>(stoi(drop(0), &tmp))
                 << '\'';
            pos += tmp;
        } else if (isdigit(chr(0)) || (chr(0) == '-' && isdigit(chr(1)))) {
            cout << c_digit << stoi(drop(0), &tmp);
            pos += tmp;
            while (chr(0) == 'u' || chr(0) == 'l') {
                cout << chr(0);
                ++pos;
            }
        } else if (match(kw)) {
            cout << c_kw << rm;
            pos += rm.length();
        } else if (word("lambda")) {
            cout << c_lambda << "lambda";
            pos += 6;
        } else if (chr(0) == '*') {
            cout << c_ptr << '*';
            ++pos;
        } else if (startswith("::")) {
            cout << c_ns << "::";
            pos += 2;
        } else if (chr(0) == '<') {
            cout << '<';
            ++pos;
            ++ind;
            ln();
        } else if (chr(0) == '>') {
            cout << '>';
            --ind;
            if (chr(1) == ' ') {
                putchar(' ');
                ++pos;
            }
            ++pos;
            if (chr(0) == '>') while (chr(0) == '>') {
                cout << '>';
                --ind;
                ++pos;
                if (chr(0) == ' ') {
                    cout << ' ';
                    ++pos;
                }
            }
            if (chr(0) == ',') {
                cout << ',';
                ++pos;
                if (chr(0) == ' ') ++pos;;
            }
            ln();
        } else {
            cout << chr(0);
            ++pos;
        }
        cout << c_reset;
    }
}
Example #27
0
ode_solver::ode_solver(SMTConfig& c,
                       Egraph & e,
                       Enode * l_int,
                       vector<Enode*> invs,
                       unordered_map<Enode*, int>& enode_to_rp_id) :
    m_config(c),
    m_egraph(e),
    m_int(l_int),
    m_invs(invs),
    m_enode_to_rp_id(enode_to_rp_id),
    m_stepControl(c.nra_ODE_step),
    m_time(nullptr) {
    // Pick the right flow_map (var |-> ODE) using current mode
    m_mode = l_int->getCdr()->getCar()->getValue();
    map<string, Enode *> & flow_map = m_egraph.flow_maps[string("flow_") + to_string(m_mode)];
    m_time = l_int->getCdr()->getCdr()->getCdr()->getCar();
    string time_str = m_time->getCar()->getName();                       // i.e. "time_1"
    m_step = stoi(time_str.substr(time_str.find_last_of("_") + 1));      // i.e. 1
    Enode * var_list = l_int->getCdr()->getCdr()->getCdr()->getCdr();

    // Collect _0, _t variables from variable list in integral literal
    while (!var_list->isEnil()) {
        string name = var_list->getCar()->getCar()->getName();
        size_t second_ = name.find_last_of("_");
        size_t first_ = name.find_last_of("_", second_ - 1);
        string name_prefix, name_postfix;
        if (first_ == string::npos) {
            name_prefix = name.substr(0, second_);
            name_postfix = name.substr(second_);
        } else {
            name_prefix = name.substr(0, first_);
            name_postfix = name.substr(first_);
        }
        if (flow_map.find(name_prefix) == flow_map.end()) {
            cerr << name_prefix << " is not found in flow_map." << endl;
            assert(flow_map.find(name_prefix) != flow_map.end());
        }

        Enode * rhs = flow_map[name_prefix];
        stringstream ss;
        rhs->print_infix(ss, true, name_postfix);
        if (rhs->isConstant() && rhs->getValue() == 0.0) {
            // If RHS of ODE == 0.0, we treat it as a parameter in CAPD
            m_pars.push_back(var_list->getCar());
            m_par_list.push_back(name);
        } else {
            // Otherwise, we treat it as an ODE variable.
            m_0_vars.push_back(var_list->getCar());
            m_t_vars.push_back(var_list->getCdr()->getCar());
            m_var_list.push_back(name);
            m_ode_list.push_back(ss.str());
        }
        var_list = var_list->getCdr()->getCdr();
    }

    // join var_list to make diff_var, ode_list to diff_fun_forward
    string diff_var = "";
    if (!m_var_list.empty()) {
        diff_var = "var:" + join(m_var_list, ", ") + ";";
    }
    string diff_fun_forward = "";
    string diff_fun_backward = "";
    if (!m_ode_list.empty()) {
        diff_fun_forward = "fun:" + join(m_ode_list, ", ") + ";";
        diff_fun_backward = "fun: -" + join(m_ode_list, ", -") + ";";
    }
    // construct diff_sys_forward (string to CAPD)
    string diff_par;
    if (m_par_list.size() > 0) {
        diff_par = "par:" + join(m_par_list, ", ") + ";";
        m_diff_sys_forward = diff_par;
        m_diff_sys_backward = diff_par;
    }
    m_diff_sys_forward  += diff_var + diff_fun_forward;
    m_diff_sys_backward += diff_var + diff_fun_backward;
    DREAL_LOG_INFO << "diff_par          : " << diff_par;
    DREAL_LOG_INFO << "diff_var          : " << diff_var;
    DREAL_LOG_INFO << "diff_fun_forward  : " << diff_fun_forward;
    DREAL_LOG_INFO << "diff_fun_backward : " << diff_fun_backward;
    DREAL_LOG_INFO << "diff_sys_forward  : " << m_diff_sys_forward;
    DREAL_LOG_INFO << "diff_sys_backward : " << m_diff_sys_backward;
    for (auto ode_str : m_ode_list) {
        string const func_str = diff_par + diff_var + "fun:" + ode_str + ";";
        m_funcs.push_back(IFunction(func_str));
    };
    m_inv = extract_invariants();
    }
Example #28
0
int main(int argc, char *argv[])
{
	string input_file;

	// Check first argument if it exists for input file, otherwise ask user
	if (argc > 1)
	{
		input_file = argv[1];
	}
	else
	{
		cout << "Please enter the path to your input file: " << endl;
		cin >> input_file;
	}

	// Open input file and check if successfully opened
	ifstream ifs(input_file);
	if (!ifs)
	{
		cout << "Failed to open input file." << endl;
		return 1;
	}

	// Cycle through each line in file
	string line;
	while (getline(ifs, line))
	{
		// Break line into two strings based on semicolon
		istringstream iss(line);
		string scrambled_sentence, pattern;
		getline(iss, scrambled_sentence, ';');
		getline(iss, pattern, ';');

		// Convert pattern string into ints
		vector<int> number_pattern;
		iss.str("");
		iss.clear();
		iss.str(pattern);
		string temp;
		while (getline(iss, temp, ' '))
		{
			int number = stoi(temp);
			number_pattern.push_back(number);
		}

		// Find missing number in pattern
		int number_of_elements = number_pattern.size();
		int missing_number = (number_of_elements + 1)*(number_of_elements + 2) / 2;
		for (auto &number : number_pattern)
		{
			missing_number -= number;
		}
		number_pattern.push_back(missing_number);

		// Unscramble sentence and print to output
		iss.str("");
		iss.clear();
		iss.str(scrambled_sentence);
		map<int, string> my_sentence;
		for (auto &n : number_pattern)
		{
			string temp;
			getline(iss, temp, ' ');
			my_sentence[n] = temp;
		}
		for (auto beg = my_sentence.begin(); beg != my_sentence.end(); beg++)
		{
			cout << beg->second << " ";
		}
		cout << endl;
	}
	return 0;
}
    static void test() {
        unordered_map< string, unordered_map< int, unordered_set< int > > > dict;

        int lineCount = -1;
        string line = "";
        if ( getline( cin, line ) ) {
            lineCount = stoi( line );
        }

        for ( int i = 0; i < lineCount; ++i ) {
            if ( getline( cin, line ) ) {
                string word = "";
                istringstream iss( line );
                for ( int j = 0; iss >> word; ++j ) {
                    // If we can find word in dict
                    if ( dict.find( word ) != dict.end() ) {
                        // If we can find the sentence index in the 2nd unordered_map
                        if ( dict[ word ].find( i ) != dict[ word ].end() ) {
                            // If we can find the word index in the unordered_set
                            if ( dict[ word ][ i ].find( j ) != dict[ word ][ i ].end() ) {
                                // This should be flagged as an error. We do nothing for now.
                            } else {
                                // Push j into the unordered set
                                dict[ word ][ i ].insert( j );
                            }
                        } else {
                            // Create a new unordered_set
                            unordered_set< int > wordIdxSet;
                            wordIdxSet.insert( j );
                            dict[ word ].insert( pair< int, unordered_set< int > >( i, wordIdxSet ) );
                        }
                    } else {
                        // ElseIf we cannot find word in dict
                        // Create a new unordered_map AND unordered_set in dict
                        unordered_set< int > wordIdxSet;
                        wordIdxSet.insert( j );
                        unordered_map< int, unordered_set< int > > wordMap;
                        wordMap.insert( pair< int, unordered_set< int > >( i, wordIdxSet ) );
                        dict.insert( pair< string, unordered_map< int, unordered_set< int > > >( word, wordMap ) );
                    }
                }
            }
        }

        if ( getline( cin, line ) ) {
            lineCount = stoi( line );
        }

        string output = "";

        for ( int i = 0; i < lineCount; ++i ) {
            if ( getline( cin, line ) ) {
                string word = "";
                istringstream iss( line );
                // In this intersectMap we store the intersection of information of all queried words
                //
                // What we do here is:
                // - Loop through each word in the query sentence
                //     - If this is the first word
                //         - Create the intersectMap with:
                //             - key == all sentence indices of first word in dict
                //               value == all word indices of first word in dict
                //     - If this is not the first word
                //         - Loop through intersectMap
                //         - If we cannot find the sentenceIdx that's already in intersectMap in the
                //           current word's unordered_map< int, unordered_set< int > >, we remove that
                //           sentenceIdx from intersectMap. If intersectMap is empty, break and print out
                //           -1 and return. Otherwise, keep going to next words
                //
                // - Print out the final result using intersectMap
                unordered_map< int, const unordered_set< int > * > intersectMap;

                // Loop through each word in the query sentence
                for ( int i = 0; iss >> word; ++i ) {
                    // If we can't find this word in dict, let's print -1 and move to the next query line
                    if ( dict.find( word ) == dict.end() ) {
                        output += "-1";
                        // cout << line << " : " << -1 << endl;
                        break;
                    }

                    // If intersectMap is already empty() and we still have word left, let's print -1 and move to the
                    // next query line
                    if ( i != 0 && intersectMap.empty() ) {
                        output += "-1";
                        // cout << line << " : " << -1 << endl;
                        break;
                    }

                    // If this is the first word
                    if ( i == 0 ) {
                        for ( unordered_map< int, unordered_set< int > >::iterator iter = dict[ word ].begin();
                              iter != dict[ word ].end(); ++iter ) {
                            intersectMap.insert( pair< int, const unordered_set< int > * >( iter->first, &( iter->second ) ) );
                        }
                    } else {
                        // If we are here, this means this is not the first word and also intersectMap is not empty,
                        // and also this non-first-word can be found in dict.
                        for ( unordered_map< int, const unordered_set< int > * >::iterator iter = intersectMap.begin();
                              iter != intersectMap.end(); ++iter ) {
                            if ( dict[ word ].find( iter->first ) == dict[ word ].end() ) {
                                // We cannot find this sentenceIdx from the intersectMap in the dict[ word ].
                                // We have to remove this sentenceIdx from the intersectMap
                                intersectMap.erase( iter->first );
                            } else {
                                // If we can find this sentenceIdx from the intersectMap in the dict[ word ].
                                // We keep this sentenceIdx
                            }
                        }

                    }
                }

                // If intersectMap is not empty(), we print out its keys
                // Otherwise, we print out -1
                if ( ! intersectMap.empty() ) {
                    for ( unordered_map< int, const unordered_set< int > * >::iterator iter = intersectMap.begin();
                          iter != intersectMap.end(); ++iter ) {
                        if ( iter != intersectMap.begin() ) {
                            output += " ";
                        }
                        output += to_string( iter->first );
                    }
                } else {
                    output += "-1";
                    // cout << line << " : " << -1 << endl;
                }
                output += "\n";
            }
        }

        cout << output;
    }
Example #30
0
int WSession::Run(int argc, char *argv[]) {
  int num_min = 0;
  unsigned int ui = 0;
  unsigned long us = 0;
  unsigned short this_usernum = 0;
  bool ooneuser = false;
  bool event_only = false;
  CommunicationType type = CommunicationType::TELNET;
  unsigned int hSockOrComm = 0;

  curatr = 0x07;
  // Set the instance, this may be changed by a command line argument
  instance_number_ = 1;
  no_hangup = false;
  ok_modem_stuff = true;

  const std::string bbs_env = environment_variable("BBS");
  if (!bbs_env.empty()) {
    if (bbs_env.find("WWIV") != string::npos) {
      std::cerr << "You are already in the BBS, type 'EXIT' instead.\n\n";
      exit(255);
    }
  }
  const string wwiv_dir = environment_variable("WWIV_DIR");
  if (!wwiv_dir.empty()) {
    File::set_current_directory(wwiv_dir);
  }

#if defined( __unix__ )
  // HACK to make WWIV5/X just work w/o any command line
  m_bUserAlreadyOn = true;
  ui = us = 9600;
  ooneuser = true;
#endif

  for (int i = 1; i < argc; i++) {
    string argumentRaw = argv[i];
    if (argumentRaw.length() > 1 && (argumentRaw[0] == '-' || argumentRaw[0] == '/')) {
      string argument = argumentRaw.substr(2);
      char ch = wwiv::UpperCase<char>(argumentRaw[1]);
      switch (ch) {
      case 'B':
      {
        // I think this roundtrip here is just to ensure argument is really a number.
        ui = static_cast<unsigned int>(atol(argument.c_str()));
        const string current_speed_string = std::to_string(ui);
        SetCurrentSpeed(current_speed_string.c_str());
        if (!us) {
          us = ui;
        }
        m_bUserAlreadyOn = true;
      }
      break;
      case 'C':
        break;
      case 'D':
        File::SetDebugLevel(stoi(argument));
        break;
      case 'E':
        event_only = true;
        break;
      case 'S':
        us = static_cast<unsigned int>(stol(argument));
        if ((us % 300) && us != 115200) {
          us = ui;
        }
        break;
      case 'Q':
        m_nOkLevel = stoi(argument);
        break;
      case 'A':
        m_nErrorLevel = stoi(argument);
        break;
      case 'O':
        ooneuser = true;
        break;
      case 'H':
        hSockOrComm = stoi(argument);
        break;
      case 'I':
      case 'N':
      {
        instance_number_ = stoi(argument);
        if (instance_number_ <= 0 || instance_number_ > 999) {
          clog << "Your Instance can only be 1..999, you tried instance #" << instance_number_ << endl;
          exit(m_nErrorLevel);
        }
      }
      break;
      case 'M':
#if !defined ( __unix__ )
        ok_modem_stuff = false;
#endif
        break;
      case 'R':
        num_min = stoi(argument);
        break;
      case 'U':
        this_usernum = StringToUnsignedShort(argument);
        if (!m_bUserAlreadyOn) {
          SetCurrentSpeed("KB");
        }
        m_bUserAlreadyOn = true;
        break;
      case 'V':
        cout << "WWIV Bulletin Board System [" << wwiv_version << beta_version << "]" << endl;
        exit(0);
        break;
      case 'W':
      {
        ok_modem_stuff = false;
        this->InitializeBBS();
        wwiv::wfc::ControlCenter control_center;
        control_center.Run();
        exit(m_nOkLevel);
      } break;
      case 'X':
      {
        char argument2Char = wwiv::UpperCase<char>(argument.at(0));
        if (argument2Char == 'T' || argument2Char == 'S') {
          // This more of a hack to make sure the Telnet
          // Server's -Bxxx parameter doesn't hose us.
          SetCurrentSpeed("115200");

          // These are needed for both Telnet or SSH
          SetUserOnline(false);
          us = 115200;
          ui = us;
          m_bUserAlreadyOn = true;
          ooneuser = true;
          using_modem = 0;
          hangup = false;
          incom = true;
          outcom = false;
          global_xx = false;
          if (argument2Char == 'T') {
            type = CommunicationType::TELNET;
          } else if (argument2Char == 'S') {
            type = CommunicationType::SSH;
            //cout << "Waiting for debugger" << endl;
            //getchar();
          }
        } else {
          clog << "Invalid Command line argument given '" << argumentRaw << "'" << std::endl;
          exit(m_nErrorLevel);
        }
      }
      break;
      case 'Z':
        no_hangup = true;
        break;
        //
        // TODO Add handling for Socket and Comm handle here
        //
        //
      case 'K':
      {
        this->InitializeBBS();
        localIO()->LocalCls();
        if ((i + 1) < argc) {
          i++;
          bout << "\r\n|#7\xFE |#5Packing specified subs: \r\n";
          while (i < argc) {
            int nSubNumToPack = atoi(argv[i]);
            pack_sub(nSubNumToPack);
            sysoplogf("* Packed Message Area %d", nSubNumToPack);
            i++;
          }
        } else {
          bout << "\r\n|#7\xFE |#5Packing all subs: \r\n";
          sysoplog("* Packing All Message Areas");
          wwiv::bbs::TempDisablePause disable_pause;
          if (!pack_all_subs()) {
            bout << "|#6Aborted.\r\n";
          }
        }
        ExitBBSImpl(m_nOkLevel);
      }
      break;
      case '?':
        ShowUsage();
        exit(0);
        break;
      case '-':
      {
        if (argumentRaw == "--help") {
          ShowUsage();
          exit(0);
        }
      }
      break;
      default:
      {
        clog << "Invalid Command line argument given '" << argument << "'\r\n\n";
        exit(m_nErrorLevel);
      }
      break;
      }
    } else {
      // Command line argument did not start with a '-' or a '/'
      clog << "Invalid Command line argument given '" << argumentRaw << "'\r\n\n";
      exit(m_nErrorLevel);
    }
  }

  // Add the environment variable or overwrite the existing one
  const string env_str = std::to_string(instance_number());
  set_environment_variable("WWIV_INSTANCE", env_str);
#ifndef _WIN32
  // TODO(rushfan): Don't think we need this, but need to make sure.
  // it was already there.
  m_bUserAlreadyOn = true;
#endif  // _WIN32
  if (!ReadConfig()) {
    // Gotta read the config before we can create the socket handles.
    // Since we may need the SSH key.
    AbortBBS(true);
  }

  CreateComm(hSockOrComm, type);
  InitializeBBS();
  localIO()->UpdateNativeTitleBar(this);

  // If we are telnet...
  if (type == CommunicationType::TELNET || type == CommunicationType::SSH) {
    ok_modem_stuff = true;
    remoteIO()->open();
  }

  if (num_min > 0) {
    syscfg.executetime = static_cast<uint16_t>((timer() + num_min * 60) / 60);
    if (syscfg.executetime > 1440) {
      syscfg.executetime -= 1440;
    }
    time_event = static_cast<double>(syscfg.executetime) * MINUTES_PER_HOUR_FLOAT;
    last_time = time_event - timer();
    if (last_time < 0.0) {
      last_time += HOURS_PER_DAY_FLOAT * SECONDS_PER_HOUR_FLOAT;
    }
  }

  if (event_only) {
    unique_ptr<WStatus> pStatus(status_manager()->GetStatus());
    cleanup_events();
    if (!IsEquals(date(), pStatus->GetLastDate())) {
      // This may be another node, but the user explicitly wanted to run the beginday
      // event from the commandline, so we'll just check the date.
      beginday(true);
    } else {
      sysoplog("!!! Wanted to run the beginday event when it's not required!!!", false);
      clog << "! WARNING: Tried to run beginday event again\r\n\n";
      sleep_for(seconds(2));
    }
    ExitBBSImpl(m_nOkLevel);
  }

  do {
    if (this_usernum) {
      usernum = this_usernum;
      ReadCurrentUser();
      if (!user()->IsUserDeleted()) {
        GotCaller(ui, us);
        usernum = this_usernum;
        ReadCurrentUser();
        read_qscn(usernum, qsc, false);
        ResetEffectiveSl();
        changedsl();
        okmacro = true;
        if (!hangup && usernum > 0 &&
          user()->IsRestrictionLogon() &&
          IsEquals(date(), user()->GetLastOn()) &&
          user()->GetTimesOnToday() > 0) {
          bout << "\r\n|#6Sorry, you can only logon once per day.\r\n\n";
          hangup = true;
        }
      } else {
        this_usernum = 0;
      }
    }
    if (!this_usernum) {
      if (m_bUserAlreadyOn) {
        GotCaller(ui, us);
      }
#if !defined ( __unix__ )
      else {
        GetCaller();
      }
#endif
    }

    if (using_modem > -1) {
      if (!this_usernum) {
        getuser();
      }
    } else {
      using_modem = 0;
      okmacro = true;
      usernum = m_unx;
      ResetEffectiveSl();
      changedsl();
    }
    this_usernum = 0;
    if (!hangup) {
      logon();
      setiia(90);
      set_net_num(0);
      while (!hangup) {
        if (filelist) {
          free(filelist);
          filelist = nullptr;
        }
        zap_ed_info();
        write_inst(INST_LOC_MAIN, usub[GetCurrentMessageArea()].subnum, INST_FLAGS_NONE);
        wwiv::menus::mainmenu();
      }
      logoff();
    }

    if (!no_hangup && using_modem && ok_modem_stuff) {
      hang_it_up();
    }
    catsl();
    frequent_init();
    if (wfc_status == 0) {
      localIO()->LocalCls();
    }
    cleanup_net();

    if (!no_hangup && ok_modem_stuff) {
      remoteIO()->dtr(false);
    }
    m_bUserAlreadyOn = false;
  } while (!ooneuser);

  return m_nOkLevel;
}