<commit_before>#include "stdafx.h"
#include "SRTSubtitleRenderer.h"
#include "SRTSubtitleEntry.h"

#include "TimeConversion.h"

using namespace SubtitleCore;

SRTSubtitleRenderer::SRTSubtitleRenderer(SubtitleCoreConfigurationData& config, VideoInfo& vidInfo, IDWriteFactory* dwFactory)
	: m_SubCoreConfig(config)
	, m_VideoInfo(vidInfo)
	, m_DWriteFactory(dwFactory)
{
	m_SubtitleType = SBT_SRT;
}

bool SRTSubtitleRenderer::ParseScript(const std::vector<std::wstring>& script)
{
	for (size_t i = 0; i < script.size(); i++)
	{
		// Ignore lines which are just the subtitle entry number
		try
		{
			// If this doesn't throw an exception, continue
			boost::lexical_cast<int>(script[i]);
			continue;
		}
		catch(boost::bad_lexical_cast e)
		{
			// This should be a timestamp
			if (CheckLineIsTimestamp(script[i]))
			{
				REFERENCE_TIME rtStart, rtEnd;

				ComputeTimestamp(script[i], rtStart, rtEnd);

				// Merge lines until we reach an empty line which delineates the start of a new
				// subtitle block
				std::wstring mergedLine;
				size_t index = i+1;
				while (script[index].empty() == false)
				{
					mergedLine += script[index] + L"\n";
					++index;
				}
				// Move overall script parsing position to start of the next subtitle block
				i = index+1;

				// Parse merged line
				ParseLine(mergedLine, rtStart, rtEnd);
			}
			else
			{
				// Something bad happened
				return false;
			}
		}
	}

	return true;
}

bool SRTSubtitleRenderer::ParseLine(const std::wstring& line)
{
	UNREFERENCED_PARAMETER(line);
	return false;
}

bool SRTSubtitleRenderer::ParseLine(const std::wstring& line, REFERENCE_TIME rtStart, REFERENCE_TIME rtEnd)
{
	SRTSubtitleEntry* entry = nullptr;

	auto& subtitle_list = m_SubtitleMap[rtStart];

	if (subtitle_list.size() == 0)
	{
		// Subtitle list with this start time was empty so add a new entry
		subtitle_list.push_back(SRTSubtitleEntry());

		entry = &subtitle_list[0];
		entry->EndTime = rtEnd;
	}
	else
	{
		// See if this entry already exists
		for (auto it = subtitle_list.begin(); it != subtitle_list.end(); ++it)
		{
			if (it->EndTime == rtEnd)
			{
				entry = &(*it);
				break;
			}
		}

		// Entry did not exist so add it
		if (!entry)
		{
			subtitle_list.push_back(SRTSubtitleEntry());

			entry = &subtitle_list[subtitle_list.size() - 1];
			entry->EndTime = rtEnd;
		}
	}

	std::wstring finalLine;

	// Check for supported HTML tags
	size_t startPos, openBracketPos, closeBracketPos;
	size_t finalStartPos, finalEndPos;
	std::vector<std::wstring> tagStack;

	startPos = 0;

	while ((openBracketPos = line.find(L"<", startPos)) != std::wstring::npos)
	{
		finalStartPos = finalLine.size();
		finalLine += line.substr(startPos, openBracketPos - startPos);
		finalEndPos = finalLine.size();

		if (finalEndPos != finalStartPos)
		{
			SRTSubtitleEntry::TextRangeFormat trf;

			trf.Range.length = finalEndPos - finalStartPos;
			trf.Range.startPosition = finalStartPos;
			trf.Style = m_SubCoreConfig.m_FontStyle;
			trf.Weight = m_SubCoreConfig.m_FontWeight;
			trf.Strikethrough = FALSE;
			trf.Underline = FALSE;

			for (auto it = tagStack.begin(); it != tagStack.end(); ++it)
			{
				if ((*it).compare(L"b") == 0)
				{
					trf.Weight = DWRITE_FONT_WEIGHT_BOLD;
				}
				else if ((*it).compare(L"i") == 0)
				{
					trf.Style = DWRITE_FONT_STYLE_ITALIC;
				}
				else if ((*it).compare(L"u") == 0)
				{
					trf.Underline = TRUE;
				}
				else if ((*it).compare(L"s") == 0)
				{
					trf.Strikethrough = TRUE;
				}
			}

			entry->SubTextFormat.push_back(trf);
		}

		// Find close bracket
		closeBracketPos = line.find(L">", openBracketPos);

		std::wstring tag = line.substr(openBracketPos+1, closeBracketPos - openBracketPos - 1);

		// Is this a closing tag?
		if (tag.find(L"/") != std::wstring::npos)
		{
			// Malformed scripts are just going to break
			tagStack.pop_back();
		}
		else
		{
			tagStack.push_back(tag);
		}

		startPos = closeBracketPos+1;
	}

	// No supporting tags found so just copy original line over
	if (finalLine.empty())
	{
		entry->Text = line;
	}
	else
	{
		entry->Text = finalLine;
	}

	return true;

}

bool SRTSubtitleRenderer::ParseFormatHeader(const std::wstring& header)
{
	UNREFERENCED_PARAMETER(header);
	return true;
}

bool SRTSubtitleRenderer::ParseFormatHeader(const unsigned char* header)
{
	UNREFERENCED_PARAMETER(header);
	return true;
}

bool SRTSubtitleRenderer::ParseData(const unsigned char* data)
{
	UNREFERENCED_PARAMETER(data);
	return false;
}

bool SRTSubtitleRenderer::ParseData(const unsigned char* data, ptrdiff_t offset)
{
	UNREFERENCED_PARAMETER(data);
	UNREFERENCED_PARAMETER(offset);
	return false;
}

bool SRTSubtitleRenderer::ParseData(const unsigned char* data, ptrdiff_t startOffset, ptrdiff_t endOffset)
{
	UNREFERENCED_PARAMETER(data);
	UNREFERENCED_PARAMETER(startOffset);
	UNREFERENCED_PARAMETER(endOffset);
	return false;
}

void SRTSubtitleRenderer::Invalidate()
{
	m_SubtitleMap.clear();
}

size_t SRTSubtitleRenderer::GetSubtitlePictureCount(REFERENCE_TIME rtNow)
{
	UNREFERENCED_PARAMETER(rtNow);
	return 0U;
}

void SRTSubtitleRenderer::GetSubtitlePicture(REFERENCE_TIME rtNow, SubtitlePicture** ppOutSubPics)
{
	UNREFERENCED_PARAMETER(rtNow);
	UNREFERENCED_PARAMETER(ppOutSubPics);
}

bool SRTSubtitleRenderer::CheckLineIsTimestamp(const std::wstring& line)
{
	return (line.find(L"-->") != std::wstring::npos &&
		line.find(L":") != std::wstring::npos &&
		line.find(L",") != std::wstring::npos);
}

void SRTSubtitleRenderer::ComputeTimestamp(const std::wstring& line, REFERENCE_TIME& rtStart, REFERENCE_TIME& rtEnd)
{
	size_t startPos, endPos;
	size_t hours, minutes, seconds, milliseconds;

	startPos = 0;

	// Get hours
	endPos = line.find(L":");
	hours = boost::lexical_cast<size_t>(line.substr(startPos, endPos - startPos));

	// Get minutes
	startPos = endPos + 1;
	endPos = line.find(L":", startPos);
	minutes = boost::lexical_cast<size_t>(line.substr(startPos, endPos - startPos));

	// Get seconds
	startPos = endPos + 1;
	endPos = line.find(L",", startPos);
	seconds = boost::lexical_cast<size_t>(line.substr(startPos, endPos - startPos));

	// Get milliseconds
	startPos = endPos + 1;
	endPos = line.find(L" ", startPos);
	milliseconds = boost::lexical_cast<size_t>(line.substr(startPos, endPos - startPos));

	// Compute starting time
	rtStart = SubtitleCoreUtilities::ConvertTimeToReferenceTime(hours, minutes, seconds, milliseconds);

	// Move to ending timestamp
	startPos = line.find(L" ", endPos+1) + 1;

	// Get hours
	endPos = line.find(L":", startPos);
	hours = boost::lexical_cast<size_t>(line.substr(startPos, endPos - startPos));

	// Get minutes
	startPos = endPos + 1;
	endPos = line.find(L":", startPos);
	minutes = boost::lexical_cast<size_t>(line.substr(startPos, endPos - startPos));

	// Get seconds
	startPos = endPos + 1;
	endPos = line.find(L",", startPos);
	seconds = boost::lexical_cast<size_t>(line.substr(startPos, endPos - startPos));

	// Get milliseconds
	startPos = endPos + 1;
	milliseconds = boost::lexical_cast<size_t>(line.substr(startPos));

	rtEnd = SubtitleCoreUtilities::ConvertTimeToReferenceTime(hours, minutes, seconds, milliseconds);
}
<commit_msg>SRT parser fixes.<commit_after>#include "stdafx.h"
#include "SRTSubtitleRenderer.h"
#include "SRTSubtitleEntry.h"

#include "TimeConversion.h"

using namespace SubtitleCore;

SRTSubtitleRenderer::SRTSubtitleRenderer(SubtitleCoreConfigurationData& config, VideoInfo& vidInfo, IDWriteFactory* dwFactory)
	: m_SubCoreConfig(config)
	, m_VideoInfo(vidInfo)
	, m_DWriteFactory(dwFactory)
{
	m_SubtitleType = SBT_SRT;
}

bool SRTSubtitleRenderer::ParseScript(const std::vector<std::wstring>& script)
{
	for (size_t i = 0; i < script.size(); i++)
	{
		// Ignore lines which are just the subtitle entry number
		if (script[i].find_first_not_of(L"0123456789") != std::wstring::npos)
		{
			// This should be a timestamp
			if (CheckLineIsTimestamp(script[i]))
			{
				REFERENCE_TIME rtStart, rtEnd;

				ComputeTimestamp(script[i], rtStart, rtEnd);

				// Merge lines until we reach an empty line which delineates the start of a new
				// subtitle block
				std::wstring mergedLine;
				size_t index = i+1;
				while (script[index].empty() == false)
				{
					mergedLine += script[index] + L"\n";
					++index;
				}
				// Move overall script parsing position to start of the next subtitle block
				i = index+1;

				// Parse merged line
				ParseLine(mergedLine, rtStart, rtEnd);
			}
			else
			{
				// Something bad happened
				return false;
			}
		}
	}

	return true;
}

bool SRTSubtitleRenderer::ParseLine(const std::wstring& line)
{
	UNREFERENCED_PARAMETER(line);
	return false;
}

bool SRTSubtitleRenderer::ParseLine(const std::wstring& line, REFERENCE_TIME rtStart, REFERENCE_TIME rtEnd)
{
	SRTSubtitleEntry* entry = nullptr;

	auto& subtitle_list = m_SubtitleMap[rtStart];

	if (subtitle_list.size() == 0)
	{
		// Subtitle list with this start time was empty so add a new entry
		subtitle_list.push_back(SRTSubtitleEntry());

		entry = &subtitle_list[0];
		entry->EndTime = rtEnd;
	}
	else
	{
		subtitle_list.push_back(SRTSubtitleEntry());

		entry = &subtitle_list[subtitle_list.size() - 1];
		entry->EndTime = rtEnd;
	}

	std::wstring finalLine;

	// Check for supported HTML tags
	size_t startPos, openBracketPos, closeBracketPos;
	size_t finalStartPos, finalEndPos;
	std::vector<std::wstring> tagStack;

	startPos = 0;

	while ((openBracketPos = line.find(L"<", startPos)) != std::wstring::npos)
	{
		finalStartPos = finalLine.size();
		finalLine += line.substr(startPos, openBracketPos - startPos);
		finalEndPos = finalLine.size();

		if (finalEndPos != finalStartPos)
		{
			SRTSubtitleEntry::TextRangeFormat trf;

			trf.Range.length = finalEndPos - finalStartPos;
			trf.Range.startPosition = finalStartPos;
			trf.Style = m_SubCoreConfig.m_FontStyle;
			trf.Weight = m_SubCoreConfig.m_FontWeight;
			trf.Strikethrough = FALSE;
			trf.Underline = FALSE;

			for (auto it = tagStack.begin(); it != tagStack.end(); ++it)
			{
				if ((*it).compare(L"b") == 0)
				{
					trf.Weight = DWRITE_FONT_WEIGHT_BOLD;
				}
				else if ((*it).compare(L"i") == 0)
				{
					trf.Style = DWRITE_FONT_STYLE_ITALIC;
				}
				else if ((*it).compare(L"u") == 0)
				{
					trf.Underline = TRUE;
				}
				else if ((*it).compare(L"s") == 0)
				{
					trf.Strikethrough = TRUE;
				}
			}

			entry->SubTextFormat.push_back(trf);
		}

		// Find close bracket
		closeBracketPos = line.find(L">", openBracketPos);

		std::wstring tag = line.substr(openBracketPos+1, closeBracketPos - openBracketPos - 1);

		// Is this a closing tag?
		if (tag.find(L"/") != std::wstring::npos)
		{
			// Malformed scripts are just going to break
			tagStack.pop_back();
		}
		else
		{
			tagStack.push_back(tag);
		}

		startPos = closeBracketPos+1;
	}

	if (startPos != line.size() - 1)
	{
		// Copy remainder line
		finalLine += line.substr(startPos);
	}

	entry->Text = finalLine;

	return true;

}

