<commit_before>#include "struct.h"
#include "variable.h"
#include "atom.h"
#include "list.h"
#include "parser.h"
#include "scanner.h"
#include "number.h"
#include "iterator.h"

#include <iostream>
#include <vector>
using namespace ::std;

int main(int argc, char **argv)
{
  string input;
  string allNowInput;
  while (true)
  {
    allNowInput = "";
    cout << "?-";
    while (true)
    {
      getline(cin, input);
      if (input == "halt." &&
          allNowInput == "")
        return 0;
      allNowInput += input;
      if (allNowInput == ""){
        break;
      }

      if (allNowInput[allNowInput.length() - 1] == '.')
      {
        Scanner s(allNowInput);
        Parser p(s);
        try
        {
          p.buildExpression();
          Node *expressionTree = p.expressionTree();
          expressionTree->evaluate();
          string result = expressionTree->getResult();
          cout << allNowInput << endl;
          cout << result << endl;
          break;
        }
        catch (std::string &msg)
        {
          cout << msg << endl;
          break;
        }
      }
      cout << "|   ";
    }
  }
}
<commit_msg>delete output input string<commit_after>#include "struct.h"
#include "variable.h"
#include "atom.h"
#include "list.h"
#include "parser.h"
#include "scanner.h"
#include "number.h"
#include "iterator.h"

#include <iostream>
#include <vector>
using namespace ::std;

int main(int argc, char **argv)
{
  string input;
  string allNowInput;
  while (true)
  {
    allNowInput = "";
    cout << "?-";
    while (true)
    {
      getline(cin, input);
      if (input == "halt." &&
          allNowInput == "")
        return 0;
      allNowInput += input;
      if (allNowInput == ""){
        break;
      }

      if (allNowInput[allNowInput.length() - 1] == '.')
      {
        Scanner s(allNowInput);
        Parser p(s);
        try
        {
          p.buildExpression();
          Node *expressionTree = p.expressionTree();
          expressionTree->evaluate();
          string result = expressionTree->getResult();
          cout << result << endl;
          break;
        }
        catch (std::string &msg)
        {
          cout << msg << endl;
          break;
        }
      }
      cout << "|   ";
    }
  }
}
<|endoftext|>


<commit_before>#include <string>
#include <getopt.h>
#include <iostream>
#include <iomanip>

int main(int argc, char *argv[]) {
    std::string filename;
    int opt;

    while ((opt = getopt(argc, argv, "f:")) != -1) {
        switch (opt) {
            case 'f':
                filename = optarg;
                break;
        }
    }

    return 0;
}

<commit_msg>Добавил функцию, считающую хеш файла<commit_after>#include <string>
#include <getopt.h>
#include <openssl/evp.h>
#include <iostream>
#include <iomanip>
#include <fstream>

void digest_file(std::string filename, unsigned char* digest) {
    std::ifstream file;
    file.open(filename, std::ios::in | std::ios::binary);

    const unsigned int BUFFER_SIZE = 4096;
    char *buffer = new char[BUFFER_SIZE];

    EVP_MD_CTX *context = EVP_MD_CTX_create();
    EVP_MD_CTX_init(context);
    EVP_DigestInit(context, EVP_sha256());

    while (!file.eof()) {
        file.read(buffer, BUFFER_SIZE);
        EVP_DigestUpdate(context, buffer, file.gcount());
    }

    unsigned int digest_size;
    EVP_DigestFinal(context, digest, &digest_size);

    EVP_MD_CTX_cleanup(context);
    EVP_MD_CTX_destroy(context);
}

int main(int argc, char *argv[]) {
    std::string filename;
    int opt;

    while ((opt = getopt(argc, argv, "f:")) != -1) {
        switch (opt) {
            case 'f':
                filename = optarg;
                break;
        }
    }

    unsigned char *digest = new unsigned char[32];
    digest_file(filename, digest);

    std::cout << std::hex;
    for (int i = 0; i < 32; ++i) {
        std::cout << std::setfill('0') << std::setw(2) << static_cast<int>(digest[i]);
    }

    return 0;
}

<|endoftext|>


<commit_before>aae0fd70-2747-11e6-aa92-e0f84713e7b8<commit_msg>this is my first commit?<commit_after>aaeed0e3-2747-11e6-88ac-e0f84713e7b8<|endoftext|>


<commit_before>1ff09594-2748-11e6-a16b-e0f84713e7b8<commit_msg>Did ANOTHER thing<commit_after>1ffbcb4f-2748-11e6-aead-e0f84713e7b8<|endoftext|>


<commit_before>#include <QApplication>
#include <QVariant>
#include <QString>
#include <QCommandLineParser>

#include "MainWindow.h"
#include "Logfile.h"
#include "Database.h"

const int VERSION_MAJOR = 1;
const int VERSION_MINOR = 0;
const int VERSION_PATCHLEVEL = 1;

constexpr int GetVersionInt() {
    return ((VERSION_MAJOR * 100) + (VERSION_MINOR * 10) + (VERSION_PATCHLEVEL));
}

QString GetVersion() {
    QString v = "V";
    v.append(QVariant(VERSION_MAJOR).toString());
    v.append(".");
    v.append(QVariant(VERSION_MINOR).toString());
    v.append(".");
    v.append(QVariant(VERSION_PATCHLEVEL).toString());

    return qMove(v);
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    a.setApplicationName("Notenarchiv");
    a.setApplicationDisplayName("Notenarchiv");
    a.setApplicationVersion(GetVersion());

    QCommandLineParser cmd;
    cmd.addHelpOption();
    cmd.addVersionOption();
    cmd.process(a);

    MainWindow w;
    w.show();

    int ret = a.exec();

    Log->Del();
    DB->Del();

    return ret;
}
<commit_msg>Deutsche Übersetzung eingebaut<commit_after>#include <QApplication>
#include <QVariant>
#include <QString>
#include <QCommandLineParser>
#include <QTranslator>
#include <QLocale>
#include <QLibraryInfo>

#include "MainWindow.h"
#include "Logfile.h"
#include "Database.h"

const int VERSION_MAJOR = 1;
const int VERSION_MINOR = 0;
const int VERSION_PATCHLEVEL = 1;

constexpr int GetVersionInt() {
    return ((VERSION_MAJOR * 100) + (VERSION_MINOR * 10) + (VERSION_PATCHLEVEL));
}

QString GetVersion() {
    QString v = "V";
    v.append(QVariant(VERSION_MAJOR).toString());
    v.append(".");
    v.append(QVariant(VERSION_MINOR).toString());
    v.append(".");
    v.append(QVariant(VERSION_PATCHLEVEL).toString());

    return qMove(v);
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    a.setApplicationName("Notenarchiv");
    a.setApplicationDisplayName("Notenarchiv");
    a.setApplicationVersion(GetVersion());

    QTranslator global_translator;
    global_translator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); // globale Übersetzung laden

    a.installTranslator(&global_translator);

    QCommandLineParser cmd;
    cmd.addHelpOption();
    cmd.addVersionOption();
    cmd.process(a);

    MainWindow w;
    w.show();

    int ret = a.exec();

    Log->Del();
    DB->Del();

    return ret;
}
<|endoftext|>


<commit_before>78f76d2e-ad58-11e7-af9a-ac87a332f658<commit_msg>No longer crashes if X<commit_after>794a5c30-ad58-11e7-904c-ac87a332f658<|endoftext|>


<commit_before>#include <cstdint>
#include <iostream>

typedef std::uint64_t u64;

u64 mulmod(u64 a, u64 b, u64 m)
{
  u64 r = 0;
  u64 s = 0;

  while (b > 0)
  {
    s = ((m - r) > a) ? r + a : r + a - m;
    r = (b & 1) * s + (1 - (b & 1)) * r;
    b >>= 1;
    a = ((m - a) > a) ? a + a : a + a - m;
  }

  return r;
}

u64 powmod(u64 a, u64 e, u64 m)
{
  u64 r = 1;

  while (e > 0)
  {
    r = (e & 1) * mulmod(r, a, m) + (1 - (e & 1)) * r;
    e >>= 1;
    a = mulmod(a, a, m);
  }

  return r;
}

u64 fib(u64 n)
{
  const u64 prime = 12200160415121876909;
  const u64 sqrt5 = 833731445503647576;
  const u64 sqrt5inv = 2606778372125104897;

  n %= prime; // It overflows long before this happens, has no real use ...

  u64 a = powmod(1 + sqrt5, n, prime);
  u64 b = powmod(prime + 1 - sqrt5, n, prime);
  u64 invpow2 = powmod(2, prime - 1 - n, prime);

  u64 phin_minus_psin = (a > b) ? a - b : (prime - b) + a;
  u64 factor = mulmod(sqrt5inv, invpow2, prime);

  return mulmod(phin_minus_psin, factor, prime);
}

int main()
{
  for (u64 i = 0; i < 94; i++)
  std::cout << fib(i) << std::endl;
  return 0;
}
<commit_msg>add traits for different integer types<commit_after>#include <cstdint>
#include <iostream>

typedef std::uint8_t  u8;
typedef std::uint16_t u16;
typedef std::uint32_t u32;
typedef std::uint64_t u64;

template <typename T> class fib_traits { };

template <> class fib_traits<u8>
{
  public:
    static const u8 fib_max   = 13;
    static const u8 prime     = 239;
    static const u8 sqrt5     = 31;
    static const u8 inv_sqrt5 = 54;
};

template <> class fib_traits<u16>
{
  public:
    static const u16 fib_max   = 24;
    static const u16 prime     = 46381;
    static const u16 sqrt5     = 22501;
    static const u16 inv_sqrt5 = 41605;
};

template <> class fib_traits<u32>
{
  public:
    static const u32 fib_max   = 47;
    static const u32 prime     = 2971215179;
    static const u32 sqrt5     = 492315461;
    static const u32 inv_sqrt5 = 692706128;
};

template <> class fib_traits<u64>
{
  public:
    static const u64 fib_max   = 93;
    static const u64 prime     = 12200160415121876909;
    static const u64 sqrt5     = 833731445503647576;
    static const u64 inv_sqrt5 = 2606778372125104897;
};

/* If your platform supports unsigned __int128, you can try this one as well.
template <> class fib_traits<u128>
{
  public:
    static const u128 fib_max   = 186;
    static const u128 prime     = 332825110087067562321196029789634457911;
    static const u128 sqrt5     = 10426323296737204245551694426008962215;
    static const u128 inv_sqrt5 = 2085264659347440849110338885201792443;
};
*/

template <typename T> T mulmod(T a, T b, T m)
{
  T r = 0;
  T s = 0;

  while (b > 0)
  {
    s = ((m - r) > a) ? r + a : r + a - m;
    r = (b & 1) * s + (1 - (b & 1)) * r;
    b >>= 1;
    a = ((m - a) > a) ? a + a : a + a - m;
  }

  return r;
}

template <typename T> T powmod(T a, T e, T m)
{
  T r = 1;

  while (e > 0)
  {
    r = (e & 1) * mulmod(r, a, m) + (1 - (e & 1)) * r;
    e >>= 1;
    a = mulmod(a, a, m);
  }

  return r;
}

