<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <clocale>
#include <iomanip>
#include <locale>
#include <codecvt>
#include <iomanip>

#pragma execution_character_set("utf-8")

int main(int argc, char *argv[])
{
    std::setlocale(LC_ALL, "Japanese");

    for (int i = 1; i >= 0 ; ++i)
    {
        if (argv[i] == nullptr) break;

        std::string fileName = argv[i];

        std::basic_ofstream<char32_t> ofs;
        ofs.imbue(std::locale(std::locale(""), new std::codecvt_utf8<char32_t>));

        std::basic_ifstream<char32_t> ifs;
        ifs.imbue(std::locale(std::locale(""), new std::codecvt_utf8<char32_t>));

        std::string outFile = argv[i];
        outFile += ".pre";

        ofs.open( "buff" , std::ios::out);
        ifs.open( argv[i] , std::ios::in);

        char32_t wc;

        //Bom削除
        if (ifs.get() < 0x0080 )
        {
            ifs.seekg(0);
        }

        bool StringMode = false;

        while ( !ifs.eof() )
        {
            wc = ifs.get();
            if (ifs.eof()) break;

            if (wc < 0x0080)
            {
                if (wc == 0x0022)
                {
                    //文字リテラル中はそのままにする
                    if (StringMode) StringMode = false;
                    else            StringMode = true;
                }
                ofs.put(wc);
            }
            else if (wc < 0xFFFF)//3バイト
            {
                if (StringMode)
                {
                    ofs.put(wc);
                }
                else {
                    ofs.put('U');
                    ofs.put('C');
                    ofs.put('N');

                    int n = wc / 16 / 16 / 16;
                    if (n < 10) ofs.put(0x30 + n);
                    else        ofs.put(0x41 + n - 10);

                    n = wc / 16 / 16 % 16;
                    if (n < 10) ofs.put(0x30 + n);
                    else        ofs.put(0x41 + n - 10);

                    n = wc / 16 % 16;
                    if (n < 10) ofs.put(0x30 + n);
                    else        ofs.put(0x41 + n - 10);

                    n = wc % 16;
                    if (n < 10) ofs.put(0x30 + n);
                    else        ofs.put(0x41 + n - 10);
                }
            }
        }

        ofs.close();
        ifs.close();

        //WindowsAPI
        rename( fileName.c_str() , outFile.c_str() );
        rename( "buff", fileName.c_str());
    }

    return 0;
}<commit_msg>変更前のファイルの扱いを変更.<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <clocale>
#include <iomanip>
#include <locale>
#include <codecvt>
#include <iomanip>
#include <Windows.h>

#pragma execution_character_set("utf-8")

int main(int argc, char *argv[])
{
	//Windows専用
	CreateDirectoryA("backup",NULL);

    for (int i = 1; i >= 0 ; ++i)
    {
        if (argv[i] == nullptr) break;

        std::string fileName = argv[i];

        std::basic_ofstream<char32_t> ofs;
        ofs.imbue(std::locale(std::locale(""), new std::codecvt_utf8<char32_t>));

        std::basic_ifstream<char32_t> ifs;
        ifs.imbue(std::locale(std::locale(""), new std::codecvt_utf8<char32_t>));

		std::string outFile = argv[i];
		int num = outFile.find_last_of('\\');
		outFile.insert(num, "\\backup");

		ofs.open( "buff" , std::ios::out);
        ifs.open( argv[i] , std::ios::in);

        char32_t wc;

        //Bom削除
        if (ifs.get() < 0x0080 )
        {
            ifs.seekg(0);
        }

        bool StringMode = false;

        while ( !ifs.eof() )
        {
            wc = ifs.get();
            if (ifs.eof()) break;

            if (wc < 0x0080)
            {
                if (wc == 0x0022)
                {
                    //文字リテラル中はそのままにする
                    if (StringMode) StringMode = false;
                    else            StringMode = true;
                }
                ofs.put(wc);
            }
            else if (wc < 0xFFFF)//3バイト
            {
                if (StringMode)
                {
                    ofs.put(wc);
                }
                else {
                    ofs.put('U');
                    ofs.put('C');
                    ofs.put('N');

                    int n = wc / 16 / 16 / 16;
                    if (n < 10) ofs.put(0x30 + n);
                    else        ofs.put(0x41 + n - 10);

                    n = wc / 16 / 16 % 16;
                    if (n < 10) ofs.put(0x30 + n);
                    else        ofs.put(0x41 + n - 10);

                    n = wc / 16 % 16;
                    if (n < 10) ofs.put(0x30 + n);
                    else        ofs.put(0x41 + n - 10);

                    n = wc % 16;
                    if (n < 10) ofs.put(0x30 + n);
                    else        ofs.put(0x41 + n - 10);
                }
            }
        }

        ofs.close();
        ifs.close();

        //環境依存？
		//元ファイルをbackupフォルダに移動
        rename( fileName.c_str() , outFile.c_str() );
		rename("buff", fileName.c_str());
    }

    return 0;
}<|endoftext|>


<commit_before>d8acfb6c-35ca-11e5-a5ac-6c40088e03e4<commit_msg>Final commit :sunglasses:<commit_after>#include <iostream>
int main()
{
  std::cout << "Hello World!" << std::endl;
  return 0;
}
<|endoftext|>


<commit_before>c08d152e-ad5c-11e7-a03a-ac87a332f658<commit_msg>lets try again<commit_after>c123f968-ad5c-11e7-a022-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>
#include "matrix.hpp"

int main() {
    std::vector<double> vector1{2, 1, 1, 0, 4, 3, 3, 1, 8,7,9,5, 6,7,9,8};
    std::vector<double> vector2{1, 1, -1, 3};

    matrix<double, 4, 4> m1{2, 1, 1, 0, 4, 3, 3, 1, 8,7,9,5, 6,7,9,8};
    nvector<double, 4> b{1, 1, -1, 3};

    std::cout << "Information about A:" << std::endl;
    auto data = m1.data();
    for (auto i = data.begin(); i != data.end(); ++i) {
        std::cout << *i << " ";
    }
    std::cout << std::endl;

    std::cout << "Information about b:" << std::endl;
    std::cout << "b has " << b.size() << " rows" << std::endl;
    for (auto i = b.begin(); i != b.end(); ++i) {
        std::cout << *i << " ";
    }
    std::cout << std::endl;

    auto x = gaussian_no_pivoting(m1, b);
    auto y = gaussian_partial_pivoting(m1, b);

    std::cout << "x is: (" << x[0] << ", " << x[1] << ", " << x[2] << ", " << x[3] << ")" << std::endl;
    std::cout << "y is: (" << y[0] << ", " << y[1] << ", " << y[2] << ", " << y[3] << ")" << std::endl;
}<commit_msg>Had to change the template classes because we need to instantiate matrices of different sizes at runtime (random matrices).<commit_after>#include <iostream>
#include "matrix.hpp"

int main() {
    std::vector<double> vector1{2, 1, 1, 0, 4, 3, 3, 1, 8,7,9,5, 6,7,9,8};
    std::vector<double> vector2{1, 1, -1, 3};

    matrix<double> m1(4, 4, {2, 1, 1, 0, 4, 3, 3, 1, 8,7,9,5, 6,7,9,8});
    nvector<double> b(4, {1, 1, -1, 3});

    std::cout << "Information about A:" << std::endl;
    auto data = m1.data();
    for (auto i = data.begin(); i != data.end(); ++i) {
        std::cout << *i << " ";
    }
    std::cout << std::endl;

    std::cout << "Information about b:" << std::endl;
    std::cout << "b has " << b.size() << " rows" << std::endl;
    for (auto i = b.begin(); i != b.end(); ++i) {
        std::cout << *i << " ";
    }
    std::cout << std::endl;

    auto x = gaussian_no_pivoting(m1, b);
    auto y = gaussian_partial_pivoting(m1, b);

    std::cout << "x is: (" << x[0] << ", " << x[1] << ", " << x[2] << ", " << x[3] << ")" << std::endl;
    std::cout << "y is: (" << y[0] << ", " << y[1] << ", " << y[2] << ", " << y[3] << ")" << std::endl;
}<|endoftext|>


<commit_before>#include <iostream>

int main() {
  std::cout << "Hello, world. " << std::endl;
  return 0;
}
<commit_msg> * Changed to exclamation mark<commit_after>#include <iostream>

int main() {
  std::cout << "Hello, world! " << std::endl;
  return 0;
}
<|endoftext|>


<commit_before>9771c921-2747-11e6-8c5a-e0f84713e7b8<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>97827f7d-2747-11e6-8556-e0f84713e7b8<|endoftext|>


<commit_before>115a6cc0-ad5d-11e7-b866-ac87a332f658<commit_msg>roselyn broke it<commit_after>11cc02eb-ad5d-11e7-8627-ac87a332f658<|endoftext|>


<commit_before>8dd25711-ad59-11e7-a8b1-ac87a332f658<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>8e6e3f38-ad59-11e7-85fe-ac87a332f658<|endoftext|>


<commit_before>// Demolition Man Verbal Morality Statute Monitor
// Created by Tony DiCola (tony@tonydicola.com)
// Released under an MIT license (http://opensource.org/licenses/MIT).

// Main application.

#include <algorithm>
#include <csignal>
#include <cstdint>
#include <stdexcept>
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>

#include <wiringPi.h>