bool SRTSubtitleRenderer::ParseFormatHeader(const std::wstring& header)
{
	UNREFERENCED_PARAMETER(header);
	return true;
}

bool SRTSubtitleRenderer::ParseFormatHeader(const unsigned char* header)
{
	UNREFERENCED_PARAMETER(header);
	return true;
}

bool SRTSubtitleRenderer::ParseData(const unsigned char* data)
{
	UNREFERENCED_PARAMETER(data);
	return false;
}

bool SRTSubtitleRenderer::ParseData(const unsigned char* data, ptrdiff_t offset)
{
	UNREFERENCED_PARAMETER(data);
	UNREFERENCED_PARAMETER(offset);
	return false;
}

bool SRTSubtitleRenderer::ParseData(const unsigned char* data, ptrdiff_t startOffset, ptrdiff_t endOffset)
{
	UNREFERENCED_PARAMETER(data);
	UNREFERENCED_PARAMETER(startOffset);
	UNREFERENCED_PARAMETER(endOffset);
	return false;
}

void SRTSubtitleRenderer::Invalidate()
{
	m_SubtitleMap.clear();
}

size_t SRTSubtitleRenderer::GetSubtitlePictureCount(REFERENCE_TIME rtNow)
{
	UNREFERENCED_PARAMETER(rtNow);
	return 0U;
}

void SRTSubtitleRenderer::GetSubtitlePicture(REFERENCE_TIME rtNow, SubtitlePicture** ppOutSubPics)
{
	UNREFERENCED_PARAMETER(rtNow);
	UNREFERENCED_PARAMETER(ppOutSubPics);
}

bool SRTSubtitleRenderer::CheckLineIsTimestamp(const std::wstring& line)
{
	return (line.find(L"-->") != std::wstring::npos &&
		line.find(L":") != std::wstring::npos &&
		line.find(L",") != std::wstring::npos);
}

void SRTSubtitleRenderer::ComputeTimestamp(const std::wstring& line, REFERENCE_TIME& rtStart, REFERENCE_TIME& rtEnd)
{
	size_t startPos, endPos;
	size_t hours, minutes, seconds, milliseconds;

	startPos = 0;

	// Get hours
	endPos = line.find(L":");
	hours = boost::lexical_cast<size_t>(line.substr(startPos, endPos - startPos));

	// Get minutes
	startPos = endPos + 1;
	endPos = line.find(L":", startPos);
	minutes = boost::lexical_cast<size_t>(line.substr(startPos, endPos - startPos));

	// Get seconds
	startPos = endPos + 1;
	endPos = line.find(L",", startPos);
	seconds = boost::lexical_cast<size_t>(line.substr(startPos, endPos - startPos));

	// Get milliseconds
	startPos = endPos + 1;
	endPos = line.find(L" ", startPos);
	milliseconds = boost::lexical_cast<size_t>(line.substr(startPos, endPos - startPos));

	// Compute starting time
	rtStart = SubtitleCoreUtilities::ConvertTimeToReferenceTime(hours, minutes, seconds, milliseconds);

	// Move to ending timestamp
	startPos = line.find(L" ", endPos+1) + 1;

	// Get hours
	endPos = line.find(L":", startPos);
	hours = boost::lexical_cast<size_t>(line.substr(startPos, endPos - startPos));

	// Get minutes
	startPos = endPos + 1;
	endPos = line.find(L":", startPos);
	minutes = boost::lexical_cast<size_t>(line.substr(startPos, endPos - startPos));

	// Get seconds
	startPos = endPos + 1;
	endPos = line.find(L",", startPos);
	seconds = boost::lexical_cast<size_t>(line.substr(startPos, endPos - startPos));

	// Get milliseconds
	startPos = endPos + 1;
	milliseconds = boost::lexical_cast<size_t>(line.substr(startPos));

	rtEnd = SubtitleCoreUtilities::ConvertTimeToReferenceTime(hours, minutes, seconds, milliseconds);
}
<|endoftext|>


<commit_before>2e321f73-2748-11e6-b4d3-e0f84713e7b8<commit_msg>I finished programming, there is nothing left to program<commit_after>2e441fa6-2748-11e6-801a-e0f84713e7b8<|endoftext|>


<commit_before>b9c800e6-ad58-11e7-bdcf-ac87a332f658<commit_msg>I'm done<commit_after>ba515078-ad58-11e7-9271-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <cmath>
#include <limits>
#include <complex>
#include <string>

//ofstream: write on files
//ifstream: read from files
//fstream: read and write from/to files

using namespace std;
ifstream myFile;
string excuse;
string output;
int choice;
string line;
int statement(int choice);
int main()
{
	cout << "Welcome to Dr. Excuse \n\n\n" << endl;
	cout << "Main Menu \n " << endl;
	cout << "1: List of Excuses \n" << endl;
	cout << "2: Random Excuse \n" << endl;
	cout << "3: New excuse \n" << endl;
	cin >> choice;
	statement(choice);

	//cout << excuse << endl;
	cin.clear();
	cin.ignore();
	cin.get();
	return 0;
}
int statement(int choice)
{
	ifstream myFile("book.txt", ifstream::in);

	switch (choice)
	{
		case 1:
				cout << "You chose 1: List: \n . \n .. \n ..." << endl;
				if (myFile.is_open())
				{
					while (getline(myFile, line))
					{
						cout << line << '\n';
					}
					myFile.close();
				}

				else{
					cout << "Program code 526 \n Unable to open file";
				}
					break;

		case 2:
			//myFile.open("book.txt");
			//myFile << "Reading this to a file .\n " << endl;
			//myFile.close();
			break;
		case 3:
			cout << "You chose 3: ...... " << endl;
			cout << "Type in your statment " << endl;
			cin >> excuse;
			getline(cin, excuse);

			break;
		default:
			break;
	}
	return 1;
}
<commit_msg>Update main.cpp<commit_after>#include <iostream>
#include <fstream>
#include <cmath>
#include <limits>
#include <complex>
#include <string>

//ofstream: write on files
//ifstream: read from files
//fstream: read and write from/to files

using namespace std;
ifstream myFile; // test
string excuse;
string output;
int choice;
string line;
int statement(int choice);
int main()
{
	cout << "Welcome to Dr. Excuse \n\n\n" << endl;
	cout << "Main Menu \n " << endl;
	cout << "1: List of Excuses \n" << endl;
	cout << "2: Random Excuse \n" << endl;
	cout << "3: New excuse \n" << endl;
	cin >> choice;
	statement(choice);

	//cout << excuse << endl;
	cin.clear();
	cin.ignore();
	cin.get();
	return 0;
}
int statement(int choice)
{
	ifstream myFile("book.txt", ifstream::in);

	switch (choice)
	{
		case 1:
				cout << "You chose 1: List: \n . \n .. \n ..." << endl;
				if (myFile.is_open())
				{
					while (getline(myFile, line))
					{
						cout << line << '\n';
					}
					myFile.close();
				}

				else{
					cout << "Program code 526 \n Unable to open file";
				}
					break;

		case 2:
			//myFile.open("book.txt");
			//myFile << "Reading this to a file .\n " << endl;
			//myFile.close();
			break;
		case 3:
			cout << "You chose 3: ...... " << endl;
			cout << "Type in your statment " << endl;
			cin >> excuse;
			getline(cin, excuse);

			break;
		default:
			break;
	}
	return 1;
}
<|endoftext|>


<commit_before>#include "hFramework.h"
#include <stdio.h>
#include "Lego_Touch.h"

using namespace hFramework;
using namespace hSensors;
class Lock {
private:
    int power = 1000;
    int angle1 = 0;
    int angle2 = 180;
    bool block = 1;
    bool locked = true;
public:
    Lock(int power, int angle1, int angle2, bool block) {
        this.power = power;
        this.angle1 = angle1;
        this.angle2 = angle2;
        this.block = block;
    };
    Lock() {};
    bool open(bool open) {
        if(open) {
            printf("\rOpening...\n");
            hMot1.rotAbs(this.angle1, this.power, this.block);
            this.locked = false;
        } else {
            printf("\rClosing...\n");
            hMot1.rotAbs(this.angle2, this.power, this.block);
            this.locked = true;
        }
        hMot1.stopRegulation();
        printf("\rDone!\n");
        return open;
    };
    bool isLocked() {
        return this.locked;
    }
    bool calibrate() {

    }
};

void hMain(void)
{
    sys.setLogDev(&Serial);
    Lego_Touch sensor(hSens1);

    bool maindown = false;
    bool open = false;

    Lock l = new Lock();

    while(!hBtn1.isPressed()) {
        bool s = sensor.isPressed();

        if(s) { // Changing mode
            if(!maindown) {
                printf("Button down, %d times more", counter);
                maindown = true;
                if(open) {
                    open = l->open(false);
                } else {
                    open = l->open(true);
                }
            }
        } else {
            if(maindown) {
                maindown = false;
            }
        }
        sys.delay_ms(50);
    }
}<commit_msg>cleared<commit_after>#include "hFramework.h"
#include <stdio.h>
#include "Lego_Touch.h"

using namespace hFramework;
using namespace hSensors;
class Lock {
private:
    int power = 1000;
    int angle1 = 0;
    int angle2 = 180;
    bool block = 1;
    bool locked = true;
public:
    Lock(int power, int angle1, int angle2, bool block) {
        this->power = power;
        this->angle1 = angle1;
        this->angle2 = angle2;
        this->block = block;
    };
    Lock() {};
    bool open(bool open) {
        if(open) {
            printf("\rOpening...\n");
            hMot1.rotAbs(this->angle1, this->power, this->block);
        } else {
            printf("\rClosing...\n");
            hMot1.rotAbs(this->angle2, this->power, this->block);
        }
        this->locked = !open;
        hMot1.stopRegulation();
        printf("\rDone!\n");
        return open;
    };
    bool isLocked() {
        return this->locked;
    }
    bool calibrate() {

    }
};

void hMain(void)
{
    sys.setLogDev(&Serial);
    Lego_Touch sensor(hSens1);

    bool maindown = false;
    bool open = false;

    Lock l = new Lock();

    while(!hBtn1.isPressed()) {
        bool s = sensor.isPressed();

        if(s) { // Changing mode
            if(!maindown) {
                printf("Button down, %d times more", counter);
                maindown = true;
                if(open) {
                    open = l.open(false);
                } else {
                    open = l.open(true);
                }
            }
        } else {
            if(maindown) {
                maindown = false;
            }
        }
        sys.delay_ms(50);
    }
}<|endoftext|>


<commit_before>#include <dxgi1_5.h>
#include <d3d11.h>

#include "glcorearb.h"
#include "wglext.h"

#include <cassert>
#include <cstdio>

#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "opengl32.lib")

#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480