template <typename T> T fib(T n)
{
  const T prime = fib_traits<T>::prime;
  const T sqrt5 = fib_traits<T>::sqrt5;
  const T sqrt5inv = fib_traits<T>::inv_sqrt5;

  u64 a = powmod(1 + sqrt5, n, prime);
  u64 b = powmod(prime + 1 - sqrt5, n, prime);
  u64 invpow2 = powmod<T>(2, prime - 1 - n, prime);

  u64 phin_minus_psin = (a > b) ? a - b : (prime - b) + a;
  u64 factor = mulmod(sqrt5inv, invpow2, prime);

  return mulmod(phin_minus_psin, factor, prime);
}

int main()
{
  for (u64 i = 0; i < 94; i++)
  std::cout << fib(i) << std::endl;
  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include "gpi/gpi.h"
#include "phitron/phitron.h"
#include "window.h"
#include "draw.h"
#include <chrono>

#define WINDOW_WIDTH 800
#define WINDOW_HEIGHT 600

//Amount of particles in test simulation
#define OBJECTS 128

using namespace std;
using namespace chrono;

uint16_t toHalfFloat(float x) {
    uint32_t &f = reinterpret_cast<uint32_t&>(x);
    return ((f >> 16) & 0x8000) | ((((f & 0x7f800000) - 0x38000000) >> 13) & 0x7c00) | ((f >> 13) & 0x03ff);
}

int main() {
    Window window("testing", WINDOW_WIDTH, WINDOW_HEIGHT);
    Renderer renderer(window);

    GroupRenderer gr(WINDOW_WIDTH, WINDOW_HEIGHT);

    steady_clock::time_point lastTime = steady_clock::now();

    phi::P3 particles[OBJECTS];
    phi::V3 colors[OBJECTS];

    std::mt19937 rand(3);

    for (unsigned i = 0; i != OBJECTS; i++) {
        particles[i].position = phi::V3(rand()/double(rand.max())*2-1, rand()/double(rand.max())*2-1, rand()/double(rand.max())/8);
        particles[i].velocity = phi::V3(rand()/double(rand.max())*2-1, rand()/double(rand.max())*2-1, rand()/double(rand.max())*2-1);
        particles[i].velocity *= 0.0005;
        particles[i].inertia = 100.0;

        colors[i] = phi::V3(rand()/double(rand.max()), rand()/double(rand.max()), rand()/double(rand.max()));
        colors[i] *= 1;
    }

    uint16_t *posbuffer = (uint16_t*)gr.buffer.buffer.map(GL_MAP_WRITE_BIT | GL_MAP_FLUSH_EXPLICIT_BIT);

    while (true) {
        SDL_Event event;
        while (window.pollEvent(event)) {
            switch (event.type) {
            case SDL_QUIT:
                return 0;
            }
        }

        for (unsigned i = 0; i != OBJECTS; i++) {
            for (unsigned j = i + 1; j != OBJECTS; j++) {
                phi::attract(0.0001, particles[i], particles[j], 0.1);
            }
            particles[i].advance();

            posbuffer[i*7 + 0] = toHalfFloat(particles[i].position.x);
            posbuffer[i*7 + 1] = toHalfFloat(particles[i].position.y);
            posbuffer[i*7 + 2] = toHalfFloat(particles[i].position.z);

            posbuffer[i*7 + 3] = toHalfFloat(colors[i].x);
            posbuffer[i*7 + 4] = toHalfFloat(colors[i].y);
            posbuffer[i*7 + 5] = toHalfFloat(colors[i].z);

            posbuffer[i*7 + 6] = toHalfFloat(0.1);
        }

        gr.buffer.buffer.sync();

        gr.render(OBJECTS, WINDOW_WIDTH, WINDOW_HEIGHT);

        window.flip();

        steady_clock::time_point thisTime = steady_clock::now();
        cout << "FPS: " << (1.0/duration_cast<duration<double>>(thisTime - lastTime).count()) << endl;
        lastTime = thisTime;
    }
    return 0;
}

<commit_msg>added OpenMP support to speed up test particle simulation for basically no reason<commit_after>#include <iostream>
#include "gpi/gpi.h"
#include "phitron/phitron.h"
#include "window.h"
#include "draw.h"
#include <chrono>

#define WINDOW_WIDTH 800
#define WINDOW_HEIGHT 600

//Amount of particles in test simulation
#define OBJECTS 512

using namespace std;
using namespace chrono;

uint16_t toHalfFloat(float x) {
    uint32_t &f = reinterpret_cast<uint32_t&>(x);
    return ((f >> 16) & 0x8000) | ((((f & 0x7f800000) - 0x38000000) >> 13) & 0x7c00) | ((f >> 13) & 0x03ff);
}

int main() {
    Window window("testing", WINDOW_WIDTH, WINDOW_HEIGHT);
    Renderer renderer(window);

    GroupRenderer gr(WINDOW_WIDTH, WINDOW_HEIGHT);

    steady_clock::time_point lastTime = steady_clock::now();

    phi::P3 particles[OBJECTS];
    phi::V3 colors[OBJECTS];

    std::mt19937 rand(3);

    for (unsigned i = 0; i != OBJECTS; i++) {
        particles[i].position = phi::V3(rand()/double(rand.max())*2-1, rand()/double(rand.max())*2-1, rand()/double(rand.max())/8);
        particles[i].velocity = phi::V3(rand()/double(rand.max())*2-1, rand()/double(rand.max())*2-1, rand()/double(rand.max())*2-1);
        particles[i].velocity *= 0.0005;
        particles[i].inertia = 100.0;

        colors[i] = phi::V3(rand()/double(rand.max()), rand()/double(rand.max()), rand()/double(rand.max()));
        colors[i] *= 1;
    }

    uint16_t *posbuffer = (uint16_t*)gr.buffer.buffer.map(GL_MAP_WRITE_BIT | GL_MAP_FLUSH_EXPLICIT_BIT);

    while (true) {
        SDL_Event event;
        while (window.pollEvent(event)) {
            switch (event.type) {
            case SDL_QUIT:
                return 0;
            }
        }

        #pragma omp parallel for
        for (unsigned i = 0; i < OBJECTS; i++)
            for (unsigned j = 0; j != OBJECTS; j++)
                if (i != j)
                    particles[i].gravitate(0.0001, particles[j].position, 0.1);

        for (unsigned i = 0; i != OBJECTS; i++) {
            particles[i].advance();
            posbuffer[i*7 + 0] = toHalfFloat(particles[i].position.x);
            posbuffer[i*7 + 1] = toHalfFloat(particles[i].position.y);
            posbuffer[i*7 + 2] = toHalfFloat(particles[i].position.z);

            posbuffer[i*7 + 3] = toHalfFloat(colors[i].x);
            posbuffer[i*7 + 4] = toHalfFloat(colors[i].y);
            posbuffer[i*7 + 5] = toHalfFloat(colors[i].z);

            posbuffer[i*7 + 6] = toHalfFloat(0.1);
        }

        gr.buffer.buffer.sync();

        gr.render(OBJECTS, WINDOW_WIDTH, WINDOW_HEIGHT);

        window.flip();

        steady_clock::time_point thisTime = steady_clock::now();
        cout << "FPS: " << (1.0/duration_cast<duration<double>>(thisTime - lastTime).count()) << endl;
        lastTime = thisTime;
    }
    return 0;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <vector>

#include "mutator.hpp"

int main(int argc, char *argv[])
{
    mtt::Mutator mut;
    if (argc == 2)
    {
        mut.addText(argv[1]);
    }
    else
    {
        mut.addText("./rechercheDuTempsPerdu.txt");
    }
    std::vector<char> text = mut.createText(10000);

    std::cout << text << std::endl;

    return 0;
}
<commit_msg>May take the number of character in the generated text as 3rd arg<commit_after>#include <iostream>
#include <vector>

#include "mutator.hpp"

int main(int argc, char *argv[])
{
    mtt::Mutator mut;
    if (argc >= 2)
    {
        mut.addText(argv[1]);
    }
    else
    {
        mut.addText("./rechercheDuTempsPerdu.txt");
    }

    std::vector<char> text;

    if (argc == 3)
    {
        text = mut.createText(atoi(argv[2]));
    }
    else
    {
        text = mut.createText(10000);
    }

    std::cout << text << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>3bce30d7-ad5d-11e7-8a45-ac87a332f658<commit_msg>For bobby to integrate at some point<commit_after>3c389191-ad5d-11e7-a195-ac87a332f658<|endoftext|>


<commit_before>#include <tins/tins.h>
#include <iostream>
#include <thread>
#include <mutex>
#include <unistd.h>
#include <chrono>

#define TIMEOUT 300

using namespace Tins;

std::map<std::string, Timestamp> devices;
std::mutex map_mutex;

std::string vendor_string(HWAddress<6> macaddr) {
	return macaddr.to_string();
}

void process(Packet p) {
	Timestamp t = p.timestamp();
	if (p.pdu()->find_pdu<Dot11ProbeRequest>(PDU::DOT11_PROBE_REQ)) {
		Dot11ProbeRequest request = p.pdu()->rfind_pdu<Dot11ProbeRequest>(PDU::DOT11_PROBE_REQ);
		std::string src_addr = vendor_string(request.addr2());
		{
			std::lock_guard<std::mutex> lock(map_mutex);
			if (devices.count(src_addr) == 0)
				std::cout << "New device [" << src_addr << "] found at " << p.timestamp().seconds() << std::endl;
			devices[src_addr] = t;
		}
	}
	else if (p.pdu()->find_pdu<Dot11Data>(PDU::DOT11_DATA)) {
		Dot11Data frame = p.pdu()->rfind_pdu<Dot11Data>(PDU::DOT11_DATA);
		std::string src_addr = vendor_string(frame.addr2());
		{
			std::lock_guard<std::mutex> lock(map_mutex);
			if (devices.count(src_addr) == 1)
				devices[src_addr] = t;
		}
	}
}

void receive_probe_requests(NetworkInterface iface) {
	SnifferConfiguration config;
	config.set_rfmon(true);
	config.set_filter("type mgt subtype probe-req || type data subtype null");
	Sniffer sniffer(iface.name(), config);
	while(true) process(sniffer.next_packet());
}

std::chrono::system_clock::rep current_time_in_seconds(){
    auto now = std::chrono::system_clock::now().time_since_epoch();
    return std::chrono::duration_cast<std::chrono::seconds>(now).count();
}

void delete_devices() {
	while(true) {
		sleep(60);
		{
			std::lock_guard<std::mutex> lock(map_mutex);
			for(auto const &m : devices) {
				unsigned int duration = current_time_in_seconds() - m.second.seconds();
				if (duration > TIMEOUT) {
					std::cout << "Device [" << m.first << "] deleted after " << duration << "s of inactivity" << std::endl;
					devices.erase(m.first);
				}
			}
		}
	}
}

int main(int argc, char *argv[]) {
	NetworkInterface iface;
	if (argc != 2)
		iface = NetworkInterface::default_interface();
	else iface = NetworkInterface(argv[1]);

	std::thread insert(receive_probe_requests, iface);
	std::thread remove(delete_devices);

	while(true) {
		sleep(10);
		{
			std::lock_guard<std::mutex> lock(map_mutex);
			std::cout << "\n" << "Number of devices in your area: " << devices.size() << std::endl;
			for(auto const &m : devices) {
				unsigned int duration = current_time_in_seconds() - m.second.seconds();
				std::cout << "[" << m.first << "] last seen " << duration << "s ago" << std::endl;
			}
			std::cout << "\n";
		}
	}

	return 0;
}
<commit_msg>less C more C++<commit_after>#include <tins/tins.h>
#include <iostream>
#include <thread>
#include <mutex>
#include <unistd.h>
#include <chrono>

using namespace Tins;

const unsigned int TIMEOUT = 300;

std::map<std::string, Timestamp> devices;
std::mutex map_mutex;

std::string vendor_string(HWAddress<6> macaddr) {
	return macaddr.to_string();
}

void process(Packet p) {
	Timestamp t = p.timestamp();
	if (p.pdu()->find_pdu<Dot11ProbeRequest>(PDU::DOT11_PROBE_REQ)) {
		Dot11ProbeRequest request = p.pdu()->rfind_pdu<Dot11ProbeRequest>(PDU::DOT11_PROBE_REQ);
		std::string src_addr = vendor_string(request.addr2());
		{
			std::lock_guard<std::mutex> lock(map_mutex);
			if (devices.count(src_addr) == 0)
				std::cout << "New device [" << src_addr << "] found at " << t.seconds() << std::endl;
			devices[src_addr] = t;
		}
	}
	else if (p.pdu()->find_pdu<Dot11Data>(PDU::DOT11_DATA)) {
		Dot11Data frame = p.pdu()->rfind_pdu<Dot11Data>(PDU::DOT11_DATA);
		std::string src_addr = vendor_string(frame.addr2());
		{
			std::lock_guard<std::mutex> lock(map_mutex);
			if (devices.count(src_addr) == 1)
				devices[src_addr] = t;
		}
	}
}

void receive_probe_requests(NetworkInterface iface) {
	SnifferConfiguration config;
	config.set_rfmon(true);
	config.set_filter("type mgt subtype probe-req || type data subtype null");
	Sniffer sniffer(iface.name(), config);
	while(true) process(sniffer.next_packet());
}

std::chrono::system_clock::rep current_time_in_seconds(){
    auto now = std::chrono::system_clock::now().time_since_epoch();
    return std::chrono::duration_cast<std::chrono::seconds>(now).count();
}

void delete_devices() {
	while(true) {
		sleep(10);
		{
			std::lock_guard<std::mutex> lock(map_mutex);
			for(auto const &m : devices) {
				unsigned int duration = current_time_in_seconds() - m.second.seconds();
				if (duration > TIMEOUT) {
					std::cout << "Device [" << m.first << "] deleted after " << duration << "s of inactivity" << std::endl;
					devices.erase(m.first);
				}
			}
		}
	}
}

int main(int argc, char *argv[]) {
	NetworkInterface iface;
	if (argc != 2)
		iface = NetworkInterface::default_interface();
	else iface = NetworkInterface(argv[1]);

	std::thread insert(receive_probe_requests, iface);
	std::thread remove(delete_devices);

	while(true) {
		sleep(10);
		{
			std::lock_guard<std::mutex> lock(map_mutex);
			std::cout << "\n" << "Number of devices in your area: " << devices.size() << std::endl;
			for(auto const &m : devices) {
				unsigned int duration = current_time_in_seconds() - m.second.seconds();
				std::cout << "[" << m.first << "] last seen " << duration << "s ago" << std::endl;
			}
			std::cout << "\n";
		}
	}

	return 0;
}
<|endoftext|>


<commit_before>9b6823ab-2747-11e6-be11-e0f84713e7b8<commit_msg>Really doesn't crash if X, now<commit_after>9b7b77b5-2747-11e6-af2d-e0f84713e7b8<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
//#include <vector>
//#include <fstream>
#include "Map.h"
#include "Zombie.h"
#include "Player.h"

using namespace std;

int main()
{
    //game start
    cout << " -----------------------------" << endl
         << "|     Plants v.s Zombies      |" << endl
         << " -----------------------------" << endl;
    constexpr int LAND_DEFAULT=8;
    constexpr int LAND_MAX=10;
    constexpr int LAND_MIN=1;
    constexpr int ZOMBIE_DEFAULT=3;
    constexpr int ZOMBIE_MAX=10;
    constexpr int ZOMBIE_MIN=1;

    string input;
    //initialize game setting
    cout << "Number of lands on the map (" << LAND_MIN << "-" << LAND_MAX << ", default: " << LAND_DEFAULT <<")...>";
    int value = LAND_DEFAULT;
    getline(cin, input);
    if(!input.empty())
    {
        istringstream stream( input );
        stream >> value;
        if(value > LAND_MAX) value = LAND_MAX;
        if(value < LAND_MIN) value = LAND_MIN;
    }
    const int LANDS=value;

    cout << "Number of zombies on the map (" << ZOMBIE_MIN << "-" << ZOMBIE_MAX << ", default: "<< ZOMBIE_DEFAULT <<")...>";
    value=ZOMBIE_DEFAULT;
    getline(cin, input);
    if(!input.empty())
    {
        istringstream stream( input );
        stream >> value;
        if(value > ZOMBIE_MAX) value = ZOMBIE_MAX;
        if(value < ZOMBIE_MIN) value = ZOMBIE_MIN;
    }
    const int ZOMBIES=value;

    //game rules
    cout << "=============================================================================" << endl
         << "Plants vs. Zombies Rule:" << endl
         << endl
         << "How to win:" << endl
         << "  (1) All zombies are dead." << endl
         << "  (2) At least one plant is live." << endl
         << "  (3) The number of dead bomb plants cannot exceed the number of zombies." << endl
         << endl
         << "How to lose:" << endl
         << "  All plants are dead." << endl
         << "=============================================================================" << endl;
    system("pause");
    system("cls");

    //game start
    //construct
    Player *player = new Player();
    Zombie *zombie = new Zombie()[ZOMBIES];
    Map *map = new Map(LANDS);
    /*vector<Plant*> plant;
    ifstream fin=open("plants.txt");
    while(!fin.eof())
    {
        char type;
        fin << type;
        if(fin.eof()) break;
        Plant *tmp = nullptr;
        switch(type)
        {
        case 'C':
            {
                tmp = new CoinPlant(fin);
            }
        case 'S':
            {
                tmp = new HornPlant(fin);
            }
        case 'B':
            {
                tmp = new BombPlant(fin);
            }
        case 'H':
            {
                tmp = new HealPlant(fin);
            }
        default:
            continue;
        }
        if(tmp)
        {
            plant.push_back(tmp);
        }
    }*/

    map->Display(*player, zombie);  //cout << *map << endl;
    cout << "------------------------------------------------" << endl;
    cout << "Zombie information:" << endl;
    for(int i=0;i<ZOMBIES;i++)
    {
        cout << '[' << i << "] " << zombie[i];
    }
    cout << endl << "================================================" << endl;

    /*while(true)
    {
        for(int i=0;i<plant.size();++i)
        {
            cout << '[' << i << "] " ;
            switch(plant[i]->type())
            {
                case 'C':
                    cout << dynamic_cast<CoinPlant *>(plant[i]);
                case 'S':
                    cout << dynamic_cast<HornPlant *>(plant[i]);
                case 'B':
                    cout << dynamic_cast<BombPlant *>(plant[i]);
                case 'H':
                    cout << dynamic_cast<HealPlant *>(plant[i]);
            }
            cout << endl;
        }
        cout << endl << *player;
        int choice = plant.size();
        cout << ":    Enter your choice (" << plant.size() << " to give up, default: " << choice << ")...>";

        if(choice=plant.size()) break;
        int cost=0;
        string plantname;
        switch(plant[choice].type())
        {
        case 'C':
            CoinPlant *tmp = new CoinPlant(*dynamic_cast<CoinPlant *>(plant[choice]))
            land->plant(tmp);
            plantname="CoinPlant";
            cost=tmp->price();
        case 'S':
            HornPlant *tmp = new HornPlant(*dynamic_cast<CoinPlant *>(plant[choice]))
            land->plant(tmp);
            plantname="HornPlant";
            cost=tmp->price();
        case 'B':
            BombPlant *tmp = new BombPlant(*dynamic_cast<CoinPlant *>(plant[choice]));
            land->plant(tmp);
            plantname="BombPlant";
            cost=tmp->price();
        case 'H':
            HealPlant *tmp = new HealPlant(*dynamic_cast<CoinPlant *>(plant[choice]));
            land->plant(tmp);
            plantname="HealPlant";
            cost=tmp->price();
        }
        if(player->money() >= cost)
        {
            cout << "You have planted " << plantname << " at land 7 !";
            break;
        }
        else
        {
            cout << "Not enough money! Please input again.";
        }
    }*/

    // destruct
    //while(!plant.empty())
    //    delete plant.pop_back();
    delete player;
    delete map;
    delete [] zombie;

    return 0;
}
<commit_msg>fix allocate use error<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
//#include <vector>
//#include <fstream>
#include "Map.h"
#include "Zombie.h"
#include "Player.h"

using namespace std;

int main()
{
    //game start
    cout << " -----------------------------" << endl
         << "|     Plants v.s Zombies      |" << endl
         << " -----------------------------" << endl;
    constexpr int LAND_DEFAULT=8;
    constexpr int LAND_MAX=10;
    constexpr int LAND_MIN=1;
    constexpr int ZOMBIE_DEFAULT=3;
    constexpr int ZOMBIE_MAX=10;
    constexpr int ZOMBIE_MIN=1;

    string input;
    //initialize game setting
    cout << "Number of lands on the map (" << LAND_MIN << "-" << LAND_MAX << ", default: " << LAND_DEFAULT <<")...>";
    int value = LAND_DEFAULT;
    getline(cin, input);
    if(!input.empty())
    {
        istringstream stream( input );
        stream >> value;
        if(value > LAND_MAX) value = LAND_MAX;
        if(value < LAND_MIN) value = LAND_MIN;
    }
    const int LANDS=value;

    cout << "Number of zombies on the map (" << ZOMBIE_MIN << "-" << ZOMBIE_MAX << ", default: "<< ZOMBIE_DEFAULT <<")...>";
    value=ZOMBIE_DEFAULT;
    getline(cin, input);
    if(!input.empty())
    {
        istringstream stream( input );
        stream >> value;
        if(value > ZOMBIE_MAX) value = ZOMBIE_MAX;
        if(value < ZOMBIE_MIN) value = ZOMBIE_MIN;
    }
    const int ZOMBIES=value;

    //game rules
    cout << "=============================================================================" << endl
         << "Plants vs. Zombies Rule:" << endl
         << endl
         << "How to win:" << endl
         << "  (1) All zombies are dead." << endl
         << "  (2) At least one plant is live." << endl
         << "  (3) The number of dead bomb plants cannot exceed the number of zombies." << endl
         << endl
         << "How to lose:" << endl
         << "  All plants are dead." << endl
         << "=============================================================================" << endl;
    system("pause");
    system("cls");

    //game start
    //construct
    Player *player = new Player;
    Zombie *zombie = new Zombie[ZOMBIES];
    Zombie::TotalNum = ZOMBIES;
    Map *map = new Map(LANDS);
    /*vector<Plant*> plant;
    ifstream fin=open("plants.txt");
    while(!fin.eof())
    {
        char type;
        fin << type;
        if(fin.eof()) break;
        Plant *tmp = nullptr;
        switch(type)
        {
        case 'C':
            {
                tmp = new CoinPlant(fin);
            }
        case 'S':
            {
                tmp = new HornPlant(fin);
            }
        case 'B':
            {
                tmp = new BombPlant(fin);
            }
        case 'H':
            {
                tmp = new HealPlant(fin);
            }
        default:
            continue;
        }
        if(tmp)
        {
            plant.push_back(tmp);
        }
    }*/

    map->Display(*player, zombie);  //cout << *map << endl;
    cout << "------------------------------------------------" << endl;
    cout << "Zombie information:" << endl;
    for(int i=0;i<ZOMBIES;i++)
    {
        cout << '[' << i << "] " << zombie[i];
    }
    cout << endl << "================================================" << endl;

    /*while(true)
    {
        for(int i=0;i<plant.size();++i)
        {
            cout << '[' << i << "] " ;
            switch(plant[i]->type())
            {
                case 'C':
                    cout << dynamic_cast<CoinPlant *>(plant[i]);
                case 'S':
                    cout << dynamic_cast<HornPlant *>(plant[i]);
                case 'B':
                    cout << dynamic_cast<BombPlant *>(plant[i]);
                case 'H':
                    cout << dynamic_cast<HealPlant *>(plant[i]);
            }
            cout << endl;
        }
        cout << endl << *player;
        int choice = plant.size();
        cout << ":    Enter your choice (" << plant.size() << " to give up, default: " << choice << ")...>";

        if(choice=plant.size()) break;
        int cost=0;
        string plantname;
        switch(plant[choice].type())
        {
        case 'C':
            CoinPlant *tmp = new CoinPlant(*dynamic_cast<CoinPlant *>(plant[choice]))
            land->plant(tmp);
            plantname="CoinPlant";
            cost=tmp->price();
        case 'S':
            HornPlant *tmp = new HornPlant(*dynamic_cast<CoinPlant *>(plant[choice]))
            land->plant(tmp);
            plantname="HornPlant";
            cost=tmp->price();
        case 'B':
            BombPlant *tmp = new BombPlant(*dynamic_cast<CoinPlant *>(plant[choice]));
            land->plant(tmp);
            plantname="BombPlant";
            cost=tmp->price();
        case 'H':
            HealPlant *tmp = new HealPlant(*dynamic_cast<CoinPlant *>(plant[choice]));
            land->plant(tmp);
            plantname="HealPlant";
            cost=tmp->price();
        }
        if(player->money() >= cost)
        {
            cout << "You have planted " << plantname << " at land 7 !";
            break;
        }
        else
        {
            cout << "Not enough money! Please input again.";
        }
    }*/

    // destruct
    //while(!plant.empty())
    //    delete plant.pop_back();
    delete player;
    delete map;
    delete [] zombie;

    return 0;
}
<|endoftext|>


<commit_before>a407a294-4b02-11e5-8916-28cfe9171a43<commit_msg>Too poor for Dropbox<commit_after>a4140368-4b02-11e5-865d-28cfe9171a43<|endoftext|>


<commit_before>/*
 *This is the program that will be loaded onto the
 *Proteus to complete Performance Test 3.
 * ROBOT NOTE:
 * The left wheel is correct, but the right wheel is backwards.
 */

#include <FEHLCD.h>
#include <FEHIO.h>
#include <FEHUtility.h>
#include <FEHMotor.h>
#include <FEHRPS.h>
#include <FEHServo.h>
//The number of counts when an inch is travelled
#define COUNTS_PER_INCH 40
//The number of counts when 1 degree is turned
#define COUNTS_PER_DEGREE 233/90
//The point South of the starting zone
#define POINT_A 18
//The point East of POINT_A
#define POINT_B 31.3
//The point North of POINT_B
#define POINT_C 52.1
//The point West of POINT_C
#define POINT_D 63.7
//The standard driving percentage
#define STD_DRIVE 25
//The fast driving percentage
#define FAST_DRIVE 50
//The slow driving percentage
#define SLOW_DRIVE 12
//The max driving speed. Only for use in extreme circumstances.
#define HYPER_DRIVE 100 //Think before you do this.
//The standard sleep time
#define SLEEP_TIME 500
//The short sleep time used in RPS checks
#define SHORT_SLEEP 50
//The CdS Threshold
#define CDS_THRESHOLD .6
//The angle to press the red button
#define RED_ANGLE 90
//The angle to press the blue button
#define BLUE_ANGLE 90
//The angle to press the white button
#define WHITE_ANGLE 90
//Servo motor minimum
#define SERVO_MIN 510
//Servo motor maximum
#define SERVO_MAX 2280
//Declare the various sensors and motors
ButtonBoard buttons(FEHIO::Bank3); //Button Board
FEHServo disk( FEHServo::Servo0); //Disk Mechanism
FEHMotor right_motor( FEHMotor::Motor0); //Right Motor (Backwards)
FEHMotor left_motor( FEHMotor::Motor1); //Left Motor
DigitalEncoder right_encoder( FEHIO::P0_0); //Right encoder
DigitalEncoder left_encoder( FEHIO::P0_2); //Left encoder
AnalogInputPin CdS( FEHIO::P1_0); //CdS cell
//DigitalInputPin right_bump( FEHIO::P1_2); //Right bump switch (if used)
//Prototypes for each function
void turnRight(int percent, int degrees, int input_counts);
void turnLeft(int percent, int degrees, int input_counts);
void driveForward(int percent, int inches, int input_counts);
void checkXPlus(float x_coordinate);
void checkXMinus(float x_coordinate);
void checkYPlus(float y_coordinate);
void checkYMinus(float y_coordinate);
void checkHeading(float heading);
void buttonsOrder();

int main(void)
{
    LCD.Clear( FEHLCD::White );
    LCD.SetFontColor( FEHLCD::Black );
    //Set servo limits
    disk.SetMin(SERVO_MIN);
    disk.SetMax(SERVO_MAX);
    disk.SetDegree(0);
    RPS.InitializeMenu();
    while(true) {
        LCD.WriteLine("Press the middle button to begin");
        while(!buttons.MiddlePressed());
        while(buttons.MiddlePressed());
        //LCD.WriteLine("Will start on light now");
        //while(CdS.Value()>CDS_THRESHOLD);
        LCD.Clear( FEHLCD::White );
        driveForward(STD_DRIVE, 13, 0);
        checkYMinus(POINT_A);
        Sleep(SLEEP_TIME);
        turnLeft(STD_DRIVE, 90, 0);
        checkHeading(90);
        Sleep(SLEEP_TIME);
        driveForward(STD_DRIVE, 11, 0);
        checkXPlus(POINT_B);
        Sleep(SLEEP_TIME);
        turnLeft(STD_DRIVE, 90, 0);
        checkHeading(180);
        Sleep(SLEEP_TIME);
        driveForward(FAST_DRIVE, 33, 0);
        driveForward(STD_DRIVE, 1, 0);
        driveForward(SLOW_DRIVE, 1, 0);
        checkYPlus(POINT_C);
        Sleep(SLEEP_TIME);
        turnLeft(STD_DRIVE, 56, 0);
        checkHeading(236);
        Sleep(SLEEP_TIME);
        driveForward(STD_DRIVE, 20, 0);
        checkYPlus(POINT_D);
        turnRight(STD_DRIVE, 15, 0);
        checkHeading(221.5);
        //buttonsOrder();
        //RAM THAT MOFO
        right_motor.SetPercent(-FAST_DRIVE);
        left_motor.SetPercent(FAST_DRIVE);
        Sleep(2.0);
        driveForward(-STD_DRIVE, 1, 0);
        Sleep(1.0);
        right_motor.SetPercent(-FAST_DRIVE);
        left_motor.SetPercent(FAST_DRIVE);
        Sleep(2.0);
        driveForward(-STD_DRIVE, 1, 0);
        right_motor.SetPercent(-FAST_DRIVE);
        left_motor.SetPercent(FAST_DRIVE);
        Sleep(2.0);
        driveForward(-STD_DRIVE, 1, 0);
        Sleep(1.0);
        right_motor.SetPercent(-FAST_DRIVE);
        left_motor.SetPercent(FAST_DRIVE);
        Sleep(2.0);
        driveForward(-STD_DRIVE, 1, 0);
        Sleep(1.0);
    }
    /*while(true) {
        LCD.WriteLine(CDS.Value());
        Sleep(.2);
    }*/
}

void turnRight(int percent, int degrees, int input_counts) //using encoders
{
    //Make input degrees and convert degrees to counts
    int counts = degrees*COUNTS_PER_DEGREE + input_counts;
    //Reset encoder counts
    right_encoder.ResetCounts();
    left_encoder.ResetCounts();
    //Set both motors to desired percent
    //hint: set right motor forward, left motor backward
    right_motor.SetPercent(percent);
    left_motor.SetPercent(percent);
    //While the average of the left and right encoder are less than counts,
    //keep running motors
    while((left_encoder.Counts() + right_encoder.Counts()) / 2. < counts);
    //Turn off motors
    right_motor.Stop();
    left_motor.Stop();
}

void turnLeft(int percent, int degrees, int input_counts) //using encoders
{
    //Make input degrees and convert degrees to counts
    int counts = degrees*COUNTS_PER_DEGREE + input_counts;
    //Reset encoder counts
    right_encoder.ResetCounts();
    left_encoder.ResetCounts();
    //Set both motors to desired percent
    right_motor.SetPercent(-percent);
    left_motor.SetPercent(-percent);
    //While the average of the left and right encoder are less than counts,
    //keep running motors
    while((left_encoder.Counts() + right_encoder.Counts()) / 2. < counts);
    //Turn off motors
    right_motor.Stop();
    left_motor.Stop();
}
void driveForward(int percent, int inches, int input_counts) {
    int counts = inches*COUNTS_PER_INCH + input_counts;
    right_encoder.ResetCounts();
    left_encoder.ResetCounts();
    right_motor.SetPercent(-percent);
    left_motor.SetPercent(percent);
    while ((left_encoder.Counts() + right_encoder.Counts())/2.<counts);
    right_motor.Stop();
    left_motor.Stop();
}
void checkXPlus(float x_coordinate) //using RPS while robot is in the +x direction
{
    //check whether the robot is within an acceptable range
    while(RPS.X() < x_coordinate - 1 || RPS.X() > x_coordinate + 1)
    {
        if(RPS.X() > x_coordinate)
        {
            //pulse the motors for a short duration in the correct direction
            driveForward(-STD_DRIVE, 0, 2);

        }
        else if(RPS.X() < x_coordinate)
        {
            //pulse the motors for a short duration in the correct direction
            driveForward(STD_DRIVE, 0, 2);
        }
        Sleep(SHORT_SLEEP);
    }
}

void checkXMinus(float x_coordinate) //using RPS while robot is in the -x direction
{
    //check whether the robot is within an acceptable range
    while(RPS.X() < x_coordinate - 1 || RPS.X() > x_coordinate + 1)
    {
        if(RPS.X() > x_coordinate)
        {
            //pulse the motors for a short duration in the correct direction
            driveForward(STD_DRIVE, 0, 2);

        }
        else if(RPS.X() < x_coordinate)
        {
            //pulse the motors for a short duration in the correct direction
            driveForward(-STD_DRIVE, 0, 2);
        }
        Sleep(SHORT_SLEEP);
    }
}

void checkYMinus(float y_coordinate) //using RPS while robot is in the -y direction
{
    //check whether the robot is within an acceptable range
    while(RPS.Y() < y_coordinate - 1 || RPS.Y() > y_coordinate + 1)
    {
        if(RPS.Y() > y_coordinate)
        {
            //pulse the motors for a short duration in the correct direction

            driveForward(STD_DRIVE, 0, 2);
        }
        else if(RPS.Y() < y_coordinate)
        {
            //pulse the motors for a short duration in the correct direction

            driveForward(-STD_DRIVE, 0, 2);
        }
        Sleep(SHORT_SLEEP);
    }
}

void checkYPlus(float y_coordinate) //using RPS while robot is in the +y direction
{
    //check whether the robot is within an acceptable range
    while(RPS.Y() < y_coordinate - 1 || RPS.Y() > y_coordinate + 1)
    {
        if(RPS.Y() > y_coordinate)
        {
            //pulse the motors for a short duration in the correct direction

            driveForward(-STD_DRIVE, 0, 2);
        }
        else if(RPS.Y() < y_coordinate)
        {
            //pulse the motors for a short duration in the correct direction

            driveForward(STD_DRIVE, 0, 2);
        }
        Sleep(SHORT_SLEEP);
    }
}

void checkHeading(float heading) //using RPS
{
    //Check if the heading is in acceptable range
    while(RPS.Heading() < heading - 1 || RPS.Heading() > heading + 1)
    {
        if(RPS.Heading() > heading)
        {
            //pulse the motors for a short duration in the correct direction

            turnRight(STD_DRIVE, 0, 1);
        }
        else if(RPS.Y() < heading)
        {
            //pulse the motors for a short duration in the correct direction

            turnLeft(STD_DRIVE, 0, 1);
        }
        Sleep(SHORT_SLEEP);
    }
}

void buttonsOrder()
{
    int red = RPS.RedButtonOrder();
    int blue = RPS.BlueButtonOrder();
    //int white = RPS.WhiteBurronOrder();
    if (red == 1) {
        if (blue == 2) {
            //Press red
            disk.SetDegree(RED_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press blue
            disk.SetDegree(BLUE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press white
            disk.SetDegree(WHITE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
        }
        else {
            //Press red
            disk.SetDegree(RED_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press white
            disk.SetDegree(WHITE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press blue
            disk.SetDegree(BLUE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
        }
    }
    else if (blue == 1) {
        if (red == 2) {
            //Press blue
            disk.SetDegree(BLUE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press red
            disk.SetDegree(RED_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press white
            disk.SetDegree(WHITE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
        }
        else {
            //Press blue
            disk.SetDegree(BLUE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press white
            disk.SetDegree(WHITE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press red
            disk.SetDegree(RED_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
        }
    }
    else {
        if (blue == 2) {
            //Press white
            disk.SetDegree(WHITE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press blue
            disk.SetDegree(BLUE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press red
            disk.SetDegree(RED_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
        }
        else {
            //Press white
            disk.SetDegree(WHITE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press red
            disk.SetDegree(RED_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press blue
            disk.SetDegree(BLUE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
        }
    }
}
<commit_msg>v0.0309.1<commit_after>/*
 *This is the program that will be loaded onto the
 *Proteus to complete Performance Test 3.
 * ROBOT NOTE:
 * The left wheel is correct, but the right wheel is backwards.
 */

#include <FEHLCD.h>
#include <FEHIO.h>
#include <FEHUtility.h>
#include <FEHMotor.h>
#include <FEHRPS.h>
#include <FEHServo.h>
//The number of counts when an inch is travelled
#define COUNTS_PER_INCH 40
//The number of counts when 1 degree is turned
#define COUNTS_PER_DEGREE 233/90
//The point South of the starting zone
#define POINT_A 18
//The point East of POINT_A
#define POINT_B 31.3
//The point North of POINT_B
#define POINT_C 52.1
//The point West of POINT_C
#define POINT_D 63.7
//The first salt bag point
#define POINT_E 20
//The second salt bag point
#define POINT_F 25
//The standard driving percentage
#define STD_DRIVE 25
//The fast driving percentage
#define FAST_DRIVE 50
//The slow driving percentage
#define SLOW_DRIVE 12
//The max driving speed. Only for use in extreme circumstances.
#define HYPER_DRIVE 100 //Think before you do this.
//The standard sleep time
#define SLEEP_TIME 500
//The short sleep time used in RPS checks
#define SHORT_SLEEP 50
//The CdS Threshold
#define CDS_THRESHOLD .6
//The angle to press the red button
#define RED_ANGLE 90
//The angle to press the blue button
#define BLUE_ANGLE 90
//The angle to press the white button
#define WHITE_ANGLE 90
//Servo motor minimum
#define SERVO_MIN 510
//Servo motor maximum
#define SERVO_MAX 2280
//Declare the various sensors and motors
ButtonBoard buttons(FEHIO::Bank3); //Button Board
FEHServo disk( FEHServo::Servo0); //Disk Mechanism
FEHMotor right_motor( FEHMotor::Motor0); //Right Motor (Backwards)
FEHMotor left_motor( FEHMotor::Motor1); //Left Motor
DigitalEncoder right_encoder( FEHIO::P0_0); //Right encoder
DigitalEncoder left_encoder( FEHIO::P0_2); //Left encoder
AnalogInputPin CdS( FEHIO::P1_0); //CdS cell
//DigitalInputPin right_bump( FEHIO::P1_2); //Right bump switch (if used)
//Prototypes for each function
void turnRight(int percent, int degrees, int input_counts);
void turnLeft(int percent, int degrees, int input_counts);
void driveForward(int percent, int inches, int input_counts);
void checkXPlus(float x_coordinate);
void checkXMinus(float x_coordinate);
void checkYPlus(float y_coordinate);
void checkYMinus(float y_coordinate);
void checkHeading(float heading);
void buttonsOrder();

int main(void)
{
    LCD.Clear( FEHLCD::White );
    LCD.SetFontColor( FEHLCD::Black );
    //Set servo limits
    disk.SetMin(SERVO_MIN);
    disk.SetMax(SERVO_MAX);
    disk.SetDegree(20);
    RPS.InitializeMenu();
    //while(true) {
    //    LCD.WriteLine("Press the middle button to begin");
    //    while(!buttons.MiddlePressed());
    //    while(buttons.MiddlePressed());
        /*LCD.WriteLine("Will start on light now");
        while(CdS.Value()>CDS_THRESHOLD);
        LCD.Clear( FEHLCD::White );
        driveForward(STD_DRIVE, 13, 0);
        checkYMinus(POINT_A);
        Sleep(SLEEP_TIME);
        turnLeft(STD_DRIVE, 90, 0);
        checkHeading(90);
        Sleep(SLEEP_TIME);
        driveForward(STD_DRIVE, 11, -50);
        checkXPlus(POINT_B);
        Sleep(SLEEP_TIME);
        turnLeft(STD_DRIVE, 90, 0);
        checkHeading(180);
        Sleep(SLEEP_TIME);
        driveForward(FAST_DRIVE, 35, 0);
        driveForward(STD_DRIVE, 2, 0);
        driveForward(SLOW_DRIVE, 1, 0);
        checkYPlus(POINT_C);
        Sleep(SLEEP_TIME);
        turnLeft(STD_DRIVE, 56, 0);
        checkHeading(236);
        Sleep(SLEEP_TIME);
        driveForward(STD_DRIVE, 20, 0);
        checkYPlus(POINT_D);
        turnRight(STD_DRIVE, 15, 0);
        checkHeading(221.5);
        buttonsOrder();*/
        /*driveForward(STD_DRIVE, 10, 0);
        checkYMinus(POINT_E);
        Sleep(SLEEP_TIME);
        turnLeft(STD_DRIVE, 20, 0);
        checkHeading(20);
        Sleep(SLEEP_TIME);
        driveForward(STD_DRIVE, 15, 0);
        checkYMinus(POINT_F);
        Sleep(SLEEP_TIME);
        driveForward(-STD_DRIVE, 2, 0);
        turnLeft(STD_DRIVE, 160, 0);
        checkHeading(180);
        driveForward(STD_DRIVE, 20, 0);
        checkYPlus(POINT_G);
        Sleep(SLEEP_TIME);
        driveForward(FAST_DRIVE, 15, 0);*/

    //}
    while(true) {
        LCD.WriteLine(RPS.X());
        LCD.WriteLine(RPS.Y());
        LCD.WriteLine(RPS.Heading());
        Sleep(1.0);
    }
}

void turnRight(int percent, int degrees, int input_counts) //using encoders
{
    //Make input degrees and convert degrees to counts
    int counts = degrees*COUNTS_PER_DEGREE + input_counts;
    //Reset encoder counts
    right_encoder.ResetCounts();
    left_encoder.ResetCounts();
    //Set both motors to desired percent
    //hint: set right motor forward, left motor backward
    right_motor.SetPercent(percent);
    left_motor.SetPercent(percent);
    //While the average of the left and right encoder are less than counts,
    //keep running motors
    while((left_encoder.Counts() + right_encoder.Counts()) / 2. < counts);
    //Turn off motors
    right_motor.Stop();
    left_motor.Stop();
}

void turnLeft(int percent, int degrees, int input_counts) //using encoders
{
    //Make input degrees and convert degrees to counts
    int counts = degrees*COUNTS_PER_DEGREE + input_counts;
    //Reset encoder counts
    right_encoder.ResetCounts();
    left_encoder.ResetCounts();
    //Set both motors to desired percent
    right_motor.SetPercent(-percent);
    left_motor.SetPercent(-percent);
    //While the average of the left and right encoder are less than counts,
    //keep running motors
    while((left_encoder.Counts() + right_encoder.Counts()) / 2. < counts);
    //Turn off motors
    right_motor.Stop();
    left_motor.Stop();
}
void driveForward(int percent, int inches, int input_counts) {
    int counts = inches*COUNTS_PER_INCH + input_counts;
    right_encoder.ResetCounts();
    left_encoder.ResetCounts();
    right_motor.SetPercent(-percent);
    left_motor.SetPercent(percent);
    while ((left_encoder.Counts() + right_encoder.Counts())/2.<counts);
    right_motor.Stop();
    left_motor.Stop();
}
void checkXPlus(float x_coordinate) //using RPS while robot is in the +x direction
{
    //check whether the robot is within an acceptable range
    while(RPS.X() < x_coordinate - 1 || RPS.X() > x_coordinate + 1)
    {
        if(RPS.X() > x_coordinate)
        {
            //pulse the motors for a short duration in the correct direction
            driveForward(-STD_DRIVE, 0, 2);

        }
        else if(RPS.X() < x_coordinate)
        {
            //pulse the motors for a short duration in the correct direction
            driveForward(STD_DRIVE, 0, 2);
        }
        Sleep(SHORT_SLEEP);
    }
}

void checkXMinus(float x_coordinate) //using RPS while robot is in the -x direction
{
    //check whether the robot is within an acceptable range
    while(RPS.X() < x_coordinate - 1 || RPS.X() > x_coordinate + 1)
    {
        if(RPS.X() > x_coordinate)
        {
            //pulse the motors for a short duration in the correct direction
            driveForward(STD_DRIVE, 0, 2);

        }
        else if(RPS.X() < x_coordinate)
        {
            //pulse the motors for a short duration in the correct direction
            driveForward(-STD_DRIVE, 0, 2);
        }
        Sleep(SHORT_SLEEP);
    }
}

void checkYMinus(float y_coordinate) //using RPS while robot is in the -y direction
{
    //check whether the robot is within an acceptable range
    while(RPS.Y() < y_coordinate - 1 || RPS.Y() > y_coordinate + 1)
    {
        if(RPS.Y() > y_coordinate)
        {
            //pulse the motors for a short duration in the correct direction

            driveForward(STD_DRIVE, 0, 2);
        }
        else if(RPS.Y() < y_coordinate)
        {
            //pulse the motors for a short duration in the correct direction

            driveForward(-STD_DRIVE, 0, 2);
        }
        Sleep(SHORT_SLEEP);
    }
}

void checkYPlus(float y_coordinate) //using RPS while robot is in the +y direction
{
    //check whether the robot is within an acceptable range
    while(RPS.Y() < y_coordinate - 1 || RPS.Y() > y_coordinate + 1)
    {
        if(RPS.Y() > y_coordinate)
        {
            //pulse the motors for a short duration in the correct direction

            driveForward(-STD_DRIVE, 0, 2);
        }
        else if(RPS.Y() < y_coordinate)
        {
            //pulse the motors for a short duration in the correct direction

            driveForward(STD_DRIVE, 0, 2);
        }
        Sleep(SHORT_SLEEP);
    }
}

void checkHeading(float heading) //using RPS
{
    //Check if the heading is in acceptable range
    while(RPS.Heading() < heading - 1 || RPS.Heading() > heading + 1)
    {
        if(RPS.Heading() > heading)
        {
            //pulse the motors for a short duration in the correct direction

            turnRight(STD_DRIVE, 0, 1);
        }
        else if(RPS.Y() < heading)
        {
            //pulse the motors for a short duration in the correct direction

            turnLeft(STD_DRIVE, 0, 1);
        }
        Sleep(SHORT_SLEEP);
    }
}

void buttonsOrder()
{
    int red = RPS.RedButtonOrder();
    int blue = RPS.BlueButtonOrder();
    //int white = RPS.WhiteBurronOrder();
    if (red == 1) {
        if (blue == 2) {
            //Press red
            disk.SetDegree(RED_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press blue
            disk.SetDegree(BLUE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press white
            disk.SetDegree(WHITE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
        }
        else {
            //Press red
            disk.SetDegree(RED_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press white
            disk.SetDegree(WHITE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press blue
            disk.SetDegree(BLUE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
        }
    }
    else if (blue == 1) {
        if (red == 2) {
            //Press blue
            disk.SetDegree(BLUE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press red
            disk.SetDegree(RED_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press white
            disk.SetDegree(WHITE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
        }
        else {
            //Press blue
            disk.SetDegree(BLUE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press white
            disk.SetDegree(WHITE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press red
            disk.SetDegree(RED_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
        }
    }
    else {
        if (blue == 2) {
            //Press white
            disk.SetDegree(WHITE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press blue
            disk.SetDegree(BLUE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press red
            disk.SetDegree(RED_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
        }
        else {
            //Press white
            disk.SetDegree(WHITE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press red
            disk.SetDegree(RED_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
            //Press blue
            disk.SetDegree(BLUE_ANGLE);
            driveForward(SLOW_DRIVE, 2, 0);
            Sleep(SLEEP_TIME);
            driveForward(-SLOW_DRIVE, 2, 0);
        }
    }
}
<|endoftext|>


<commit_before>f9bdf705-ad59-11e7-92d2-ac87a332f658<commit_msg>this is my first commit?<commit_after>fa1cd423-ad59-11e7-90d1-ac87a332f658<|endoftext|>


<commit_before>#include "main.h"
#include "vardeclvisitor.h"

#include <boost/core/demangle.hpp>
#include <chrono>
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Tooling/Tooling.h>
#include <experimental/string_view>
#include <iostream>
#include <llvm/Support/CommandLine.h>
#include <sstream>
#include <typeinfo>
#include <utility>
#include <vector>

std::vector<const char *> get_fake_args() {
	//TODO: load this from a config file or something
	auto buffer =
		"test.cpp\0"
		"--\0"
		"--std=c++1z\0"
		"-D__STDC_CONSTANT_MACROS\0"
		"-D__STDC_LIMIT_MACROS\0"
		"-I.\0"
		"-I/usr/lib/llvm-3.9/include\0"
		"-I/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-clang\0"
		"-I/usr/lib/llvm-3.9/lib/clang/3.9.1/include\0";
	std::vector<const char *> argv{buffer};
	for (auto p = buffer;; p++) {
		if (!*p) {
			p++;
			if (!*p) {
				return argv;
			}
			argv.push_back(p);
		}
	}
}

template <class T, class String_t>
T from_string(const String_t &s) {
	T t{};
	std::stringstream ss{s};
	ss >> t;
	if (!ss) {
		throw std::runtime_error("Failed converting string \"" + std::string{s} + "\" to type \"" + boost::core::demangle(typeid(T).name()) + "\"");
	}
	return t;
}

int main(int argc, const char **argv) {
	for (int i = 0; i < argc; i++) {
		std::cout << argv[i] << '\n';
	}
	if (argc < 3) {
		return -1;
	}
	auto filename = argv[1];
	auto line = from_string<unsigned int>(argv[2]);
	auto range = argc >= 3 ? from_string<unsigned int>(argv[3]) : 1u;

	auto fake_args = get_fake_args();
	fake_args.insert(std::begin(fake_args), argv[0]);
	int fake_argc = static_cast<int>(fake_args.size());
	const char **fake_argv = fake_args.data();

	auto start = std::chrono::high_resolution_clock::now();
	std::ios::sync_with_stdio(false);
	llvm::cl::OptionCategory myToolCategory("my-tool options");
	clang::tooling::CommonOptionsParser optionsParser(fake_argc, fake_argv, myToolCategory);
	clang::tooling::ClangTool tool(optionsParser.getCompilations(), optionsParser.getSourcePathList());

	DeclarationPrinter declprinter{filename, line, range};
	clang::ast_matchers::DeclarationMatcher var_decl_matcher = clang::ast_matchers::varDecl().bind("declaration");

	clang::ast_matchers::MatchFinder finder;
	finder.addMatcher(var_decl_matcher, &declprinter);

	const auto &retval = tool.run(clang::tooling::newFrontendActionFactory(&finder).get());
	std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start).count() / 1000. << "s\n";
	return retval;
}<commit_msg>Using proper filename.<commit_after>#include "main.h"
#include "vardeclvisitor.h"

#include <boost/core/demangle.hpp>
#include <chrono>
#include <clang/Tooling/CommonOptionsParser.h>
#include <clang/Tooling/Tooling.h>
#include <experimental/string_view>
#include <iostream>
#include <llvm/Support/CommandLine.h>
#include <sstream>
#include <typeinfo>
#include <utility>
#include <vector>

std::vector<const char *> get_fake_args() {
	//TODO: load this from a config file or something
	auto buffer =
		"--\0"
		"--std=c++1z\0"
		"-D__STDC_CONSTANT_MACROS\0"
		"-D__STDC_LIMIT_MACROS\0"
		"-I.\0"
		"-I/usr/lib/llvm-3.9/include\0"
		"-I/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-clang\0"
		"-I/usr/lib/llvm-3.9/lib/clang/3.9.1/include\0";
	std::vector<const char *> argv{buffer};
	for (auto p = buffer;; p++) {
		if (!*p) {
			p++;
			if (!*p) {
				return argv;
			}
			argv.push_back(p);
		}
	}
}

template <class T, class String_t>
T from_string(const String_t &s) {
	T t{};
	std::stringstream ss{s};
	ss >> t;
	if (!ss) {
		throw std::runtime_error("Failed converting string \"" + std::string{s} + "\" to type \"" + boost::core::demangle(typeid(T).name()) + "\"");
	}
	return t;
}

int main(int argc, const char **argv) {
	for (int i = 0; i < argc; i++) {
		std::cout << argv[i] << '\n';
	}
	if (argc < 3) {
		return -1;
	}
	auto filename = argv[1];
	auto line = from_string<unsigned int>(argv[2]);
	auto range = argc >= 3 ? from_string<unsigned int>(argv[3]) : 1u;

	auto fake_args = get_fake_args();
	fake_args.insert(std::begin(fake_args), filename);
	fake_args.insert(std::begin(fake_args), argv[0]);
	int fake_argc = static_cast<int>(fake_args.size());
	const char **fake_argv = fake_args.data();

	auto start = std::chrono::high_resolution_clock::now();
	std::ios::sync_with_stdio(false);
	llvm::cl::OptionCategory myToolCategory("my-tool options");
	clang::tooling::CommonOptionsParser optionsParser(fake_argc, fake_argv, myToolCategory);
	clang::tooling::ClangTool tool(optionsParser.getCompilations(), optionsParser.getSourcePathList());

	DeclarationPrinter declprinter{filename, line, range};
	clang::ast_matchers::DeclarationMatcher var_decl_matcher = clang::ast_matchers::varDecl().bind("declaration");

	clang::ast_matchers::MatchFinder finder;
	finder.addMatcher(var_decl_matcher, &declprinter);

	const auto &retval = tool.run(clang::tooling::newFrontendActionFactory(&finder).get());
	std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start).count() / 1000. << "s\n";
	return retval;
}
<|endoftext|>


<commit_before>/*
 * MIT License
 *
 * Copyright (c) 2017 Johannes Winkelmann
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <iostream>
#include <sstream>
#include <cmath>

#include "svggen.h"

#include "dial_dotsandnumbers.h"
#include "dial_circletests.h"
#include "dial_secondsat9.h"

int main(int argc, char** argv)
{
    SvgGen gen;

    gen.start(600, 400, "mm");

    char sel = '0'; // default
    if (argc > 1) {
        sel = argv[1][0];
    }

    switch (sel) {
    case '1':
        dial_dotsAndNumbers(gen, 20, 20);
        break;
    case '2':
        dial_circleTests(gen, 5, 5);
        break;
    default:
        dial_secondsAt9(gen, 5, 5);
    }

    gen.end();

    std::cout << gen.str() << std::endl;
    return 0;
}
<commit_msg>reduce bounding box<commit_after>/*
 * MIT License
 *
 * Copyright (c) 2017 Johannes Winkelmann
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <iostream>
#include <sstream>
#include <cmath>

#include "svggen.h"

#include "dial_dotsandnumbers.h"
#include "dial_circletests.h"
#include "dial_secondsat9.h"

int main(int argc, char** argv)
{
    SvgGen gen;

    double width = 120;
    double height = 120;

    gen.start(width, height, "mm");

    char sel = '0'; // default
    if (argc > 1) {
        sel = argv[1][0];
    }

    switch (sel) {
    case '1':
        dial_dotsAndNumbers(gen, 5, 5);
        break;
    case '2':
        dial_circleTests(gen, 5, 5);
        break;
    default:
        dial_secondsAt9(gen, 5, 5);
    }

    // bounding box
    // gen.rect(1, 1, width-1, height-1, "fill='transparent' stroke='#cccccc'");

    gen.end();

    std::cout << gen.str() << std::endl;
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include "obscure.h"

using namespace std;
using namespace Magick;

static const struct option opts[] = {{"help", no_argument, 0, 'h'},
                                     {"alt-image", required_argument, 0, 'm'},
                                     {"output", required_argument, 0, 'o'},
                                     {"root", no_argument, 0, 'd'},
                                     {"display", no_argument, 0, 'D'},
                                     {"blur", optional_argument, 0, 'b'},
                                     {"shade", optional_argument, 0, 'S'},
                                     {"swirl", optional_argument, 0, 's'},
                                     {"spread", optional_argument, 0, 'p'},
                                     {"implode", optional_argument, 0, 'i'},
                                     {"wave", optional_argument, 0, 'w'},
                                     {0, 0, 0, 0}};

static void help() {
  cout << "ShantyLocker [OPTIONS...]         " << endl;
  cout << "    -h --help                        "
       << "Show help" << endl;
  cout << "    -m --alt-image [path]            "
       << "Use image at [path] as background to transpose obfuscated windows "
          "onto. Can't be used with --root"
       << endl;
  cout << "    -o --output [path]               "
       << "Save resulting lock screen image to path" << endl;
  cout << "    -d --root                        "
       << "Obfuscate the desktop as one window, instead of each visible window "
          "individually"
       << endl;
  cout << "    -D --display                     "
          "Display the generated image for fast option tweaking"
       << endl;
  cout << "  Obfuscation methodologies:         (built-in functions provided "
          "by ImageMagick)"
       << endl;
  cout << "    -b --blur [radius]               Blurs image. [radius] "
          "specifies the radius of the Gaussian"
       << endl;
  cout << "    -S --shade [value]               " << endl;
  cout << "    -s --swirl [degrees]             Swirl the image from the "
          "center by [degrees]"
       << endl;
  cout << "    -p --spread [amount]             Spread pixels randomly within "
          "image by [amount]"
       << endl;
  cout << "    -i --implode [factor]            Implode image by [factor]"
       << endl;
  cout << "    -w --wave [amplitude]            Must use with --alt-image for best effect"
       << endl;
}

int main(int argc, char** argv) {
  vector<function<void(Image&, double)>> operations;
  vector<double> params;

  // Default values for operations
  double rad = 5;
  double shade_factor = 20;
  double swirl_factor = 720;
  size_t spread_factor = 12;
  double implode_factor = 50;
  double amp = 5;
  bool desktop = false;
  bool display = false;

  // Default destination image to x:root
  Image base("x:root");

  string alt_image;

  // Get user's home directory, returns /home/user
  string path(getpwuid(getuid())->pw_dir);
  path += "/.config/shantylocker.png";

  int optidx;
  int c;

  while ((c = getopt_long(argc, argv, "hm:o:dDb::S::s::p::i::w::", opts,
                          &optidx)) != -1) {
    switch (c) {
      case 'h':
        help();
        return 0;

      case 'm':
        alt_image = string(optarg);
        base = Image(alt_image);
        break;

      case 'o':
        path = string(optarg);

      case 'd':
        desktop = true;
        break;

      case 'D':
        display = true;
        break;

      case 'b':
        rad = optarg ? stod(string(optarg)) : rad;
        operations.push_back(blur);
        params.push_back(rad);
        break;

      case 'S':
        shade_factor = optarg ? stod(string(optarg)) : shade_factor;
        operations.push_back(shade);
        params.push_back(shade_factor);
        break;

      case 's':
        swirl_factor = optarg ? stod(string(optarg)) : swirl_factor;
        operations.push_back(swirl);
        params.push_back(swirl_factor);
        break;
      case 'p':
        spread_factor = optarg ? (size_t)stoi(string(optarg)) : spread_factor;
        operations.push_back(spread);
        params.push_back(spread_factor);
        break;
      case 'i':
        implode_factor = optarg ? stod(string(optarg)) : implode_factor;
        operations.push_back(implode);
        params.push_back(implode_factor);
        break;

      case 'w':
        amp = optarg ? stod(string(optarg)) : amp;
        operations.push_back(wave);
        params.push_back(amp);
        break;

      case '?':
        help();
        return 1;
      default:
        if (optopt == 'c')
          fprintf(stderr, "Option -%c requires an argument.\n", optopt);
        else if (isprint(optopt))
          fprintf(stderr, "Unknown option -%c.\n", optopt);
        else
          fprintf(stderr, "Unknown option character '\\x%x'.\n", optopt);
        return 1;
    }
  }

  InitializeMagick(*argv);

  int screens;

  // 1st parameter takes display name. If NULL, uses DISPLAY env
  xcb_connection_t* connection = xcb_connect(NULL, &screens);

  // Get the first screen
  const xcb_setup_t* setup = xcb_get_setup(connection);
  xcb_screen_iterator_t iter = xcb_setup_roots_iterator(setup);
  xcb_screen_t* screen = iter.data;

  // Either fill visible_windows, or insert root window
  vector<unique_ptr<rectangle_t>> visible_windows;
  if (desktop) {
    visible_windows.push_back(make_unique<rectangle_t>(0, 0, screen->width_in_pixels,
                                                       screen->height_in_pixels));
  }
  else {
      get_visible_windows(connection, screen, visible_windows);
  }
  execute_operations(visible_windows, operations, params, base);

  if (display) {
      base.display();
  }

  base.write(path);
  TerminateMagick();
  xcb_disconnect(connection);
  return 0;
}<commit_msg>Added some input checking and exiting on improper input<commit_after>#include <iostream>
#include "obscure.h"

using namespace std;
using namespace Magick;

static const struct option opts[] = {{"help", no_argument, 0, 'h'},
                                     {"alt-image", required_argument, 0, 'm'},
                                     {"output", required_argument, 0, 'o'},
                                     {"root", no_argument, 0, 'd'},
                                     {"display", no_argument, 0, 'D'},
                                     {"blur", optional_argument, 0, 'b'},
                                     {"shade", optional_argument, 0, 'S'},
                                     {"swirl", optional_argument, 0, 's'},
                                     {"spread", optional_argument, 0, 'p'},
                                     {"implode", optional_argument, 0, 'i'},
                                     {"wave", optional_argument, 0, 'w'},
                                     {0, 0, 0, 0}};

static void help() {
  cout << "ShantyLocker [OPTIONS...]         " << endl;
  cout << "    -h --help                        "
       << "Show help" << endl;
  cout << "    -m --alt-image [path]            "
       << "Use image at [path] as background to transpose obfuscated windows "
          "onto. Can't be used with --root"
       << endl;
  cout << "    -o --output [path]               "
       << "Save resulting lock screen image to path" << endl;
  cout << "    -d --root                        "
       << "Obfuscate the desktop as one window, instead of each visible window "
          "individually"
       << endl;
  cout << "    -D --display                     "
          "Display the generated image for fast option tweaking"
       << endl;
  cout << "  Obfuscation methodologies:         (built-in functions provided "
          "by ImageMagick)"
       << endl;
  cout << "    -b --blur [radius]               Blurs image. [radius] "
          "specifies the radius of the Gaussian"
       << endl;
  cout << "    -S --shade [value]               " << endl;
  cout << "    -s --swirl [degrees]             Swirl the image from the "
          "center by [degrees]"
       << endl;
  cout << "    -p --spread [amount]             Spread pixels randomly within "
          "image by [amount]"
       << endl;
  cout << "    -i --implode [factor]            Implode image by [factor]"
       << endl;
  cout << "    -w --wave [amplitude]            Must use with --alt-image for best effect"
       << endl;
}

int main(int argc, char** argv) {
  vector<function<void(Image&, double)>> operations;
  vector<double> params;

  // Default values for operations
  double rad = 5;
  double shade_factor = 20;
  double swirl_factor = 720;
  size_t spread_factor = 12;
  double implode_factor = 50;
  double amp = 5;
  bool desktop = false;
  bool display = false;

  // Default destination image to x:root
  Image base("x:root");

  string alt_image;

  // Get user's home directory, returns /home/user
  string path(getpwuid(getuid())->pw_dir);
  path += "/.config/shantylocker.png";

  int optidx;
  int c;

  while ((c = getopt_long(argc, argv, "hm:o:dDb::S::s::p::i::w::", opts,
                          &optidx)) != -1) {
    switch (c) {
      case 'h':
        help();
        return 0;

      case 'm':
        alt_image = string(optarg);
        if (alt_image[0] == '-') {
            cerr << "Argument required for -m or --root option" << endl;
            throw new invalid_argument("Argument required for -m or --root option");
        }
        base = Image(alt_image);
        break;

      case 'o':
        path = string(optarg);
        if (path[0] == '-') {
            cerr << "Argument required for -o or --output option" << endl;
            throw new invalid_argument("Argument required for -o or --output option");
        }
        break;

      case 'd':
        desktop = true;
        break;

      case 'D':
        display = true;
        break;

      case 'b':
        try {
            rad = stod(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --blur. Using default..." << endl;
        }
        operations.push_back(blur);
        params.push_back(rad);
        break;

      case 'S':
        try {
          shade_factor = stod(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --shade. Using default..." << endl;
        }
        operations.push_back(shade);
        params.push_back(shade_factor);
        break;

      case 's':
        try {
            swirl_factor = stod(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --swirl. Using default..." << endl;
        }
        operations.push_back(swirl);
        params.push_back(swirl_factor);
        break;
      case 'p':
        try {
            spread_factor = (size_t)stoi(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --spread. Using default..." << endl;
        }
        operations.push_back(spread);
        params.push_back(spread_factor);
        break;
      case 'i':
        try {
            implode_factor = stod(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --implode. Using default..." << endl;
        }
        operations.push_back(implode);
        params.push_back(implode_factor);
        break;

      case 'w':
        try {
            amp = stod(string(optarg));
        } catch (const invalid_argument& e) {
            cerr << "Invalid option to --wave. Using default..." << endl;
        }
        operations.push_back(wave);
        params.push_back(amp);
        break;

      case '?':
        help();
        return 1;
      default:
        if (optopt == 'c') {
            fprintf(stderr, "Option -%c requires an argument.\n", optopt);
        }
        else if (isprint(optopt)) {
            fprintf(stderr, "Unknown option -%c.\n", optopt);
        }
        else {
            fprintf(stderr, "Unknown option character '\\x%x'.\n", optopt);
        }
        return 1;
    }
  }

  InitializeMagick(*argv);

  int screens;

  // 1st parameter takes display name. If NULL, uses DISPLAY env
  xcb_connection_t* connection = xcb_connect(NULL, &screens);

  // Get the first screen
  const xcb_setup_t* setup = xcb_get_setup(connection);
  xcb_screen_iterator_t iter = xcb_setup_roots_iterator(setup);
  xcb_screen_t* screen = iter.data;

  // Either fill visible_windows, or insert root window
  vector<unique_ptr<rectangle_t>> visible_windows;
  if (desktop) {
    visible_windows.push_back(make_unique<rectangle_t>(0, 0, screen->width_in_pixels,
                                                       screen->height_in_pixels));
  }
  else {
      get_visible_windows(connection, screen, visible_windows);
  }
  execute_operations(visible_windows, operations, params, base);

  if (display) {
      base.display();
  }

  base.write(path);
  TerminateMagick();
  xcb_disconnect(connection);
  return 0;
}<|endoftext|>


<commit_before>/*
 * main.cpp
 *
 *  Created on: Sep 4, 2017
 *      Author: pete
 */

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <wiriginPi.h>
#include "ds18b20/DS18B20.h"
#include "geiger/PocketGeiger.h"
#include "tsl2561/tsl2561.h"

void *tsl;
DS18B20 ds18b20_1;
DS18B20 ds18b20_2;

void onRadiation()
{
	std::cout << "Wild Gamma Rays are a happenin: " << PocketGeiger::instance().uSvh();
	std::cout << "uSv/h +/- " << PocketGeiger::instance().uSvhError();
}

void onNoise()
{
	std::cout << "too much noise";
}

PI_THREAD (luxThread)
{
	int c;
	long lux;

	if (tsl != NULL) {
		while (1) {
			lux = tsl2561_lux(tsl);
			std::cout << "lux: " << lux;
			usleep(3 * 1000 * 1000);
		}
	}
}

PI_THREAD (tempThread)
{
	ds18b20_1.open("sdlk");
	ds18b20_2.open("lksd");

	while (1) {
		ds18b20_1.read();
		ds18b20_2.read();
		std::cout << __PRETTY_FUNCTION__ << ": temp=" << ds18b20_1.tempF();
		std::cout << __PRETTY_FUNCTION__ << ": temp=" << ds18b20_2.tempF();
		usleep(1000 * 1000);
	}
}

void runtime()
{

	piThreadCreate(luxThread);

	while (1) {
		sleep(1);
	}
}

int main(int argc, char *argv[])
{
	pid_t pid;

	if ((tsl = tsl2561_init(0x39, "/dev/i2c-1")) == NULL) {
		std::cerr << "Unable to open TSL device";
	}

	PocketGeiger::instance().registerRadiationCallback(&onRadiation);
	PocketGeiger::instance().registerNoiseCallback(&onRadiation);

	tsl2561_enable_autogain(tsl);
	tsl2561_set_integration_time(tsl, TSL2561_INTEGRATION_TIME_13MS);

	pid = fork();
	if (pid == 0) {
		runtime();
	}
	else if (pid < 0) {
		std::cerr << "fork failed";
	}
	else {
		fclose(stdout);
		fclose(stdin);
		fclose(stderr);
	}
	exit(0);
}
<commit_msg>Added some actual functions. Now we need to test it<commit_after>/*
 * main.cpp
 *
 *  Created on: Sep 4, 2017
 *      Author: pete
 */

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <unistd.h>
#include <wiringPi.h>
#include "ds18b20/DS18B20.h"
#include "geiger/PocketGeiger.h"
#include "tsl2561/tsl2561.h"

void *tsl;
DS18B20 ds18b20_1;
DS18B20 ds18b20_2;

void onRadiation()
{
	std::cout << "Wild Gamma Rays are a happenin: " << PocketGeiger::instance().uSvh();
	std::cout << "uSv/h +/- " << PocketGeiger::instance().uSvhError();
}

void onNoise()
{
	std::cout << "too much noise";
}

PI_THREAD (luxThread)
{
	int c;
	long lux;

	if (tsl != NULL) {
		while (1) {
			lux = tsl2561_lux(tsl);
			std::cout << "lux: " << lux;
			usleep(3 * 1000 * 1000);
		}
	}
}

PI_THREAD (tempThread)
{
	ds18b20_1.open("sdlk");
	ds18b20_2.open("lksd");

	while (1) {
		ds18b20_1.read();
		ds18b20_2.read();
		std::cout << __PRETTY_FUNCTION__ << ": temp=" << ds18b20_1.tempF();
		std::cout << __PRETTY_FUNCTION__ << ": temp=" << ds18b20_2.tempF();
		usleep(1000 * 1000);
	}
}

void runtime()
{

	piThreadCreate(luxThread);

	while (1) {
		sleep(1);
	}
}

int main(int argc, char *argv[])
{
	pid_t pid;

	if ((tsl = tsl2561_init(0x39, "/dev/i2c-1")) == NULL) {
		std::cerr << "Unable to open TSL device";
	}

	PocketGeiger::instance().registerRadiationCallback(&onRadiation);
	PocketGeiger::instance().registerNoiseCallback(&onRadiation);

	tsl2561_enable_autogain(tsl);
	tsl2561_set_integration_time(tsl, TSL2561_INTEGRATION_TIME_13MS);

	pid = fork();
	if (pid == 0) {
		runtime();
	}
	else if (pid < 0) {
		std::cerr << "fork failed";
	}
	else {
		fclose(stdout);
		fclose(stdin);
		fclose(stderr);
	}
	exit(0);
}
<|endoftext|>


<commit_before>#include "skipList.h"
#include <time.h>

int main()
{
  srand(time(NULL));
  SkipList<int, int> list;
  for (int i = 1; i < 100; i++)
    list.insert(createNode(i, 10));
  for (int i = 1; i < 100; i += 2)
    list.remove(i);
  list.dump();

  return 0;
}<commit_msg>Add test for skipList.find<commit_after>#include "skipList.h"
#include <time.h>

int main()
{
  srand(time(NULL));
  SkipList<int, int> list;
  for (int i = 1; i < 100; i++)
    list.insert(createNode(i, 10));
  for (int i = 1; i < 100; i += 2)
    list.remove(i);
  list.dump();

  int ret = -1;
  if (list.find(10, ret))
    std::cout << ret << std::endl;
  else
    std::cout << "Not found!" << std::endl;

  return 0;
}<|endoftext|>


<commit_before>7c39018c-ad5b-11e7-b9a7-ac87a332f658<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>7ca8e863-ad5b-11e7-a207-ac87a332f658<|endoftext|>


<commit_before>aee249b8-2747-11e6-8189-e0f84713e7b8<commit_msg>Nope, didn't work, now it does<commit_after>aef3baba-2747-11e6-a147-e0f84713e7b8<|endoftext|>


<commit_before>// Rectangles

#include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

#include "named_rect.h"

struct Results {
  std::vector<char> overlaps;
  std::vector<char> contains;
  std::vector<char> containedBy;
  std::vector<char> touches;
};

// A structure to store our results in.
using ResultsType = std::unordered_map<char, Results>;

// Get the corresponding Result object for the given rectangle name.
Results* getResults(ResultsType* results, char name) {
  bool inserted = false;
  auto it = results->find(name);
  if (it == std::end(*results))
    std::tie(it, inserted) = results->insert(std::make_pair(name, Results()));

  return &it->second;
}

// Given a list of rectangle names, print them out in a comma separated line.
void printNames(std::ostream& os, const std::vector<char>& names) {
  if (names.empty()) {
    os << '0';
  } else {
    const size_t size = names.size();
    for (size_t i = 0; i < size; ++i) {
      os << names[i];
      if (i < size - 1)
        os << ',';
    }
  }
  os << std::endl;
}

void printResults(std::ostream& os, const ResultsType& results) {
  for (const auto& it : results) {
    os << it.first << std::endl;
    printNames(os, it.second.overlaps);
    printNames(os, it.second.contains);
    printNames(os, it.second.containedBy);
    printNames(os, it.second.touches);
    os << std::endl;
  }
}

int main(int argc, char* argv[]) {
  std::string inFilename, outFilename;

  if (argc < 2) {
    std::cout << "USAGE: " << argv[0] << " <input file> [<output file>]"
        << std::endl;
    return 1;
  }

  if (argc >= 2)
    inFilename = std::string(argv[1]);

  if (argc >= 3)
    outFilename = std::string(argv[2]);

  std::vector<NamedRect> rectangles;

  // Read the rectangles in the file into our list of rectangles.
  std::cout << "Loading rectangles from file: " << inFilename << std::endl;
  if (!readRectanglesFromFile(inFilename, &rectangles)) {
    std::cerr << "Could not open input file: " << inFilename << std::endl;
    return 1;
  }

#if 0
  for (const auto& rect : rectangles)
  std::cout << "Rect: " << rect << std::endl;
#endif  // 0

  std::cout << "Calculating results..." << std::endl;

  // For each rectangle, log the results against each other rectangle.
  ResultsType results;
  for (const auto& first : rectangles) {
    Results* r = getResults(&results, first.name);

    for (const auto& second : rectangles) {
      // We don't test again ourselves.
      if (first.name == second.name)
        continue;

      if (first.rect.overlaps(second.rect))
        r->overlaps.push_back(second.name);
      if (first.rect.contains(second.rect))
        r->contains.push_back(second.name);
      if (second.rect.contains(first.rect))
        r->containedBy.push_back(first.name);
      if (first.rect.touches(second.rect))
        r->touches.push_back(second.name);
    }
  }

  if (outFilename.empty()) {
    std::cout << "Results:" << std::endl;
    printResults(std::cout, results);
  } else {
    std::cout << "Writing output to file: " << outFilename << std::endl;
    std::ofstream outFile(outFilename, std::ios::out);
    if (!outFile.is_open()) {
      std::cerr << "Could not open output file for writing: " << outFilename
          << std::endl;
      return 1;
    }
    printResults(outFile, results);
  }

  return 0;
}
<commit_msg>Check if results are not null.<commit_after>// Rectangles

#include <cassert>
#include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

#include "named_rect.h"

struct Results {
  std::vector<char> overlaps;
  std::vector<char> contains;
  std::vector<char> containedBy;
  std::vector<char> touches;
};

// A structure to store our results in.
using ResultsType = std::unordered_map<char, Results>;

// Get the corresponding Result object for the given rectangle name.
Results* getResults(ResultsType* results, char name) {
  assert(results);
  bool inserted = false;
  auto it = results->find(name);
  if (it == std::end(*results))
    std::tie(it, inserted) = results->insert(std::make_pair(name, Results()));

  return &it->second;
}

// Given a list of rectangle names, print them out in a comma separated line.
void printNames(std::ostream& os, const std::vector<char>& names) {
  if (names.empty()) {
    os << '0';
  } else {
    const size_t size = names.size();
    for (size_t i = 0; i < size; ++i) {
      os << names[i];
      if (i < size - 1)
        os << ',';
    }
  }
  os << std::endl;
}

void printResults(std::ostream& os, const ResultsType& results) {
  for (const auto& it : results) {
    os << it.first << std::endl;
    printNames(os, it.second.overlaps);
    printNames(os, it.second.contains);
    printNames(os, it.second.containedBy);
    printNames(os, it.second.touches);
    os << std::endl;
  }
}

int main(int argc, char* argv[]) {
  std::string inFilename, outFilename;

  if (argc < 2) {
    std::cout << "USAGE: " << argv[0] << " <input file> [<output file>]"
        << std::endl;
    return 1;
  }

  if (argc >= 2)
    inFilename = std::string(argv[1]);

  if (argc >= 3)
    outFilename = std::string(argv[2]);

  std::vector<NamedRect> rectangles;

  // Read the rectangles in the file into our list of rectangles.
  std::cout << "Loading rectangles from file: " << inFilename << std::endl;
  if (!readRectanglesFromFile(inFilename, &rectangles)) {
    std::cerr << "Could not open input file: " << inFilename << std::endl;
    return 1;
  }

#if 0
  for (const auto& rect : rectangles)
  std::cout << "Rect: " << rect << std::endl;
#endif  // 0

  std::cout << "Calculating results..." << std::endl;

  // For each rectangle, log the results against each other rectangle.
  ResultsType results;
  for (const auto& first : rectangles) {
    Results* r = getResults(&results, first.name);

    for (const auto& second : rectangles) {
      // We don't test again ourselves.
      if (first.name == second.name)
        continue;

      if (first.rect.overlaps(second.rect))
        r->overlaps.push_back(second.name);
      if (first.rect.contains(second.rect))
        r->contains.push_back(second.name);
      if (second.rect.contains(first.rect))
        r->containedBy.push_back(first.name);
      if (first.rect.touches(second.rect))
        r->touches.push_back(second.name);
    }
  }

  if (outFilename.empty()) {
    std::cout << "Results:" << std::endl;
    printResults(std::cout, results);
  } else {
    std::cout << "Writing output to file: " << outFilename << std::endl;
    std::ofstream outFile(outFilename, std::ios::out);
    if (!outFile.is_open()) {
      std::cerr << "Could not open output file for writing: " << outFilename
          << std::endl;
      return 1;
    }
    printResults(outFile, results);
  }

  return 0;
}
<|endoftext|>