#include "Adafruit_Thermal.h"
#include "AlsaError.h"
#include "AlsaSink.h"
#include "AlsaSource.h"
#include "DemoManMonitor.h"
#include "PocketSphinxKWS.h"

using namespace std;

#define ALARM_FILE		"alarm_movie_padded.raw"
#define RECORD_HW		"plughw:0,0"
#define PLAYBACK_HW		"plughw:1,0"
#define KEYWORD_FILE	"keywords.txt"
#define PRINTER_PORT	"/dev/ttyAMA0"
#define QUIET_PIN		0

bool shouldRun = true;

void setQuietMode(DemoManMonitor& monitor, bool quietMode) {
	monitor.setQuietMode(quietMode);
	if (quietMode) {
		cout << "Quiet mode enabled." << endl;
	}
	else {
		cout << "Quiet mode disabled." << endl;
	}
}

int main(int argc, char* argv[]) {
	try {
		cout << "Demolition Man Verbal Morality Statute Monitor" << endl;
		cout << "Loading..." << endl;

		// Signal handler to catch ctrl-c in the main loop and shut down gracefully (i.e. call destructors).
		signal(SIGINT, [](int param){ shouldRun = false; });

		// Initialize wiringPi library and quiet switch input.
		wiringPiSetup () ;
		pinMode(QUIET_PIN, INPUT);
		bool quietSwitch = (digitalRead(QUIET_PIN) == HIGH);

		// Initialize printer.
		Adafruit_Thermal printer(PRINTER_PORT);
		printer.begin();

		// Load alarm raw audio.
		ifstream input(ALARM_FILE, ios::in | ios::binary);
		input.seekg (0, input.end);
		size_t length = input.tellg();
		input.seekg (0, input.beg);
		vector<uint8_t> alarm(length);
		input.read((char*)alarm.data(), length);

		// Initialize audio sink and source.
		AlsaSink sink;
		sink.open(PLAYBACK_HW, 44100, 1, SND_PCM_FORMAT_S16_LE);
		AlsaSource source;
		source.open(RECORD_HW, 16000, 1, SND_PCM_FORMAT_S16_LE);

		// Initialize keyword spotter.
		PocketSphinxKWS spotter;
		spotter.initialize(PocketSphinxKWS::parseConfig(argc, argv), KEYWORD_FILE);

		// Initialize main logic.
		DemoManMonitor monitor(8000, &printer, &source, &sink, &spotter, &alarm);
		setQuietMode(monitor, quietSwitch);

		cout << "Listening... (press Ctrl-C to stop)" << endl;

		while (shouldRun) {
			// Check quite mode switch and update state.
			bool newQuietSwitch = (digitalRead(QUIET_PIN) == HIGH);
			if (newQuietSwitch != quietSwitch) {
				quietSwitch = newQuietSwitch;
				setQuietMode(monitor, quietSwitch);
			}
			// Update main logic state.
			monitor.update();
		}
	}
	catch (AlsaError ex) {
		cerr << "ALSA ERROR " << ex.message << " (" << ex.code << ") while calling: " << ex.what() << endl;
		return 1;
	}
	catch (exception ex) {
		cerr << "ERROR: " << ex.what() << endl;
		return 1;
	}

	return 0;
}
<commit_msg>LED test<commit_after>// Demolition Man Verbal Morality Statute Monitor
// Created by Tony DiCola (tony@tonydicola.com)
// Released under an MIT license (http://opensource.org/licenses/MIT).

// Main application.

#include <algorithm>
#include <csignal>
#include <cstdint>
#include <stdexcept>
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>

#include <wiringPi.h>

#include "Adafruit_Thermal.h"
#include "AlsaError.h"
#include "AlsaSink.h"
#include "AlsaSource.h"
#include "DemoManMonitor.h"
#include "PocketSphinxKWS.h"

using namespace std;

#define ALARM_FILE		"alarm_movie_padded.raw"
#define RECORD_HW		"plughw:0,0"
#define PLAYBACK_HW		"plughw:1,0"
#define KEYWORD_FILE	"keywords.txt"
#define PRINTER_PORT	"/dev/ttyAMA0"
#define QUIET_PIN		0
#define LED_PIN			4

bool shouldRun = true;

void setQuietMode(DemoManMonitor& monitor, bool quietMode) {
	monitor.setQuietMode(quietMode);
	if (quietMode) {
		cout << "Quiet mode enabled." << endl;
	}
	else {
		cout << "Quiet mode disabled." << endl;
	}
}

int main(int argc, char* argv[]) {
	try {
		cout << "Demolition Man Verbal Morality Statute Monitor" << endl;
		cout << "Loading..." << endl;

		// Signal handler to catch ctrl-c in the main loop and shut down gracefully (i.e. call destructors).
		signal(SIGINT, [](int param){ shouldRun = false; });

		// Initialize wiringPi library and quiet switch input.
		wiringPiSetup () ;
		pinMode(QUIET_PIN, INPUT);
		bool quietSwitch = (digitalRead(QUIET_PIN) == HIGH);

		pinMode(LED_PIN, OUTPUT);
		digitalWrite(LED_PIN, HIGH);

		// Initialize printer.
		Adafruit_Thermal printer(PRINTER_PORT);
		printer.begin();

		// Load alarm raw audio.
		ifstream input(ALARM_FILE, ios::in | ios::binary);
		input.seekg (0, input.end);
		size_t length = input.tellg();
		input.seekg (0, input.beg);
		vector<uint8_t> alarm(length);
		input.read((char*)alarm.data(), length);

		// Initialize audio sink and source.
		AlsaSink sink;
		sink.open(PLAYBACK_HW, 44100, 1, SND_PCM_FORMAT_S16_LE);
		AlsaSource source;
		source.open(RECORD_HW, 16000, 1, SND_PCM_FORMAT_S16_LE);

		// Initialize keyword spotter.
		PocketSphinxKWS spotter;
		spotter.initialize(PocketSphinxKWS::parseConfig(argc, argv), KEYWORD_FILE);

		// Initialize main logic.
		DemoManMonitor monitor(8000, &printer, &source, &sink, &spotter, &alarm);
		setQuietMode(monitor, quietSwitch);

		cout << "Listening... (press Ctrl-C to stop)" << endl;

		while (shouldRun) {
			// Check quite mode switch and update state.
			bool newQuietSwitch = (digitalRead(QUIET_PIN) == HIGH);
			if (newQuietSwitch != quietSwitch) {
				quietSwitch = newQuietSwitch;
				setQuietMode(monitor, quietSwitch);
			}
			// Update main logic state.
			monitor.update();
		}

		digitalWrite(LED_PIN, LOW);
	}
	catch (AlsaError ex) {
		cerr << "ALSA ERROR " << ex.message << " (" << ex.code << ") while calling: " << ex.what() << endl;
		return 1;
	}
	catch (exception ex) {
		cerr << "ERROR: " << ex.what() << endl;
		return 1;
	}

	return 0;
}
<|endoftext|>


<commit_before>b73bf5e1-4b02-11e5-9ea9-28cfe9171a43<commit_msg>Tuesday, turns out it was tuesday<commit_after>b748a380-4b02-11e5-911f-28cfe9171a43<|endoftext|>


<commit_before>/*Published under The MIT License (MIT)
See LICENSE*/

// Christopher Hernandez

#include <iostream>
#include <cstdlib>
#include <ctime>
#include "colony.h"

int _length;
int _width;
int _gens;

double calculateAvgTime(double** times) {
  double total = 0;
  for(int j = 0; j < _length; j++) {
 		for(int i = 0; i < _width; i++) {
      total += times[j][i]; // add up all times
    }
  }
  return total / (_length * _width); // sum / n = avg
}

int main(int argc, char** argv) {
  clock_t begin = clock();

  _length = atoi(argv[1]);
  _width = atoi(argv[2]);
  _gens = atoi(argv[3]);
  bool print = true;
  if (argv[4]) { // if 4th parameter exists don't print
    if (std::strncmp(argv[4],"--no-print", 10) == 0) {
      print = false;
    }
  }
  // Create colony
  Colony c(_length, _width, _gens);

  for (int i = 0; i < _gens; i++) {
    if (print) {
      system("clear"); // clear console
      c.printGrid();
      c.evolve();
      system("sleep .1"); // give console time to catch up
    } else {
      c.evolve();
    }
  }

  clock_t end = clock(); // end gen time
  double elapsed = double(end - begin) /  CLOCKS_PER_SEC;
  std::cout << "Average timestep: " << calculateAvgTime(c.getTimes()) << std::endl;
  std::cout << "Total Time: " << elapsed << std::endl;
  return 0;
}
<commit_msg>strncmp not part of std lib<commit_after>/*Published under The MIT License (MIT)
See LICENSE*/

// Christopher Hernandez

#include <iostream>
#include <cstdlib>
#include <ctime>
#include "colony.h"

int _length;
int _width;
int _gens;

double calculateAvgTime(double** times) {
  double total = 0;
  for(int j = 0; j < _length; j++) {
 		for(int i = 0; i < _width; i++) {
      total += times[j][i]; // add up all times
    }
  }
  return total / (_length * _width); // sum / n = avg
}