void APIENTRY DebugCallbackGL(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam)
{
    OutputDebugStringA("DebugCallbackGL: ");
    OutputDebugStringA(message);
    OutputDebugStringA("\n");
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
    case WM_CLOSE:
        ExitProcess(0);
    }

    return DefWindowProc(hWnd, msg, wParam, lParam);
}

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    bool ok;
    HRESULT hr;

    // Register window class
    WNDCLASSEX wc = {};
    wc.cbSize = sizeof(wc);
    wc.style = CS_OWNDC;
    wc.lpfnWndProc = WndProc;
    wc.hInstance = GetModuleHandleW(NULL);
    wc.hCursor = LoadCursorW(NULL, IDC_ARROW);
    wc.lpszClassName = TEXT("WindowClass");
    ok = RegisterClassExW(&wc) != NULL;
    assert(ok);

    // Determine size of window based on window style
    DWORD dwStyle = WS_OVERLAPPEDWINDOW;
    DWORD dwExStyle = 0;
    RECT wr = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT };
    ok = AdjustWindowRectEx(&wr, dwStyle, FALSE, dwExStyle) != FALSE;
    assert(ok);

    TCHAR* title = TEXT("OpenGL on DXGI");

    // Create window
    HWND hWnd = CreateWindowEx(
        dwExStyle, TEXT("WindowClass"), title, dwStyle,
        CW_USEDEFAULT, CW_USEDEFAULT,
        wr.right - wr.left, wr.bottom - wr.top,
        NULL, NULL, hInstance, NULL);
    assert(hWnd);

    // Unhide the window
    ShowWindow(hWnd, SW_SHOWDEFAULT);

    // Create window that will be used to create a GL context
    HWND gl_hWnd = CreateWindowEx(0, TEXT("WindowClass"), 0, 0, 0, 0, 0, 0, 0, 0, hInstance, 0);
    assert(gl_hWnd);

    HDC gl_hDC = GetDC(gl_hWnd);
    assert(gl_hDC);

    // set pixelformat for window that supports OpenGL
    PIXELFORMATDESCRIPTOR gl_pfd = {};
    gl_pfd.nSize = sizeof(gl_pfd);
    gl_pfd.nVersion = 1;
    gl_pfd.dwFlags = PFD_SUPPORT_OPENGL;

    int chosenPixelFormat = ChoosePixelFormat(gl_hDC, &gl_pfd);
    ok = SetPixelFormat(gl_hDC, chosenPixelFormat, &gl_pfd) != FALSE;
    assert(ok);

    // Create dummy GL context that will be used to create the real context
    HGLRC dummy_hGLRC = wglCreateContext(gl_hDC);
    assert(dummy_hGLRC);

    // Use the dummy context to get function to create a better context
    ok = wglMakeCurrent(gl_hDC, dummy_hGLRC) != FALSE;
    assert(ok);

    PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");

    int contextFlagsGL = 0;
#ifdef _DEBUG
    contextFlagsGL |= WGL_CONTEXT_DEBUG_BIT_ARB;
#endif

    int contextAttribsGL[] = {
        WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
        WGL_CONTEXT_MINOR_VERSION_ARB, 3,
        WGL_CONTEXT_FLAGS_ARB, contextFlagsGL,
        WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
        0
    };

    HGLRC hGLRC = wglCreateContextAttribsARB(gl_hDC, NULL, contextAttribsGL);
    assert(hGLRC);

    // Switch to the new context and ditch the old one
    ok = wglMakeCurrent(gl_hDC, hGLRC) != FALSE;
    assert(ok);
    ok = wglDeleteContext(dummy_hGLRC) != FALSE;
    assert(ok);

    // Grab WGL functions
    PFNWGLDXOPENDEVICENVPROC wglDXOpenDeviceNV = (PFNWGLDXOPENDEVICENVPROC)wglGetProcAddress("wglDXOpenDeviceNV");
    PFNWGLDXREGISTEROBJECTNVPROC wglDXRegisterObjectNV = (PFNWGLDXREGISTEROBJECTNVPROC)wglGetProcAddress("wglDXRegisterObjectNV");
    PFNWGLDXUNREGISTEROBJECTNVPROC wglDXUnregisterObjectNV = (PFNWGLDXUNREGISTEROBJECTNVPROC)wglGetProcAddress("wglDXUnregisterObjectNV");
    PFNWGLDXLOCKOBJECTSNVPROC wglDXLockObjectsNV = (PFNWGLDXLOCKOBJECTSNVPROC)wglGetProcAddress("wglDXLockObjectsNV");
    PFNWGLDXUNLOCKOBJECTSNVPROC wglDXUnlockObjectsNV = (PFNWGLDXUNLOCKOBJECTSNVPROC)wglGetProcAddress("wglDXUnlockObjectsNV");

    // Fall back to GetProcAddress to get GL 1 functions. wglGetProcAddress returns NULL on those.
    HMODULE hOpenGL32 = LoadLibrary(TEXT("OpenGL32.dll"));

    // Grab OpenGL functions
    PFNGLENABLEPROC glEnable = (PFNGLENABLEPROC)GetProcAddress(hOpenGL32, "glEnable");
    PFNGLDISABLEPROC glDisable = (PFNGLDISABLEPROC)GetProcAddress(hOpenGL32, "glDisable");
    PFNGLCLEARPROC glClear = (PFNGLCLEARPROC)GetProcAddress(hOpenGL32, "glClear");
    PFNGLSCISSORPROC glScissor = (PFNGLSCISSORPROC)GetProcAddress(hOpenGL32, "glScissor");
    PFNGLGENTEXTURESPROC glGenTextures = (PFNGLGENTEXTURESPROC)GetProcAddress(hOpenGL32, "glGenTextures");
    PFNGLGENFRAMEBUFFERSPROC glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)wglGetProcAddress("glGenFramebuffers");
    PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)wglGetProcAddress("glBindFramebuffer");
    PFNGLFRAMEBUFFERTEXTURE2DPROC glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)wglGetProcAddress("glFramebufferTexture2D");

    // Enable OpenGL debugging
#ifdef _DEBUG
    glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
    PFNGLDEBUGMESSAGECALLBACKPROC glDebugMessageCallback = (PFNGLDEBUGMESSAGECALLBACKPROC)wglGetProcAddress("glDebugMessageCallback");
    glDebugMessageCallback(DebugCallbackGL, 0);
#endif

    // create D3D11 device, context and swap chain.
    ID3D11Device *device;
    ID3D11DeviceContext *devCtx;
    IDXGISwapChain *swapChain;
    HANDLE hFrameLatencyWaitableObject;

    DXGI_SWAP_CHAIN_DESC scd = {};
    scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    scd.SampleDesc.Count = 1;
    scd.BufferCount = 3;
    scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    scd.OutputWindow = hWnd;
    scd.Windowed = TRUE;
    scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
    scd.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;

    UINT flags = 0;
#if _DEBUG
    flags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

    hr = D3D11CreateDeviceAndSwapChain(NULL,                        // pAdapter
        D3D_DRIVER_TYPE_HARDWARE,    // DriverType
        NULL,                        // Software
        flags,                       // Flags (Do not set D3D11_CREATE_DEVICE_SINGLETHREADED)
        NULL,                        // pFeatureLevels
        0,                           // FeatureLevels
        D3D11_SDK_VERSION,           // SDKVersion
        &scd,                        // pSwapChainDesc
        &swapChain,                  // ppSwapChain
        &device,                     // ppDevice
        NULL,                        // pFeatureLevel
        &devCtx);                    // ppImmediateContext
    assert(SUCCEEDED(hr));

    // get frame latency waitable object
    IDXGISwapChain2* swapChain2;
    hr = swapChain->QueryInterface(&swapChain2);
    hFrameLatencyWaitableObject = swapChain2->GetFrameLatencyWaitableObject();

    // Create depth stencil texture
    ID3D11Texture2D *dxDepthBuffer;
    hr = device->CreateTexture2D(
        &CD3D11_TEXTURE2D_DESC(DXGI_FORMAT_R24G8_TYPELESS, SCREEN_WIDTH, SCREEN_HEIGHT, 1, 1, D3D11_BIND_DEPTH_STENCIL),
        NULL,
        &dxDepthBuffer);
    assert(SUCCEEDED(hr));

    // Create depth stencil view
    ID3D11DepthStencilView *depthBufferView;
    hr = device->CreateDepthStencilView(
        dxDepthBuffer,
        &CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D, DXGI_FORMAT_D24_UNORM_S8_UINT),
        &depthBufferView);
    assert(SUCCEEDED(hr));

    // Register D3D11 device with GL
    HANDLE gl_handleD3D;
    gl_handleD3D = wglDXOpenDeviceNV(device);

    // register the Direct3D depth/stencil buffer as texture2d in opengl
    GLuint dsvNameGL;
    glGenTextures(1, &dsvNameGL);
    HANDLE dsvHandleGL = wglDXRegisterObjectNV(gl_handleD3D, dxDepthBuffer, dsvNameGL, GL_TEXTURE_2D, WGL_ACCESS_READ_WRITE_NV);

    // Initialize GL FBO
    GLuint fbo;
    glGenFramebuffers(1, &fbo);

    // attach the Direct3D depth buffer to FBO
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, dsvNameGL, 0);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, dsvNameGL, 0);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    // GL RTV will be recreated every frame to use the FLIP swap chain
    GLuint rtvNameGL;
    glGenTextures(1, &rtvNameGL);

    // main loop
    while (true)
    {
        // Handle all events
        MSG msg;
        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        // Wait until the previous frame is presented before drawing the next frame
        ok = WaitForSingleObject(hFrameLatencyWaitableObject, INFINITE) == WAIT_OBJECT_0;
        assert(ok);

        // Fetch the current swapchain backbuffer from the FLIP swap chain
        ID3D11Texture2D *dxColorBuffer;
        hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID *)&dxColorBuffer);
        assert(SUCCEEDED(hr));

        // Create RTV for swapchain backbuffer
        ID3D11RenderTargetView *colorBufferView;
        hr = device->CreateRenderTargetView(
            dxColorBuffer,
            &CD3D11_RENDER_TARGET_VIEW_DESC(D3D11_RTV_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM),
            &colorBufferView);
        assert(SUCCEEDED(hr));

        // register current backbuffer
        HANDLE rtvHandleGL = wglDXRegisterObjectNV(gl_handleD3D, dxColorBuffer, rtvNameGL, GL_TEXTURE_2D, WGL_ACCESS_READ_WRITE_NV);

        // Attach Direct3D color buffer to FBO
        glBindFramebuffer(GL_FRAMEBUFFER, fbo);
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rtvNameGL, 0);
        glBindFramebuffer(GL_FRAMEBUFFER, 0);

        // Attach back buffer and depth texture to redertarget for the device.
        devCtx->OMSetRenderTargets(1, &colorBufferView, depthBufferView);

        // Direct3d renders to the render targets
        float dxClearColor[] = { 1.0f, 0.0f, 0.0f, 1.0f };
        devCtx->ClearRenderTargetView(colorBufferView, dxClearColor);

        // lock the dsv/rtv for GL access
        wglDXLockObjectsNV(gl_handleD3D, 1, &dsvHandleGL);
        wglDXLockObjectsNV(gl_handleD3D, 1, &rtvHandleGL);

        // OpenGL renders to the render targets
        glBindFramebuffer(GL_FRAMEBUFFER, fbo);
        // clear half the screen, so half the screen will be from DX and half from GL
        glEnable(GL_SCISSOR_TEST);
        glScissor(0, 0, SCREEN_WIDTH / 2, SCREEN_HEIGHT);
        glClear(GL_COLOR_BUFFER_BIT);
        glDisable(GL_SCISSOR_TEST);
        glBindFramebuffer(GL_FRAMEBUFFER, 0);

        // unlock the dsv/rtv
        wglDXUnlockObjectsNV(gl_handleD3D, 1, &dsvHandleGL);
        wglDXUnlockObjectsNV(gl_handleD3D, 1, &rtvHandleGL);

        // DXGI presents the results on the screen
        hr = swapChain->Present(0, 0);
        assert(SUCCEEDED(hr));

        // release current backbuffer back to the swap chain
        wglDXUnregisterObjectNV(gl_handleD3D, rtvHandleGL);
        colorBufferView->Release();
        dxColorBuffer->Release();
    }
}<commit_msg>improved colors to help differentiate<commit_after>#include <dxgi1_5.h>
#include <d3d11.h>

#include "glcorearb.h"
#include "wglext.h"

#include <cassert>
#include <cstdio>

#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "opengl32.lib")

#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480

void APIENTRY DebugCallbackGL(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam)
{
    OutputDebugStringA("DebugCallbackGL: ");
    OutputDebugStringA(message);
    OutputDebugStringA("\n");
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
    case WM_CLOSE:
        ExitProcess(0);
    }

    return DefWindowProc(hWnd, msg, wParam, lParam);
}

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    bool ok;
    HRESULT hr;

    // Register window class
    WNDCLASSEX wc = {};
    wc.cbSize = sizeof(wc);
    wc.style = CS_OWNDC;
    wc.lpfnWndProc = WndProc;
    wc.hInstance = GetModuleHandleW(NULL);
    wc.hCursor = LoadCursorW(NULL, IDC_ARROW);
    wc.lpszClassName = TEXT("WindowClass");
    ok = RegisterClassExW(&wc) != NULL;
    assert(ok);

    // Determine size of window based on window style
    DWORD dwStyle = WS_OVERLAPPEDWINDOW;
    DWORD dwExStyle = 0;
    RECT wr = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT };
    ok = AdjustWindowRectEx(&wr, dwStyle, FALSE, dwExStyle) != FALSE;
    assert(ok);

    TCHAR* title = TEXT("OpenGL on DXGI");

    // Create window
    HWND hWnd = CreateWindowEx(
        dwExStyle, TEXT("WindowClass"), title, dwStyle,
        CW_USEDEFAULT, CW_USEDEFAULT,
        wr.right - wr.left, wr.bottom - wr.top,
        NULL, NULL, hInstance, NULL);
    assert(hWnd);

    // Unhide the window
    ShowWindow(hWnd, SW_SHOWDEFAULT);

    // Create window that will be used to create a GL context
    HWND gl_hWnd = CreateWindowEx(0, TEXT("WindowClass"), 0, 0, 0, 0, 0, 0, 0, 0, hInstance, 0);
    assert(gl_hWnd);

    HDC gl_hDC = GetDC(gl_hWnd);
    assert(gl_hDC);

    // set pixelformat for window that supports OpenGL
    PIXELFORMATDESCRIPTOR gl_pfd = {};
    gl_pfd.nSize = sizeof(gl_pfd);
    gl_pfd.nVersion = 1;
    gl_pfd.dwFlags = PFD_SUPPORT_OPENGL;

    int chosenPixelFormat = ChoosePixelFormat(gl_hDC, &gl_pfd);
    ok = SetPixelFormat(gl_hDC, chosenPixelFormat, &gl_pfd) != FALSE;
    assert(ok);

    // Create dummy GL context that will be used to create the real context
    HGLRC dummy_hGLRC = wglCreateContext(gl_hDC);
    assert(dummy_hGLRC);

    // Use the dummy context to get function to create a better context
    ok = wglMakeCurrent(gl_hDC, dummy_hGLRC) != FALSE;
    assert(ok);

    PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");

    int contextFlagsGL = 0;
#ifdef _DEBUG
    contextFlagsGL |= WGL_CONTEXT_DEBUG_BIT_ARB;
#endif

    int contextAttribsGL[] = {
        WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
        WGL_CONTEXT_MINOR_VERSION_ARB, 3,
        WGL_CONTEXT_FLAGS_ARB, contextFlagsGL,
        WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
        0
    };

    HGLRC hGLRC = wglCreateContextAttribsARB(gl_hDC, NULL, contextAttribsGL);
    assert(hGLRC);

    // Switch to the new context and ditch the old one
    ok = wglMakeCurrent(gl_hDC, hGLRC) != FALSE;
    assert(ok);
    ok = wglDeleteContext(dummy_hGLRC) != FALSE;
    assert(ok);

    // Grab WGL functions
    PFNWGLDXOPENDEVICENVPROC wglDXOpenDeviceNV = (PFNWGLDXOPENDEVICENVPROC)wglGetProcAddress("wglDXOpenDeviceNV");
    PFNWGLDXREGISTEROBJECTNVPROC wglDXRegisterObjectNV = (PFNWGLDXREGISTEROBJECTNVPROC)wglGetProcAddress("wglDXRegisterObjectNV");
    PFNWGLDXUNREGISTEROBJECTNVPROC wglDXUnregisterObjectNV = (PFNWGLDXUNREGISTEROBJECTNVPROC)wglGetProcAddress("wglDXUnregisterObjectNV");
    PFNWGLDXLOCKOBJECTSNVPROC wglDXLockObjectsNV = (PFNWGLDXLOCKOBJECTSNVPROC)wglGetProcAddress("wglDXLockObjectsNV");
    PFNWGLDXUNLOCKOBJECTSNVPROC wglDXUnlockObjectsNV = (PFNWGLDXUNLOCKOBJECTSNVPROC)wglGetProcAddress("wglDXUnlockObjectsNV");

    // Fall back to GetProcAddress to get GL 1 functions. wglGetProcAddress returns NULL on those.
    HMODULE hOpenGL32 = LoadLibrary(TEXT("OpenGL32.dll"));

    // Grab OpenGL functions
    PFNGLENABLEPROC glEnable = (PFNGLENABLEPROC)GetProcAddress(hOpenGL32, "glEnable");
    PFNGLDISABLEPROC glDisable = (PFNGLDISABLEPROC)GetProcAddress(hOpenGL32, "glDisable");
    PFNGLCLEARPROC glClear = (PFNGLCLEARPROC)GetProcAddress(hOpenGL32, "glClear");
    PFNGLCLEARCOLORPROC glClearColor = (PFNGLCLEARCOLORPROC)GetProcAddress(hOpenGL32, "glClearColor");
    PFNGLSCISSORPROC glScissor = (PFNGLSCISSORPROC)GetProcAddress(hOpenGL32, "glScissor");
    PFNGLGENTEXTURESPROC glGenTextures = (PFNGLGENTEXTURESPROC)GetProcAddress(hOpenGL32, "glGenTextures");
    PFNGLGENFRAMEBUFFERSPROC glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)wglGetProcAddress("glGenFramebuffers");
    PFNGLBINDFRAMEBUFFERPROC glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)wglGetProcAddress("glBindFramebuffer");
    PFNGLFRAMEBUFFERTEXTURE2DPROC glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)wglGetProcAddress("glFramebufferTexture2D");

    // Enable OpenGL debugging
#ifdef _DEBUG
    glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
    PFNGLDEBUGMESSAGECALLBACKPROC glDebugMessageCallback = (PFNGLDEBUGMESSAGECALLBACKPROC)wglGetProcAddress("glDebugMessageCallback");
    glDebugMessageCallback(DebugCallbackGL, 0);
#endif

    // create D3D11 device, context and swap chain.
    ID3D11Device *device;
    ID3D11DeviceContext *devCtx;
    IDXGISwapChain *swapChain;
    HANDLE hFrameLatencyWaitableObject;

    DXGI_SWAP_CHAIN_DESC scd = {};
    scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    scd.SampleDesc.Count = 1;
    scd.BufferCount = 3;
    scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    scd.OutputWindow = hWnd;
    scd.Windowed = TRUE;
    scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
    scd.Flags = DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;

    UINT flags = 0;
#if _DEBUG
    flags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

    hr = D3D11CreateDeviceAndSwapChain(NULL,                        // pAdapter
        D3D_DRIVER_TYPE_HARDWARE,    // DriverType
        NULL,                        // Software
        flags,                       // Flags (Do not set D3D11_CREATE_DEVICE_SINGLETHREADED)
        NULL,                        // pFeatureLevels
        0,                           // FeatureLevels
        D3D11_SDK_VERSION,           // SDKVersion
        &scd,                        // pSwapChainDesc
        &swapChain,                  // ppSwapChain
        &device,                     // ppDevice
        NULL,                        // pFeatureLevel
        &devCtx);                    // ppImmediateContext
    assert(SUCCEEDED(hr));

    // get frame latency waitable object
    IDXGISwapChain2* swapChain2;
    hr = swapChain->QueryInterface(&swapChain2);
    hFrameLatencyWaitableObject = swapChain2->GetFrameLatencyWaitableObject();

    // Create depth stencil texture
    ID3D11Texture2D *dxDepthBuffer;
    hr = device->CreateTexture2D(
        &CD3D11_TEXTURE2D_DESC(DXGI_FORMAT_R24G8_TYPELESS, SCREEN_WIDTH, SCREEN_HEIGHT, 1, 1, D3D11_BIND_DEPTH_STENCIL),
        NULL,
        &dxDepthBuffer);
    assert(SUCCEEDED(hr));

    // Create depth stencil view
    ID3D11DepthStencilView *depthBufferView;
    hr = device->CreateDepthStencilView(
        dxDepthBuffer,
        &CD3D11_DEPTH_STENCIL_VIEW_DESC(D3D11_DSV_DIMENSION_TEXTURE2D, DXGI_FORMAT_D24_UNORM_S8_UINT),
        &depthBufferView);
    assert(SUCCEEDED(hr));

    // Register D3D11 device with GL
    HANDLE gl_handleD3D;
    gl_handleD3D = wglDXOpenDeviceNV(device);

    // register the Direct3D depth/stencil buffer as texture2d in opengl
    GLuint dsvNameGL;
    glGenTextures(1, &dsvNameGL);
    HANDLE dsvHandleGL = wglDXRegisterObjectNV(gl_handleD3D, dxDepthBuffer, dsvNameGL, GL_TEXTURE_2D, WGL_ACCESS_READ_WRITE_NV);

    // Initialize GL FBO
    GLuint fbo;
    glGenFramebuffers(1, &fbo);

    // attach the Direct3D depth buffer to FBO
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, dsvNameGL, 0);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, dsvNameGL, 0);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    // GL RTV will be recreated every frame to use the FLIP swap chain
    GLuint rtvNameGL;
    glGenTextures(1, &rtvNameGL);

    // main loop
    while (true)
    {
        // Handle all events
        MSG msg;
        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        // Wait until the previous frame is presented before drawing the next frame
        ok = WaitForSingleObject(hFrameLatencyWaitableObject, INFINITE) == WAIT_OBJECT_0;
        assert(ok);

        // Fetch the current swapchain backbuffer from the FLIP swap chain
        ID3D11Texture2D *dxColorBuffer;
        hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID *)&dxColorBuffer);
        assert(SUCCEEDED(hr));

        // Create RTV for swapchain backbuffer
        ID3D11RenderTargetView *colorBufferView;
        hr = device->CreateRenderTargetView(
            dxColorBuffer,
            &CD3D11_RENDER_TARGET_VIEW_DESC(D3D11_RTV_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM),
            &colorBufferView);
        assert(SUCCEEDED(hr));

        // register current backbuffer
        HANDLE rtvHandleGL = wglDXRegisterObjectNV(gl_handleD3D, dxColorBuffer, rtvNameGL, GL_TEXTURE_2D, WGL_ACCESS_READ_WRITE_NV);

        // Attach Direct3D color buffer to FBO
        glBindFramebuffer(GL_FRAMEBUFFER, fbo);
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rtvNameGL, 0);
        glBindFramebuffer(GL_FRAMEBUFFER, 0);

        // Attach back buffer and depth texture to redertarget for the device.
        devCtx->OMSetRenderTargets(1, &colorBufferView, depthBufferView);

        // Direct3d renders to the render targets
        float dxClearColor[] = { 0.5f, 0.0f, 0.0f, 1.0f };
        devCtx->ClearRenderTargetView(colorBufferView, dxClearColor);

        // lock the dsv/rtv for GL access
        wglDXLockObjectsNV(gl_handleD3D, 1, &dsvHandleGL);
        wglDXLockObjectsNV(gl_handleD3D, 1, &rtvHandleGL);

        // OpenGL renders to the render targets
        glBindFramebuffer(GL_FRAMEBUFFER, fbo);
        // clear half the screen, so half the screen will be from DX and half from GL
        glEnable(GL_SCISSOR_TEST);
        glScissor(0, 0, SCREEN_WIDTH / 2, SCREEN_HEIGHT);
        glClearColor(0.0f, 0.5f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        glDisable(GL_SCISSOR_TEST);
        glBindFramebuffer(GL_FRAMEBUFFER, 0);

        // unlock the dsv/rtv
        wglDXUnlockObjectsNV(gl_handleD3D, 1, &dsvHandleGL);
        wglDXUnlockObjectsNV(gl_handleD3D, 1, &rtvHandleGL);

        // DXGI presents the results on the screen
        hr = swapChain->Present(0, 0);
        assert(SUCCEEDED(hr));

        // release current backbuffer back to the swap chain
        wglDXUnregisterObjectNV(gl_handleD3D, rtvHandleGL);
        colorBufferView->Release();
        dxColorBuffer->Release();
    }
}<|endoftext|>