int main(int argc, char** argv) {
  clock_t begin = clock();

  _length = atoi(argv[1]);
  _width = atoi(argv[2]);
  _gens = atoi(argv[3]);
  bool print = true;
  if (argv[4]) { // if 4th parameter exists don't print
    if (strncmp(argv[4],"--no-print", 10) == 0) {
      print = false;
    }
  }
  // Create colony
  Colony c(_length, _width, _gens);

  for (int i = 0; i < _gens; i++) {
    if (print) {
      system("clear"); // clear console
      c.printGrid();
      c.evolve();
      system("sleep .1"); // give console time to catch up
    } else {
      c.evolve();
    }
  }

  clock_t end = clock(); // end gen time
  double elapsed = double(end - begin) /  CLOCKS_PER_SEC;
  std::cout << "Average timestep: " << calculateAvgTime(c.getTimes()) << std::endl;
  std::cout << "Total Time: " << elapsed << std::endl;
  return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#include    "../StroikaPreComp.h"

#include    <thread>

#if     qPlatform_POSIX
#include    <unistd.h>
#include    <fstream>
#elif   qPlatform_Windows
#include    <Windows.h>
#endif

#include    "../Characters/SDKString.h"
#include    "../Characters/Format.h"
#include    "../Characters/String_Constant.h"
#include    "../Characters/String2Int.h"
#include    "../Containers/Set.h"
#if     qPlatform_POSIX
#include    "../Execution/ErrNoException.h"
#elif   qPlatform_Windows
#include    "../Execution/Platform/Windows/Exception.h"
#endif
#include    "../Memory/SmallStackBuffer.h"
#include    "../IO/FileSystem/BinaryFileInputStream.h"
#include    "../Streams/BasicBinaryInputOutputStream.h"
#include    "../Streams/TextInputStreamBinaryAdapter.h"

#include    "SystemConfiguration.h"

#if     qPlatform_POSIX
#include    "../DataExchange/INI/Reader.h"
#include    "../Execution/ProcessRunner.h"
#include    "../Streams/iostream/FStreamSupport.h"
#endif

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Configuration;
using   namespace   Stroika::Foundation::Containers;
using   namespace   Stroika::Foundation::Streams;

using   Characters::String_Constant;
using   Characters::SDKChar;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

/*
 ********************************************************************************
 ***************** Configuration::SystemConfiguration::CPU **********************
 ********************************************************************************
 */
unsigned int    SystemConfiguration::CPU::GetNumberOfSockets () const
{
    Set<unsigned int>   socketIds;
    for (auto i : fCores) {
        socketIds.Add (i.fSocketID);
    }
    return static_cast<unsigned int> (socketIds.size ());
}

/*
 ********************************************************************************
 *************** Configuration::GetSystemConfiguration_CPU **********************
 ********************************************************************************
 */
SystemConfiguration::CPU Configuration::GetSystemConfiguration_CPU ()
{
    using CPU = SystemConfiguration::CPU;
    CPU result;

#if     qPlatform_POSIX
    {
        using   Streams::TextInputStreamBinaryAdapter;
        using   IO::FileSystem::BinaryFileInputStream;
        using   Characters::String2Int;
        const   String_Constant kProcCPUInfoFileName_ { L"/proc/cpuinfo" };

        CPU::CoreDetails    coreDetails;
        // Note - /procfs files always unseekable
        for (String line : TextInputStreamBinaryAdapter (BinaryFileInputStream::mk (kProcCPUInfoFileName_, BinaryFileInputStream::eNotSeekable)).ReadLines ()) {
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
            DbgTrace (L"***in Configuration::GetSystemConfiguration_CPU capture_ line=%s", line.c_str ());
#endif
            static  const   String_Constant kModelNameLabel_ { L"model name	: " };
            //static    const   String_Constant kProcessorIDLabel_ { L"processor    : " };
            static  const   String_Constant kSocketIDLabel_ { L"physical id	: " };          // a bit of a guess?
            if (line.StartsWith (kModelNameLabel_)) {
                coreDetails.fModelName = line.SubString (kModelNameLabel_.length ()).Trim ();
            }
            else if (line.StartsWith (kSocketIDLabel_)) {
                unsigned int socketID = String2Int<unsigned int> (line.SubString (kSocketIDLabel_.length ()).Trim ());
                coreDetails.fSocketID = socketID;
            }
            if (line.Trim ().empty ()) {
                // ends each socket
                result.fCores.Append (coreDetails);
                coreDetails = CPU::CoreDetails ();
            }
        }
        if (coreDetails.fSocketID != 0 or not coreDetails.fModelName.empty ()) {
            result.fCores.Append (coreDetails);
        }
    }
#elif   qPlatform_Windows
    SYSTEM_INFO sysInfo;        // GetNativeSystemInfo cannot fail so no need to initialize data
    ::GetNativeSystemInfo (&sysInfo);
    //unclear if this is count of logical or physical cores, or how to compute the other.
    //@todo - fix as above for POSIX... maybe ask Sterl? But for now KISS
    //
    // Can use https://msdn.microsoft.com/en-us/library/hskdteyh%28v=vs.90%29.aspx?f=255&MSPPError=-2147217396
    //  __cpuid
    // to find this information (at least modelname string.
    //
    for (DWORD i = 0; i < sysInfo.dwNumberOfProcessors; ++i) {
        result.fCores.Append (CPU::CoreDetails ());
    }
#endif

    return result;
}

/*
 ********************************************************************************
 ************** Configuration::GetSystemConfiguration_Memory ********************
 ********************************************************************************
 */
SystemConfiguration::Memory Configuration::GetSystemConfiguration_Memory ()
{
    using   Memory = SystemConfiguration::Memory;
    Memory  result;
#if     qPlatform_POSIX
    result.fPageSize = ::sysconf (_SC_PAGESIZE);
    result.fTotalPhysicalRAM = ::sysconf (_SC_PHYS_PAGES) * result.fPageSize;
#elif   qPlatform_Windows
    SYSTEM_INFO sysInfo;
    ::GetNativeSystemInfo (&sysInfo);
    result.fPageSize = sysInfo.dwPageSize;

    MEMORYSTATUSEX memStatus;
    memStatus.dwLength = sizeof (memStatus);
    Verify (::GlobalMemoryStatusEx (&memStatus));
    result.fTotalPhysicalRAM = memStatus.ullTotalPhys;
    result.fTotalVirtualRAM = memStatus.ullTotalVirtual;
#endif
    return result;
}

/*
 ********************************************************************************
 ******** Configuration::GetSystemConfiguration_OperatingSystem *****************
 ********************************************************************************
 */
SystemConfiguration::OperatingSystem    Configuration::GetSystemConfiguration_OperatingSystem ()
{
    using   OperatingSystem =   SystemConfiguration::OperatingSystem;
    static  const   OperatingSystem    kCachedResult_ = []() ->OperatingSystem {
        OperatingSystem    tmp;
#if     qPlatform_POSIX
        tmp.fTokenName = String_Constant (L"Unix");
        try {
            tmp.fTokenName = Execution::ProcessRunner (L"uname").Run (String ()).Trim ();
        }
        catch (...)
        {
            DbgTrace ("Failure running uname");
        }
        try {
            ifstream s;
            Streams::iostream::OpenInputFileStream (&s, L"/etc/os-release");
            DataExchange::INI::Profile p = DataExchange::INI::Reader ().ReadProfile (s);
            tmp.fShortPrettyName = p.fUnnamedSection.fProperties.LookupValue (L"NAME");
            tmp.fPrettyNameWithMajorVersion = p.fUnnamedSection.fProperties.LookupValue (L"PRETTY_NAME");
        }
        catch (...)
        {
            DbgTrace ("Failure reading /etc/os-release");
        }
        if (tmp.fShortPrettyName.empty ())
        {
            tmp.fShortPrettyName = tmp.fTokenName;
        }
        if (tmp.fPrettyNameWithMajorVersion.empty ())
        {
            tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;
        }
        if (tmp.fRFC1945CompatProductTokenWithVersion.empty ())
        {
            tmp.fRFC1945CompatProductTokenWithVersion = tmp.fShortPrettyName.Trim ().ReplaceAll (L" ", L"-");
            if (not tmp.fMajorMinorVersionString.empty ()) {
                tmp.fRFC1945CompatProductTokenWithVersion += L"/" + tmp.fMajorMinorVersionString;
            }
        }
        //
        // @todo FIX/FIND BETTER WAY!
        //
        //http://docs.oracle.com/cd/E36784_01/html/E36874/sysconf-3c.html
        // Quite uncertain - this is not a good reference
        //      --LGP 2014-10-18
        //
        tmp.fBits = ::sysconf (_SC_V6_LP64_OFF64) == _POSIX_V6_LP64_OFF64 ? 64 : 32;
#elif   qPlatform_Windows
        tmp.fTokenName = String_Constant (L"Windows");
        /*
         *  Microslop declares this deprecated, but then fails to provide a reasonable alternative.
         *
         *  Sigh.
         *
         *  http://msdn.microsoft.com/en-us/library/windows/desktop/ms724429(v=vs.85).aspx -  GetFileVersionInfo (kernel32.dll)
         *  is a painful, and stupid alternative.
         */
        DISABLE_COMPILER_MSC_WARNING_START(4996)
        OSVERSIONINFOEX   osvi;
        memset(&osvi, 0, sizeof (osvi));
        osvi.dwOSVersionInfoSize = sizeof (osvi);
        Verify (::GetVersionEx (reinterpret_cast<LPOSVERSIONINFO> (&osvi)));
        DISABLE_COMPILER_MSC_WARNING_END(4996)
        if (osvi.dwMajorVersion == 6)
        {
            if (osvi.dwMinorVersion == 0) {
                tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows Vista") : String_Constant (L"Windows Server 2008");
            }
            else if (osvi.dwMinorVersion == 1) {
                tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows 7") : String_Constant (L"Windows Server 2008 R2");
            }
            else if (osvi.dwMinorVersion == 2) {
                tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows 8") : String_Constant (L"Windows Server 2012");
            }
            else if (osvi.dwMinorVersion == 3) {
                if (osvi.wProductType == VER_NT_WORKSTATION)
                    tmp.fShortPrettyName = String_Constant (L"Windows 8.1");
            }
        }
        if (tmp.fShortPrettyName.empty ())
        {
            tmp.fShortPrettyName = Characters::Format (L"Windows %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
        }
        tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;
        tmp.fMajorMinorVersionString = Characters::Format (L"%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
        tmp.fRFC1945CompatProductTokenWithVersion = Characters::Format (L"Windows/%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
        if (sizeof (void*) == 4)
        {
            tmp.fBits = 32;
            //IsWow64Process is not available on all supported versions of Windows.
            //Use GetModuleHandle to get a handle to the DLL that contains the function
            //and GetProcAddress to get a pointer to the function if available.
            typedef BOOL (WINAPI * LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
            LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
            if(NULL != fnIsWow64Process) {
                BOOL    isWOW64 = false;
                (void)fnIsWow64Process (GetCurrentProcess(), &isWOW64);
                if (isWOW64) {
                    tmp.fBits = 64;
                }
            }
        }
        else {
            // In windows, a 64 bit app cannot run on 32-bit windows
            Assert (sizeof (void*) == 8);
            tmp.fBits = 64;
        }
#else
        AssertNotImplemented ();
#endif
        return tmp;
    } ();
    return kCachedResult_;
}

/*
 ********************************************************************************
 ***************** GetSystemConfiguration_ComputerNames *************************
 ********************************************************************************
 */
#if     0 && qPlatform_POSIX
// ALTERNATE APPROACH TO CONSIDER
string  name;
{
    struct addrinfo* res;
    struct addrinfo hints;
    memset(&hints, '\0', sizeof(hints));
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_CANONNAME;
    int e = getaddrinfo(nullptr, nullptr, &hints, &res);
    if (e != 0) {
        //printf("failure %s\n", gai_strerror (e));
        return String ();
    }
    int sock = -1;
    for (struct addrinfo* r = res; r != NULL; r = r->ai_next) {
        name = r->ai_canonname ;
        break;
    }
    freeaddrinfo(res);
}
return String::FromSDKString (name);
#endif
SystemConfiguration::ComputerNames Configuration::GetSystemConfiguration_ComputerNames ()
{
    using ComputerNames = SystemConfiguration::ComputerNames;
    ComputerNames   result;
#if     qPlatform_POSIX
    char    nameBuf[1024];
    Execution::ThrowErrNoIfNegative (gethostname (nameBuf, NEltsOf (nameBuf)));
    nameBuf[NEltsOf (nameBuf) - 1] = '\0';  // http://linux.die.net/man/2/gethostname says not necessarily nul-terminated
    result.fHostname = String::FromNarrowSDKString (nameBuf);
#elif   qPlatform_Windows
    constexpr   COMPUTER_NAME_FORMAT    kUseNameFormat_ = ComputerNameNetBIOS;  // total WAG -- LGP 2014-10-10
    DWORD   dwSize = 0;
    (void) ::GetComputerNameEx (kUseNameFormat_, nullptr, &dwSize);
    Memory::SmallStackBuffer<SDKChar> buf(dwSize);
    Execution::Platform::Windows::ThrowIfFalseGetLastError (::GetComputerNameEx (kUseNameFormat_, buf, &dwSize));
    result.fHostname = String::FromSDKString (buf);
#else
    AssertNotImplemented ();
#endif
    return result;
}

/*
 ********************************************************************************
 ****************** SystemConfiguration GetSystemConfiguration ******************
 ********************************************************************************
 */
inline  SystemConfiguration GetSystemConfiguration ()
{
    return SystemConfiguration {
        GetSystemConfiguration_CPU (),
        GetSystemConfiguration_Memory (),
        GetSystemConfiguration_OperatingSystem (),
        GetSystemConfiguration_ComputerNames ()
    };
}
<commit_msg>fixed missing namespace in definition<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#include    "../StroikaPreComp.h"

#include    <thread>

#if     qPlatform_POSIX
#include    <unistd.h>
#include    <fstream>
#elif   qPlatform_Windows
#include    <Windows.h>
#endif

#include    "../Characters/SDKString.h"
#include    "../Characters/Format.h"
#include    "../Characters/String_Constant.h"
#include    "../Characters/String2Int.h"
#include    "../Containers/Set.h"
#if     qPlatform_POSIX
#include    "../Execution/ErrNoException.h"
#elif   qPlatform_Windows
#include    "../Execution/Platform/Windows/Exception.h"
#endif
#include    "../Memory/SmallStackBuffer.h"
#include    "../IO/FileSystem/BinaryFileInputStream.h"
#include    "../Streams/BasicBinaryInputOutputStream.h"
#include    "../Streams/TextInputStreamBinaryAdapter.h"

#include    "SystemConfiguration.h"

#if     qPlatform_POSIX
#include    "../DataExchange/INI/Reader.h"
#include    "../Execution/ProcessRunner.h"
#include    "../Streams/iostream/FStreamSupport.h"
#endif

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Configuration;
using   namespace   Stroika::Foundation::Containers;
using   namespace   Stroika::Foundation::Streams;

using   Characters::String_Constant;
using   Characters::SDKChar;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

/*
 ********************************************************************************
 ***************** Configuration::SystemConfiguration::CPU **********************
 ********************************************************************************
 */
unsigned int    SystemConfiguration::CPU::GetNumberOfSockets () const
{
    Set<unsigned int>   socketIds;
    for (auto i : fCores) {
        socketIds.Add (i.fSocketID);
    }
    return static_cast<unsigned int> (socketIds.size ());
}

/*
 ********************************************************************************
 *************** Configuration::GetSystemConfiguration_CPU **********************
 ********************************************************************************
 */
SystemConfiguration::CPU Configuration::GetSystemConfiguration_CPU ()
{
    using CPU = SystemConfiguration::CPU;
    CPU result;

#if     qPlatform_POSIX
    {
        using   Streams::TextInputStreamBinaryAdapter;
        using   IO::FileSystem::BinaryFileInputStream;
        using   Characters::String2Int;
        const   String_Constant kProcCPUInfoFileName_ { L"/proc/cpuinfo" };

        CPU::CoreDetails    coreDetails;
        // Note - /procfs files always unseekable
        for (String line : TextInputStreamBinaryAdapter (BinaryFileInputStream::mk (kProcCPUInfoFileName_, BinaryFileInputStream::eNotSeekable)).ReadLines ()) {
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
            DbgTrace (L"***in Configuration::GetSystemConfiguration_CPU capture_ line=%s", line.c_str ());
#endif
            static  const   String_Constant kModelNameLabel_ { L"model name	: " };
            //static    const   String_Constant kProcessorIDLabel_ { L"processor    : " };
            static  const   String_Constant kSocketIDLabel_ { L"physical id	: " };          // a bit of a guess?
            if (line.StartsWith (kModelNameLabel_)) {
                coreDetails.fModelName = line.SubString (kModelNameLabel_.length ()).Trim ();
            }
            else if (line.StartsWith (kSocketIDLabel_)) {
                unsigned int socketID = String2Int<unsigned int> (line.SubString (kSocketIDLabel_.length ()).Trim ());
                coreDetails.fSocketID = socketID;
            }
            if (line.Trim ().empty ()) {
                // ends each socket
                result.fCores.Append (coreDetails);
                coreDetails = CPU::CoreDetails ();
            }
        }
        if (coreDetails.fSocketID != 0 or not coreDetails.fModelName.empty ()) {
            result.fCores.Append (coreDetails);
        }
    }
#elif   qPlatform_Windows
    SYSTEM_INFO sysInfo;        // GetNativeSystemInfo cannot fail so no need to initialize data
    ::GetNativeSystemInfo (&sysInfo);
    //unclear if this is count of logical or physical cores, or how to compute the other.
    //@todo - fix as above for POSIX... maybe ask Sterl? But for now KISS
    //
    // Can use https://msdn.microsoft.com/en-us/library/hskdteyh%28v=vs.90%29.aspx?f=255&MSPPError=-2147217396
    //  __cpuid
    // to find this information (at least modelname string.
    //
    for (DWORD i = 0; i < sysInfo.dwNumberOfProcessors; ++i) {
        result.fCores.Append (CPU::CoreDetails ());
    }
#endif

    return result;
}

/*
 ********************************************************************************
 ************** Configuration::GetSystemConfiguration_Memory ********************
 ********************************************************************************
 */
SystemConfiguration::Memory Configuration::GetSystemConfiguration_Memory ()
{
    using   Memory = SystemConfiguration::Memory;
    Memory  result;
#if     qPlatform_POSIX
    result.fPageSize = ::sysconf (_SC_PAGESIZE);
    result.fTotalPhysicalRAM = ::sysconf (_SC_PHYS_PAGES) * result.fPageSize;
#elif   qPlatform_Windows
    SYSTEM_INFO sysInfo;
    ::GetNativeSystemInfo (&sysInfo);
    result.fPageSize = sysInfo.dwPageSize;

    MEMORYSTATUSEX memStatus;
    memStatus.dwLength = sizeof (memStatus);
    Verify (::GlobalMemoryStatusEx (&memStatus));
    result.fTotalPhysicalRAM = memStatus.ullTotalPhys;
    result.fTotalVirtualRAM = memStatus.ullTotalVirtual;
#endif
    return result;
}

/*
 ********************************************************************************
 ******** Configuration::GetSystemConfiguration_OperatingSystem *****************
 ********************************************************************************
 */
SystemConfiguration::OperatingSystem    Configuration::GetSystemConfiguration_OperatingSystem ()
{
    using   OperatingSystem =   SystemConfiguration::OperatingSystem;
    static  const   OperatingSystem    kCachedResult_ = []() ->OperatingSystem {
        OperatingSystem    tmp;
#if     qPlatform_POSIX
        tmp.fTokenName = String_Constant (L"Unix");
        try {
            tmp.fTokenName = Execution::ProcessRunner (L"uname").Run (String ()).Trim ();
        }
        catch (...)
        {
            DbgTrace ("Failure running uname");
        }
        try {
            ifstream s;
            Streams::iostream::OpenInputFileStream (&s, L"/etc/os-release");
            DataExchange::INI::Profile p = DataExchange::INI::Reader ().ReadProfile (s);
            tmp.fShortPrettyName = p.fUnnamedSection.fProperties.LookupValue (L"NAME");
            tmp.fPrettyNameWithMajorVersion = p.fUnnamedSection.fProperties.LookupValue (L"PRETTY_NAME");
        }
        catch (...)
        {
            DbgTrace ("Failure reading /etc/os-release");
        }
        if (tmp.fShortPrettyName.empty ())
        {
            tmp.fShortPrettyName = tmp.fTokenName;
        }
        if (tmp.fPrettyNameWithMajorVersion.empty ())
        {
            tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;
        }
        if (tmp.fRFC1945CompatProductTokenWithVersion.empty ())
        {
            tmp.fRFC1945CompatProductTokenWithVersion = tmp.fShortPrettyName.Trim ().ReplaceAll (L" ", L"-");
            if (not tmp.fMajorMinorVersionString.empty ()) {
                tmp.fRFC1945CompatProductTokenWithVersion += L"/" + tmp.fMajorMinorVersionString;
            }
        }
        //
        // @todo FIX/FIND BETTER WAY!
        //
        //http://docs.oracle.com/cd/E36784_01/html/E36874/sysconf-3c.html
        // Quite uncertain - this is not a good reference
        //      --LGP 2014-10-18
        //
        tmp.fBits = ::sysconf (_SC_V6_LP64_OFF64) == _POSIX_V6_LP64_OFF64 ? 64 : 32;
#elif   qPlatform_Windows
        tmp.fTokenName = String_Constant (L"Windows");
        /*
         *  Microslop declares this deprecated, but then fails to provide a reasonable alternative.
         *
         *  Sigh.
         *
         *  http://msdn.microsoft.com/en-us/library/windows/desktop/ms724429(v=vs.85).aspx -  GetFileVersionInfo (kernel32.dll)
         *  is a painful, and stupid alternative.
         */
        DISABLE_COMPILER_MSC_WARNING_START(4996)
        OSVERSIONINFOEX   osvi;
        memset(&osvi, 0, sizeof (osvi));
        osvi.dwOSVersionInfoSize = sizeof (osvi);
        Verify (::GetVersionEx (reinterpret_cast<LPOSVERSIONINFO> (&osvi)));
        DISABLE_COMPILER_MSC_WARNING_END(4996)
        if (osvi.dwMajorVersion == 6)
        {
            if (osvi.dwMinorVersion == 0) {
                tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows Vista") : String_Constant (L"Windows Server 2008");
            }
            else if (osvi.dwMinorVersion == 1) {
                tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows 7") : String_Constant (L"Windows Server 2008 R2");
            }
            else if (osvi.dwMinorVersion == 2) {
                tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L"Windows 8") : String_Constant (L"Windows Server 2012");
            }
            else if (osvi.dwMinorVersion == 3) {
                if (osvi.wProductType == VER_NT_WORKSTATION)
                    tmp.fShortPrettyName = String_Constant (L"Windows 8.1");
            }
        }
        if (tmp.fShortPrettyName.empty ())
        {
            tmp.fShortPrettyName = Characters::Format (L"Windows %d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
        }
        tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;
        tmp.fMajorMinorVersionString = Characters::Format (L"%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
        tmp.fRFC1945CompatProductTokenWithVersion = Characters::Format (L"Windows/%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion);
        if (sizeof (void*) == 4)
        {
            tmp.fBits = 32;
            //IsWow64Process is not available on all supported versions of Windows.
            //Use GetModuleHandle to get a handle to the DLL that contains the function
            //and GetProcAddress to get a pointer to the function if available.
            typedef BOOL (WINAPI * LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
            LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");
            if(NULL != fnIsWow64Process) {
                BOOL    isWOW64 = false;
                (void)fnIsWow64Process (GetCurrentProcess(), &isWOW64);
                if (isWOW64) {
                    tmp.fBits = 64;
                }
            }
        }
        else {
            // In windows, a 64 bit app cannot run on 32-bit windows
            Assert (sizeof (void*) == 8);
            tmp.fBits = 64;
        }
#else
        AssertNotImplemented ();
#endif
        return tmp;
    } ();
    return kCachedResult_;
}

/*
 ********************************************************************************
 ***************** GetSystemConfiguration_ComputerNames *************************
 ********************************************************************************
 */
#if     0 && qPlatform_POSIX
// ALTERNATE APPROACH TO CONSIDER
string  name;
{
    struct addrinfo* res;
    struct addrinfo hints;
    memset(&hints, '\0', sizeof(hints));
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_CANONNAME;
    int e = getaddrinfo(nullptr, nullptr, &hints, &res);
    if (e != 0) {
        //printf("failure %s\n", gai_strerror (e));
        return String ();
    }
    int sock = -1;
    for (struct addrinfo* r = res; r != NULL; r = r->ai_next) {
        name = r->ai_canonname ;
        break;
    }
    freeaddrinfo(res);
}
return String::FromSDKString (name);
#endif
SystemConfiguration::ComputerNames Configuration::GetSystemConfiguration_ComputerNames ()
{
    using ComputerNames = SystemConfiguration::ComputerNames;
    ComputerNames   result;
#if     qPlatform_POSIX
    char    nameBuf[1024];
    Execution::ThrowErrNoIfNegative (gethostname (nameBuf, NEltsOf (nameBuf)));
    nameBuf[NEltsOf (nameBuf) - 1] = '\0';  // http://linux.die.net/man/2/gethostname says not necessarily nul-terminated
    result.fHostname = String::FromNarrowSDKString (nameBuf);
#elif   qPlatform_Windows
    constexpr   COMPUTER_NAME_FORMAT    kUseNameFormat_ = ComputerNameNetBIOS;  // total WAG -- LGP 2014-10-10
    DWORD   dwSize = 0;
    (void) ::GetComputerNameEx (kUseNameFormat_, nullptr, &dwSize);
    Memory::SmallStackBuffer<SDKChar> buf(dwSize);
    Execution::Platform::Windows::ThrowIfFalseGetLastError (::GetComputerNameEx (kUseNameFormat_, buf, &dwSize));
    result.fHostname = String::FromSDKString (buf);
#else
    AssertNotImplemented ();
#endif
    return result;
}

/*
 ********************************************************************************
 ****************** SystemConfiguration GetSystemConfiguration ******************
 ********************************************************************************
 */
inline  SystemConfiguration Configuration::GetSystemConfiguration ()
{
    return SystemConfiguration {
        GetSystemConfiguration_CPU (),
        GetSystemConfiguration_Memory (),
        GetSystemConfiguration_OperatingSystem (),
        GetSystemConfiguration_ComputerNames ()
    };
}
<|endoftext|>


<commit_before>/**
* For use with the Arduino/Genuino IDE
*
* Program controlling motors
*
* License information:
* The MIT License (MIT)
*
* 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
* he 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 <Stepper.h>

enum EMotor {
	MOTOR_ALL,
	MOTOR_ONE,
	MOTOR_TWO,
	MOTOR_THREE
};

// Number of steps (signals) required to do a 360° rotation (?)
const int steps_per_revolution = 200;

// Motor1 pins 1 to 4
const int m1_p1 = 10;
const int m1_p2 = 11;
const int m1_p3 = 12;
const int m1_p4 = 13;

// Motor2 pins 5 to 8
const int m2_p1 = 5;
const int m2_p2 = 6;
const int m2_p3 = 7;
const int m2_p4 = 8;

// Motor3 pins 9 to 12
const int m3_p1 = 9;
const int m3_p2 = 10;
const int m3_p3 = 11;
const int m3_p4 = 12;

// Button input, pin 13
const int buttonPin = 2;

// Button pressed(1) or released(0)?
// int savedButtonState = 0;
int aperatureActive = 0;
unsigned int timeDuration = 0;

// This the approx.(!) time in milliseconds after the aperature closes automatically
// TODO: Is there a time library or can we use C time?
const int automaticCollapseMS = 10000;

// These variables define the amount the motor works, it's kinda like RPM, think 1 revolution = 360°
// don't know for sure how this is linked to the Stepper constructor paramter1 so be careful testing this!
const int motor1AM = 10;
const int motor2AM = 10;
const int motor3AM = 10;

Stepper motor1(steps_per_revolution, m1_p1, m1_p2, m1_p3, m1_p4);
Stepper motor2(steps_per_revolution, m2_p1, m2_p2, m2_p3, m2_p4);
Stepper motor3(steps_per_revolution, m3_p1, m3_p2, m3_p3, m3_p4);

void SetMotorSpeed(EMotor motor, unsigned int speed) {
	switch (motor) {
		case MOTOR_ONE:
			motor1.setSpeed(speed);
		break;
		case MOTOR_TWO:
			motor2.setSpeed(speed);
		break;
		case MOTOR_THREE:
			motor3.setSpeed(speed);
		break;
		case MOTOR_ALL:
			motor1.setSpeed(speed);
			motor2.setSpeed(speed);
			motor3.setSpeed(speed);
		break;
	}
}

// @revolutions = positive amounts move the motorknob forwards, negative amounts backwards
// remember that .step() is blocking, so if we want to move all motors at once we need a different approach/function
// with revolution deltas
void MoveMotor(EMotor motor, int revolutions) {
	switch (motor) {
		case MOTOR_ONE:
			motor1.step(revolutions);
		break;
		case MOTOR_TWO:
			motor2.step(revolutions);
		break;
		case MOTOR_THREE:
			motor3.step(revolutions);
		break;
		case MOTOR_ALL:
			motor1.step(revolutions);
			motor2.step(revolutions);
			motor3.step(revolutions);
		break;
	}
}

void setup() {
	// Setup the button pin as input
	pinMode(buttonPin, INPUT);

	// Set the motor speed for all motor, change if necessary calling each one seperately
	SetMotorSpeed(MOTOR_ALL, 60);		// Check C++98 enum?

	Serial.begin(9600);

	Serial.print("Program starting");
}

void loop() {
	int currentButtonState = digitalRead(buttonPin);

	if (aperatureActive == 0 && currentButtonState == 1) {
		// Someone pressed the button while the aperature was inactive, start rolling out..

		// Step the motors
		// Remember: For now this moves the motors one after another.. see MoveMotor comments
		MoveMotor(MOTOR_ONE, motor1AM);
		MoveMotor(MOTOR_TWO, motor2AM);
		MoveMotor(MOTOR_THREE, motor3AM);

		// Save the state
		aperatureActive = 1;
	}
	else if (aperatureActive == 1 && currentButtonState == 1) {
		// The aperature was active  and the button was pressed, roll in

		// Step the motors backwards, so we start with motor 3
		MoveMotor(MOTOR_THREE, -1 * motor3AM);
		MoveMotor(MOTOR_TWO, -1 * motor2AM);
		MoveMotor(MOTOR_ONE, -1 * motor1AM);

		// Save the state
		aperatureActive = 0;

		// Set time to null
		timeDuration = 0;
	}
	else if (aperatureActive == 1 && timeDuration >= automaticCollapseMS) {
		// Automatic collapse after time duration, roll in

		// Step the motors backwards, so we start with motor 3
		MoveMotor(MOTOR_THREE, -1 * motor3AM);
		MoveMotor(MOTOR_TWO, -1 * motor2AM);
		MoveMotor(MOTOR_ONE, -1 * motor1AM);

		// Save the state
		aperatureActive = 0;

		// Set time to null
		timeDuration = 0;
	}
	else if (aperatureActive == 1) {
		delay(1);	// Delay for a milliseconds
		timeDuration = timeDuration + 1;	// And save that
	}
	else {
		// Aperature is not doing anything, Sleep to preserve power?
		delay(1);

		Serial.print("No action");
	}
}

<commit_msg>awdawdadw<commit_after>/**
* For use with the Arduino/Genuino IDE
*
* Program controlling motors
*
* License information:
* The MIT License (MIT)
*
* 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
* he 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 <Stepper.h>

enum EMotor {
	MOTOR_ALL,
	MOTOR_ONE,
	MOTOR_TWO,
	MOTOR_THREE
};

// Number of steps (signals) required to do a 360° rotation (?)
const int steps_per_revolution = 200;

// Motor1 pins 1 to 4
const int m1_p1 = 10;
const int m1_p2 = 11;
const int m1_p3 = 12;
const int m1_p4 = 13;

// Motor2 pins 5 to 8
const int m2_p1 = 5;
const int m2_p2 = 6;
const int m2_p3 = 7;
const int m2_p4 = 8;

// Motor3 pins 9 to 12
const int m3_p1 = 9;
const int m3_p2 = 10;
const int m3_p3 = 11;
const int m3_p4 = 12;

// Button input, pin 13
const int buttonPin = 2;

// Button pressed(1) or released(0)?
// int savedButtonState = 0;
int aperatureActive = 0;
unsigned int timeDuration = 0;

// This the approx.(!) time in milliseconds after the aperature closes automatically
// TODO: Is there a time library or can we use C time?
const int automaticCollapseMS = 10000;

// These variables define the amount the motor works, it's kinda like RPM, think 1 revolution = 360°
// don't know for sure how this is linked to the Stepper constructor paramter1 so be careful testing this!
const int motor1AM = 10;
const int motor2AM = 10;
const int motor3AM = 10;

Stepper motor1(steps_per_revolution, m1_p1, m1_p2, m1_p3, m1_p4);
Stepper motor2(steps_per_revolution, m2_p1, m2_p2, m2_p3, m2_p4);
Stepper motor3(steps_per_revolution, m3_p1, m3_p2, m3_p3, m3_p4);

void SetMotorSpeed(EMotor motor, unsigned int speed) {
	switch (motor) {
		case MOTOR_ONE:
			motor1.setSpeed(speed);
		break;
		case MOTOR_TWO:
			motor2.setSpeed(speed);
		break;
		case MOTOR_THREE:
			motor3.setSpeed(speed);
		break;
		case MOTOR_ALL:
			motor1.setSpeed(speed);
			motor2.setSpeed(speed);
			motor3.setSpeed(speed);
		break;
	}
}

// @revolutions = positive amounts move the motorknob forwards, negative amounts backwards
// remember that .step() is blocking, so if we want to move all motors at once we need a different approach/function
// with revolution deltas
void MoveMotor(EMotor motor, int revolutions) {
	switch (motor) {
		case MOTOR_ONE:
			motor1.step(revolutions);
		break;
		case MOTOR_TWO:
			motor2.step(revolutions);
		break;
		case MOTOR_THREE:
			motor3.step(revolutions);
		break;
		case MOTOR_ALL:
			motor1.step(revolutions);
			motor2.step(revolutions);
			motor3.step(revolutions);
		break;
	}
}

void setup() {
	// Setup the button pin as input
	pinMode(buttonPin, INPUT);

	// Set the motor speed for all motor, change if necessary calling each one seperately
	SetMotorSpeed(MOTOR_ALL, 60);		// Check C++98 enum?

	Serial.begin(9600);

	Serial.print("Program starting");
}

void loop() {
	int currentButtonState = digitalRead(buttonPin);

	if (aperatureActive == 0 && digitalRead(buttonPin) == HIGH) {
		Serial.print("Button pressed, starting motors forward");
		// Someone pressed the button while the aperature was inactive, start rolling out..

		// Step the motors
		// Remember: For now this moves the motors one after another.. see MoveMotor comments
		MoveMotor(MOTOR_ONE, motor1AM);
		MoveMotor(MOTOR_TWO, motor2AM);
		MoveMotor(MOTOR_THREE, motor3AM);

		// Save the state
		aperatureActive = 1;
	}
	else if (aperatureActive == 1 && digitalRead(buttonPin)== HIGH) {
		Serial.print("Button pressed, starting motors backwards");
		// The aperature was active  and the button was pressed, roll in

		// Step the motors backwards, so we start with motor 3
		MoveMotor(MOTOR_THREE, -1 * motor3AM);
		MoveMotor(MOTOR_TWO, -1 * motor2AM);
		MoveMotor(MOTOR_ONE, -1 * motor1AM);

		// Save the state
		aperatureActive = 0;

		// Set time to null
		timeDuration = 0;
	}
	else if (aperatureActive == 1 && timeDuration >= automaticCollapseMS) {
		Serial.print("Time run out, starting motors backwards");
		// Automatic collapse after time duration, roll in

		// Step the motors backwards, so we start with motor 3
		MoveMotor(MOTOR_THREE, -1 * motor3AM);
		MoveMotor(MOTOR_TWO, -1 * motor2AM);
		MoveMotor(MOTOR_ONE, -1 * motor1AM);

		// Save the state
		aperatureActive = 0;

		// Set time to null
		timeDuration = 0;
	}
	else if (aperatureActive == 1) {
		delay(1);	// Delay for a milliseconds
		timeDuration = timeDuration + 1;	// And save that
	}
	else {
		// Aperature is not doing anything, Sleep to preserve power?
		delay(1);
	}
}

<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <stack>
#include <dirent.h>
#include <stdio.h>
#include <string.h>

using namespace std;

vector<string> getFiles(string filePath)
{
    const char* DIR_PATH = filePath.c_str();

    vector<string> directories;

    DIR *dir = opendir(DIR_PATH);

    struct dirent *entry = readdir(dir);

    while (entry != NULL)
    {
        if (entry->d_type == DT_DIR) {
            if(!strcmp(entry->d_name, "..") || !strcmp(entry->d_name, ".")) {

            } else {
                directories.push_back(filePath + "/" + entry->d_name);
            }
        }

        entry = readdir(dir);
    }

    closedir(dir);

    return directories;
}

int main(void)
{
    string searchedDir = "/home/simon/Plocha/Simon";

    stack<string> actDir;

    actDir.push(searchedDir);

    string actSearchedDir;

    vector<string> dirFound;

    string newString = searchedDir;

    int dirCount = 0;

    while(actDir.size() > 0) {
        actSearchedDir = actDir.top();actDir.pop();

        cout << actSearchedDir << endl;

        dirFound = getFiles(actSearchedDir.c_str());

        for(unsigned i = 0; i < dirFound.size(); i++) {
            if(!dirFound.empty()) {
                newString = dirFound.at(i);
                //cout << newString << endl;
                actDir.push(newString);
            } else {
                break;
            }
        }
        dirCount++;
    }

    cout << "Bylo nalezeno celkem " << dirCount-1 << " složek";

    return 0;
}
<commit_msg>Formální dodělávky<commit_after>#include <iostream>
#include <vector>
#include <stack>
#include <dirent.h>
#include <string.h>

using namespace std;

/*
 * The function returns directories found in directory.
 * First parameter is path where you want to find directories.
 * You can also use double slashes like this ...../dir/dir//dir. Not reomanded!
 */
vector<string> getDirs(string dirPath)
{
    // Converting path to const char* because the function opendir is programmed in c
    // and c methods parameters accepts only const char* so I must convert it.
    const char* DIR_PATH = dirPath.c_str();

    // Declaration of dynamic array that contains found directories by path.
    vector<string> directories;

    // Call a function to try to open the dir by path.
    // If it doesnt exists the function will return segmentation error.
    DIR *dir = opendir(DIR_PATH);

    // Then try to read the dir
    struct dirent *entry = readdir(dir);

    // While dir has a directory.
    while (entry != NULL)
    {
        // If type of stream is directory.
        if (entry->d_type == DT_DIR) {
            // If the "directory" name is not ".." or ".".
            if(!strcmp(entry->d_name, "..") || !strcmp(entry->d_name, ".")) {

            } else {
                // push the actual dir path PLUS actual directory to the dynamic array.
                directories.push_back(dirPath + "/" + entry->d_name);
            }
        }

        entry = readdir(dir);
    }

    // Close the dir.
    closedir(dir);

    return directories;
}

int main(void)
{
    // A root path where you want to start searching.
    string searchedDir = "/home/simon/Plocha/Simon";

    stack<string> actDir;

    actDir.push(searchedDir);

    string actSearchedDir;

    vector<string> dirFound;

    int dirCount = 0;

    while(actDir.size() > 0) {
        actSearchedDir = actDir.top();actDir.pop();

        cout << actSearchedDir << endl;

        dirFound = getDirs(actSearchedDir.c_str());

        for(unsigned i = 0; i < dirFound.size(); i++) {
            if(!dirFound.empty()) {
                actDir.push(dirFound.at(i));
            } else {
                break;
            }
        }
        dirCount++;
    }

    cout << "Bylo nalezeno celkem " << dirCount-1 << " složek";

    return 0;
}
<|endoftext|>


<commit_before>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

******************************************************************************/
#include "nomlib/graphics/TrueTypeFont.hpp"

namespace nom {

TrueTypeFont::TrueTypeFont ( void )
{
NOM_LOG_TRACE ( NOM );

  this->font = nullptr;
  this->coords = Coords ( 0, 0, 0, 0 );
  this->color = Color4u ( 0, 0, 0 );
  this->text_buffer = "\0";
  this->text_style = FontStyle::Regular; // default text styling effect
  this->text_alignment = TextAlignment::MiddleLeft;
  this->rendering = RenderStyle::Solid; // Fast, but ugly
  this->style_options = 0;
  this->filename = "\0";
  this->font_size = 12;
  this->use_cache = false;
}

TrueTypeFont::~TrueTypeFont ( void )
{
NOM_LOG_TRACE ( NOM );
}

IFont::SharedPtr TrueTypeFont::clone ( void ) const
{
  return IFont::SharedPtr ( new TrueTypeFont ( *this ), priv::Free_TrueTypeFont );
}

bool TrueTypeFont::valid ( void ) const
{
  if ( this->font.get() != nullptr )
  {
    return true;
  }
  else
  {
    return false;
  }
}

const std::string& TrueTypeFont::getText ( void ) const
{
  return this->text_buffer;
}

int32 TrueTypeFont::getFontWidth ( void ) const
{
  return this->coords.width;
}

int32 TrueTypeFont::getFontHeight ( void ) const
{
  return this->coords.height;
}

IFont::FontStyle TrueTypeFont::getFontStyle ( void ) const
{
  return this->text_style;
}

const Color4u& TrueTypeFont::getColor ( void ) const
{
  return this->color;
}

const Coords& TrueTypeFont::getPosition ( void ) const
{
  return this->coords;
}

uint32 TrueTypeFont::getNewline ( void ) const
{
  // Not implemented
  return 0;
}

uint32 TrueTypeFont::getSpacing ( void ) const
{
  // Not implemented
  return 0;
}

IFont::TextAlignment TrueTypeFont::getTextJustification ( void ) const
{
  return this->text_alignment;
}

void TrueTypeFont::setColor ( const Color4u& color )
{
  this->color = color;
}

void TrueTypeFont::setPosition ( const Coords& coords )
{
  this->coords.x = coords.x;
  this->coords.y = coords.y;
}

void TrueTypeFont::setFontSize ( int32 point_size )
{
  int32 original_font_size = this->font_size;

  this->font_size = point_size;

  if ( this->rebuild() == false )
  {
NOM_LOG_ERR ( NOM, "Could not set new font size." );
    this->font_size = original_font_size;
    return;
  }
}

void TrueTypeFont::setFontStyle ( int32 style, uint8 options )
{
  switch ( style )
  {
    default: break;
    case FontStyle::Regular:
    {
      TTF_SetFontStyle ( this->font.get(), TTF_STYLE_NORMAL );
    }
    break;

    case FontStyle::Bold:
    {
      TTF_SetFontStyle ( this->font.get(), TTF_STYLE_BOLD );
    }
    break;

    case FontStyle::Italic:
    {
      TTF_SetFontStyle ( this->font.get(), TTF_STYLE_ITALIC );
    }
    break;

    case FontStyle::Underlined:
    {
      TTF_SetFontStyle ( this->font.get(), TTF_STYLE_UNDERLINE );
    }
    break;

    /// Text effect utilizing alpha channels for the appearance of gray text
    case FontStyle::Faded:
    {
      this->text_style = FontStyle::Faded;
      this->style_options = options;
    break;
    }
  }
}

int32 TrueTypeFont::getFontOutline ( void ) const
{
  return TTF_GetFontOutline ( this->font.get() );
}

void TrueTypeFont::setFontOutline ( int32 depth )
{
  TTF_SetFontOutline ( this->font.get(), depth );
}

IFont::RenderStyle TrueTypeFont::getRenderingStyle ( void ) const
{
  return this->rendering;
}

void TrueTypeFont::setRenderingStyle ( IFont::RenderStyle style )
{
  this->rendering = style;
}

void TrueTypeFont::setText ( const std::string& text )
{
  if ( text.length() < 1 ) return;

  this->text_buffer = text;

  // Update the width & height of text string, if we can
  if ( TTF_SizeText ( this->font.get(), this->text_buffer.c_str(), &this->coords.width, &this->coords.height ) == -1 )
  {
NOM_LOG_ERR ( NOM, "Failed to set font width & height." );
  }
}

void TrueTypeFont::setSpacing ( uint32 spaces )
{
  // Not implemented
}

void TrueTypeFont::setTextJustification ( IFont::TextAlignment alignment )
{
  this->text_alignment = alignment;
}

bool TrueTypeFont::load ( const std::string& filename, const Color4u& colorkey,
                          bool use_cache
                        )
{
  this->font = std::shared_ptr<TTF_Font> ( TTF_OpenFont ( filename.c_str(), this->font_size ), nom::priv::TTF_FreeFont );

  if ( this->valid() == false )
  {
NOM_LOG_ERR ( NOM, "Could not load TTF file: " + filename );
    return false;
  }

  // Store the new filename & caching choice for future reference; primarily
  // used when rebuilding font metrics, such as when we change the font point
  // size or load a new font.
  this->filename = filename;
  this->use_cache = use_cache;

  return true;
}

void TrueTypeFont::update ( void )
{
  // Update display coordinates
  this->font_buffer.set_position ( Point2i ( this->coords.x, this->coords.y ) );

  // Update the rendered text surface here for drawing
  if ( this->getText().c_str() == nullptr ) return;

  if ( this->rendering == RenderStyle::Shaded ) // Moderate-quality
  {
    this->font_buffer.initialize ( TTF_RenderText_Shaded
                                  (
                                    this->font.get(),
                                    this->getText().c_str(),
                                    SDL_COLOR(this->color),
                                    // TODO; implement me -- a second color
                                    // possibility means needing two colors in
                                    // class
                                    SDL_COLOR ( Color4u ( 97, 97, 97 ) )
                                  )
                                );
  }
  else if ( this->rendering == RenderStyle::Blended ) // Highest-quality
  {
    this->font_buffer.initialize ( TTF_RenderText_Blended
                                  (
                                    this->font.get(),
                                    this->getText().c_str(),
                                    SDL_COLOR(this->color)
                                  )
                                );
  }
  else // Low-quality rendering (the default)
  {
    this->font_buffer.initialize ( TTF_RenderText_Solid
                                  (
                                    this->font.get(),
                                    this->getText().c_str(),
                                    SDL_COLOR(this->color)
                                  )
                                );
  }

  if ( this->text_style == FontStyle::Faded )
  {
    this->font_buffer.set_alpha ( this->style_options );
  }
}

void TrueTypeFont::draw ( SDL_Renderer* target ) const
{
  if ( this->font_buffer.valid() )
  {
    this->font_buffer.draw ( target );
  }
}

void TrueTypeFont::draw ( const Window& target ) const
{
  if ( this->font_buffer.valid() )
  {
    this->font_buffer.draw ( target.renderer() );
  }
}

bool TrueTypeFont::rebuild ( void )
{
  if ( this->load ( this->filename, NOM_COLOR4U_BLACK, this->use_cache ) == false )
  {
NOM_LOG_ERR ( NOM, "Could not rebuild font metrics." );
    return false;
  }

  return true;
}

namespace priv {

void Free_TrueTypeFont ( TrueTypeFont* ptr )
{
  // Do nothing custom deleter
  //
  // FIXME; this is a known bug (memory leak).
}

} // namespace priv
} // namespace nom

<commit_msg>TrueTypeFont: Add additional validity checks<commit_after>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

******************************************************************************/
#include "nomlib/graphics/TrueTypeFont.hpp"

namespace nom {

TrueTypeFont::TrueTypeFont ( void )
{
NOM_LOG_TRACE ( NOM );

  this->font = nullptr;
  this->coords = Coords ( 0, 0, 0, 0 );
  this->color = Color4u ( 0, 0, 0 );
  this->text_buffer = "\0";
  this->text_style = FontStyle::Regular; // default text styling effect
  this->text_alignment = TextAlignment::MiddleLeft;
  this->rendering = RenderStyle::Solid; // Fast, but ugly
  this->style_options = 0;
  this->filename = "\0";
  this->font_size = 12;
  this->use_cache = false;
}

TrueTypeFont::~TrueTypeFont ( void )
{
NOM_LOG_TRACE ( NOM );
}

IFont::SharedPtr TrueTypeFont::clone ( void ) const
{
  return IFont::SharedPtr ( new TrueTypeFont ( *this ), priv::Free_TrueTypeFont );
}

bool TrueTypeFont::valid ( void ) const
{
  if ( this->font.get() != nullptr )
  {
    return true;
  }
  else
  {
    return false;
  }
}

const std::string& TrueTypeFont::getText ( void ) const
{
  return this->text_buffer;
}

int32 TrueTypeFont::getFontWidth ( void ) const
{
  return this->coords.width;
}

int32 TrueTypeFont::getFontHeight ( void ) const
{
  return this->coords.height;
}

IFont::FontStyle TrueTypeFont::getFontStyle ( void ) const
{
  return this->text_style;
}

const Color4u& TrueTypeFont::getColor ( void ) const
{
  return this->color;
}

const Coords& TrueTypeFont::getPosition ( void ) const
{
  return this->coords;
}

uint32 TrueTypeFont::getNewline ( void ) const
{
  // Not implemented
  return 0;
}

uint32 TrueTypeFont::getSpacing ( void ) const
{
  // Not implemented
  return 0;
}

IFont::TextAlignment TrueTypeFont::getTextJustification ( void ) const
{
  return this->text_alignment;
}

void TrueTypeFont::setColor ( const Color4u& color )
{
  this->color = color;
}

void TrueTypeFont::setPosition ( const Coords& coords )
{
  this->coords.x = coords.x;
  this->coords.y = coords.y;
}

void TrueTypeFont::setFontSize ( int32 point_size )
{
  int32 original_font_size = this->font_size;

  this->font_size = point_size;

  if ( this->rebuild() == false )
  {
NOM_LOG_ERR ( NOM, "Could not set new font size." );
    this->font_size = original_font_size;
    return;
  }
}

void TrueTypeFont::setFontStyle ( int32 style, uint8 options )
{
  switch ( style )
  {
    default: break;
    case FontStyle::Regular:
    {
      TTF_SetFontStyle ( this->font.get(), TTF_STYLE_NORMAL );
    }
    break;

    case FontStyle::Bold:
    {
      TTF_SetFontStyle ( this->font.get(), TTF_STYLE_BOLD );
    }
    break;

    case FontStyle::Italic:
    {
      TTF_SetFontStyle ( this->font.get(), TTF_STYLE_ITALIC );
    }
    break;

    case FontStyle::Underlined:
    {
      TTF_SetFontStyle ( this->font.get(), TTF_STYLE_UNDERLINE );
    }
    break;

    /// Text effect utilizing alpha channels for the appearance of gray text
    case FontStyle::Faded:
    {
      this->text_style = FontStyle::Faded;
      this->style_options = options;
    break;
    }
  }
}

int32 TrueTypeFont::getFontOutline ( void ) const
{
  return TTF_GetFontOutline ( this->font.get() );
}

void TrueTypeFont::setFontOutline ( int32 depth )
{
  TTF_SetFontOutline ( this->font.get(), depth );
}

IFont::RenderStyle TrueTypeFont::getRenderingStyle ( void ) const
{
  return this->rendering;
}

void TrueTypeFont::setRenderingStyle ( IFont::RenderStyle style )
{
  this->rendering = style;
}

void TrueTypeFont::setText ( const std::string& text )
{
  if ( text.length() < 1 ) return;

  this->text_buffer = text;

  // Font is not valid -- TTF_SizeText will crash if we go further
  if ( ! this->valid() ) return;

  // Update the width & height of text string, if we can
  if ( TTF_SizeText ( this->font.get(), this->text_buffer.c_str(), &this->coords.width, &this->coords.height ) == -1 )
  {
NOM_LOG_ERR ( NOM, "Failed to set font width & height." );
  }
}

void TrueTypeFont::setSpacing ( uint32 spaces )
{
  // Not implemented
}

void TrueTypeFont::setTextJustification ( IFont::TextAlignment alignment )
{
  this->text_alignment = alignment;
}

bool TrueTypeFont::load ( const std::string& filename, const Color4u& colorkey,
                          bool use_cache
                        )
{
  this->font = std::shared_ptr<TTF_Font> ( TTF_OpenFont ( filename.c_str(), this->font_size ), nom::priv::TTF_FreeFont );

  if ( this->valid() == false )
  {
NOM_LOG_ERR ( NOM, "Could not load TTF file: " + filename );
    return false;
  }

  // Store the new filename & caching choice for future reference; primarily
  // used when rebuilding font metrics, such as when we change the font point
  // size or load a new font.
  this->filename = filename;
  this->use_cache = use_cache;

  return true;
}

void TrueTypeFont::update ( void )
{
  // Font is not valid -- nothing to draw
  if ( ! this->valid() ) return;

  // No text string set -- nothing to draw
  if ( this->getText().length() < 1 ) return;

  // Update display coordinates
  this->font_buffer.set_position ( Point2i ( this->coords.x, this->coords.y ) );

  // Update the rendered text surface here for drawing
  if ( this->rendering == RenderStyle::Shaded ) // Moderate-quality
  {
    this->font_buffer.initialize ( TTF_RenderText_Shaded
                                  (
                                    this->font.get(),
                                    this->getText().c_str(),
                                    SDL_COLOR(this->color),
                                    // TODO; implement me -- a second color
                                    // possibility means needing two colors in
                                    // class
                                    SDL_COLOR ( Color4u ( 97, 97, 97 ) )
                                  )
                                );
  }
  else if ( this->rendering == RenderStyle::Blended ) // Highest-quality
  {
    this->font_buffer.initialize ( TTF_RenderText_Blended
                                  (
                                    this->font.get(),
                                    this->getText().c_str(),
                                    SDL_COLOR(this->color)
                                  )
                                );
  }
  else // Low-quality rendering (the default)
  {
    this->font_buffer.initialize ( TTF_RenderText_Solid
                                  (
                                    this->font.get(),
                                    this->getText().c_str(),
                                    SDL_COLOR(this->color)
                                  )
                                );
  }

  if ( this->text_style == FontStyle::Faded )
  {
    this->font_buffer.set_alpha ( this->style_options );
  }
}

void TrueTypeFont::draw ( SDL_Renderer* target ) const
{
  if ( this->font_buffer.valid() )
  {
    this->font_buffer.draw ( target );
  }
}

void TrueTypeFont::draw ( const Window& target ) const
{
  if ( this->font_buffer.valid() )
  {
    this->font_buffer.draw ( target.renderer() );
  }
}

bool TrueTypeFont::rebuild ( void )
{
  if ( this->load ( this->filename, NOM_COLOR4U_BLACK, this->use_cache ) == false )
  {
NOM_LOG_ERR ( NOM, "Could not rebuild font metrics." );
    return false;
  }

  return true;
}

namespace priv {

void Free_TrueTypeFont ( TrueTypeFont* ptr )
{
  // Do nothing custom deleter
  //
  // FIXME; this is a known bug (memory leak).
}

} // namespace priv
} // namespace nom

<|endoftext|>


<commit_before><commit_msg>only one constructor with defaults<commit_after><|endoftext|>


<commit_before>#include "mainwindow.hxx"
#include <QApplication>
#include <windows.h>

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	MainWindow w;
	w.show();

	return a.exec();
}
<commit_msg>minor source code cleanup<commit_after>#include "mainwindow.hxx"
#include <QApplication>

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	MainWindow w;
	w.show();

	return a.exec();
}
<|endoftext|>