<commit_before>/*
 * main.cpp
 *
 *  Created on: 06.10.2013
 *      Author: mats
 */

#include <Disp.h>
#include <GPIO.h>

#include <iostream>
#include <unistd.h>
#include <signal.h>

// FUNCTION PROTOTYPING
void msleep( unsigned milisec );
void sig_handler( int sig );

// GLOBAL VARIABLES
bool ctrl_c_pressed = false;

int main()
{
	if( signal(SIGINT, sig_handler) == SIG_ERR )
		std::cout << "Can't catch SIGINT" << std::endl;

	GPIO* led1 = new GPIO(4, OUT);
	GPIO* led2 = new GPIO(3, OUT);
	GPIO* led3 = new GPIO(2, OUT);
	GPIO* button1 = new GPIO(17, IN);
	GPIO* button2 = new GPIO(27, IN);
	GPIO* button3 = new GPIO(22, IN);
	Disp* pvc160101 = new Disp();

	while(1)
	{
		led1->setValue( button1->getValue() );
		led2->setValue( button2->getValue() );
		led3->setValue( button3->getValue() );

		msleep(300);

		if( ctrl_c_pressed )
			break;
	}

	delete pvc160101;
	delete led1; delete led2; delete led3;
	delete button1; delete button2; delete button3;
}

void msleep( unsigned milisec )
{
	for(unsigned i=0; i<milisec; ++i)
		usleep( 1000 );
}

void sig_handler( int sig )
{
	if (sig == SIGINT)
		ctrl_c_pressed = true;
}
<commit_msg>removed comments<commit_after>#include <Disp.h>
#include <GPIO.h>

#include <iostream>
#include <unistd.h>
#include <signal.h>

// FUNCTION PROTOTYPING
void msleep( unsigned milisec );
void sig_handler( int sig );

// GLOBAL VARIABLES
bool ctrl_c_pressed = false;

int main()
{
	if( signal(SIGINT, sig_handler) == SIG_ERR )
		std::cout << "Can't catch SIGINT" << std::endl;

	GPIO* led1 = new GPIO(4, OUT);
	GPIO* led2 = new GPIO(3, OUT);
	GPIO* led3 = new GPIO(2, OUT);
	GPIO* button1 = new GPIO(17, IN);
	GPIO* button2 = new GPIO(27, IN);
	GPIO* button3 = new GPIO(22, IN);
	Disp* pvc160101 = new Disp();

	while(1)
	{
		led1->setValue( button1->getValue() );
		led2->setValue( button2->getValue() );
		led3->setValue( button3->getValue() );

		msleep(300);

		if( ctrl_c_pressed )
			break;
	}

	delete pvc160101;
	delete led1; delete led2; delete led3;
	delete button1; delete button2; delete button3;
}

void msleep( unsigned milisec )
{
	for(unsigned i=0; i<milisec; ++i)
		usleep( 1000 );
}

void sig_handler( int sig )
{
	if (sig == SIGINT)
		ctrl_c_pressed = true;
}
<|endoftext|>


<commit_before>/**
 * @file sailfish_tools_system_action.cpp
 * @brief SUID root actions execution
 * @copyright (C) 2014 Jolla Ltd.
 * @par License: LGPL 2.1 http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
 */

#include "config.hpp"

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <error.h>
#include <errno.h>
#include <string.h>

#include <functional>
#include <iostream>

typedef std::function<int (int, char *[])> action_type;

static int restart_service(const std::string &name)
{
    std::string cmd("systemctl restart " + name + ".service");
    std::cerr << "Executing " << cmd << std::endl;
    return system(cmd.c_str());
}

static struct {
    std::string name;
    action_type fn;
} actions[] = {
    { "repair_rpm_db", [](int, char *[]) {
            return system((application_dir + "/repair_rpm_db.sh").c_str());
        }},
    { "restart_dalvik", [](int, char *[]) {
            return restart_service("aliendalvik");
        }},
    { "restart_network", [](int, char *[]) {
            return restart_service("connman");
        }}
};

int main(int argc, char *argv[])
{
    setuid(0);
    if (argc < 2) {
        error(1, EINVAL, "Need to provide action name");
    }

    const std::string cmd(argv[1]);
    for (const auto &action: actions) {
        if (cmd == action.name) {
            auto rc = action.fn(argc, argv);
            if (rc)
                perror("Executing action");
            return rc;
        }
    }

    error(1, EINVAL, "Unknown action: %s", cmd.c_str());
    return 1; // just for compiler, error exits ^
}
<commit_msg>[sysaction] rework to be more secure and helpful<commit_after>/**
 * @file sailfish_tools_system_action.cpp
 * @brief SUID root actions execution
 * @copyright (C) 2014 Jolla Ltd.
 * @par License: LGPL 2.1 http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
 */

#include "config.hpp"

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <error.h>
#include <errno.h>
#include <string.h>

#include <iostream>
#include <sstream>
#include <map>

namespace utilities {

namespace {

struct action_ctx {};

struct Error : public std::exception
{
    Error(std::string const &msg) : res(errno), msg_(msg) {}
    virtual ~Error() noexcept(true) {}

    virtual const char* what() const noexcept(true)
    {
        return (msg_ + ". errno=" + ::strerror(res)).c_str();
    }

    int res;
    std::string msg_;
};

void system(std::string const &cmd)
{
    std::cerr << "Executing " << cmd << std::endl;
    if (::system(cmd.c_str()))
        throw Error(cmd);
}

void service_do(const std::string &name, const std::string &action)
{
    std::stringstream cmd_line;
    cmd_line << "systemctl " << action << " " << name << ".service";
    system(cmd_line.str());
}

void execute_own_utility(std::string const &file_name)
{
    system((application_dir + "/" + file_name));
}

typedef void (*action_type)(action_ctx const*);

std::map<std::string, action_type> actions = {
    { "repair_rpm_db", [](action_ctx const *) {
            execute_own_utility("repair_rpm_db.sh");
        }},
    { "restart_dalvik", [](action_ctx const *) {
            service_do("aliendalvik", "restart");
        }},
    { "restart_network", [](action_ctx const *) {
            return service_do("connman", "restart");
        }}
};

class BecomeRoot
{
public:
    BecomeRoot() : uid_(escalate()) { }
    ~BecomeRoot() {
        if (uid_)
            ::setuid(uid_);
    }
private:

    static uid_t escalate()
    {
        auto uid = ::getuid();
        if (uid) {
            if (::setuid(0) < 0)
                throw Error("Error setting root uid");
        }
        return uid;
    }

    uid_t uid_;
};

int exit_usage(std::string const &prog_name, int rc)
{
    std::stringstream s;
    s << "Usage: " << prog_name << " [-h|--help|ACTION]\n\tACTION is one of:";
    for (auto const &name_action : actions)
        s << " " << name_action.first;

    std::cerr << s.str() << std::endl;
    exit(rc);
    return rc;
}

}

int main(int argc, char *argv[])
{
    int rc = 1;
    if (argc < 2 || !argv[1]) {
        return exit_usage(argv[0], 1);
    }
    const std::string name(argv[1]);

    if (name == "-h" || name == "--help")
        return exit_usage(argv[0], 0);

    auto execute = [](action_type const &action) {
        BecomeRoot root;
        action(nullptr);
    };

    auto it = actions.find(name);
    if (it == actions.end()) {
        return exit_usage(argv[0], 1);
    }
    try {
        execute(it->second);
    } catch (std::exception const &e) {
        std::cerr << "Error " << e.what()
                  << ". While executing action: " << name.c_str()
                  << std::endl;
    } catch (...) {
        std::cerr << "Unknown error "
                  << ". While executing action: " << name.c_str()
                  << std::endl;
    }
    rc = 0;
    return rc;
}

}

int main(int argc, char *argv[])
{
    return utilities::main(argc, argv);
}

<|endoftext|>


<commit_before>// FRAGMENT(includes)
#include <iostream>
#include <seqan/index.h>

using namespace seqan;

// FRAGMENT(initialization)
int main ()
{
	typedef Index<CharString> TIndex;
	TIndex index("How many wood would a woodchuck chuck.");
	Iterator< TIndex, TopDown<ParentLinks<> > >::Type it(index);
// FRAGMENT(iteration)

	do {
		std::cout << '"' << representative(it) << '"' << std::endl;
		if (!goDown(it) && !goRight(it))
			while (goUp(it) && !goRight(it)) ;
	} while (!isRoot(it));

	return 0;
}
<commit_msg>fixed: fragment<commit_after>// FRAGMENT(initialization)
#include <iostream>
#include <seqan/index.h>

using namespace seqan;

int main ()
{
	typedef Index<CharString> TIndex;
	TIndex index("How many wood would a woodchuck chuck.");
	Iterator< TIndex, TopDown<ParentLinks<> > >::Type it(index);
// FRAGMENT(iteration)

	do {
		std::cout << '"' << representative(it) << '"' << std::endl;
		if (!goDown(it) && !goRight(it))
			while (goUp(it) && !goRight(it)) ;
	} while (!isRoot(it));

	return 0;
}
<|endoftext|>


<commit_before><commit_msg>revise a bit<commit_after><|endoftext|>


<commit_before>#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <string>
#include <curl/curl.h>
#include <openssl/hmac.h>
#include <openssl/bio.h>
#include <openssl/evp.h>

using std::string;
using std::cout;
using std::endl;
using std::strcpy;

struct pair {
    string key, value;
    pair() {}
    pair(string k, string v) {
        key = k;
        value = v;
    }
    bool operator<(const pair &other) const {
        if (key == other.key) {
            return value < other.value;
        }
        return key < other.key;
    }
    string to_string() { return key + "=" + value; }
};

const char ASCII_TABLE[67] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";

string find_and_replace(string &s, const string &to_replace, const string &replace_with) {
    return s.replace(s.find(to_replace), to_replace.length(), replace_with);
}

string gen_alphanum(int len) {
    string buff;
    std::srand(time(0));
    for (int i = 0; i < len; i++) {
        buff += ASCII_TABLE[std::rand() % 62];
    }
    return buff;
}

string hmac_sha1(unsigned const char *key, unsigned const char *data, int key_size, int data_size) {
    unsigned int i;
    HMAC_CTX ctx;
    unsigned int len;
    unsigned char out[40];
    HMAC_Init(&ctx, &key, key_size, EVP_sha1());
    HMAC_Update(&ctx, data, data_size);
    HMAC_Final(&ctx, out, &len);
    /*unsigned char *HMAC(EVP_sha1(), key, sizeof(key),
                    data, sizeof(data), out, sizeof(out));*/
    HMAC_cleanup(&ctx);
    std::stringstream buff;
    for (i = 0; i < len; i++) {
        buff << std::hex << (int)out[i];
    }
    return buff.str();
}

string base64(string data) {
    BIO *bio, *b64;
    char message[data.size()];
    strcpy(message, data.c_str());
    b64 = BIO_new(BIO_f_base64());
    bio = BIO_new_fp(stdout, BIO_NOCLOSE);
    BIO_push(b64, bio);
    BIO_write(b64, message, strlen(message));
    BIO_flush(b64);

    BIO_free_all(b64);
    return data;
}

int main() {
    string username;
    cout << "Enter Twitter Username: ";
    getline(std::cin, username);
    ::pair app_info[8] = {::pair("screen_name", username),
                          ::pair("oauth_consumer_key", username),
                          ::pair("oauth_nonce", gen_alphanum(42)),
                          ::pair("oauth_signature", ""),
                          ::pair("oauth_signature_method", "HMAC_SHA1"),
                          ::pair("oauth_timestamp", std::to_string(time(0))),
                          ::pair("oauth_token", ""),
                          ::pair("oauth_version", "1.0")};

    string secrets[2];
    string line;
    std::ifstream infile("twitter.conf");
    while (std::getline(infile, line)) {
        if (line.find("ckey") != string::npos) {
            find_and_replace(line, "ckey=", "");
            app_info[1].value = line;
        } else if (line.find("csecret") != string::npos) {
            find_and_replace(line, "csecret=", "");
            secrets[0] = line;
        } else if (line.find("atoken") != string::npos) {
            find_and_replace(line, "atoken=", "");
            app_info[6].value = line;
        } else if (line.find("asecret") != string::npos) {
            find_and_replace(line, "asecret=", "");
            secrets[1] = line;
        } else {
            continue;
        }
    }

    ::pair encode_info[8];
    CURL *curl = curl_easy_init();
    char *temp0;
    for (int i = 0; i < 8; i++) {
        temp0 = curl_easy_escape(curl, app_info[i].key.c_str(), app_info[i].key.size());
        encode_info[i] = pair(string(temp0), "");
        curl_free(temp0);
        temp0 = curl_easy_escape(curl, app_info[i].value.c_str(), app_info[i].value.size());
        encode_info[i].value = string(temp0);
        curl_free(temp0);
    }
    std::sort(encode_info, encode_info + 7);
    string out = encode_info[0].to_string();
    for (int i = 1; i < 7; i++) {
        out += "&" + encode_info[i].to_string();
    }
    string url = "https://api.twitter.com/1.1/users/lookup.json";
    temp0 = curl_easy_escape(curl, url.c_str(), url.size());
    char *temp1 = curl_easy_escape(curl, out.c_str(), out.size());
    out = "GET&" + string(temp0) + "&" + string(temp1);
    curl_free(temp0);
    curl_free(temp1);

    string sign_key;
    temp0 = curl_easy_escape(curl, secrets[0].c_str(), secrets[0].size());
    temp1 = curl_easy_escape(curl, secrets[1].c_str(), secrets[1].size());
    sign_key = string(temp0) + "&" + string(temp1);
    curl_free(temp0);
    curl_free(temp1);

    char key[sign_key.size()];
    char data[out.size()];
    strcpy(key, sign_key.c_str());
    strcpy(data, out.c_str());

    app_info[3].value = base64(hmac_sha1((unsigned const char *)key, (unsigned const char *)data,
                                         sizeof(key), sizeof(data)));
    string command =
        "curl --get \'" + url + "\' --data \'screen_name=" + app_info[0].value +
        "\' --header \'Authorization: OAuth oauth_consumer_key=\"" + app_info[1].value +
        "\", oauth_nonce=\"" + app_info[2].value + "\", oauth_signature=\"" + app_info[3].value +
        "\", oauth_signature_method=\"" + app_info[4].value + "\", oauth_timestamp=\"" +
        app_info[5].value + "\", oauth_token=\"" + app_info[6].value + "\", oauth_version=\"" +
        app_info[7].value + "\" --verbose > lookup.json";
    cout << command << endl;
    // std::system(command.c_str());
    /*string url = "https://twitter.com/" + username + "#page-container";
    CURL *curl;
    CURLcode res;
    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }*/

    curl_easy_cleanup(curl);
    return 0;
}
<commit_msg>Finished base64 encoding using OpenSSL<commit_after>#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <string>
#include <curl/curl.h>
#include <openssl/hmac.h>
#include <openssl/bio.h>
#include <openssl/evp.h>

using std::string;
using std::cout;
using std::endl;
using std::strcpy;

struct pair {
    string key, value;
    pair() {}
    pair(string k, string v) {
        key = k;
        value = v;
    }
    bool operator<(const pair &other) const {
        if (key == other.key) {
            return value < other.value;
        }
        return key < other.key;
    }
    string to_string() { return key + "=" + value; }
};

const char ASCII_TABLE[67] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";

string find_and_replace(string &s, const string &to_replace, const string &replace_with) {
    return s.replace(s.find(to_replace), to_replace.length(), replace_with);
}

string gen_alphanum(int len) {
    string buff;
    std::srand(time(0));
    for (int i = 0; i < len; i++) {
        buff += ASCII_TABLE[std::rand() % 62];
    }
    return buff;
}

string hmac_sha1(unsigned const char *key, unsigned const char *data, int key_size, int data_size) {
    unsigned int i;
    HMAC_CTX ctx;
    unsigned int len;
    unsigned char out[40];
    HMAC_Init(&ctx, &key, key_size, EVP_sha1());
    HMAC_Update(&ctx, data, data_size);
    HMAC_Final(&ctx, out, &len);
    /*unsigned char *HMAC(EVP_sha1(), key, sizeof(key),
                    data, sizeof(data), out, sizeof(out));*/
    HMAC_cleanup(&ctx);
    std::stringstream buff;
    for (i = 0; i < len; i++) {
        buff << std::hex << (int)out[i];
    }
    return buff.str();
}

string base64(string data) {
    BIO *b64, *bmem;
    char message[data.size()];
    strcpy(message, data.c_str());
    char *buff;
    b64 = BIO_new(BIO_f_base64());               // BIO to perform b64 encode
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);  // No newlines in data
    bmem = BIO_new(BIO_s_mem());                 // BIO to hold result
    BIO_push(b64, bmem);                         // Chains b64 to bmem
    BIO_write(b64, message, data.size());
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
    /*bio = BIO_new_fp(stdout, BIO_NOCLOSE);
    BIO_push(b64, bio);*/
    long len = BIO_get_mem_data(bmem, &buff);
    string ret = string(buff, len);
    BIO_free_all(b64);
    return ret;
}

int main() {
    string username;
    cout << "Enter Twitter Username: ";
    getline(std::cin, username);
    pair app_info[8] = {pair("screen_name", username),
                        pair("oauth_consumer_key", username),
                        pair("oauth_nonce", gen_alphanum(42)),
                        pair("oauth_signature", ""),
                        pair("oauth_signature_method", "HMAC_SHA1"),
                        pair("oauth_timestamp", std::to_string(time(0))),
                        pair("oauth_token", ""),
                        pair("oauth_version", "1.0")};

    string secrets[2];
    string line;
    std::ifstream infile("twitter.conf");
    while (std::getline(infile, line)) {
        if (line.find("ckey") != string::npos) {
            find_and_replace(line, "ckey=", "");
            app_info[1].value = line;
        } else if (line.find("csecret") != string::npos) {
            find_and_replace(line, "csecret=", "");
            secrets[0] = line;
        } else if (line.find("atoken") != string::npos) {
            find_and_replace(line, "atoken=", "");
            app_info[6].value = line;
        } else if (line.find("asecret") != string::npos) {
            find_and_replace(line, "asecret=", "");
            secrets[1] = line;
        } else {
            continue;
        }
    }

    ::pair encode_info[8];
    CURL *curl = curl_easy_init();
    char *temp0;
    for (int i = 0; i < 8; i++) {
        temp0 = curl_easy_escape(curl, app_info[i].key.c_str(), app_info[i].key.size());
        encode_info[i] = pair(string(temp0), "");
        curl_free(temp0);
        temp0 = curl_easy_escape(curl, app_info[i].value.c_str(), app_info[i].value.size());
        encode_info[i].value = string(temp0);
        curl_free(temp0);
    }
    std::sort(encode_info, encode_info + 7);
    string out = encode_info[0].to_string();
    for (int i = 1; i < 7; i++) {
        out += "&" + encode_info[i].to_string();
    }
    string url = "https://api.twitter.com/1.1/users/lookup.json";
    temp0 = curl_easy_escape(curl, url.c_str(), url.size());
    char *temp1 = curl_easy_escape(curl, out.c_str(), out.size());
    out = "GET&" + string(temp0) + "&" + string(temp1);
    curl_free(temp0);
    curl_free(temp1);

    string sign_key;
    temp0 = curl_easy_escape(curl, secrets[0].c_str(), secrets[0].size());
    temp1 = curl_easy_escape(curl, secrets[1].c_str(), secrets[1].size());
    sign_key = string(temp0) + "&" + string(temp1);
    curl_free(temp0);
    curl_free(temp1);

    char key[sign_key.size()];
    char data[out.size()];
    strcpy(key, sign_key.c_str());
    strcpy(data, out.c_str());
    string sha1hash = hmac_sha1((unsigned const char *)key, (unsigned const char *)data,
                                sizeof(key), sizeof(data));
    cout << sha1hash << endl;
    app_info[3].value = base64(sha1hash);
    cout << app_info[3].value << endl;
    string command =
        "curl --get \'" + url + "\' --data \'screen_name=" + app_info[0].value +
        "\' --header \'Authorization: OAuth oauth_consumer_key=\"" + app_info[1].value +
        "\", oauth_nonce=\"" + app_info[2].value + "\", oauth_signature=\"" + app_info[3].value +
        "\", oauth_signature_method=\"" + app_info[4].value + "\", oauth_timestamp=\"" +
        app_info[5].value + "\", oauth_token=\"" + app_info[6].value + "\", oauth_version=\"" +
        app_info[7].value + "\" --verbose > lookup.json";
    // cout << command << endl;
    // std::system(command.c_str());
    /*string url = "https://twitter.com/" + username + "#page-container";
    CURL *curl;
    CURLcode res;
    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
    }*/

    curl_easy_cleanup(curl);
    return 0;
}
<|endoftext|>


<commit_before>#include "eval.hpp"

#include <iostream>

using klmr::lisp::value;
using klmr::lisp::environment;

auto read(std::string const& input) -> value {
    (void) input;
    using namespace klmr::lisp;

    static auto items = std::vector<value> {
        list{
            symbol{"define"},
            symbol{"double"},
            list{
                symbol{"lambda"},
                list{symbol{"n"}},
                list{
                    symbol{"*"},
                    symbol{"n"},
                    symbol{"n"}
                }
            }
        },

        list{
            symbol{"double"},
            literal<double>{4}
        }
    };

    static auto current = 0u;

    return current < items.size() ? items[current++] : value{nil}; // FIXME placeholder
}

auto get_global_environment() -> environment {
    using namespace klmr::lisp;
    auto env = environment{};
    env.set(symbol{"*"},
        call{env, {"a", "b"}, [] (environment& env) {
            return as_literal(as_raw<double>(env["a"]) * as_raw<double>(env["b"]));
        }}
    );
    env.set(symbol{"lambda"},
        macro{env, {"args", "expr"}, [] (environment& env) {
            auto&& args = as_list(env["args"]);
            auto formals = std::vector<symbol>(length(args));
            std::transform(begin(args), end(args), begin(formals), as_symbol);
            auto expr = env["expr"];
            // FIXME Capture by value incurs expensive copy. Solved in C++14.
            return call{env, formals, [expr](environment& frame) {
                return eval(expr, frame);
            }};
        }}
    );
    env.set(symbol{"define"},
        macro{env, {"name", "expr"}, [] (environment& env) {
            auto&& name = as_symbol(env["name"]);
            parent(env)->set(name, eval(env["expr"], env));
            return nil;
        }}
    );
    return env;
}

auto repl(std::string prompt) -> void {
    auto input = std::string{};
    auto global_env = get_global_environment();
    for (;;) {
        std::cout << prompt << std::flush;
        if (not getline(std::cin, input))
            return;
        auto&& result = eval(read(input), global_env);
        std::cout << result << '\n';
    }
}

auto main() -> int
try {
    repl(">>> ");
} catch (klmr::lisp::name_error const& msg) {
    std::cerr << msg.what() << '\n';
    return 1;
}
<commit_msg>Fix test function name<commit_after>#include "eval.hpp"

#include <iostream>

using klmr::lisp::value;
using klmr::lisp::environment;

auto read(std::string const& input) -> value {
    (void) input;
    using namespace klmr::lisp;

    static auto items = std::vector<value> {
        list{
            symbol{"define"},
            symbol{"square"},
            list{
                symbol{"lambda"},
                list{symbol{"n"}},
                list{
                    symbol{"*"},
                    symbol{"n"},
                    symbol{"n"}
                }
            }
        },

        list{
            symbol{"square"},
            literal<double>{4}
        }
    };

    static auto current = 0u;

    return current < items.size() ? items[current++] : value{nil}; // FIXME placeholder
}

auto get_global_environment() -> environment {
    using namespace klmr::lisp;
    auto env = environment{};
    env.set(symbol{"*"},
        call{env, {"a", "b"}, [] (environment& env) {
            return as_literal(as_raw<double>(env["a"]) * as_raw<double>(env["b"]));
        }}
    );
    env.set(symbol{"lambda"},
        macro{env, {"args", "expr"}, [] (environment& env) {
            auto&& args = as_list(env["args"]);
            auto formals = std::vector<symbol>(length(args));
            std::transform(begin(args), end(args), begin(formals), as_symbol);
            auto expr = env["expr"];
            // FIXME Capture by value incurs expensive copy. Solved in C++14.
            return call{env, formals, [expr](environment& frame) {
                return eval(expr, frame);
            }};
        }}
    );
    env.set(symbol{"define"},
        macro{env, {"name", "expr"}, [] (environment& env) {
            auto&& name = as_symbol(env["name"]);
            parent(env)->set(name, eval(env["expr"], env));
            return nil;
        }}
    );
    return env;
}

auto repl(std::string prompt) -> void {
    auto input = std::string{};
    auto global_env = get_global_environment();
    for (;;) {
        std::cout << prompt << std::flush;
        if (not getline(std::cin, input))
            return;
        auto&& result = eval(read(input), global_env);
        std::cout << result << '\n';
    }
}

auto main() -> int
try {
    repl(">>> ");
} catch (klmr::lisp::name_error const& msg) {
    std::cerr << msg.what() << '\n';
    return 1;
}
<|endoftext|>


<commit_before>#include "dlx.h"
#include "partial_cross.h"
#include <iostream>
#include <vector>
#include <utility>
#include <tuple>

using namespace std;

vector<int> try_placement(int idx, int x, int y);

int main(void) {
  // Get initial grid
  int num_cols = num_pieces + board_x * board_y;
  auto grid_pair = initialize(num_cols);
  header * root = grid_pair.first;
  vector<header *> grid = grid_pair.second;

  // Build the grid
  // First, properly set tile flags
  for(int i = 0; i < num_pieces; ++i) grid[i]->tile = true;

  // Next, add rows for placements
  for(int i = 0; i < num_pieces; ++i) {
    for(int x = 0; x < board_x; ++x) {
      for(int y = 0; y < board_y; ++y) {
        for (int rotate = 0; rotate < 4; ++rotate) {
          for (int reflect = 0; reflect < 2; ++reflect) {
            vector<int> covered = try_placement(i, x, y, rotate, reflect);
            if(covered.size() == 0)
              continue;
            auto covered_iter = covered.cbegin();
            for(int j = 0; j < num_cols; ++j) {
              node * row_node = new node();
              row_node->used = (j == i || j == *covered_iter);
              if(j == *covered_iter) ++covered_iter;
              grid[j]->insert(row_node);
            }
          }
        }
      }
    }
  }

  // Get count
  int count = 0;
  count_sols(root, count);

  // Output count
  cout << "Found " << count << " solutions!\n";
  return 0;
}

int ** make_matrix(int dim_x, int dim_y) {
  int** matrix = new int*[dim_y];
  for (int i = 0; i < dim_y; ++i) {
    matrix[i] = new int[dim_x];
    for (int j = 0; j < dim_x; ++j) {
      matrix[i][j] = 0;
    }
  }
  return matrix;
}

int ** get_tile(int idx) {
  int ** orig_tile = pieces[idx];
  int dim_x = piecedims_x[idx];
  int dim_y = piecedims_y[idx];

  int ** tile = make_matrix(dim_x, dim_y);
  for (int i = 0; i < dim_y; ++i) {
    for (int j = 0; j < dim_x; ++j) {
      tile[i][j] = orig_tile[i][j];
    }
  }
  return tile;
}

void cleanup(int ** tile, int dim_x, int dim_y) {
  for (int i = 0; i < dim_y; ++i) {
      delete [] tile[i];
  }
  delete [] tile;
}

/* Reflect across the x-axis. */
int ** reflect(int ** tile, int dim_x, int dim_y) {
  int ** reflected = make_matrix(dim_x, dim_y);
  for (int i = 0; i < dim_y; ++i) {
    for (int j = 0; j < dim_x; ++j) {
      reflected[dim_y - 1 - i][j] = tile[i][j];
    }
  }
  cleanup(tile, dim_x, dim_y);
  return reflected;
}

int ** rotate(int ** tile, int dim_x, int dim_y) {
  int ** rotated = make_matrix(dim_y, dim_x);
  for (int i = 0; i < dim_y; ++i) {
    for (int j = 0; j < dim_x; ++j) {
      rotated[j][dim_y - 1 - i] = tile[i][j];
    }
  }
  cleanup(tile, dim_x, dim_y);
  return rotated;
}

tuple<int **,tuple<int, int> > transform_tile(int idx, int _rotate, int _reflect) {
  int ** tile = get_tile(idx);
  int dim_x = piecedims_x[idx];
  int dim_y = piecedims_y[idx];
  if (_reflect == 1) {
    tile = reflect(tile, dim_x, dim_y);
  }

  for (int r = 0; r < _rotate; r++) {
    tile = rotate(tile, dim_x, dim_y);
    int temp = dim_x;
    dim_x = dim_y;
    dim_y = temp;
  }

  tuple<int, int> dims = make_tuple(dim_x, dim_y);

  return make_tuple(tile, dims);
}

vector<int> try_placement(int idx, int x, int y, int rotate, int reflect) {
  // Try placing tile idx at (x, y)
  // If it's valid, return a vector of the parts of the board covered
  // If it isn't valid, return an empty vector
  auto tuple = transform_tile(idx, rotate, reflect);
  int ** tile = get<0>(tuple);
  auto dims = get<1>(tuple);
  int dim_x = get<0>(dims);
  int dim_y = get<1>(dims);
}
<commit_msg>finished placements'<commit_after>#include "dlx.h"
#include "partial_cross.h"
#include <iostream>
#include <vector>
#include <utility>
#include <tuple>

using namespace std;

vector<int> try_placement(int idx, int x, int y, int r, int rr);

int main(void) {
  // Get initial grid
  int num_cols = num_pieces + board_x * board_y;
  auto grid_pair = initialize(num_cols);
  header * root = grid_pair.first;
  vector<header *> grid = grid_pair.second;

  // Build the grid
  // First, properly set tile flags
  for(int i = 0; i < num_pieces; ++i) grid[i]->tile = true;

  // Next, add rows for placements
  for(int i = 0; i < num_pieces; ++i) {
    for(int x = 0; x < board_x; ++x) {
      for(int y = 0; y < board_y; ++y) {
        for (int rotate = 0; rotate < 4; ++rotate) {
          for (int reflect = 0; reflect < 2; ++reflect) {
            vector<int> covered = try_placement(i, x, y, rotate, reflect);
            if(covered.size() == 0)
              continue;
            auto covered_iter = covered.cbegin();
            for(int j = 0; j < num_cols; ++j) {
              node * row_node = new node();
              row_node->used = (j == i || j == *covered_iter);
              if(j == *covered_iter) ++covered_iter;
              grid[j]->insert(row_node);
            }
          }
        }
      }
    }
  }

  // Get count
  int count = 0;
  count_sols(root, count);

  // Output count
  cout << "Found " << count << " solutions!\n";
  return 0;
}

int ** make_matrix(int dim_x, int dim_y) {
  int** matrix = new int*[dim_y];
  for (int i = 0; i < dim_y; ++i) {
    matrix[i] = new int[dim_x];
    for (int j = 0; j < dim_x; ++j) {
      matrix[i][j] = 0;
    }
  }
  return matrix;
}

int ** get_tile(int idx) {
  int ** orig_tile = pieces[idx];
  int dim_x = piecedims_x[idx];
  int dim_y = piecedims_y[idx];

  int ** tile = make_matrix(dim_x, dim_y);
  for (int i = 0; i < dim_y; ++i) {
    for (int j = 0; j < dim_x; ++j) {
      tile[i][j] = orig_tile[i][j];
    }
  }
  return tile;
}

void cleanup(int ** tile, int dim_x, int dim_y) {
  for (int i = 0; i < dim_y; ++i) {
      delete [] tile[i];
  }
  delete [] tile;
}

/* Reflect across the x-axis. */
int ** reflect(int ** tile, int dim_x, int dim_y) {
  int ** reflected = make_matrix(dim_x, dim_y);
  for (int i = 0; i < dim_y; ++i) {
    for (int j = 0; j < dim_x; ++j) {
      reflected[dim_y - 1 - i][j] = tile[i][j];
    }
  }
  cleanup(tile, dim_x, dim_y);
  return reflected;
}

int ** rotate(int ** tile, int dim_x, int dim_y) {
  int ** rotated = make_matrix(dim_y, dim_x);
  for (int i = 0; i < dim_y; ++i) {
    for (int j = 0; j < dim_x; ++j) {
      rotated[j][dim_y - 1 - i] = tile[i][j];
    }
  }
  cleanup(tile, dim_x, dim_y);
  return rotated;
}

tuple<int **,tuple<int, int> > transform_tile(int idx, int _rotate, int _reflect) {
  int ** tile = get_tile(idx);
  int dim_x = piecedims_x[idx];
  int dim_y = piecedims_y[idx];
  if (_reflect == 1) {
    tile = reflect(tile, dim_x, dim_y);
  }

  for (int r = 0; r < _rotate; r++) {
    tile = rotate(tile, dim_x, dim_y);
    int temp = dim_x;
    dim_x = dim_y;
    dim_y = temp;
  }

  tuple<int, int> dims = make_tuple(dim_x, dim_y);

  return make_tuple(tile, dims);
}

vector<int> try_placement(int idx, int x, int y, int rotate, int reflect) {
  // Try placing tile idx at (x, y)
  // If it's valid, return a vector of the parts of the board covered
  // If it isn't valid, return an empty vector
  auto tuple = transform_tile(idx, rotate, reflect);
  int ** tile = get<0>(tuple);
  auto dims = get<1>(tuple);
  int dim_x = get<0>(dims);
  int dim_y = get<1>(dims);

  vector<int> indices;
  for (int i = 0; i < dim_y; ++i) {
    for (int j = 0; j < dim_x; ++j) {
      int board_i = i + y;
      int board_j = j + x;
      /* Fell off board. */
      if (board_i >= board_y || board_j >= board_x) {
        return vector<int>();
      }

      /* Mismatch. */
      if (board[board_i][board_j] != tile[i][j]) {
        return vector<int>();
      }

      /* Otherwise, we add the index. */
      indices.push_back(board_i + board_j * board_x);
    }
  }

  return indices;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <cstdlib> //C standard library <stdlib.h>, /* atoi */
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h> //C standard library <stdlib.h>, /* atoi */
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <fcntl.h>
#ifdef _WIN32
#include <windows.h>
#define chdir _chdir

#else
#include <unistd.h>
#endif

//INLCUDING COMMANDS
//#include "commands/cat.h"

using namespace std;

enum TipoComando{PIPE, REDIRECT, NEITHER};

int executeCommand(vector<string>&);
vector<string> getTokens(string, char);
char** vectorToCharPP (vector<string> tokenized);
TipoComando identificarComando(int, char**, char**, char**);
void Pipe(string, char**, char**, char**);
void Redirect(string, char**, char**, char**);
void Neither(string, char**, char**, char**);

string PATH, CURR_DIR;

int main(int argc, char const *argv[]){
	CURR_DIR = getenv("PWD");
	PATH = CURR_DIR+"/commands/bin/";
	int status = 0;
	while(!status) {
		cout << "mi_sh> ";
		string line;
		getline(cin,line);
		vector<string> tokens = getTokens(line, ' ');
		status = executeCommand(tokens);
	};
	if(status != 1){
		cerr << "ERROR " << status << ": al ejecutar el comando" << endl;
	}
	return 0;
}

/*
ejecuta los comandos conocidos por el programa
retorna 0 cuando todo salio bien y continuar con el programa
retorna 1 para salir del programa sin errores
retorna cualquier otro valor con error
*/
int executeCommand(vector<string>& tokens){
	if(tokens.size() == 0){
		cerr << "No hay commando a ejecutar" << endl;
		return 0;
	}
	int childErr;

	if(tokens.size() > 0){
		if(tokens[0] == "cd"){
			if(tokens.size()== 2){
				chdir(tokens[1].c_str());
			}
			return 0;
		}else{

			char *comando1[50], *comando2[50];

			TipoComando tipo_comando;
			char** argvData = vectorToCharPP (tokens);
			int argcData = tokens.size();

			//string commandPath = PATH + argvData[0];

			tipo_comando = identificarComando(argcData, argvData, comando1, comando2);

			if(tipo_comando == PIPE){
				cout << "Entra a Pipe" << endl;

				Pipe(PATH, argvData, comando1, comando2);

			}else if(tipo_comando == REDIRECT){
				cout << "Entra a REDIRECT" << endl;

				Redirect(PATH, argvData, comando1, comando2);

			}else{
				cout << "entra a NEITHER" << endl;

				Neither(PATH, argvData, comando1, comando2);
			}
		}
		/*int ppid, chpid;

		if(tokens[0] == "cd"){
			if(tokens.size()== 2){
				chdir(tokens[1].c_str());
			}
			return 0;

		}else{
			if((chpid=fork()) == 0){
				char** argvData = vectorToCharPP (tokens);
				int argcData = tokens.size();

				string commandPath = PATH + argvData[0];

				childErr = execvp(commandPath.c_str(), argvData);
				cout << "Comando " << argvData[0] <<": Fallido" << endl;

				return childErr;
			}else{
				wait(NULL);
				return 0;
			}
			return -1;
		}*/

	}

}

//retorna los tokens de la terminal
vector<string> getTokens(string toTokenize, char delimiter){
	vector<string> v;
	string::iterator stringIT = toTokenize.begin();
	for(string::iterator i = toTokenize.begin(); i != toTokenize.end(); i++){
		if(*i == delimiter){
			v.push_back(string(stringIT,i));
			stringIT=i+1;
		}
	}
	v.push_back(string(stringIT,toTokenize.end()));
	return v;
}
/*
retorna un char** al enviarle un vector<string>
vectorToCharPP = de vector a char puntero puntero
*/
char** vectorToCharPP (vector<string> tokenized){
	char** tokens;
	int tokenAmount = tokenized.size();
	tokens = new char*[tokenAmount+1];
	for(int i = 0; i < tokenAmount; i++){
		tokens[i] = new char[tokenized[i].length()];
		strcpy(tokens[i],tokenized[i].c_str());
	}
	tokens[tokenAmount] = NULL;
	return tokens;
}

TipoComando identificarComando(int argcData, char** argvData, char** comando1, char** comando2){
	cout << "Entra a identificar" << endl;

	TipoComando tipo = NEITHER;
	int temp = -1;

	for(int i = 0; i < argcData; i++){
		if(strcmp(argvData[i], "|") == 0){
			tipo = PIPE;
			temp = i;

		}else if (strcmp(argvData[i], ">>") == 0){
			tipo = REDIRECT;
			temp = i;
		}
	}

	if(tipo != NEITHER){
		for(int i = 0; i < temp; i++){
			comando1[i] = argvData[i];
		}

		int count = 0;
		for(int i=temp+1; i<argcData; i++){
			comando2[count] = argvData[i];
			count++;
		}

		comando1[temp] = NULL;
		comando2[count] = NULL;
	}

	return tipo;
}

void Pipe(string PATH, char** argvData, char** comando1, char** comando2){

	int a[2];
	pid_t pid;

	pipe(a);

	if(fork() == 0){//PROCESO PADRE
		string commandPath = PATH + comando2[0];

		dup2(a[0], 0);
		close(a[1]);

		execvp(commandPath.c_str(), argvData);//No estoy segura de ese argvData en el execvp
		perror("Error en el execvp");
	}else if((pid == fork()) == 0){//PROCESO HIJO
		string commandPath = PATH + comando1[0];

		dup2(a[1], 1);
		close(a[0]);

		execvp(commandPath.c_str(), argvData);
		perror("Error en el execvp");
	} else {
		waitpid(pid, NULL, 0);
	}

}

void Redirect(string PATH, char** argvData, char** comando1, char** comando2){
	int contador;
	int file;
	int a[2];
	char caracter;
	pid_t pid;

	pipe(a);

	if(fork() == 0){
		string commandPath = PATH + comando2[0];

		file = open(commandPath.c_str(), O_RDWR | O_CREAT, 0666);

		if(file < 0){
			printf("Error: %s\n", strerror(errno));
		}

					//dup(a[0]);
		dup2(a[0], 0);
		close(a[1]);

		while((contador = read(0, &caracter, 1)) > 0){
			write(file, &caracter, 1);
		}

		execlp("echo", "echo", NULL);
	}else if((pid = fork()) == 0){
		string commandPath = PATH + comando1[0];

		dup2(a[1], 1);
		close(a[0]);

		execvp(commandPath.c_str(), comando1);//probar sin argvData
		perror("execvp error en el execvp");
	}else{
		waitpid(pid, NULL, 0);
		close(a[0]);
		close(a[1]);
	}
}

void Neither(string PATH, char** argvData, char** comando1, char** comando2){
	const char *amperson;
	pid_t pid;
	amperson = "&";
	bool encontro = false;

	if(strcmp(argvData[argcData-1], amperson) == 0){
		encontro = true;
	}

	pid = fork();

	if(pid < 0){
		perror("Hubo un error");

	}else if(pid == 0){

		if(encontro){
			argvData[argcData-1] = NULL;
			argcData--;
		}

		execvp(argvData[0], argvData);
		perror("Error en el execvp");

	}else if( !encontro){
		waitpid(pid, NULL, 0);
	}
}<commit_msg>arreglando una variable<commit_after>#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <cstdlib> //C standard library <stdlib.h>, /* atoi */
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h> //C standard library <stdlib.h>, /* atoi */
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <fcntl.h>
#ifdef _WIN32
#include <windows.h>
#define chdir _chdir

#else
#include <unistd.h>
#endif

//INLCUDING COMMANDS
//#include "commands/cat.h"

using namespace std;

enum TipoComando{PIPE, REDIRECT, NEITHER};

int executeCommand(vector<string>&);
vector<string> getTokens(string, char);
char** vectorToCharPP (vector<string> tokenized);
TipoComando identificarComando(int, char**, char**, char**);
void Pipe(string, char**, char**, char**);
void Redirect(string, char**, char**, char**);
void Neither(string, int, char**, char**, char**);

string PATH, CURR_DIR;

int main(int argc, char const *argv[]){
	CURR_DIR = getenv("PWD");
	PATH = CURR_DIR+"/commands/bin/";
	int status = 0;
	while(!status) {
		cout << "mi_sh> ";
		string line;
		getline(cin,line);
		vector<string> tokens = getTokens(line, ' ');
		status = executeCommand(tokens);
	};
	if(status != 1){
		cerr << "ERROR " << status << ": al ejecutar el comando" << endl;
	}
	return 0;
}

/*
ejecuta los comandos conocidos por el programa
retorna 0 cuando todo salio bien y continuar con el programa
retorna 1 para salir del programa sin errores
retorna cualquier otro valor con error
*/
int executeCommand(vector<string>& tokens){
	if(tokens.size() == 0){
		cerr << "No hay commando a ejecutar" << endl;
		return 0;
	}
	int childErr;

	if(tokens.size() > 0){
		if(tokens[0] == "cd"){
			if(tokens.size()== 2){
				chdir(tokens[1].c_str());
			}
			return 0;
		}else{

			char *comando1[50], *comando2[50];

			TipoComando tipo_comando;
			char** argvData = vectorToCharPP (tokens);
			int argcData = tokens.size();

			//string commandPath = PATH + argvData[0];

			tipo_comando = identificarComando(argcData, argvData, comando1, comando2);

			if(tipo_comando == PIPE){
				cout << "Entra a Pipe" << endl;

				Pipe(PATH, argvData, comando1, comando2);

			}else if(tipo_comando == REDIRECT){
				cout << "Entra a REDIRECT" << endl;

				Redirect(PATH, argvData, comando1, comando2);

			}else{
				cout << "entra a NEITHER" << endl;

				Neither(PATH, argcData, argvData, comando1, comando2);
			}
		}
		/*int ppid, chpid;

		if(tokens[0] == "cd"){
			if(tokens.size()== 2){
				chdir(tokens[1].c_str());
			}
			return 0;

		}else{
			if((chpid=fork()) == 0){
				char** argvData = vectorToCharPP (tokens);
				int argcData = tokens.size();

				string commandPath = PATH + argvData[0];

				childErr = execvp(commandPath.c_str(), argvData);
				cout << "Comando " << argvData[0] <<": Fallido" << endl;

				return childErr;
			}else{
				wait(NULL);
				return 0;
			}
			return -1;
		}*/

	}

}

//retorna los tokens de la terminal
vector<string> getTokens(string toTokenize, char delimiter){
	vector<string> v;
	string::iterator stringIT = toTokenize.begin();
	for(string::iterator i = toTokenize.begin(); i != toTokenize.end(); i++){
		if(*i == delimiter){
			v.push_back(string(stringIT,i));
			stringIT=i+1;
		}
	}
	v.push_back(string(stringIT,toTokenize.end()));
	return v;
}
/*
retorna un char** al enviarle un vector<string>
vectorToCharPP = de vector a char puntero puntero
*/
char** vectorToCharPP (vector<string> tokenized){
	char** tokens;
	int tokenAmount = tokenized.size();
	tokens = new char*[tokenAmount+1];
	for(int i = 0; i < tokenAmount; i++){
		tokens[i] = new char[tokenized[i].length()];
		strcpy(tokens[i],tokenized[i].c_str());
	}
	tokens[tokenAmount] = NULL;
	return tokens;
}

TipoComando identificarComando(int argcData, char** argvData, char** comando1, char** comando2){
	cout << "Entra a identificar" << endl;

	TipoComando tipo = NEITHER;
	int temp = -1;

	for(int i = 0; i < argcData; i++){
		if(strcmp(argvData[i], "|") == 0){
			tipo = PIPE;
			temp = i;

		}else if (strcmp(argvData[i], ">>") == 0){
			tipo = REDIRECT;
			temp = i;
		}
	}

	if(tipo != NEITHER){
		for(int i = 0; i < temp; i++){
			comando1[i] = argvData[i];
		}

		int count = 0;
		for(int i=temp+1; i<argcData; i++){
			comando2[count] = argvData[i];
			count++;
		}

		comando1[temp] = NULL;
		comando2[count] = NULL;
	}

	return tipo;
}

void Pipe(string PATH, char** argvData, char** comando1, char** comando2){

	int a[2];
	pid_t pid;

	pipe(a);

	if(fork() == 0){//PROCESO PADRE
		string commandPath = PATH + comando2[0];

		dup2(a[0], 0);
		close(a[1]);

		execvp(commandPath.c_str(), argvData);//No estoy segura de ese argvData en el execvp
		perror("Error en el execvp");
	}else if((pid == fork()) == 0){//PROCESO HIJO
		string commandPath = PATH + comando1[0];

		dup2(a[1], 1);
		close(a[0]);

		execvp(commandPath.c_str(), argvData);
		perror("Error en el execvp");
	} else {
		waitpid(pid, NULL, 0);
	}

}

void Redirect(string PATH, char** argvData, char** comando1, char** comando2){
	int contador;
	int file;
	int a[2];
	char caracter;
	pid_t pid;

	pipe(a);

	if(fork() == 0){
		string commandPath = PATH + comando2[0];

		file = open(commandPath.c_str(), O_RDWR | O_CREAT, 0666);

		if(file < 0){
			printf("Error: %s\n", strerror(errno));
		}

					//dup(a[0]);
		dup2(a[0], 0);
		close(a[1]);

		while((contador = read(0, &caracter, 1)) > 0){
			write(file, &caracter, 1);
		}

		execlp("echo", "echo", NULL);
	}else if((pid = fork()) == 0){
		string commandPath = PATH + comando1[0];

		dup2(a[1], 1);
		close(a[0]);

		execvp(commandPath.c_str(), comando1);//probar sin argvData
		perror("execvp error en el execvp");
	}else{
		waitpid(pid, NULL, 0);
		close(a[0]);
		close(a[1]);
	}
}

void Neither(string PATH, int argcData, char** argvData, char** comando1, char** comando2){
	const char *amperson;
	pid_t pid;
	amperson = "&";
	bool encontro = false;

	if(strcmp(argvData[argcData-1], amperson) == 0){
		encontro = true;
	}

	pid = fork();

	if(pid < 0){
		perror("Hubo un error");

	}else if(pid == 0){

		if(encontro){
			argvData[argcData-1] = NULL;
			argcData--;
		}

		execvp(argvData[0], argvData);
		perror("Error en el execvp");

	}else if( !encontro){
		waitpid(pid, NULL, 0);
	}
}<|endoftext|>