text stringlengths 54 60.6k |
|---|
<commit_before>9c75db73-327f-11e5-9417-9cf387a8033e<commit_msg>9c7bf0ae-327f-11e5-8244-9cf387a8033e<commit_after>9c7bf0ae-327f-11e5-8244-9cf387a8033e<|endoftext|> |
<commit_before>00e6ab85-2e4f-11e5-bbda-28cfe91dbc4b<commit_msg>00ed2402-2e4f-11e5-9cfe-28cfe91dbc4b<commit_after>00ed2402-2e4f-11e5-9cfe-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <chrono>
#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include <SFML/Graphics.hpp>
#include "ButtonWidget.hpp"
#include "GUIEnvironment.hpp"
#include "ProgressWidget.hpp"
#include "TextWidget.hpp"
#include "TextInputWidget.hpp"
#include "VerticalLayout.hpp"
#include "ScrollableWidget.hpp"
#include "WindowWidget.hpp"
typedef std::chrono::high_resolution_clock CLOCK;
void determineFpsAndDeltaTime(sf::Text &txtStatFPS, float &dt,
CLOCK::time_point &timePoint1);
int main()
{
unsigned int windowWidth{ 1280 };
unsigned int windowHeight{ 720 };
sf::RenderWindow window(sf::VideoMode{ windowWidth, windowHeight }, "GUI-SFML");
sf::Font font;
if (!font.loadFromFile("assets/fonts/LiberationSans-Regular.ttf"))
{
std::cout << "Error by loading Font" << std::endl;
}
sf::Text txtStatFPS;
txtStatFPS.setFont(font);
txtStatFPS.setCharacterSize(12);
txtStatFPS.setFillColor(sf::Color::White);
float dt{0.f};
CLOCK::time_point timePoint1{ CLOCK::now() };
gsf::GUIEnvironment guiEnvironment;
std::unique_ptr<gsf::TextWidget> textWidget{
std::make_unique<gsf::TextWidget>("Im a Text", font, 12, sf::Color::White) };
textWidget->centerOrigin();
textWidget->setBackgroundColor(sf::Color::Red);
textWidget->setCharacterSize(60);
textWidget->setPosition(windowWidth / 2.f, windowHeight / 2.f);
guiEnvironment.addWidget(std::move(textWidget));
std::unique_ptr<gsf::ScrollableWidget> scrollableWidget{
std::make_unique<gsf::ScrollableWidget>(300, 200) };
scrollableWidget->setBackgroundColor(sf::Color::Blue);
std::unique_ptr<gsf::VerticalLayout> layout{
std::make_unique<gsf::VerticalLayout>() };
layout->setPosition(0.f , 0.f);
layout->setBackgroundColor(sf::Color::Cyan);
std::unique_ptr<gsf::ProgressWidget> progressWidget{
std::make_unique<gsf::ProgressWidget>(260, 40) };
progressWidget->setPosition(460, 460);
progressWidget->setBackgroundColor(sf::Color::White);
progressWidget->setOutlineThickness(5.f);
progressWidget->setOutlineColor(sf::Color::Blue);
progressWidget->setProgress(50);
guiEnvironment.addWidget(std::move(progressWidget));
for (int i{ 0 }; i != 6; i++)
{
std::string textString{ "Text Num " + std::to_string(i) };
std::unique_ptr<gsf::TextWidget> text{ std::make_unique<gsf::TextWidget>
(textString, font, 40, sf::Color::White) };
if (i % 2 == 0)
{
text->setBackgroundColor(sf::Color::Green);
}
else
{
text->setBackgroundColor(sf::Color::Magenta);
}
std::function<void(gsf::Widget*, sf::Vector2f)> leftClickListener =
[] (gsf::Widget* widget, sf::Vector2f mousePos)
{
gsf::TextWidget *textWidget = static_cast<gsf::TextWidget*>(widget);
std::cout << "TextWidget: Left Mouse Button Clicked. Text: "
<< textWidget->getText() << std::endl;
};
text->setOnLeftClickListener(leftClickListener);
layout->attachChild(std::move(text));
}
scrollableWidget->attachChild(std::move(layout));
std::unique_ptr<gsf::WindowWidget> windowWidget{
std::make_unique<gsf::WindowWidget>(300.f, 360.f, "", font) };
windowWidget->setPosition(60.f , 40.f);
windowWidget->setBackgroundColor(sf::Color::White);
windowWidget->attachChild(std::move(scrollableWidget));
windowWidget->setIsVisible(true);
guiEnvironment.addWidget(std::move(windowWidget));
std::unique_ptr<gsf::WindowWidget> windowWidget2{
std::make_unique<gsf::WindowWidget>(300.f, 360.f, "", font) };
windowWidget2->setPosition(240.f , 40.f);
windowWidget2->setBackgroundColor(sf::Color::Red);
windowWidget2->setTopBarFillColor(sf::Color::Green);
windowWidget2->setCloseButtonFillColor(sf::Color::Blue);
windowWidget2->setWindowTitle("Test");
windowWidget2->setWindowTitleColor(sf::Color::Red);
guiEnvironment.addWidget(std::move(windowWidget2));
std::unique_ptr<gsf::WindowWidget> windowWidget3{
std::make_unique<gsf::WindowWidget>
(300.f, 360.f, "Test Window TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT", font) };
windowWidget3->setPosition(300.f , 60.f);
windowWidget3->setOutlineThickness(12.f);
windowWidget3->setOutlineColor(sf::Color::White);
windowWidget3->setBackgroundColor(sf::Color::Blue);
guiEnvironment.addWidget(std::move(windowWidget3));
// BUTTON TEST
std::unique_ptr<gsf::ButtonWidget> buttonWidget{
std::make_unique<gsf::ButtonWidget>
(200.f, 80.f, "TTTTTTTTTTTTTTTTTTTTTTClick me", font) };
buttonWidget->setPosition(620.f , 360.f);
buttonWidget->setOutlineThickness(8.f);
buttonWidget->setOnLeftClickListener([] (gsf::Widget* widget, sf::Vector2f mousePos)
{
std::cout << "Button Left Click\n";
});
buttonWidget->setOnRightClickListener([] (gsf::Widget* widget, sf::Vector2f mousePos)
{
std::cout << "Button Right Click\n";
});
buttonWidget->setOnMiddleClickListener([] (gsf::Widget* widget, sf::Vector2f mousePos)
{
std::cout << "Button Middle Click\n";
});
guiEnvironment.addWidget(std::move(buttonWidget));
// SCROLLBAR TEST
std::unique_ptr<gsf::ScrollableWidget> scrollableWidget3{
std::make_unique<gsf::ScrollableWidget>(300, 200) };
scrollableWidget3->setPosition(820.f, 420.f);
scrollableWidget3->setBackgroundColor(sf::Color::Yellow);
std::unique_ptr<gsf::VerticalLayout> layout4{
std::make_unique<gsf::VerticalLayout>() };
layout4->setBackgroundColor(sf::Color::Cyan);
for (int i{0}; i != 10; i++)
{
std::string textString{ "Text Text Text Text Text Text Text Num "
+ std::to_string(i) };
std::unique_ptr<gsf::TextWidget> text{
std::make_unique<gsf::TextWidget>
(textString, font, 40, sf::Color::White) };
if (i % 2 == 0)
{
text->setBackgroundColor(sf::Color::Green);
}
else
{
text->setBackgroundColor(sf::Color::Magenta);
}
std::function<void(gsf::Widget*, sf::Vector2f)> leftClickListener =
[] (gsf::Widget* widget, sf::Vector2f mousePos)
{
gsf::TextWidget *textWidget = static_cast<gsf::TextWidget*>(widget);
std::cout << "TextWidget: Left Mouse Button Clicked. Text: "
<< textWidget->getText() << std::endl;
};
text->setOnLeftClickListener(leftClickListener);
//text->setBackgroundColor(sf::Color::Red);
layout4->attachChild(std::move(text));
}
scrollableWidget3->attachChild(std::move(layout4));
guiEnvironment.addWidget(std::move(scrollableWidget3));
std::unique_ptr<gsf::TextInputWidget> textInput1{
std::make_unique<gsf::TextInputWidget>(300, 60, font) };
textInput1->setPosition(520.f, 320.f);
textInput1->setBackgroundColor(sf::Color::White);
guiEnvironment.addWidget(std::move(textInput1));
while (window.isOpen())
{
determineFpsAndDeltaTime(txtStatFPS, dt, timePoint1);
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
guiEnvironment.handleEvent(event);
}
guiEnvironment.update(dt);
window.clear();
window.draw(guiEnvironment);
window.draw(txtStatFPS);
window.display();
}
return 0;
}
void determineFpsAndDeltaTime(sf::Text &txtStatFPS,
float &dt, CLOCK::time_point &timePoint1)
{
CLOCK::time_point timePoint2{ CLOCK::now() };
std::chrono::duration<float> timeSpan{ timePoint2 - timePoint1 };
timePoint1 = CLOCK::now();
// Get deltaTime as float in seconds
dt = std::chrono::duration_cast<std::chrono::duration<float,std::ratio<1>>>
(timeSpan).count();
float fps{ 1.f / dt };
txtStatFPS.setString("FPS: " + std::to_string(fps));
}
<commit_msg>Implement char removing when enter backspace or delete key<commit_after>#include <chrono>
#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include <SFML/Graphics.hpp>
#include "ButtonWidget.hpp"
#include "GUIEnvironment.hpp"
#include "ProgressWidget.hpp"
#include "TextWidget.hpp"
#include "TextInputWidget.hpp"
#include "VerticalLayout.hpp"
#include "ScrollableWidget.hpp"
#include "WindowWidget.hpp"
typedef std::chrono::high_resolution_clock CLOCK;
void determineFpsAndDeltaTime(sf::Text &txtStatFPS, float &dt,
CLOCK::time_point &timePoint1);
int main()
{
unsigned int windowWidth{ 1280 };
unsigned int windowHeight{ 720 };
sf::RenderWindow window(sf::VideoMode{ windowWidth, windowHeight }, "GUI-SFML");
sf::Font font;
if (!font.loadFromFile("assets/fonts/LiberationSans-Regular.ttf"))
{
std::cout << "Error by loading Font" << std::endl;
}
sf::Text txtStatFPS;
txtStatFPS.setFont(font);
txtStatFPS.setCharacterSize(12);
txtStatFPS.setFillColor(sf::Color::White);
float dt{0.f};
CLOCK::time_point timePoint1{ CLOCK::now() };
gsf::GUIEnvironment guiEnvironment;
std::unique_ptr<gsf::TextWidget> textWidget{
std::make_unique<gsf::TextWidget>("Im a Text", font, 12, sf::Color::White) };
textWidget->centerOrigin();
textWidget->setBackgroundColor(sf::Color::Red);
textWidget->setCharacterSize(60);
textWidget->setPosition(windowWidth / 2.f, windowHeight / 2.f);
guiEnvironment.addWidget(std::move(textWidget));
std::unique_ptr<gsf::ScrollableWidget> scrollableWidget{
std::make_unique<gsf::ScrollableWidget>(300, 200) };
scrollableWidget->setBackgroundColor(sf::Color::Blue);
std::unique_ptr<gsf::VerticalLayout> layout{
std::make_unique<gsf::VerticalLayout>() };
layout->setPosition(0.f , 0.f);
layout->setBackgroundColor(sf::Color::Cyan);
std::unique_ptr<gsf::ProgressWidget> progressWidget{
std::make_unique<gsf::ProgressWidget>(260, 40) };
progressWidget->setPosition(460, 460);
progressWidget->setBackgroundColor(sf::Color::White);
progressWidget->setOutlineThickness(5.f);
progressWidget->setOutlineColor(sf::Color::Blue);
progressWidget->setProgress(50);
guiEnvironment.addWidget(std::move(progressWidget));
for (int i{ 0 }; i != 6; i++)
{
std::string textString{ "Text Num " + std::to_string(i) };
std::unique_ptr<gsf::TextWidget> text{ std::make_unique<gsf::TextWidget>
(textString, font, 40, sf::Color::White) };
if (i % 2 == 0)
{
text->setBackgroundColor(sf::Color::Green);
}
else
{
text->setBackgroundColor(sf::Color::Magenta);
}
std::function<void(gsf::Widget*, sf::Vector2f)> leftClickListener =
[] (gsf::Widget* widget, sf::Vector2f mousePos)
{
gsf::TextWidget *textWidget = static_cast<gsf::TextWidget*>(widget);
std::cout << "TextWidget: Left Mouse Button Clicked. Text: "
<< textWidget->getText() << std::endl;
};
text->setOnLeftClickListener(leftClickListener);
layout->attachChild(std::move(text));
}
scrollableWidget->attachChild(std::move(layout));
std::unique_ptr<gsf::WindowWidget> windowWidget{
std::make_unique<gsf::WindowWidget>(300.f, 360.f, "", font) };
windowWidget->setPosition(60.f , 40.f);
windowWidget->setBackgroundColor(sf::Color::White);
windowWidget->attachChild(std::move(scrollableWidget));
windowWidget->setIsVisible(true);
guiEnvironment.addWidget(std::move(windowWidget));
std::unique_ptr<gsf::WindowWidget> windowWidget2{
std::make_unique<gsf::WindowWidget>(300.f, 360.f, "", font) };
windowWidget2->setPosition(240.f , 40.f);
windowWidget2->setBackgroundColor(sf::Color::Red);
windowWidget2->setTopBarFillColor(sf::Color::Green);
windowWidget2->setCloseButtonFillColor(sf::Color::Blue);
windowWidget2->setWindowTitle("Test");
windowWidget2->setWindowTitleColor(sf::Color::Red);
guiEnvironment.addWidget(std::move(windowWidget2));
std::unique_ptr<gsf::WindowWidget> windowWidget3{
std::make_unique<gsf::WindowWidget>
(300.f, 360.f, "Test Window TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT", font) };
windowWidget3->setPosition(300.f , 60.f);
windowWidget3->setOutlineThickness(12.f);
windowWidget3->setOutlineColor(sf::Color::White);
windowWidget3->setBackgroundColor(sf::Color::Blue);
guiEnvironment.addWidget(std::move(windowWidget3));
// BUTTON TEST
std::unique_ptr<gsf::ButtonWidget> buttonWidget{
std::make_unique<gsf::ButtonWidget>
(200.f, 80.f, "TTTTTTTTTTTTTTTTTTTTTTClick me", font) };
buttonWidget->setPosition(620.f , 360.f);
buttonWidget->setOutlineThickness(8.f);
buttonWidget->setOnLeftClickListener([] (gsf::Widget* widget, sf::Vector2f mousePos)
{
std::cout << "Button Left Click\n";
});
buttonWidget->setOnRightClickListener([] (gsf::Widget* widget, sf::Vector2f mousePos)
{
std::cout << "Button Right Click\n";
});
buttonWidget->setOnMiddleClickListener([] (gsf::Widget* widget, sf::Vector2f mousePos)
{
std::cout << "Button Middle Click\n";
});
guiEnvironment.addWidget(std::move(buttonWidget));
// SCROLLBAR TEST
std::unique_ptr<gsf::ScrollableWidget> scrollableWidget3{
std::make_unique<gsf::ScrollableWidget>(300, 200) };
scrollableWidget3->setPosition(820.f, 420.f);
scrollableWidget3->setBackgroundColor(sf::Color::Yellow);
std::unique_ptr<gsf::VerticalLayout> layout4{
std::make_unique<gsf::VerticalLayout>() };
layout4->setBackgroundColor(sf::Color::Cyan);
for (int i{0}; i != 10; i++)
{
std::string textString{ "Text Text Text Text Text Text Text Num "
+ std::to_string(i) };
std::unique_ptr<gsf::TextWidget> text{
std::make_unique<gsf::TextWidget>
(textString, font, 40, sf::Color::White) };
if (i % 2 == 0)
{
text->setBackgroundColor(sf::Color::Green);
}
else
{
text->setBackgroundColor(sf::Color::Magenta);
}
std::function<void(gsf::Widget*, sf::Vector2f)> leftClickListener =
[] (gsf::Widget* widget, sf::Vector2f mousePos)
{
gsf::TextWidget *textWidget = static_cast<gsf::TextWidget*>(widget);
std::cout << "TextWidget: Left Mouse Button Clicked. Text: "
<< textWidget->getText() << std::endl;
};
text->setOnLeftClickListener(leftClickListener);
//text->setBackgroundColor(sf::Color::Red);
layout4->attachChild(std::move(text));
}
scrollableWidget3->attachChild(std::move(layout4));
guiEnvironment.addWidget(std::move(scrollableWidget3));
std::unique_ptr<gsf::TextInputWidget> textInput1{
std::make_unique<gsf::TextInputWidget>(300.f, 60.f, font) };
textInput1->setPosition(520.f, 320.f);
textInput1->setBackgroundColor(sf::Color::White);
guiEnvironment.addWidget(std::move(textInput1));
while (window.isOpen())
{
determineFpsAndDeltaTime(txtStatFPS, dt, timePoint1);
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
guiEnvironment.handleEvent(event);
}
guiEnvironment.update(dt);
window.clear();
window.draw(guiEnvironment);
window.draw(txtStatFPS);
window.display();
}
return 0;
}
void determineFpsAndDeltaTime(sf::Text &txtStatFPS,
float &dt, CLOCK::time_point &timePoint1)
{
CLOCK::time_point timePoint2{ CLOCK::now() };
std::chrono::duration<float> timeSpan{ timePoint2 - timePoint1 };
timePoint1 = CLOCK::now();
// Get deltaTime as float in seconds
dt = std::chrono::duration_cast<std::chrono::duration<float,std::ratio<1>>>
(timeSpan).count();
float fps{ 1.f / dt };
txtStatFPS.setString("FPS: " + std::to_string(fps));
}
<|endoftext|> |
<commit_before>5e5893f2-2d16-11e5-af21-0401358ea401<commit_msg>5e5893f3-2d16-11e5-af21-0401358ea401<commit_after>5e5893f3-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>181b9351-2e4f-11e5-b4b9-28cfe91dbc4b<commit_msg>18221f91-2e4f-11e5-8c93-28cfe91dbc4b<commit_after>18221f91-2e4f-11e5-8c93-28cfe91dbc4b<|endoftext|> |
<commit_before>10529b0c-2e4f-11e5-b63a-28cfe91dbc4b<commit_msg>105d352e-2e4f-11e5-a6f6-28cfe91dbc4b<commit_after>105d352e-2e4f-11e5-a6f6-28cfe91dbc4b<|endoftext|> |
<commit_before>782d29a8-5216-11e5-b267-6c40088e03e4<commit_msg>7834ac86-5216-11e5-9bf6-6c40088e03e4<commit_after>7834ac86-5216-11e5-9bf6-6c40088e03e4<|endoftext|> |
<commit_before>b264d582-327f-11e5-88a6-9cf387a8033e<commit_msg>b26a8d8a-327f-11e5-b0e6-9cf387a8033e<commit_after>b26a8d8a-327f-11e5-b0e6-9cf387a8033e<|endoftext|> |
<commit_before>e491a0bd-313a-11e5-bf4b-3c15c2e10482<commit_msg>e497e85c-313a-11e5-9e32-3c15c2e10482<commit_after>e497e85c-313a-11e5-9e32-3c15c2e10482<|endoftext|> |
<commit_before>#include "MainGameScene.h"
#include "BaseController.h"
#include "MainGameGridLayer.h"
USING_NS_CC;
void testDataMethod();
MainGameScene::MainGameScene():
m_gridLayer(NULL),
m_statusBar(NULL),
m_toolBar(NULL)
{
}
MainGameScene::~MainGameScene()
{
}
MainGameScene *MainGameScene::create(BaseController *pDelegate)
{
MainGameScene *scene=new MainGameScene();
do {
CC_BREAK_IF(!scene || !(scene->initWith(pDelegate)));
scene->autorelease();
return scene;
} while (0);
CC_SAFE_DELETE(scene);
return NULL;
}
bool MainGameScene::initWith(BaseController *pDelegate)
{
bool tRet = false;
do{
CC_BREAK_IF(!init());
CC_BREAK_IF(!pDelegate);
m_delegate=pDelegate;
this->constructUI();
tRet = true;
}while(0);
return tRet;
}
void MainGameScene::constructUI()
{
do{
m_gridLayer=new MainGameGridLayer();
CC_BREAK_IF(!m_gridLayer);
m_gridLayer->initWithDelegate(m_delegate);
//m_gridLayer->constructUI();
addChild(m_gridLayer);
/*
m_statusBar=CCLayer::create();
CC_BREAK_IF(!m_statusBar);
addChild(m_statusBar);
m_toolBar=CCLayer::create();
CC_BREAK_IF(!m_toolBar);
addChild(m_toolBar);
CCLayerColor *statusInfoContainer=CCLayerColor::create(ccc4(256, 0, 0, 256));
statusInfoContainer->setContentSize(CCSizeMake(WIN_SIZE.width, 80.0));
statusInfoContainer->setPosition(CCPointZero);
m_statusBar->addChild(statusInfoContainer);
CCLayerColor *toolContainer=CCLayerColor::create(ccc4(0, 256, 0, 256));
toolContainer->setContentSize(CCSizeMake(WIN_SIZE.width,80.0));
toolContainer->setPosition(ccp(0,WIN_SIZE.height-80));
m_toolBar->addChild(statusInfoContainer);
//status bar
CCLabelTTF *coinLabel=NULL;
CCLabelTTF *roundLabel=NULL;
CCLabelTTF *scoreLabel=NULL;
CCLabelTTF *killdMonsterLabel=NULL;
CCLabelTTF *healthLabel=NULL;
CCSprite *baseDamageIcon=NULL;
CCSprite *shieldIcon=NULL;
CCSprite *weaponDamageIcon=NULL;
CCLabelTTF *baseDamageLabel=NULL;
CCLabelTTF *shieldLabel=NULL;
CCLabelTTF *weaponDamageLabel=NULL;
//tool bar
*/
testDataMethod();
}while(0);
}
#include "CSVParser.h"
void testDataMethod(void)
{
printf("testDataMethod");
CSVParser *csvParser = new CSVParser();
csvParser->openFile("testdata.csv");
CCArray *dataArray = CCArray::create();
CCArray *keys = CCArray::create();
CCDictionary *dictionary;
string strLine = "";
for (int i = 0; i < csvParser->getRows(); i++) {
for (int j = 0; j < csvParser->getCols(); j++) {
CCString *string = CCString::create(csvParser->getData(i, j));
if (i == 0) {
keys->addObject(string);
} else {
if (j==0) {
dictionary = CCDictionary::create();
}
CCString *strKey = (CCString *)keys->objectAtIndex(j);
dictionary->setObject(string, strKey->getCString());
if (j== csvParser->getCols()-1) {
dataArray->addObject(dictionary);
}
}
}
}
CCArray *allKeys = dictionary->allKeys();
for (int i = 0; i < allKeys->count(); i++) {
CCString *key = (CCString *)allKeys->objectAtIndex(i);
cout<<"key=" + string(key->getCString())<<endl;
}
CCDictionary *dict = NULL;
CCObject *object = NULL;
CCDictElement *dElement = NULL;
CCARRAY_FOREACH(dataArray, object)
{
dict = (CCDictionary *)object;
CCDICT_FOREACH(dict, dElement)
{
string key = dElement->getStrKey();
CCString *value = (CCString *)dElement->getObject();
cout<<"key="+key + " ------ value=" + value->getCString()<<endl;
}
// cout<<"\n"<<endl;
}
// for (int i = 0; i < dictionary->count(); i++) {
// cout<<dictionary->objectForKey("") <<endl;
// }
// dictionary->set
delete csvParser;
}
<commit_msg>注释掉测试方法<commit_after>#include "MainGameScene.h"
#include "BaseController.h"
#include "MainGameGridLayer.h"
USING_NS_CC;
void testDataMethod();
MainGameScene::MainGameScene():
m_gridLayer(NULL),
m_statusBar(NULL),
m_toolBar(NULL)
{
}
MainGameScene::~MainGameScene()
{
}
MainGameScene *MainGameScene::create(BaseController *pDelegate)
{
MainGameScene *scene=new MainGameScene();
do {
CC_BREAK_IF(!scene || !(scene->initWith(pDelegate)));
scene->autorelease();
return scene;
} while (0);
CC_SAFE_DELETE(scene);
return NULL;
}
bool MainGameScene::initWith(BaseController *pDelegate)
{
bool tRet = false;
do{
CC_BREAK_IF(!init());
CC_BREAK_IF(!pDelegate);
m_delegate=pDelegate;
this->constructUI();
tRet = true;
}while(0);
return tRet;
}
void MainGameScene::constructUI()
{
do{
m_gridLayer=new MainGameGridLayer();
CC_BREAK_IF(!m_gridLayer);
m_gridLayer->initWithDelegate(m_delegate);
//m_gridLayer->constructUI();
addChild(m_gridLayer);
/*
m_statusBar=CCLayer::create();
CC_BREAK_IF(!m_statusBar);
addChild(m_statusBar);
m_toolBar=CCLayer::create();
CC_BREAK_IF(!m_toolBar);
addChild(m_toolBar);
CCLayerColor *statusInfoContainer=CCLayerColor::create(ccc4(256, 0, 0, 256));
statusInfoContainer->setContentSize(CCSizeMake(WIN_SIZE.width, 80.0));
statusInfoContainer->setPosition(CCPointZero);
m_statusBar->addChild(statusInfoContainer);
CCLayerColor *toolContainer=CCLayerColor::create(ccc4(0, 256, 0, 256));
toolContainer->setContentSize(CCSizeMake(WIN_SIZE.width,80.0));
toolContainer->setPosition(ccp(0,WIN_SIZE.height-80));
m_toolBar->addChild(statusInfoContainer);
//status bar
CCLabelTTF *coinLabel=NULL;
CCLabelTTF *roundLabel=NULL;
CCLabelTTF *scoreLabel=NULL;
CCLabelTTF *killdMonsterLabel=NULL;
CCLabelTTF *healthLabel=NULL;
CCSprite *baseDamageIcon=NULL;
CCSprite *shieldIcon=NULL;
CCSprite *weaponDamageIcon=NULL;
CCLabelTTF *baseDamageLabel=NULL;
CCLabelTTF *shieldLabel=NULL;
CCLabelTTF *weaponDamageLabel=NULL;
//tool bar
*/
// testDataMethod();
}while(0);
}
#include "CSVParser.h"
void testDataMethod(void)
{
printf("testDataMethod");
CSVParser *csvParser = new CSVParser();
csvParser->openFile("testdata.csv");
CCArray *dataArray = CCArray::create();
CCArray *keys = CCArray::create();
CCDictionary *dictionary;
string strLine = "";
for (int i = 0; i < csvParser->getRows(); i++) {
for (int j = 0; j < csvParser->getCols(); j++) {
CCString *string = CCString::create(csvParser->getData(i, j));
if (i == 0) {
keys->addObject(string);
} else {
if (j==0) {
dictionary = CCDictionary::create();
}
CCString *strKey = (CCString *)keys->objectAtIndex(j);
dictionary->setObject(string, strKey->getCString());
if (j== csvParser->getCols()-1) {
dataArray->addObject(dictionary);
}
}
}
}
CCArray *allKeys = dictionary->allKeys();
for (int i = 0; i < allKeys->count(); i++) {
CCString *key = (CCString *)allKeys->objectAtIndex(i);
cout<<"key=" + string(key->getCString())<<endl;
}
CCDictionary *dict = NULL;
CCObject *object = NULL;
CCDictElement *dElement = NULL;
CCARRAY_FOREACH(dataArray, object)
{
dict = (CCDictionary *)object;
CCDICT_FOREACH(dict, dElement)
{
string key = dElement->getStrKey();
CCString *value = (CCString *)dElement->getObject();
cout<<"key="+key + " ------ value=" + value->getCString()<<endl;
}
// cout<<"\n"<<endl;
}
// for (int i = 0; i < dictionary->count(); i++) {
// cout<<dictionary->objectForKey("") <<endl;
// }
// dictionary->set
delete csvParser;
}
<|endoftext|> |
<commit_before>/* This file is part of Fabula.
Copyright (C) 2010 Mike McQuaid <mike@mikemcquaid.com>
Fabula is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Fabula is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Fabula. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MainWindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication application(argc, argv);
application.setApplicationName(QString::fromAscii("Fabula"));
application.setApplicationVersion(QString::fromAscii(PROJECT_VERSION));
application.setOrganizationDomain(QString::fromAscii("mikemcquaid.com"));
application.setOrganizationName(QString::fromAscii("Mike McQuaid"));
#ifdef Q_WS_MAC
application.setAttribute(Qt::AA_DontShowIconsInMenus);
#else
application.setWindowIcon(":/icons/audio-input-microphone.png");
#endif
MainWindow mainWindow;
mainWindow.show();
return application.exec();
}
<commit_msg>Fix Windows window icon failure.<commit_after>/* This file is part of Fabula.
Copyright (C) 2010 Mike McQuaid <mike@mikemcquaid.com>
Fabula is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Fabula is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Fabula. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MainWindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication application(argc, argv);
application.setApplicationName(QString::fromAscii("Fabula"));
application.setApplicationVersion(QString::fromAscii(PROJECT_VERSION));
application.setOrganizationDomain(QString::fromAscii("mikemcquaid.com"));
application.setOrganizationName(QString::fromAscii("Mike McQuaid"));
#ifdef Q_WS_MAC
application.setAttribute(Qt::AA_DontShowIconsInMenus);
#else
application.setWindowIcon(QIcon(":/icons/audio-input-microphone.png"));
#endif
MainWindow mainWindow;
mainWindow.show();
return application.exec();
}
<|endoftext|> |
<commit_before>5f6811f3-ad5a-11e7-aec6-ac87a332f658<commit_msg>I finished programming, there is nothing left to program<commit_after>5fec8073-ad5a-11e7-a7c8-ac87a332f658<|endoftext|> |
<commit_before>46809ae8-2d3d-11e5-8e14-c82a142b6f9b<commit_msg>46ff2f17-2d3d-11e5-b909-c82a142b6f9b<commit_after>46ff2f17-2d3d-11e5-b909-c82a142b6f9b<|endoftext|> |
<commit_before>107c0498-585b-11e5-a751-6c40088e03e4<commit_msg>10856d12-585b-11e5-8483-6c40088e03e4<commit_after>10856d12-585b-11e5-8483-6c40088e03e4<|endoftext|> |
<commit_before>2bef1228-2f67-11e5-a1c0-6c40088e03e4<commit_msg>2bf86d48-2f67-11e5-9fb1-6c40088e03e4<commit_after>2bf86d48-2f67-11e5-9fb1-6c40088e03e4<|endoftext|> |
<commit_before>6c621858-2e3a-11e5-8c87-c03896053bdd<commit_msg>6c6fd676-2e3a-11e5-b406-c03896053bdd<commit_after>6c6fd676-2e3a-11e5-b406-c03896053bdd<|endoftext|> |
<commit_before>aa32db23-2e4f-11e5-8c83-28cfe91dbc4b<commit_msg>aa3b680c-2e4f-11e5-8d3b-28cfe91dbc4b<commit_after>aa3b680c-2e4f-11e5-8d3b-28cfe91dbc4b<|endoftext|> |
<commit_before>128b1da3-2e4f-11e5-83da-28cfe91dbc4b<commit_msg>12924373-2e4f-11e5-a9d0-28cfe91dbc4b<commit_after>12924373-2e4f-11e5-a9d0-28cfe91dbc4b<|endoftext|> |
<commit_before>d2c33a45-313a-11e5-9bc9-3c15c2e10482<commit_msg>d2c90a35-313a-11e5-9743-3c15c2e10482<commit_after>d2c90a35-313a-11e5-9743-3c15c2e10482<|endoftext|> |
<commit_before>76532ff4-2d53-11e5-baeb-247703a38240<commit_msg>7653aea2-2d53-11e5-baeb-247703a38240<commit_after>7653aea2-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>5ed96888-5216-11e5-9fec-6c40088e03e4<commit_msg>5ee24eb0-5216-11e5-b58a-6c40088e03e4<commit_after>5ee24eb0-5216-11e5-b58a-6c40088e03e4<|endoftext|> |
<commit_before>5f78965c-2e4f-11e5-ac4e-28cfe91dbc4b<commit_msg>5f7f8a6e-2e4f-11e5-9bfe-28cfe91dbc4b<commit_after>5f7f8a6e-2e4f-11e5-9bfe-28cfe91dbc4b<|endoftext|> |
<commit_before>ac3a8f00-327f-11e5-aa67-9cf387a8033e<commit_msg>ac40a02b-327f-11e5-954b-9cf387a8033e<commit_after>ac40a02b-327f-11e5-954b-9cf387a8033e<|endoftext|> |
<commit_before>a1aaa08f-4b02-11e5-b8ae-28cfe9171a43<commit_msg>updated some files<commit_after>a1b65eb0-4b02-11e5-9111-28cfe9171a43<|endoftext|> |
<commit_before>69a3f3d4-2fa5-11e5-b488-00012e3d3f12<commit_msg>69a5a182-2fa5-11e5-82d5-00012e3d3f12<commit_after>69a5a182-2fa5-11e5-82d5-00012e3d3f12<|endoftext|> |
<commit_before>1219b9de-2e4f-11e5-a5b0-28cfe91dbc4b<commit_msg>1221ee19-2e4f-11e5-abaf-28cfe91dbc4b<commit_after>1221ee19-2e4f-11e5-abaf-28cfe91dbc4b<|endoftext|> |
<commit_before>bdc264b0-2747-11e6-af0c-e0f84713e7b8<commit_msg>update testing<commit_after>bdd6a2f5-2747-11e6-812f-e0f84713e7b8<|endoftext|> |
<commit_before>1275e278-2748-11e6-bddd-e0f84713e7b8<commit_msg>Hey we can now do a thing<commit_after>12835838-2748-11e6-88fb-e0f84713e7b8<|endoftext|> |
<commit_before>aec0e4e3-2e4f-11e5-b4c0-28cfe91dbc4b<commit_msg>aec7fdae-2e4f-11e5-bbbf-28cfe91dbc4b<commit_after>aec7fdae-2e4f-11e5-bbbf-28cfe91dbc4b<|endoftext|> |
<commit_before>ca20806b-4b02-11e5-8870-28cfe9171a43<commit_msg>fixes, fixes for everyone<commit_after>ca3064d9-4b02-11e5-9ddd-28cfe9171a43<|endoftext|> |
<commit_before>ce81b9d9-327f-11e5-ab96-9cf387a8033e<commit_msg>ce8832d7-327f-11e5-92dd-9cf387a8033e<commit_after>ce8832d7-327f-11e5-92dd-9cf387a8033e<|endoftext|> |
<commit_before>77d4545c-2d53-11e5-baeb-247703a38240<commit_msg>77d4db3e-2d53-11e5-baeb-247703a38240<commit_after>77d4db3e-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>2473930c-2f67-11e5-a830-6c40088e03e4<commit_msg>247a49ec-2f67-11e5-9c18-6c40088e03e4<commit_after>247a49ec-2f67-11e5-9c18-6c40088e03e4<|endoftext|> |
<commit_before>4ff6a2c2-2e3a-11e5-89ce-c03896053bdd<commit_msg>5006ab54-2e3a-11e5-84bc-c03896053bdd<commit_after>5006ab54-2e3a-11e5-84bc-c03896053bdd<|endoftext|> |
<commit_before>5e2f3fca-2e3a-11e5-ae2f-c03896053bdd<commit_msg>5e411d5a-2e3a-11e5-86f3-c03896053bdd<commit_after>5e411d5a-2e3a-11e5-86f3-c03896053bdd<|endoftext|> |
<commit_before>/*
Copyright (C) 2014 Marcus Soll
All rights reserved.
You may use this file under the terms of BSD license as follows:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
* Neither the name of the Jolla Ltd nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
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 HOLDERS 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 <QDebug>
#include <QList>
#include <QTime>
#include <QString>
#include <QtAlgorithms>
#include "getscore.h"
#include "gene.h"
#include "omp.h"
// Parameters of learning
int rounds = 100;
int population = 32;
int children = 32;
int mutationRate = 0.1;
int redoTests = 5;
struct TestScenario {
QString player1;
QString player2;
int player;
};
QList<TestScenario> getScenarios();
int main(int argc, char *argv[])
{
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
omp_set_num_threads(omp_get_num_procs()*2);
QList<Gene> currentPopulation;
QList<TestScenario> scenatios = getScenarios();
GetScore calc;
for(int i = 0; i < population; ++i)
{
currentPopulation.append(Gene(mutationRate));
}
for(int round = 1; round <= rounds; ++round)
{
qDebug() << "Current round: " << round;
QList<Gene> newPopulation = currentPopulation;
for(int i = 0; i < children; ++i)
{
Gene children = currentPopulation[qrand()%population];
children.mutate();
newPopulation.append(children);
}
for(int testnr=0; testnr < population+children; ++testnr)
{
qDebug() << "\tGene " << testnr;
int score = 0;
newPopulation[testnr].saveFiles();
#pragma omp parallel for schedule(dynamic) private(calc) reduction(+:score)
for(int test = 0; test < scenatios.size(); ++test)
{
calc.startTest(scenatios[test].player1, scenatios[test].player2,scenatios[test].player);
while(calc.scoreCalculated()) {qDebug() << "Waiting";}
score += calc.getScore();
}
newPopulation[testnr].saveScore(score);
}
currentPopulation.clear();
qSort(newPopulation);
for(int i = 0; i < population; ++i)
{
currentPopulation.append(newPopulation[i]);
}
qDebug() << "++++++++++\nBest score: " << currentPopulation[0].getScore() << "\n++++++++++\n";
currentPopulation[0].saveFiles("./inputToHidden1.endOfRound.txt", "./hidden1ToHidden2.endOfRound.txt", "./hidden2ToOutput.endOfRound.txt");
}
currentPopulation[0].saveFiles();
qDebug() << "Finished";
}
QList<TestScenario> getScenarios()
{
QList<TestScenario> scenarios;
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Greedy AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Greedy AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Tree AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Tree AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Balanced AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Balanced AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Static Rule AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Static Rule AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Adaptive Tree AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Adaptive Tree AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Control AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Control AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Assembly AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Assembly AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
return scenarios;
}
<commit_msg>Increased rounds.<commit_after>/*
Copyright (C) 2014 Marcus Soll
All rights reserved.
You may use this file under the terms of BSD license as follows:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* 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.
* Neither the name of the Jolla Ltd nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
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 HOLDERS 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 <QDebug>
#include <QList>
#include <QTime>
#include <QString>
#include <QtAlgorithms>
#include "getscore.h"
#include "gene.h"
#include "omp.h"
// Parameters of learning
int rounds = 1000000;
int population = 32;
int children = 32;
int mutationRate = 0.1;
int redoTests = 5;
struct TestScenario {
QString player1;
QString player2;
int player;
};
QList<TestScenario> getScenarios();
int main(int argc, char *argv[])
{
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
omp_set_num_threads(omp_get_num_procs()*2);
QList<Gene> currentPopulation;
QList<TestScenario> scenatios = getScenarios();
GetScore calc;
for(int i = 0; i < population; ++i)
{
currentPopulation.append(Gene(mutationRate));
}
for(int round = 1; round <= rounds; ++round)
{
qDebug() << "Current round: " << round;
QList<Gene> newPopulation = currentPopulation;
for(int i = 0; i < children; ++i)
{
Gene children = currentPopulation[qrand()%population];
children.mutate();
newPopulation.append(children);
}
for(int testnr=0; testnr < population+children; ++testnr)
{
qDebug() << "\tGene " << testnr;
int score = 0;
newPopulation[testnr].saveFiles();
#pragma omp parallel for schedule(dynamic) private(calc) reduction(+:score)
for(int test = 0; test < scenatios.size(); ++test)
{
calc.startTest(scenatios[test].player1, scenatios[test].player2,scenatios[test].player);
while(calc.scoreCalculated()) {qDebug() << "Waiting";}
score += calc.getScore();
}
newPopulation[testnr].saveScore(score);
}
currentPopulation.clear();
qSort(newPopulation);
for(int i = 0; i < population; ++i)
{
currentPopulation.append(newPopulation[i]);
}
qDebug() << "++++++++++\nBest score: " << currentPopulation[0].getScore() << "\n++++++++++\n";
currentPopulation[0].saveFiles("./inputToHidden1.endOfRound.txt", "./hidden1ToHidden2.endOfRound.txt", "./hidden2ToOutput.endOfRound.txt");
}
currentPopulation[0].saveFiles();
qDebug() << "Finished";
}
QList<TestScenario> getScenarios()
{
QList<TestScenario> scenarios;
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Greedy AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Greedy AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Tree AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Tree AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Balanced AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Balanced AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Static Rule AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Static Rule AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Adaptive Tree AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Adaptive Tree AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Control AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Control AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player1 = "Assembly AI";
test.player2 = "Neural Network AI";
test.player = 2;
scenarios.append(test);
}
for(int i=0; i<redoTests; ++i)
{
TestScenario test;
test.player2 = "Assembly AI";
test.player1 = "Neural Network AI";
test.player = 1;
scenarios.append(test);
}
return scenarios;
}
<|endoftext|> |
<commit_before>e5644102-313a-11e5-baff-3c15c2e10482<commit_msg>e569ef78-313a-11e5-887f-3c15c2e10482<commit_after>e569ef78-313a-11e5-887f-3c15c2e10482<|endoftext|> |
<commit_before>791905e2-2d53-11e5-baeb-247703a38240<commit_msg>79198daa-2d53-11e5-baeb-247703a38240<commit_after>79198daa-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>5fae86a8-2e3a-11e5-836b-c03896053bdd<commit_msg>5fbe8f26-2e3a-11e5-938c-c03896053bdd<commit_after>5fbe8f26-2e3a-11e5-938c-c03896053bdd<|endoftext|> |
<commit_before>c460a811-327f-11e5-a00c-9cf387a8033e<commit_msg>c466bbc5-327f-11e5-8e7d-9cf387a8033e<commit_after>c466bbc5-327f-11e5-8e7d-9cf387a8033e<|endoftext|> |
<commit_before>d8ab0106-585a-11e5-982c-6c40088e03e4<commit_msg>d8b5a442-585a-11e5-b994-6c40088e03e4<commit_after>d8b5a442-585a-11e5-b994-6c40088e03e4<|endoftext|> |
<commit_before>#include <iostream>
#include <string.h>
using namespace std;
// disable if you dont want it to be loud
#define VERBOSE 1
// definition
bool findExtension(string,string);
int main(int argc, char *argv[])
{
#if VERBOSE
cout << "number of arguments: " << argc << endl;
for (int i = 0; i < argc; i++)
{
cout << i << ": " << argv[i] << endl;
}
#endif
// if there are more than 1 arguments, do the conversion
if (argc > 1)
{
// open file for reading - one at a time
for (int i = 0; i < argc; i++)
{
// convert the char[] to string for easier parsing
string temp = argv[i];
if (findExtension(".grb", temp))
{
}
}
}
else
{
// nothing to convert, abort
return 0;
}
// end of program
return 0;
system("pause");
}
bool findExtension(string extension, string argument_string)
{
return true;
}
<commit_msg>finalized structure for conversion<commit_after>#include <iostream>
#include <string.h>
using namespace std;
// disable if you dont want it to be loud
#define VERBOSE 1
// definition
bool findExtension(string,string);
int main(int argc, char *argv[])
{
#if VERBOSE
cout << "number of arguments: " << argc << endl;
for (int i = 0; i < argc; i++)
{
cout << i << ": " << argv[i] << endl;
}
#endif
// if there are more than 1 arguments, do the conversion
if (argc > 1)
{
// open file for reading - one at a time
for (int i = 0; i < argc; i++)
{
// convert the char[] to string for easier parsing
string temp = argv[i];
/************************** ADD NEW EXTENSIONS HERE **************************/
if (findExtension(".grb", temp))
{
// extension found, convert to *.GKO - board outline
}
else if (findExtension(".drl", temp))
{
// extension found, convert to *.XLN - drill file
}
}
}
else
{
// nothing to convert, abort
return 0;
}
// end of program
return 0;
system("pause");
}
bool findExtension(string extension, string argument_string)
{
return true;
}
<|endoftext|> |
<commit_before>9ebbc8ba-327f-11e5-a013-9cf387a8033e<commit_msg>9ec1fbeb-327f-11e5-ba44-9cf387a8033e<commit_after>9ec1fbeb-327f-11e5-ba44-9cf387a8033e<|endoftext|> |
<commit_before>76e64fc8-2d53-11e5-baeb-247703a38240<commit_msg>76e6d704-2d53-11e5-baeb-247703a38240<commit_after>76e6d704-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>64d683fa-2e4f-11e5-8eda-28cfe91dbc4b<commit_msg>64dcf594-2e4f-11e5-be0e-28cfe91dbc4b<commit_after>64dcf594-2e4f-11e5-be0e-28cfe91dbc4b<|endoftext|> |
<commit_before>956c397e-35ca-11e5-8f2c-6c40088e03e4<commit_msg>9572d506-35ca-11e5-9f5f-6c40088e03e4<commit_after>9572d506-35ca-11e5-9f5f-6c40088e03e4<|endoftext|> |
<commit_before>856278ff-2d15-11e5-af21-0401358ea401<commit_msg>85627900-2d15-11e5-af21-0401358ea401<commit_after>85627900-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>2b3ff12e-2748-11e6-bf4d-e0f84713e7b8<commit_msg>That didn't fix it<commit_after>2b4d21e6-2748-11e6-a179-e0f84713e7b8<|endoftext|> |
<commit_before>d5aef454-35ca-11e5-8ab5-6c40088e03e4<commit_msg>d5b5dc88-35ca-11e5-a674-6c40088e03e4<commit_after>d5b5dc88-35ca-11e5-a674-6c40088e03e4<|endoftext|> |
<commit_before>f38a57ab-2d3e-11e5-8b0b-c82a142b6f9b<commit_msg>f4262ed1-2d3e-11e5-878c-c82a142b6f9b<commit_after>f4262ed1-2d3e-11e5-878c-c82a142b6f9b<|endoftext|> |
<commit_before>5bf6743b-2d16-11e5-af21-0401358ea401<commit_msg>5bf6743c-2d16-11e5-af21-0401358ea401<commit_after>5bf6743c-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>c77829d9-327f-11e5-bfcc-9cf387a8033e<commit_msg>c77e01c7-327f-11e5-a038-9cf387a8033e<commit_after>c77e01c7-327f-11e5-a038-9cf387a8033e<|endoftext|> |
<commit_before>
#include <cassert>
#include <cstring>
#include <thread>
#include <unistd.h>
#include <climits>
#include <iostream>
//#include <boost/filesystem.hpp>
#include "global.h"
#include "state.h"
#include "server/server_internal.h"
#include "partition/partition_db.h"
#include "daemons/daemons.h"
#include "util/hash.h"
#include "ble/ble_client_internal.h"
#define NOT_IMPLEMENTED printf("NOT_IMPLEMENTED\n"); exit(0);
#define DEBUG(x) printf("%d\n", x);
static void InitializeState()
{
g_current_node_state = new NodeStateMachine();
char hostname[HOST_NAME_MAX + 1];
if (gethostname(hostname, sizeof(hostname)) != 0)
{
perror("Unable to gethostname for current machine. Exiting.");
exit(1);
}
std::cout << "Machine hostname : " << hostname << std::endl;
g_current_node_id = hostToNodeId(std::string(hostname)); // from hash.h
std::cout << "Machine node id : " << g_current_node_id << std::endl;
// the intial partition map must exist <---------need boost
// assert(boost::filesystem::exists(boost::filesystem::path(g_cached_partition_map_filename)));
g_cached_partition_table = new PartitionTable(g_cached_partition_map_filename);
// initialize partition table
int num_partitions = g_cached_partition_table->getNumPartitions();
int num_replicas = g_cached_partition_table->getNumReplicas();
node_t *partition_table = g_cached_partition_table->getPartitionTable();
std::cout << "initialize for " << num_partitions << " partitions and " << num_replicas << " replicas" << std::endl;
// build list of partitions owned from scratch
for (partition_t partition_id = 0; partition_id < num_partitions; partition_id++)
{
int base_index = partition_id * num_replicas;
for (int i = 0; i < num_replicas; i++)
{
if (partition_table[i + base_index] == g_current_node_id)
{
PartitionMetadata pm;
pm.db = new PartitionDB(GetPartitionDBFilename(partition_id));
pm.state = PartitionState::STABLE;
g_current_node_state->partitions_owned_map[partition_id] = pm;
}
}
}
// cluster member list must exist <---------need boost
// assert(boost::filesystem::exists(boost::filesystem::path(g_cluster_member_list_filename)));
g_current_node_state->loadClusterMemberList(g_cluster_member_list_filename);
g_current_node_state->state = NodeState::STABLE;
// save the partition state
g_current_node_state->savePartitionState(g_owned_partition_state_filename);
g_current_node_state->saveNodeState(g_current_node_state_filename);
}
// Citation: argument parsing from word2vec by T. Mikolov
static int ArgPos(const char *str, int argc, const char **argv, bool has_additional)
{
int a;
for (a = 1; a < argc; a++)
{
if (strcmp(str, argv[a]) == 0)
{
if (has_additional && a == argc - 1)
{
printf("Argument missing for %s\n", str);
exit(1);
}
DEBUG(a)
return a;
}
}
return -1;
}
int main(int argc, const char *argv[])
{
int i;
bool join = false, recover = false, debug = false;
if ((i = ArgPos("--datadir", argc, argv, true)) > 0)
g_db_files_dirname = std::string(argv[i+1]);
if ((i = ArgPos("--nodestate", argc, argv, true)) > 0)
g_current_node_state_filename = std::string(argv[i+1]);
if ((i = ArgPos("--clustermembers", argc, argv, true)) > 0)
g_cluster_member_list_filename = std::string(argv[i+1]);
if ((i = ArgPos("--ownershipmap", argc, argv, true)) > 0)
g_owned_partition_state_filename = std::string(argv[i+1]);
if ((i = ArgPos("--partitionmap", argc, argv, true)) > 0)
g_cached_partition_map_filename = std::string(argv[i+1]);
if ((i = ArgPos("--join", argc, argv, false)) > 0)
join = true;
if ((i = ArgPos("--recover", argc, argv, false)) > 0)
recover = true;
if ((i = ArgPos("--debug", argc, argv, false)) > 0)
debug = true;
std::cout << "DB directory : " << g_db_files_dirname << std::endl;
std::cout << "Node state file : " << g_current_node_state_filename << std::endl;
std::cout << "Cluster members file : " << g_cluster_member_list_filename << std::endl;
std::cout << "Ownership map file : " << g_owned_partition_state_filename << std::endl;
std::cout << "Partition-node map file : " << g_cached_partition_map_filename << std::endl;
if (join && recover)
{
perror("cannot join and recover\n");
exit(0);
}
if (g_db_files_dirname == "")
{
perror("must specify a directory for database files\n");
exit(0);
}
if (g_current_node_state_filename == "")
{
perror("must specify a filename for persisting node state\n");
exit(0);
}
if (g_cluster_member_list_filename == "")
{
perror("must specify a file for list of cluster members\n");
exit(0);
}
if (g_owned_partition_state_filename == "")
{
perror("must specify a file for owned partition state\n");
exit(0);
}
if (g_cached_partition_map_filename == "")
{
perror("must specify a file for partition map\n");
exit(0);
}
if (join)
{
NOT_IMPLEMENTED
}
else if (recover)
{
NOT_IMPLEMENTED
}
else
{
InitializeState();
}
// std::thread rebalance_thread(LoadBalanceDaemon, 60 * 5); // 5 minutes
std::thread gc_thread(GarbageCollectDaemon, 60 * 60 * 12); // 12 hrs
if (debug) // simulate data
{
std::thread simulate_put_thread(SimulatePutDaemon, 1, 42);
simulate_put_thread.detach();
}
gc_thread.join();
// rebalance_thread.join();
}<commit_msg>updated argument passing constants and comments<commit_after>
#include <cassert>
#include <cstring>
#include <thread>
#include <unistd.h>
#include <climits>
#include <iostream>
//#include <boost/filesystem.hpp>
#include "global.h"
#include "state.h"
#include "server/server_internal.h"
#include "partition/partition_db.h"
#include "daemons/daemons.h"
#include "util/hash.h"
#include "ble/ble_client_internal.h"
#define NOT_IMPLEMENTED printf("NOT_IMPLEMENTED\n"); exit(0);
#define DEBUG(x) printf("%d\n", x);
static void InitializeState()
{
g_current_node_state = new NodeStateMachine();
char hostname[HOST_NAME_MAX + 1];
if (gethostname(hostname, sizeof(hostname)) != 0)
{
perror("Unable to gethostname for current machine. Exiting.");
exit(1);
}
std::cout << "Machine hostname : " << hostname << std::endl;
g_current_node_id = hostToNodeId(std::string(hostname)); // from hash.h
std::cout << "Machine node id : " << g_current_node_id << std::endl;
// the intial partition map must exist <---------need boost
// assert(boost::filesystem::exists(boost::filesystem::path(g_cached_partition_map_filename)));
g_cached_partition_table = new PartitionTable(g_cached_partition_map_filename);
// initialize partition table
int num_partitions = g_cached_partition_table->getNumPartitions();
int num_replicas = g_cached_partition_table->getNumReplicas();
node_t *partition_table = g_cached_partition_table->getPartitionTable();
std::cout << "initialize for " << num_partitions << " partitions and " << num_replicas << " replicas" << std::endl;
// build list of partitions owned from scratch
for (partition_t partition_id = 0; partition_id < num_partitions; partition_id++)
{
int base_index = partition_id * num_replicas;
for (int i = 0; i < num_replicas; i++)
{
if (partition_table[i + base_index] == g_current_node_id)
{
PartitionMetadata pm;
pm.db = new PartitionDB(GetPartitionDBFilename(partition_id));
pm.state = PartitionState::STABLE;
g_current_node_state->partitions_owned_map[partition_id] = pm;
}
}
}
// cluster member list must exist <---------need boost
// assert(boost::filesystem::exists(boost::filesystem::path(g_cluster_member_list_filename)));
g_current_node_state->loadClusterMemberList(g_cluster_member_list_filename);
g_current_node_state->state = NodeState::STABLE;
// save the partition state
g_current_node_state->savePartitionState(g_owned_partition_state_filename);
g_current_node_state->saveNodeState(g_current_node_state_filename);
}
// Citation: modified argument parsing function adapted from word2vec by T. Mikolov
static int ArgPos(const char *str, int argc, const char **argv, bool has_additional)
{
int i;
for (i = 1; i < argc; i++)
{
if (strcmp(str, argv[i]) == 0)
{
if (has_additional && i == argc - 1)
{
printf("Argument missing for %s\n", str);
exit(1);
}
return i;
}
}
return -1;
}
int main(int argc, const char *argv[])
{
int i;
bool join = false, recover = false, debug = false;
if ((i = ArgPos("--datadir", argc, argv, true)) > 0)
g_db_files_dirname = std::string(argv[i+1]);
if ((i = ArgPos("--nodestate", argc, argv, true)) > 0)
g_current_node_state_filename = std::string(argv[i+1]);
if ((i = ArgPos("--clustermembers", argc, argv, true)) > 0)
g_cluster_member_list_filename = std::string(argv[i+1]);
if ((i = ArgPos("--ownershipmap", argc, argv, true)) > 0)
g_owned_partition_state_filename = std::string(argv[i+1]);
if ((i = ArgPos("--partitionmap", argc, argv, true)) > 0)
g_cached_partition_map_filename = std::string(argv[i+1]);
if ((i = ArgPos("--join", argc, argv, false)) > 0)
join = true;
if ((i = ArgPos("--recover", argc, argv, false)) > 0)
recover = true;
if ((i = ArgPos("--debug", argc, argv, false)) > 0)
debug = true;
std::cout << "DB directory : " << g_db_files_dirname << std::endl;
std::cout << "Node state file : " << g_current_node_state_filename << std::endl;
std::cout << "Cluster members file : " << g_cluster_member_list_filename << std::endl;
std::cout << "Ownership map file : " << g_owned_partition_state_filename << std::endl;
std::cout << "Partition-node map file : " << g_cached_partition_map_filename << std::endl;
if (join && recover)
{
perror("cannot join and recover\n");
exit(0);
}
if (g_db_files_dirname == "")
{
perror("must specify a directory for database files\n");
exit(0);
}
if (g_current_node_state_filename == "")
{
perror("must specify a filename for persisting node state\n");
exit(0);
}
if (g_cluster_member_list_filename == "")
{
perror("must specify a file for list of cluster members\n");
exit(0);
}
if (g_owned_partition_state_filename == "")
{
perror("must specify a file for owned partition state\n");
exit(0);
}
if (g_cached_partition_map_filename == "")
{
perror("must specify a file for partition map\n");
exit(0);
}
if (join)
{
NOT_IMPLEMENTED
}
else if (recover)
{
NOT_IMPLEMENTED
}
else
{
InitializeState();
}
// std::thread rebalance_thread(LoadBalanceDaemon, 60 * 5); // 5 minutes
std::thread gc_thread(GarbageCollectDaemon, 60 * 60 * 12); // 12 hrs
if (debug) // simulate data
{
std::thread simulate_put_thread(SimulatePutDaemon, 1, 42);
simulate_put_thread.detach();
}
gc_thread.join();
// rebalance_thread.join();
}<|endoftext|> |
<commit_before><commit_msg>40f71770-2e3a-11e5-bd46-c03896053bdd<commit_after><|endoftext|> |
<commit_before>6a4f7614-2fa5-11e5-9f02-00012e3d3f12<commit_msg>6a514ad4-2fa5-11e5-ab35-00012e3d3f12<commit_after>6a514ad4-2fa5-11e5-ab35-00012e3d3f12<|endoftext|> |
<commit_before>695dea24-2fa5-11e5-9f23-00012e3d3f12<commit_msg>695fbee4-2fa5-11e5-9bcc-00012e3d3f12<commit_after>695fbee4-2fa5-11e5-9bcc-00012e3d3f12<|endoftext|> |
<commit_before>37d5f828-5216-11e5-92cf-6c40088e03e4<commit_msg>37dcd118-5216-11e5-b4d7-6c40088e03e4<commit_after>37dcd118-5216-11e5-b4d7-6c40088e03e4<|endoftext|> |
<commit_before>78db98d8-2d53-11e5-baeb-247703a38240<commit_msg>78dc1880-2d53-11e5-baeb-247703a38240<commit_after>78dc1880-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>5bf673a7-2d16-11e5-af21-0401358ea401<commit_msg>5bf673a8-2d16-11e5-af21-0401358ea401<commit_after>5bf673a8-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>66564f74-2fa5-11e5-8381-00012e3d3f12<commit_msg>665b7f94-2fa5-11e5-a3e0-00012e3d3f12<commit_after>665b7f94-2fa5-11e5-a3e0-00012e3d3f12<|endoftext|> |
<commit_before>7e7919f9-2d15-11e5-af21-0401358ea401<commit_msg>7e7919fa-2d15-11e5-af21-0401358ea401<commit_after>7e7919fa-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>0877be90-585b-11e5-8933-6c40088e03e4<commit_msg>087f4280-585b-11e5-97da-6c40088e03e4<commit_after>087f4280-585b-11e5-97da-6c40088e03e4<|endoftext|> |
<commit_before>7826ec08-2d53-11e5-baeb-247703a38240<commit_msg>78276ba6-2d53-11e5-baeb-247703a38240<commit_after>78276ba6-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>8b332604-2d14-11e5-af21-0401358ea401<commit_msg>8b332605-2d14-11e5-af21-0401358ea401<commit_after>8b332605-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>4c42269e-2e4f-11e5-8e96-28cfe91dbc4b<commit_msg>4c493bc0-2e4f-11e5-9d03-28cfe91dbc4b<commit_after>4c493bc0-2e4f-11e5-9d03-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <map>
#include <iostream>
#include <sstream>
#include <fstream>
#include <readline/readline.h>
#include <readline/history.h>
#include "sexpr.hpp"
#include "ast.hpp"
#include "eval.hpp"
#include "parse.hpp"
#include "unpack.hpp"
#include "type.hpp"
const bool debug = true;
struct history {
const std::string filename;
history(const std::string& filename="/tmp/slap.history")
: filename(filename) {
read_history(filename.c_str());
}
~history() {
write_history(filename.c_str());
}
};
template<class F>
static void read_loop(const F& f) {
const history lock;
while(const char* line = readline("> ")) {
if(!*line) continue;
add_history(line);
std::stringstream ss(line);
f(ss);
}
};
static ref<env> prelude() {
using namespace unpack;
auto res = make_ref<env>();
(*res)
.def("+", closure(+[](const integer& lhs, const integer& rhs) -> integer {
return lhs + rhs;
}))
.def("-", closure(+[](const integer& lhs, const integer& rhs) -> integer {
return lhs - rhs;
}))
.def("=", closure(+[](const integer& lhs, const integer& rhs) -> boolean {
return lhs == rhs;
}))
.def("nil", value::list())
.def("cons", closure(2, [](const value* args) -> value {
return args[0] >>= args[1].cast<value::list>();
}))
;
return res;
};
int main(int argc, char** argv) {
auto re = prelude();
auto ts = make_ref<type::state>();
{
using namespace type;
using type::integer;
using type::boolean;
using type::list;
using type::real;
// arithmetic
(*ts)
.def("+", integer >>= integer >>= integer)
.def("-", integer >>= integer >>= integer)
.def("=", integer >>= integer >>= boolean);
// lists
{
const auto a = ts->fresh();
ts->def("nil", list(a));
}
{
const auto a = ts->fresh();
ts->def("cons", a >>= list(a) >>= list(a));
}
// constructors
(*ts)
.def("integer", integer >>= integer)
.def("real", real >>= real)
.def("boolean", boolean >>= boolean)
;
{
// pair
const auto a = ts->fresh();
const auto b = ts->fresh();
const mono pair =
make_ref<constant>(symbol("pair"),
kind::term() >>= kind::term() >>= kind::term());
ts->def("pair",
pair(a)(b) >>= rec(row("first", a) |= row("second", a) |= empty));
}
{
// functor
const mono f = ts->fresh(kind::term() >>= kind::term());
const mono a = ts->fresh(kind::term());
const mono b = ts->fresh(kind::term());
const mono functor
= make_ref<constant>("functor", f.kind() >>= kind::term());
ts->def("functor", functor(f) >>=
rec(row("map", f(a) >>= (a >>= b) >>= f(b)) |= empty))
;
}
{
// test
const mono a = ts->fresh();
const mono b = ts->fresh();
const mono value = make_ref<constant>("value", kind::term() >>= kind::term());
ts->def("value", value(a) >>= rec( row("get", b >>= a) |= empty ));
}
}
// parser::debug::stream = &std::clog;
using parser::operator+;
static const auto program = parser::debug("prog") |= +[](std::istream& in) {
return sexpr::parse(in);
} >> parser::drop(parser::eof()) | parser::error<std::deque<sexpr>>("parse error");
static const auto handler =
[&](std::istream& in) {
try {
if(auto exprs = program(in)) {
for(const sexpr& s : exprs.get()) {
// std::cout << "parsed: " << s << std::endl;
const ast::toplevel a = ast::toplevel::check(s);
if(debug) std::cout << "ast: " << a << std::endl;
// toplevel expression?
if(auto e = a.get<ast::io>()->get<ast::expr>()) {
const type::mono t = type::mono::infer(ts, *e);
const type::poly p = ts->generalize(t);
// TODO: cleanup variables with depth greater than current in
// substitution
std::cout << " : " << p;
const value v = eval(re, *e);
std::cout << " = " << v << std::endl;
}
}
return true;
}
} catch(ast::error& e) {
std::cerr << "syntax error: " << e.what() << std::endl;
} catch(type::error& e) {
std::cerr << "type error: " << e.what() << std::endl;
} catch(std::runtime_error& e) {
std::cerr << "runtime error: " << e.what() << std::endl;
}
return false;
};
if(argc > 1) {
const char* filename = argv[1];
if(auto ifs = std::ifstream(filename)) {
return handler(ifs) ? 0 : 1;
} else {
std::cerr << "io error: " << "cannot read " << filename << std::endl;
return 1;
}
} else {
read_loop(handler);
}
return 0;
}
<commit_msg>list functions<commit_after>#include <map>
#include <iostream>
#include <sstream>
#include <fstream>
#include <readline/readline.h>
#include <readline/history.h>
#include "sexpr.hpp"
#include "ast.hpp"
#include "eval.hpp"
#include "parse.hpp"
#include "unpack.hpp"
#include "type.hpp"
const bool debug = true;
struct history {
const std::string filename;
history(const std::string& filename="/tmp/slap.history")
: filename(filename) {
read_history(filename.c_str());
}
~history() {
write_history(filename.c_str());
}
};
template<class F>
static void read_loop(const F& f) {
const history lock;
while(const char* line = readline("> ")) {
if(!*line) continue;
add_history(line);
std::stringstream ss(line);
f(ss);
}
};
static ref<env> prelude() {
using namespace unpack;
auto res = make_ref<env>();
(*res)
.def("+", closure(+[](const integer& lhs, const integer& rhs) -> integer {
return lhs + rhs;
}))
.def("-", closure(+[](const integer& lhs, const integer& rhs) -> integer {
return lhs - rhs;
}))
.def("=", closure(+[](const integer& lhs, const integer& rhs) -> boolean {
return lhs == rhs;
}))
.def("nil", value::list())
.def("cons", closure(2, [](const value* args) -> value {
return args[0] >>= args[1].cast<value::list>();
}))
.def("isnil", closure(+[](const value::list& self) -> boolean {
return boolean(self);
}))
.def("head", closure(1, [](const value* args) -> value {
return args[0].cast<value::list>()->head;
}))
.def("tail", closure(1, [](const value* args) -> value {
return args[0].cast<value::list>()->tail;
}))
;
return res;
};
int main(int argc, char** argv) {
auto re = prelude();
auto ts = make_ref<type::state>();
{
using namespace type;
using type::integer;
using type::boolean;
using type::list;
using type::real;
// arithmetic
(*ts)
.def("+", integer >>= integer >>= integer)
.def("-", integer >>= integer >>= integer)
.def("=", integer >>= integer >>= boolean);
// lists
{
const auto a = ts->fresh();
ts->def("nil", list(a));
}
{
const auto a = ts->fresh();
ts->def("cons", a >>= list(a) >>= list(a));
}
//
{
const auto a = ts->fresh();
ts->def("isnil", list(a) >>= boolean);
}
{
const auto a = ts->fresh();
ts->def("head", list(a) >>= a);
}
{
const auto a = ts->fresh();
ts->def("tail", list(a) >>= list(a));
}
// constructors
(*ts)
.def("integer", integer >>= integer)
.def("real", real >>= real)
.def("boolean", boolean >>= boolean)
;
{
// pair
const auto a = ts->fresh();
const auto b = ts->fresh();
const mono pair =
make_ref<constant>(symbol("pair"),
kind::term() >>= kind::term() >>= kind::term());
ts->def("pair",
pair(a)(b) >>= rec(row("first", a) |= row("second", a) |= empty));
}
{
// functor
const mono f = ts->fresh(kind::term() >>= kind::term());
const mono a = ts->fresh(kind::term());
const mono b = ts->fresh(kind::term());
const mono functor
= make_ref<constant>("functor", f.kind() >>= kind::term());
ts->def("functor", functor(f) >>=
rec(row("map", f(a) >>= (a >>= b) >>= f(b)) |= empty))
;
}
{
// test
const mono a = ts->fresh();
const mono b = ts->fresh();
const mono value = make_ref<constant>("value", kind::term() >>= kind::term());
ts->def("value", value(a) >>= rec( row("get", b >>= a) |= empty ));
}
}
// parser::debug::stream = &std::clog;
using parser::operator+;
static const auto program = parser::debug("prog") |= +[](std::istream& in) {
return sexpr::parse(in);
} >> parser::drop(parser::eof()) | parser::error<std::deque<sexpr>>("parse error");
static const auto handler =
[&](std::istream& in) {
try {
if(auto exprs = program(in)) {
for(const sexpr& s : exprs.get()) {
// std::cout << "parsed: " << s << std::endl;
const ast::toplevel a = ast::toplevel::check(s);
if(debug) std::cout << "ast: " << a << std::endl;
// toplevel expression?
if(auto e = a.get<ast::io>()->get<ast::expr>()) {
const type::mono t = type::mono::infer(ts, *e);
const type::poly p = ts->generalize(t);
// TODO: cleanup variables with depth greater than current in
// substitution
std::cout << " : " << p;
const value v = eval(re, *e);
std::cout << " = " << v << std::endl;
}
}
return true;
}
} catch(ast::error& e) {
std::cerr << "syntax error: " << e.what() << std::endl;
} catch(type::error& e) {
std::cerr << "type error: " << e.what() << std::endl;
} catch(std::runtime_error& e) {
std::cerr << "runtime error: " << e.what() << std::endl;
}
return false;
};
if(argc > 1) {
const char* filename = argv[1];
if(auto ifs = std::ifstream(filename)) {
return handler(ifs) ? 0 : 1;
} else {
std::cerr << "io error: " << "cannot read " << filename << std::endl;
return 1;
}
} else {
read_loop(handler);
}
return 0;
}
<|endoftext|> |
<commit_before>8b332538-2d14-11e5-af21-0401358ea401<commit_msg>8b332539-2d14-11e5-af21-0401358ea401<commit_after>8b332539-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>c9089642-35ca-11e5-876d-6c40088e03e4<commit_msg>c90f3268-35ca-11e5-94c9-6c40088e03e4<commit_after>c90f3268-35ca-11e5-94c9-6c40088e03e4<|endoftext|> |
<commit_before>#include <unistd.h>
#include <iostream>
#include <GRand>
int main(void){
GRand::Core::Config cfg;
GRand::Core::Config::autoConf(cfg);
GRand::Core* e = GRand::Core::start(cfg);
e->addPersistantInstruction([](){ glClearColor(0.05f, 0.05f, 0.05f, 0.0f);} );
e->addPersistantInstruction([](){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); });
GRand::Material mat;
GRand::GPUBuffer gb;
gb.loadFile("./testModels/monkey.dae");
GRand::Mesh mesh(e, &mat);
mesh.set(gb);
PUSH_CORE_INSTA(e, mat, mat.addShader(GL_FRAGMENT_SHADER, "./shaders/phongFrag.glsl"); );
PUSH_CORE_INSTA(e, mat, mat.addShader(GL_VERTEX_SHADER, "./shaders/phongVert.glsl"); );
//PUSH_CORE_INSTA(e, mat, mat.addShader(GL_FRAGMENT_SHADER, "./shaders/simpleFrag.glsl"); );
//PUSH_CORE_INSTA(e, mat, mat.addShader(GL_VERTEX_SHADER, "./shaders/simpleVert.glsl"); );
PUSH_CORE_INSTA(e, mat, mat.link());
GRand::Controller* ctrl = mesh.genController();
//ctrl->translate(Eigen::Vector3f(0,0,1.0f));
//ctrl->rotate(1.571f, Eigen::Vector3f::UnitX());
//ctrl->scale(Eigen::Vector3f(0.8f, 0.8f, 0.8f));
GRand::Camera cam(e);
cam.setPos(Eigen::Vector3f(4,3,3));
ctrl->rotate(-1.571, Eigen::Vector3f::UnitX());
ctrl->scale(Eigen::Vector3f(0.3, 0.3, 0.3));
while (e->getStateValidity()) {
usleep(10000);
ctrl->rotate(0.01, Eigen::Vector3f::UnitY());
}
delete e;
return 0;
}
<commit_msg>something beautifull to see<commit_after>#include <unistd.h>
#include <iostream>
#include <GRand>
int main(void){
GRand::Core::Config cfg;
GRand::Core::Config::autoConf(cfg);
GRand::Core* e = GRand::Core::start(cfg);
e->addPersistantInstruction([](){ glClearColor(0.05f, 0.05f, 0.05f, 0.0f);} );
e->addPersistantInstruction([](){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); });
GRand::Material mat;
GRand::GPUBuffer gb;
gb.loadFile("./testModels/monkey.dae");
GRand::Mesh mesh(e, &mat);
mesh.set(gb);
PUSH_CORE_INSTA(e, mat, mat.addShader(GL_FRAGMENT_SHADER, "./shaders/phongFrag.glsl"); );
PUSH_CORE_INSTA(e, mat, mat.addShader(GL_VERTEX_SHADER, "./shaders/phongVert.glsl"); );
//PUSH_CORE_INSTA(e, mat, mat.addShader(GL_FRAGMENT_SHADER, "./shaders/simpleFrag.glsl"); );
//PUSH_CORE_INSTA(e, mat, mat.addShader(GL_VERTEX_SHADER, "./shaders/simpleVert.glsl"); );
PUSH_CORE_INSTA(e, mat, mat.link());
GRand::Controller* ctrl = mesh.genController();
//ctrl->translate(Eigen::Vector3f(0,0,1.0f));
//ctrl->rotate(1.571f, Eigen::Vector3f::UnitX());
//ctrl->scale(Eigen::Vector3f(0.8f, 0.8f, 0.8f));
GRand::Camera cam(e);
//cam.setPos(Eigen::Vector3f(4,3,3));
ctrl->translate(Eigen::Vector3f(0,2,0));
ctrl->scale(Eigen::Vector3f(0.3, 0.3, 0.3));
ctrl->rotate(-1.571, Eigen::Vector3f::UnitX());
while (e->getStateValidity()) {
usleep(10000);
ctrl->rotate(0.01, Eigen::Vector3f::UnitY());
}
delete e;
return 0;
}
<|endoftext|> |
<commit_before>23e1a09e-2f67-11e5-a862-6c40088e03e4<commit_msg>23e93ca2-2f67-11e5-bd1d-6c40088e03e4<commit_after>23e93ca2-2f67-11e5-bd1d-6c40088e03e4<|endoftext|> |
<commit_before>59b7f70c-5216-11e5-bd0e-6c40088e03e4<commit_msg>59bec242-5216-11e5-978a-6c40088e03e4<commit_after>59bec242-5216-11e5-978a-6c40088e03e4<|endoftext|> |
<commit_before>93ef7b19-ad5a-11e7-9350-ac87a332f658<commit_msg>gsghfklghjsad<commit_after>94825aa1-ad5a-11e7-b3e1-ac87a332f658<|endoftext|> |
<commit_before>83000e9f-2d15-11e5-af21-0401358ea401<commit_msg>83000ea0-2d15-11e5-af21-0401358ea401<commit_after>83000ea0-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>0d54c600-2e4f-11e5-b93f-28cfe91dbc4b<commit_msg>0d5b7a51-2e4f-11e5-86f5-28cfe91dbc4b<commit_after>0d5b7a51-2e4f-11e5-86f5-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <iostream>
int main()
{
std::cout << "Hello World!" << std::endl;
return 0;
}
<commit_msg>My Life for Auir<commit_after>5f7ee407-2749-11e6-9b6f-e0f84713e7b8<|endoftext|> |
<commit_before>/*
Copyright (c) 2013, Sean Kasun
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* 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 HOLDER 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 <QtWidgets/QApplication>
#include <QTranslator>
#include <QLocale>
#include "minutor.h"
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
QString locale = QLocale::system().name();
QTranslator translator;
translator.load(QString("minutor_")+locale);
app.installTranslator(&translator);
app.setApplicationName("Minutor");
app.setApplicationVersion("2.0.1");
app.setOrganizationName("seancode");
Minutor minutor;
// Process the cmdline arguments:
auto args = app.arguments();
size_t numArgs = args.size();
for (size_t i = 0; i < numArgs; i++)
{
if (((args[i] == "-w") || (args[i] == "--world")) && (i + 1 < numArgs))
{
minutor.loadWorld(args[i + 1]);
continue;
}
if (((args[i] == "-j") || (args[i] == "--jump")) && (i + 2 < numArgs))
{
minutor.jumpToXZ(args[i + 1].toInt(), args[i + 2].toInt());
}
} // for itr - args[]
minutor.show();
return app.exec();
}
<commit_msg>removed use of auto<commit_after>/*
Copyright (c) 2013, Sean Kasun
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* 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 HOLDER 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 <QtWidgets/QApplication>
#include <QTranslator>
#include <QLocale>
#include "minutor.h"
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
QString locale = QLocale::system().name();
QTranslator translator;
translator.load(QString("minutor_")+locale);
app.installTranslator(&translator);
app.setApplicationName("Minutor");
app.setApplicationVersion("2.0.1");
app.setOrganizationName("seancode");
Minutor minutor;
// Process the cmdline arguments:
QStringList args = app.arguments();
size_t numArgs = args.size();
for (size_t i = 0; i < numArgs; i++)
{
if (((args[i] == "-w") || (args[i] == "--world")) && (i + 1 < numArgs))
{
minutor.loadWorld(args[i + 1]);
continue;
}
if (((args[i] == "-j") || (args[i] == "--jump")) && (i + 2 < numArgs))
{
minutor.jumpToXZ(args[i + 1].toInt(), args[i + 2].toInt());
}
} // for itr - args[]
minutor.show();
return app.exec();
}
<|endoftext|> |
<commit_before>dde00e9e-585a-11e5-b298-6c40088e03e4<commit_msg>dde6bfbe-585a-11e5-a9f2-6c40088e03e4<commit_after>dde6bfbe-585a-11e5-a9f2-6c40088e03e4<|endoftext|> |
<commit_before>b0f1a875-327f-11e5-b33a-9cf387a8033e<commit_msg>b0f7aef5-327f-11e5-b293-9cf387a8033e<commit_after>b0f7aef5-327f-11e5-b293-9cf387a8033e<|endoftext|> |
<commit_before>4c33e5e8-2e4f-11e5-8a98-28cfe91dbc4b<commit_msg>4c3a9e3a-2e4f-11e5-b23b-28cfe91dbc4b<commit_after>4c3a9e3a-2e4f-11e5-b23b-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdexcept>
#include "dummy_solver.h"
#include "hermes2d.h"
#include "_hermes2d_api.h"
// The time-dependent laminar incompressible Navier-Stokes equations are
// discretized in time via the implicit Euler method. The convective term
// is linearized simply by replacing the velocity in front of the nabla
// operator with the velocity from last time step. Velocity is approximated
// using continuous elements, and pressure by means or discontinuous (L2)
// elements. This makes the velocity discretely divergence-free, meaning
// that the integral of div(v) over every element is zero. The problem
// has a steady symmetric solution which is unstable. Note that after some
// time (around t = 100), numerical errors induce oscillations. The
// approximation becomes unsteady and thus diverges from the exact solution.
// Interestingly, this happens even with a completely symmetric mesh.
//
// PDE: incompressible Navier-Stokes equations in the form
// \partial v / \partial t - \Delta v / Re + (v \cdot \nabla) v + \nabla p = 0,
// div v = 0
//
// BC: u_1 is a time-dependent constant and u_2 = 0 on Gamma_4 (inlet)
// u_1 = u_2 = 0 on Gamma_1 (bottom), Gamma_3 (top) and Gamma_5 (obstacle)
// "do nothing" on Gamma_2 (outlet)
//
// TODO: Implement Crank-Nicolson so that comparisons with implicit Euler can be made
//
// The following parameters can be played with:
const double RE = 1000.0; // Reynolds number
const double VEL_INLET = 1.0; // inlet velocity (reached after STARTUP_TIME)
const double STARTUP_TIME = 1.0; // during this time, inlet velocity increases gradually
// from 0 to VEL_INLET, then it stays constant
const double TAU = 0.5; // time step
const double FINAL_TIME = 3000.0; // length of time interval
const int P_INIT_VEL = 2; // polynomial degree for velocity components
const int P_INIT_PRESSURE = 1; // polynomial degree for pressure
// Note: P_INIT_VEL should always be greater than
// P_INIT_PRESSURE because of the inf-sup condition
const double H = 5.0; // domain height (necessary to define the parabolic
// velocity profile at inlet)
// boundary markers
int marker_bottom = 1;
int marker_right = 2;
int marker_top = 3;
int marker_left = 4;
int marker_obstacle = 5;
// global time variable
double TIME = 0;
// definition of boundary conditions
int xvel_bc_type(int marker) {
if (marker == marker_right) return BC_NONE;
else return BC_ESSENTIAL;
}
int yvel_bc_type(int marker) {
if (marker == marker_right) return BC_NONE;
else return BC_ESSENTIAL;
}
int press_bc_type(int marker)
{ return BC_NONE; }
scalar xvel_bc_value(int marker, double x, double y) {
if (marker == marker_left) {
// time-dependent inlet velocity
//double val_y = VEL_INLET; //constant profile
double val_y = VEL_INLET * y*(H-y) / (H/2.)/(H/2.); //parabolic profile with peak VEL_INLET at y = H/2
if (TIME <= STARTUP_TIME) return val_y * TIME/STARTUP_TIME;
else return val_y;
}
else return 0;
}
// velocities from the previous time step
Solution xprev, yprev;
scalar bilinear_form_sym_0_0_1_1(RealFunction* fu, RealFunction* fv, RefMap* ru, RefMap* rv)
{ return int_grad_u_grad_v(fu, fv, ru, rv) / RE +
int_u_v(fu, fv, ru, rv) / TAU; }
scalar bilinear_form_unsym_0_0_1_1(RealFunction* fu, RealFunction* fv, RefMap* ru, RefMap* rv)
{ return int_w_nabla_u_v(&xprev, &yprev, fu, fv, ru, rv); }
scalar bilinear_form_unsym_0_2(RealFunction* fp, RealFunction* fv, RefMap* rp, RefMap* rv)
{ return -int_u_dvdx(fp, fv, rp, rv); }
scalar bilinear_form_unsym_1_2(RealFunction* fp, RealFunction* fv, RefMap* rp, RefMap* rv)
{ return -int_u_dvdy(fp, fv, rp, rv); }
scalar linear_form_0(RealFunction* fv, RefMap* rv)
{ return int_u_v(&xprev, fv, xprev.get_refmap(), rv) / TAU; }
scalar linear_form_1(RealFunction* fv, RefMap* rv)
{ return int_u_v(&yprev, fv, yprev.get_refmap(), rv) / TAU; }
int main(int argc, char* argv[])
{
// Initialize Python
Py_Initialize();
PySys_SetArgv(argc, argv);
if (import_hermes2d___hermes2d())
throw std::runtime_error("hermes2d failed to import.");
cmd("import utils");
// load the mesh file
Mesh mesh;
mesh.load("domain-quad.mesh"); // unstructured triangular mesh available in domain-tri.mesh
// a-priori mesh refinements
mesh.refine_all_elements();
mesh.refine_towards_boundary(marker_obstacle, 4, false);
mesh.refine_towards_boundary(marker_bottom, 4);
mesh.refine_towards_boundary(marker_top, 4);
// display the mesh
//MeshView mview("Navier-Stokes Example - Mesh", 100, 100, 1100, 400);
//mview.show(&mesh);
//mview.wait_for_keypress();
// initialize the shapesets and the cache
H1ShapesetBeuchler shapeset_h1;
PrecalcShapeset pss_h1(&shapeset_h1);
L2Shapeset shapeset_l2;
PrecalcShapeset pss_l2(&shapeset_l2);
// H1 spaces for velocities and L2 for pressure
H1Space xvel(&mesh, &shapeset_h1);
H1Space yvel(&mesh, &shapeset_h1);
L2Space press(&mesh, &shapeset_l2);
// initialize boundary conditions
xvel.set_bc_types(xvel_bc_type);
xvel.set_bc_values(xvel_bc_value);
yvel.set_bc_types(yvel_bc_type);
press.set_bc_types(press_bc_type);
// set velocity and pressure polynomial degrees
xvel.set_uniform_order(P_INIT_VEL);
yvel.set_uniform_order(P_INIT_VEL);
press.set_uniform_order(P_INIT_PRESSURE);
// assign degrees of freedom
int ndofs = 0;
ndofs += xvel.assign_dofs(ndofs);
ndofs += yvel.assign_dofs(ndofs);
ndofs += press.assign_dofs(ndofs);
// initial BC: xprev and yprev are zero
xprev.set_zero(&mesh);
yprev.set_zero(&mesh);
// set up weak formulation
WeakForm wf(3);
wf.add_biform(0, 0, bilinear_form_sym_0_0_1_1, SYM);
wf.add_biform(0, 0, bilinear_form_unsym_0_0_1_1, UNSYM, ANY, 2, &xprev, &yprev);
wf.add_biform(1, 1, bilinear_form_sym_0_0_1_1, SYM);
wf.add_biform(1, 1, bilinear_form_unsym_0_0_1_1, UNSYM, ANY, 2, &xprev, &yprev);
wf.add_biform(0, 2, bilinear_form_unsym_0_2, ANTISYM);
wf.add_biform(1, 2, bilinear_form_unsym_1_2, ANTISYM);
wf.add_liform(0, linear_form_0, ANY, 1, &xprev);
wf.add_liform(1, linear_form_1, ANY, 1, &yprev);
// visualization
//VectorView vview("velocity [m/s]", 0, 0, 1500, 470);
//ScalarView pview("pressure [Pa]", 0, 530, 1500, 470);
//vview.set_min_max_range(0, 1.6);
//pview.show_mesh(false);
// fixing scale width (for nicer videos). Note: creation of videos is
// discussed in a separate example
//vview.fix_scale_width(5);
//pview.fix_scale_width(5);
// set up the linear system
DummySolver umfpack;
LinSystem sys(&wf, &umfpack);
sys.set_spaces(3, &xvel, &yvel, &press);
sys.set_pss(3, &pss_h1, &pss_h1, &pss_l2);
cmd("from hermes2d import Linearizer, Vectorizer");
cmd("from scipy.sparse import csc_matrix");
cmd("from scipy.sparse.linalg.dsolve import spsolve");
cmd("from scipy.sparse.linalg import cg");
// main loop
char title[100];
int num_time_steps = FINAL_TIME / TAU;
for (int i = 1; i <= num_time_steps; i++)
{
TIME += TAU;
info("\n---- Time step %d, time = %g -----------------------------------", i, TIME);
// this is needed to update the time-dependent boundary conditions
ndofs = 0;
ndofs += xvel.assign_dofs(ndofs);
ndofs += yvel.assign_dofs(ndofs);
ndofs += press.assign_dofs(ndofs);
// assemble and solve
Solution xsln, ysln, psln;
psln.set_zero(&mesh);
sys.assemble();
//sys.solve(3, &xsln, &ysln, &psln);
int *Ap, *Ai, n, nnz;
scalar *Ax;
sys.get_matrix(Ap, Ai, Ax, n);
nnz = Ap[n];
scalar *rhs;
sys.get_rhs(rhs, n);
insert_int_array("Ap", Ap, n+1);
insert_int_array("Ai", Ai, nnz);
insert_double_array("Ax", Ax, nnz);
insert_double_array("rhs", rhs, n);
cmd("A = csc_matrix((Ax, Ai, Ap))");
cmd("x = spsolve(A, rhs)");
double *X;
array_double_numpy2c_inplace(get_symbol("x"), &X, &n);
xsln.set_fe_solution(sys.get_space(0), sys.get_pss(0), X);
ysln.set_fe_solution(sys.get_space(1), sys.get_pss(1), X);
psln.set_fe_solution(sys.get_space(2), sys.get_pss(2), X);
insert_object("xsln", Solution_from_C(&xsln));
insert_object("ysln", Solution_from_C(&ysln));
insert_object("psln", Solution_from_C(&psln));
cmd("l = Linearizer()");
cmd("l.process_solution(psln)");
cmd("vert = l.get_vertices()");
cmd("triangles = l.get_triangles()");
cmd("utils.plot(vert, triangles)");
cmd("v = Vectorizer()");
cmd("v.process_solution(xsln, ysln)");
cmd("v_vert = v.get_vertices()");
cmd("v_triangles = v.get_triangles()");
cmd("utils.plot_vec(v_vert, v_triangles)");
//cmd("import IPython; IPython.ipapi.set_trace()");
// visualization
sprintf(title, "Velocity, time %g", TIME);
//vview.set_title(title);
//vview.show(&xprev, &yprev, EPS_LOW);
sprintf(title, "Pressure, time %g", TIME);
//pview.set_title(title);
//pview.show(&psln);
xprev = xsln;
yprev = ysln;
}
//View::wait();
}
<commit_msg>Plot the mesh<commit_after>#include <stdio.h>
#include <stdexcept>
#include "dummy_solver.h"
#include "hermes2d.h"
#include "_hermes2d_api.h"
// The time-dependent laminar incompressible Navier-Stokes equations are
// discretized in time via the implicit Euler method. The convective term
// is linearized simply by replacing the velocity in front of the nabla
// operator with the velocity from last time step. Velocity is approximated
// using continuous elements, and pressure by means or discontinuous (L2)
// elements. This makes the velocity discretely divergence-free, meaning
// that the integral of div(v) over every element is zero. The problem
// has a steady symmetric solution which is unstable. Note that after some
// time (around t = 100), numerical errors induce oscillations. The
// approximation becomes unsteady and thus diverges from the exact solution.
// Interestingly, this happens even with a completely symmetric mesh.
//
// PDE: incompressible Navier-Stokes equations in the form
// \partial v / \partial t - \Delta v / Re + (v \cdot \nabla) v + \nabla p = 0,
// div v = 0
//
// BC: u_1 is a time-dependent constant and u_2 = 0 on Gamma_4 (inlet)
// u_1 = u_2 = 0 on Gamma_1 (bottom), Gamma_3 (top) and Gamma_5 (obstacle)
// "do nothing" on Gamma_2 (outlet)
//
// TODO: Implement Crank-Nicolson so that comparisons with implicit Euler can be made
//
// The following parameters can be played with:
const double RE = 1000.0; // Reynolds number
const double VEL_INLET = 1.0; // inlet velocity (reached after STARTUP_TIME)
const double STARTUP_TIME = 1.0; // during this time, inlet velocity increases gradually
// from 0 to VEL_INLET, then it stays constant
const double TAU = 0.5; // time step
const double FINAL_TIME = 3000.0; // length of time interval
const int P_INIT_VEL = 2; // polynomial degree for velocity components
const int P_INIT_PRESSURE = 1; // polynomial degree for pressure
// Note: P_INIT_VEL should always be greater than
// P_INIT_PRESSURE because of the inf-sup condition
const double H = 5.0; // domain height (necessary to define the parabolic
// velocity profile at inlet)
// boundary markers
int marker_bottom = 1;
int marker_right = 2;
int marker_top = 3;
int marker_left = 4;
int marker_obstacle = 5;
// global time variable
double TIME = 0;
// definition of boundary conditions
int xvel_bc_type(int marker) {
if (marker == marker_right) return BC_NONE;
else return BC_ESSENTIAL;
}
int yvel_bc_type(int marker) {
if (marker == marker_right) return BC_NONE;
else return BC_ESSENTIAL;
}
int press_bc_type(int marker)
{ return BC_NONE; }
scalar xvel_bc_value(int marker, double x, double y) {
if (marker == marker_left) {
// time-dependent inlet velocity
//double val_y = VEL_INLET; //constant profile
double val_y = VEL_INLET * y*(H-y) / (H/2.)/(H/2.); //parabolic profile with peak VEL_INLET at y = H/2
if (TIME <= STARTUP_TIME) return val_y * TIME/STARTUP_TIME;
else return val_y;
}
else return 0;
}
// velocities from the previous time step
Solution xprev, yprev;
scalar bilinear_form_sym_0_0_1_1(RealFunction* fu, RealFunction* fv, RefMap* ru, RefMap* rv)
{ return int_grad_u_grad_v(fu, fv, ru, rv) / RE +
int_u_v(fu, fv, ru, rv) / TAU; }
scalar bilinear_form_unsym_0_0_1_1(RealFunction* fu, RealFunction* fv, RefMap* ru, RefMap* rv)
{ return int_w_nabla_u_v(&xprev, &yprev, fu, fv, ru, rv); }
scalar bilinear_form_unsym_0_2(RealFunction* fp, RealFunction* fv, RefMap* rp, RefMap* rv)
{ return -int_u_dvdx(fp, fv, rp, rv); }
scalar bilinear_form_unsym_1_2(RealFunction* fp, RealFunction* fv, RefMap* rp, RefMap* rv)
{ return -int_u_dvdy(fp, fv, rp, rv); }
scalar linear_form_0(RealFunction* fv, RefMap* rv)
{ return int_u_v(&xprev, fv, xprev.get_refmap(), rv) / TAU; }
scalar linear_form_1(RealFunction* fv, RefMap* rv)
{ return int_u_v(&yprev, fv, yprev.get_refmap(), rv) / TAU; }
int main(int argc, char* argv[])
{
// Initialize Python
Py_Initialize();
PySys_SetArgv(argc, argv);
if (import_hermes2d___hermes2d())
throw std::runtime_error("hermes2d failed to import.");
cmd("import utils");
// load the mesh file
Mesh mesh;
mesh.load("domain-quad.mesh"); // unstructured triangular mesh available in domain-tri.mesh
// a-priori mesh refinements
mesh.refine_all_elements();
mesh.refine_towards_boundary(marker_obstacle, 4, false);
mesh.refine_towards_boundary(marker_bottom, 4);
mesh.refine_towards_boundary(marker_top, 4);
// plot the mesh:
//insert_object("mesh", Mesh_from_C(&mesh));
//cmd("mesh.plot(lib='mpl', method='orders')");
// display the mesh
//MeshView mview("Navier-Stokes Example - Mesh", 100, 100, 1100, 400);
//mview.show(&mesh);
//mview.wait_for_keypress();
// initialize the shapesets and the cache
H1ShapesetBeuchler shapeset_h1;
PrecalcShapeset pss_h1(&shapeset_h1);
L2Shapeset shapeset_l2;
PrecalcShapeset pss_l2(&shapeset_l2);
// H1 spaces for velocities and L2 for pressure
H1Space xvel(&mesh, &shapeset_h1);
H1Space yvel(&mesh, &shapeset_h1);
L2Space press(&mesh, &shapeset_l2);
// initialize boundary conditions
xvel.set_bc_types(xvel_bc_type);
xvel.set_bc_values(xvel_bc_value);
yvel.set_bc_types(yvel_bc_type);
press.set_bc_types(press_bc_type);
// set velocity and pressure polynomial degrees
xvel.set_uniform_order(P_INIT_VEL);
yvel.set_uniform_order(P_INIT_VEL);
press.set_uniform_order(P_INIT_PRESSURE);
// assign degrees of freedom
int ndofs = 0;
ndofs += xvel.assign_dofs(ndofs);
ndofs += yvel.assign_dofs(ndofs);
ndofs += press.assign_dofs(ndofs);
// initial BC: xprev and yprev are zero
xprev.set_zero(&mesh);
yprev.set_zero(&mesh);
// set up weak formulation
WeakForm wf(3);
wf.add_biform(0, 0, bilinear_form_sym_0_0_1_1, SYM);
wf.add_biform(0, 0, bilinear_form_unsym_0_0_1_1, UNSYM, ANY, 2, &xprev, &yprev);
wf.add_biform(1, 1, bilinear_form_sym_0_0_1_1, SYM);
wf.add_biform(1, 1, bilinear_form_unsym_0_0_1_1, UNSYM, ANY, 2, &xprev, &yprev);
wf.add_biform(0, 2, bilinear_form_unsym_0_2, ANTISYM);
wf.add_biform(1, 2, bilinear_form_unsym_1_2, ANTISYM);
wf.add_liform(0, linear_form_0, ANY, 1, &xprev);
wf.add_liform(1, linear_form_1, ANY, 1, &yprev);
// visualization
//VectorView vview("velocity [m/s]", 0, 0, 1500, 470);
//ScalarView pview("pressure [Pa]", 0, 530, 1500, 470);
//vview.set_min_max_range(0, 1.6);
//pview.show_mesh(false);
// fixing scale width (for nicer videos). Note: creation of videos is
// discussed in a separate example
//vview.fix_scale_width(5);
//pview.fix_scale_width(5);
// set up the linear system
DummySolver umfpack;
LinSystem sys(&wf, &umfpack);
sys.set_spaces(3, &xvel, &yvel, &press);
sys.set_pss(3, &pss_h1, &pss_h1, &pss_l2);
cmd("from hermes2d import Linearizer, Vectorizer");
cmd("from scipy.sparse import csc_matrix");
cmd("from scipy.sparse.linalg.dsolve import spsolve");
cmd("from scipy.sparse.linalg import cg");
// main loop
char title[100];
int num_time_steps = FINAL_TIME / TAU;
for (int i = 1; i <= num_time_steps; i++)
{
TIME += TAU;
info("\n---- Time step %d, time = %g -----------------------------------", i, TIME);
// this is needed to update the time-dependent boundary conditions
ndofs = 0;
ndofs += xvel.assign_dofs(ndofs);
ndofs += yvel.assign_dofs(ndofs);
ndofs += press.assign_dofs(ndofs);
// assemble and solve
Solution xsln, ysln, psln;
psln.set_zero(&mesh);
sys.assemble();
//sys.solve(3, &xsln, &ysln, &psln);
int *Ap, *Ai, n, nnz;
scalar *Ax;
sys.get_matrix(Ap, Ai, Ax, n);
nnz = Ap[n];
scalar *rhs;
sys.get_rhs(rhs, n);
insert_int_array("Ap", Ap, n+1);
insert_int_array("Ai", Ai, nnz);
insert_double_array("Ax", Ax, nnz);
insert_double_array("rhs", rhs, n);
cmd("A = csc_matrix((Ax, Ai, Ap))");
cmd("x = spsolve(A, rhs)");
double *X;
array_double_numpy2c_inplace(get_symbol("x"), &X, &n);
xsln.set_fe_solution(sys.get_space(0), sys.get_pss(0), X);
ysln.set_fe_solution(sys.get_space(1), sys.get_pss(1), X);
psln.set_fe_solution(sys.get_space(2), sys.get_pss(2), X);
insert_object("xsln", Solution_from_C(&xsln));
insert_object("ysln", Solution_from_C(&ysln));
insert_object("psln", Solution_from_C(&psln));
cmd("l = Linearizer()");
cmd("l.process_solution(psln)");
cmd("vert = l.get_vertices()");
cmd("triangles = l.get_triangles()");
cmd("utils.plot(vert, triangles)");
cmd("v = Vectorizer()");
cmd("v.process_solution(xsln, ysln)");
cmd("v_vert = v.get_vertices()");
cmd("v_triangles = v.get_triangles()");
cmd("utils.plot_vec(v_vert, v_triangles)");
//cmd("import IPython; IPython.ipapi.set_trace()");
// visualization
sprintf(title, "Velocity, time %g", TIME);
//vview.set_title(title);
//vview.show(&xprev, &yprev, EPS_LOW);
sprintf(title, "Pressure, time %g", TIME);
//pview.set_title(title);
//pview.show(&psln);
xprev = xsln;
yprev = ysln;
}
//View::wait();
}
<|endoftext|> |
<commit_before>5130e4fe-5216-11e5-81bd-6c40088e03e4<commit_msg>51376264-5216-11e5-beec-6c40088e03e4<commit_after>51376264-5216-11e5-beec-6c40088e03e4<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <malloc.h>
#include <memory.h>
#include <string.h>
#include <tchar.h>
#include <string>
#include <map>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <Windowsx.h>
#include <commctrl.h>
#include <shellapi.h>
#include <Shlwapi.h>
#include <process.h>
#include <vector>
#include <ctime>
#include <cstring>
#include "files.h"
#include "whff.h"
#include "bitmap.h"
#include <map>
#include "luawrap.h"
#include "froglies.h"
#define CLASSNAME "winss"
#define WINDOWTITLE "svchost"
#define ICON_MESSAGE (WM_USER + 1)
#define NOTNOW 0
#define WAITING 1
#define DRAGGING 2
namespace FrogLies{
bool running;
HHOOK kbdhook;
HHOOK mouhook;
HWND hwnd;
NOTIFYICONDATA nid;
HICON IconA;
HICON IconB;
char clickDrag; //States are NOTNOW, WAITING, DRAGGING.
POINT dragStart;
POINT dragEnd;
POINT coords;
HCURSOR dragCursor;
HCURSOR dfltCursor;
void CheckKeys();
std::map<std::string,int> keyspressed;
int ReadKey( std::string key ){
if( keyspressed[key] == 2 ){
keyspressed[key] = 1;
return 2;
}
if( keyspressed[key] == 3 ){
keyspressed[key] = 0;
return 2;
}
return keyspressed[key];
}
void SetClipboard( std::string text ) {
if(OpenClipboard(NULL)) {
HGLOBAL clipbuffer;
char *buffer;
EmptyClipboard();
clipbuffer = GlobalAlloc(GMEM_DDESHARE, text.length()+1);
buffer = (char*)GlobalLock(clipbuffer);
strcpy(buffer, text.c_str());
GlobalUnlock(clipbuffer);
SetClipboardData(CF_TEXT,clipbuffer);
CloseClipboard();
}
}
LRESULT CALLBACK handlemouse(int code, WPARAM wp, LPARAM lp){
if (clickDrag){
if ((wp == WM_LBUTTONDOWN || wp == WM_LBUTTONUP || wp == WM_MOUSEMOVE)){
MSLLHOOKSTRUCT st_hook = *((MSLLHOOKSTRUCT*)lp);
dragEnd = st_hook.pt;
if (clickDrag == WAITING){
coords = dragEnd;
}
else{
coords.x = dragEnd.x - dragStart.x;
coords.y = dragEnd.y - dragStart.y;
}
//printf("State: %i \t MPos: [%i, %i] \t Coord: [%i, %i]\n", clickDrag, dragEnd.x, dragEnd.y, coords.x, coords.y);
//printf("HANDMOUS- wp: 0x%X \t md: 0x%X \t fl: 0x%X\n", wp, st_hook.mouseData, st_hook.flags);
if (wp == WM_LBUTTONDOWN){
dragStart = dragEnd;
clickDrag = DRAGGING;
printf("DOWN!\n");
}
if (wp == WM_LBUTTONUP){
//takeScreenShotAndClipTo(dragStart, dragEnd);
clickDrag = NOTNOW;
printf("UP!\n");
UnhookWindowsHookEx(mouhook);
mouhook = NULL;
SetCursor(dfltCursor);
}
}
}
else{
return CallNextHookEx(mouhook, code, wp, lp);
}
}
LRESULT CALLBACK handlekeys(int code, WPARAM wp, LPARAM lp){
if (code == HC_ACTION && (wp == WM_SYSKEYUP || wp == WM_KEYUP)){
char tmp[0xFF] = {0};
std::string str;
DWORD msg = 1;
KBDLLHOOKSTRUCT st_hook = *((KBDLLHOOKSTRUCT*)lp);
msg += (st_hook.scanCode << 16);
msg += (st_hook.flags << 24);
GetKeyNameText(msg, tmp, 0xFF);
str = std::string(tmp);
if( keyspressed[str] == 2 )
keyspressed[str] = 3;
else
keyspressed[str] = 0;
//fprintf(out, "%s\n", str.c_str());
printf("%s up\n", str.c_str());
}
else if (code == HC_ACTION && (wp == WM_SYSKEYDOWN || wp == WM_KEYDOWN)) {
char tmp[0xFF] = {0};
std::string str;
DWORD msg = 1;
KBDLLHOOKSTRUCT st_hook = *((KBDLLHOOKSTRUCT*)lp);
msg += (st_hook.scanCode << 16);
msg += (st_hook.flags << 24);
GetKeyNameText(msg, tmp, 0xFF);
str = std::string(tmp);
if( keyspressed[str] == 0 )
keyspressed[str] = 2;
else
keyspressed[str] = 1;
printf("%s down\n", str.c_str());
}
CheckKeys();
return CallNextHookEx(kbdhook, code, wp, lp);
}
LRESULT CALLBACK windowprocedure(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam){
//printf("FISH!");
printf("WINDPROC- wp: 0x%X \t lp: 0x%X\n", wparam, lparam);
switch (msg){
case WM_CREATE:
//printf("FISH!");
break;
case ICON_MESSAGE:
switch(lparam){
case WM_LBUTTONDBLCLK:
MessageBox(NULL, "Tray icon double clicked!", "clicked", MB_OK);
break;
case WM_LBUTTONUP:
MessageBox(NULL, "Tray icon clicked!", "clicked", MB_OK);
break;
default:
return DefWindowProc(hwnd, msg, wparam, lparam);
};
break;
case WM_CLOSE: case WM_DESTROY:
running = false;
break;
default:
return DefWindowProc(hwnd, msg, wparam, lparam);
};
return 0;
}
std::string Timestamp() {
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
char str[64];
snprintf(str, 64, "ss at %s", asctime(timeinfo));
int i = 0;
while (str[i]){
i++;
if (str[i] == ' '){
str[i] = '_'; }
}
std::string ToReturn(str);
return ToReturn;
}
void CheckKeys(){
if( ShortcutDesk.IsHit() ){
WHFF whff("");
Bitmap mb = GetWindow(GetDesktopWindow());
void* data = mb.ReadPNG();
whff.Upload( Timestamp(), data, mb.PNGLen(), GetMimeFromExt("png"));
SetClipboard( whff.GetLastUpload() );
}
if (ShortcutWin.IsHit()) {
WHFF whff("");
Bitmap mb = GetWindow(GetForegroundWindow());
void* data = mb.ReadPNG();
whff.Upload( Timestamp(), data, mb.PNGLen(), GetMimeFromExt("png"));
SetClipboard( whff.GetLastUpload() );
}
if (ShortcutCrop.IsHit()) {
printf("hi\n");
clickDrag = WAITING;
mouhook = SetWindowsHookEx(WH_MOUSE_LL, (HOOKPROC)handlemouse, GetModuleHandle(NULL), 0);
SetCursor(dragCursor);
}
if (ShortcutClip.IsHit()) {
WHFF whff("");
if (!OpenClipboard(NULL))
return;
HANDLE hClipboardData = GetClipboardData(CF_TEXT);
char *pchData = (char*)GlobalLock(hClipboardData);
void* data = (void*)pchData;
printf("%s\n", pchData);
whff.Upload( Timestamp()+".txt", data, strlen(pchData), GetMimeFromExt("txt"));
GlobalUnlock(hClipboardData);
CloseClipboard();
SetClipboard( whff.GetLastUpload() );
}
if (ShortcutQuit.IsHit()) {
PostMessage( hwnd, WM_CLOSE, 0, 0 );
}
}
void GUIThread( void* ){
while( running ){
Sleep(1000);
nid.hIcon = IconA;
Shell_NotifyIcon(NIM_MODIFY, &nid);
Sleep(1000);
nid.hIcon = IconB;
Shell_NotifyIcon(NIM_MODIFY, &nid);
}
}
static int SetShortcut( Shortcut* s, const char* value ){
if( s->IsValid() ){
s->Set( value );
}
return 1;
}
void ReadConf( std::string fname ){
size_t len;
char* d = (char*)read_file_to_buffer( fname, len );
if( d == 0 )
return;
printf("Using non-standard configuration\n");
d = (char*)realloc( d, len+1 );
d[len] = 0;
std::string buff = d;
free( d );
Lua L( buff.c_str(), "Configuration", 0 );
L.funcreg<int, Shortcut*, const char*, SetShortcut >("shortcut");
L.set("SHORTCUT_WIN", &ShortcutWin);
L.set("SHORTCUT_DESK", &ShortcutDesk);
L.set("SHORTCUT_CROP", &ShortcutCrop);
L.set("SHORTCUT_CLIP", &ShortcutClip);
L.set("SHORTCUT_QUIT", &ShortcutQuit);
L.run();
}
}
using namespace FrogLies;
int WINAPI WinMain(HINSTANCE thisinstance, HINSTANCE previnstance, LPSTR cmdline, int ncmdshow){
ReadConf( "conf.cfg" );
HWND fgwindow = GetForegroundWindow(); /* Current foreground window */
MSG msg;
WNDCLASSEX windowclass;
HINSTANCE modulehandle;
windowclass.hInstance = thisinstance;
windowclass.lpszClassName = CLASSNAME;
windowclass.lpfnWndProc = windowprocedure;
windowclass.style = CS_DBLCLKS;
windowclass.cbSize = sizeof(WNDCLASSEX);
windowclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
windowclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
windowclass.hCursor = LoadCursor(NULL, IDC_ARROW);
windowclass.lpszMenuName = NULL;
windowclass.cbClsExtra = 0;
windowclass.cbWndExtra = 0;
windowclass.hbrBackground = (HBRUSH)COLOR_BACKGROUND;
if (!(RegisterClassEx(&windowclass))){ return 1; }
hwnd = CreateWindowEx(0, CLASSNAME, WINDOWTITLE, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, HWND_DESKTOP, NULL,
thisinstance, NULL);
if (!(hwnd)){ return 1; }
ShowWindow(hwnd, SW_HIDE);
UpdateWindow(hwnd);
SetForegroundWindow(fgwindow); /* Give focus to the previous fg window */
dragCursor = LoadCursor(thisinstance, IDC_CROSS);
dfltCursor = GetCursor();
modulehandle = GetModuleHandle(NULL);
//#define BEGIN_IN_DRAGMODE
#ifdef BEGIN_IN_DRAGMODE
mouhook = SetWindowsHookEx(WH_MOUSE_LL, (HOOKPROC)handlemouse, modulehandle, 0);
SetCursor(dragCursor);
clickDrag = WAITING;
#endif
IconA = (HICON) LoadImage( thisinstance, "img/icona.ico", IMAGE_ICON, 32, 32, LR_LOADFROMFILE );
IconB = (HICON) LoadImage( thisinstance, "img/iconb.ico", IMAGE_ICON, 32, 32, LR_LOADFROMFILE );
nid.cbSize = sizeof(NOTIFYICONDATA);
nid.uID = 100;
nid.hWnd = hwnd;
//nid.uVersion = NOTIFYICON_VERSION;
nid.uCallbackMessage = ICON_MESSAGE;
nid.hIcon = IconB; //= LoadIcon(NULL, IDI_APPLICATION);
snprintf(nid.szTip, 64, "Icon");
nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
Shell_NotifyIcon(NIM_ADD, &nid);
kbdhook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)handlekeys, modulehandle, 0);
mouhook = NULL;
running = true;
_beginthread( GUIThread, 1000, NULL );
//GUIThread(0);
while (running) {
if (!GetMessage(&msg, NULL, 0, 0))
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
Shell_NotifyIcon(NIM_DELETE, &nid);
return 0;
}
<commit_msg>Began finishing croprect.<commit_after>#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <malloc.h>
#include <memory.h>
#include <string.h>
#include <tchar.h>
#include <string>
#include <map>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <Windowsx.h>
#include <commctrl.h>
#include <shellapi.h>
#include <Shlwapi.h>
#include <process.h>
#include <vector>
#include <ctime>
#include <cstring>
#include "files.h"
#include "whff.h"
#include "bitmap.h"
#include <map>
#include "luawrap.h"
#include "froglies.h"
#define CLASSNAME "winss"
#define WINDOWTITLE "svchost"
#define ICON_MESSAGE (WM_USER + 1)
#define NOTNOW 0
#define WAITING 1
#define DRAGGING 2
namespace FrogLies{
bool running;
HHOOK kbdhook;
HHOOK mouhook;
HWND hwnd;
NOTIFYICONDATA nid;
HICON IconA;
HICON IconB;
char clickDrag; //States are NOTNOW, WAITING, DRAGGING.
POINT dragStart;
POINT dragEnd;
POINT coords;
HCURSOR dragCursor;
HCURSOR dfltCursor;
void CheckKeys();
std::map<std::string,int> keyspressed;
int ReadKey( std::string key ){
if( keyspressed[key] == 2 ){
keyspressed[key] = 1;
return 2;
}
if( keyspressed[key] == 3 ){
keyspressed[key] = 0;
return 2;
}
return keyspressed[key];
}
void SetClipboard( std::string text ) {
if(OpenClipboard(NULL)) {
HGLOBAL clipbuffer;
char *buffer;
EmptyClipboard();
clipbuffer = GlobalAlloc(GMEM_DDESHARE, text.length()+1);
buffer = (char*)GlobalLock(clipbuffer);
strcpy(buffer, text.c_str());
GlobalUnlock(clipbuffer);
SetClipboardData(CF_TEXT,clipbuffer);
CloseClipboard();
}
}
void drawtext( int x, int y, char* str ){
HDC screenDC = ::GetDC(0);
COLORREF cBack, cTxt;
cBack = RGB(255, 255, 255);
cTxt = RGB(10, 10, 10);
SetBkColor(screenDC, cBack);
SetTextColor(screenDC, cTxt);
//SetBkMode(screenDC, TRANSPARENT);
TextOut( screenDC, x, y, str, strlen( str ) );
//::Rectangle(screenDC, 200, 200, 300, 300);
::ReleaseDC(0, screenDC);
}
void drawrect( int x, int y, int w, int h ){
HDC screenDC = ::GetDC(0);
COLORREF cBack, cTxt;
cBack = RGB(0, 0, 0);
cTxt = RGB(150,150, 100);
SetBkColor(screenDC, cTxt);
Rectangle( screenDC, x, y, w, h );
//::Rectangle(screenDC, 200, 200, 300, 300);
ReleaseDC(0, screenDC);
}
void drawlinedrect( int x1, int y1, int x2, int y2 ){
HDC screenDC = GetDC(0);
COLORREF cBack, cTxt;
cBack = RGB(0, 0, 0);
cTxt = RGB(150,150, 100);
SetBkColor(screenDC, cTxt);
MoveToEx(screenDC, x1, y1, NULL);
LineTo(screenDC, x1, y2);
LineTo(screenDC, x2, y2);
LineTo(screenDC, x2, y1);
LineTo(screenDC, x1, y1);
//::Rectangle(screenDC, 200, 200, 300, 300);
ReleaseDC(0, screenDC);
}
std::string Timestamp() {
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
char str[64];
snprintf(str, 64, "ss at %s", asctime(timeinfo));
int i = 0;
while (str[i]){
i++;
if (str[i] == ' '){
str[i] = '_'; }
}
std::string ToReturn(str);
return ToReturn;
}
LRESULT CALLBACK handlemouse(int code, WPARAM wp, LPARAM lp){
if (clickDrag){
if ((wp == WM_LBUTTONDOWN || wp == WM_LBUTTONUP || wp == WM_MOUSEMOVE)){
MSLLHOOKSTRUCT st_hook = *((MSLLHOOKSTRUCT*)lp);
dragEnd = st_hook.pt;
if (clickDrag == WAITING){
coords = dragEnd;
}
else{
coords.x = dragEnd.x - dragStart.x;
coords.y = dragEnd.y - dragStart.y;
}
if (clickDrag == DRAGGING){
drawlinedrect(dragStart.x, dragStart.y, dragEnd.x, dragEnd.y);
}
//printf("State: %i \t MPos: [%i, %i] \t Coord: [%i, %i]\n", clickDrag, dragEnd.x, dragEnd.y, coords.x, coords.y);
//printf("HANDMOUS- wp: 0x%X \t md: 0x%X \t fl: 0x%X\n", wp, st_hook.mouseData, st_hook.flags);
if (wp == WM_LBUTTONDOWN){
dragStart = dragEnd;
clickDrag = DRAGGING;
printf("DOWN!\n");
}
if (wp == WM_LBUTTONUP){
//takeScreenShotAndClipTo(dragStart, dragEnd);
WHFF whff("");
Bitmap mb = GetWindow(GetDesktopWindow());
POINT xy;
xy.x = (dragStart.x < dragEnd.x)?(dragStart.x):(dragEnd.x);
xy.y = (dragStart.y < dragEnd.y)?(dragStart.y):(dragEnd.y);
POINT wh;
wh.x = (dragStart.x > dragEnd.x)?(dragStart.x):(dragEnd.x) - xy.x;
wh.y = (dragStart.y < dragEnd.y)?(dragStart.y):(dragEnd.y) - xy.y;
mb.Crop(xy.x, xy.y, wh.x, wh.y);
void* data = mb.ReadPNG();
whff.Upload( Timestamp(), data, mb.PNGLen(), GetMimeFromExt("png"));
SetClipboard( whff.GetLastUpload() );
clickDrag = NOTNOW;
printf("UP!\n");
UnhookWindowsHookEx(mouhook);
mouhook = NULL;
SetCursor(dfltCursor);
}
}
}
else{
return CallNextHookEx(mouhook, code, wp, lp);
}
}
LRESULT CALLBACK handlekeys(int code, WPARAM wp, LPARAM lp){
if (code == HC_ACTION && (wp == WM_SYSKEYUP || wp == WM_KEYUP)){
char tmp[0xFF] = {0};
std::string str;
DWORD msg = 1;
KBDLLHOOKSTRUCT st_hook = *((KBDLLHOOKSTRUCT*)lp);
msg += (st_hook.scanCode << 16);
msg += (st_hook.flags << 24);
GetKeyNameText(msg, tmp, 0xFF);
str = std::string(tmp);
if( keyspressed[str] == 2 )
keyspressed[str] = 3;
else
keyspressed[str] = 0;
//fprintf(out, "%s\n", str.c_str());
printf("%s up\n", str.c_str());
}
else if (code == HC_ACTION && (wp == WM_SYSKEYDOWN || wp == WM_KEYDOWN)) {
char tmp[0xFF] = {0};
std::string str;
DWORD msg = 1;
KBDLLHOOKSTRUCT st_hook = *((KBDLLHOOKSTRUCT*)lp);
msg += (st_hook.scanCode << 16);
msg += (st_hook.flags << 24);
GetKeyNameText(msg, tmp, 0xFF);
str = std::string(tmp);
if( keyspressed[str] == 0 )
keyspressed[str] = 2;
else
keyspressed[str] = 1;
printf("%s down\n", str.c_str());
}
CheckKeys();
return CallNextHookEx(kbdhook, code, wp, lp);
}
LRESULT CALLBACK windowprocedure(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam){
//printf("FISH!");
printf("WINDPROC- wp: 0x%X \t lp: 0x%X\n", wparam, lparam);
switch (msg){
case WM_CREATE:
//printf("FISH!");
break;
case ICON_MESSAGE:
switch(lparam){
case WM_LBUTTONDBLCLK:
MessageBox(NULL, "Tray icon double clicked!", "clicked", MB_OK);
break;
case WM_LBUTTONUP:
MessageBox(NULL, "Tray icon clicked!", "clicked", MB_OK);
break;
default:
return DefWindowProc(hwnd, msg, wparam, lparam);
};
break;
case WM_CLOSE: case WM_DESTROY:
running = false;
break;
default:
return DefWindowProc(hwnd, msg, wparam, lparam);
};
return 0;
}
void CheckKeys(){
if( ShortcutDesk.IsHit() ){
WHFF whff("");
Bitmap mb = GetWindow(GetDesktopWindow());
void* data = mb.ReadPNG();
whff.Upload( Timestamp(), data, mb.PNGLen(), GetMimeFromExt("png"));
SetClipboard( whff.GetLastUpload() );
}
if (ShortcutWin.IsHit()) {
WHFF whff("");
Bitmap mb = GetWindow(GetForegroundWindow());
void* data = mb.ReadPNG();
whff.Upload( Timestamp(), data, mb.PNGLen(), GetMimeFromExt("png"));
SetClipboard( whff.GetLastUpload() );
}
if (ShortcutCrop.IsHit()) {
printf("hi\n");
clickDrag = WAITING;
mouhook = SetWindowsHookEx(WH_MOUSE_LL, (HOOKPROC)handlemouse, GetModuleHandle(NULL), 0);
SetCursor(dragCursor);
}
if (ShortcutClip.IsHit()) {
WHFF whff("");
if (!OpenClipboard(NULL))
return;
HANDLE hClipboardData = GetClipboardData(CF_TEXT);
char *pchData = (char*)GlobalLock(hClipboardData);
void* data = (void*)pchData;
printf("%s\n", pchData);
whff.Upload( Timestamp()+".txt", data, strlen(pchData), GetMimeFromExt("txt"));
GlobalUnlock(hClipboardData);
CloseClipboard();
SetClipboard( whff.GetLastUpload() );
}
if (ShortcutQuit.IsHit()) {
PostMessage( hwnd, WM_CLOSE, 0, 0 );
}
}
void GUIThread( void* ){
while( running ){
Sleep(1000);
nid.hIcon = IconA;
Shell_NotifyIcon(NIM_MODIFY, &nid);
Sleep(1000);
nid.hIcon = IconB;
Shell_NotifyIcon(NIM_MODIFY, &nid);
}
}
static int SetShortcut( Shortcut* s, const char* value ){
if( s->IsValid() ){
s->Set( value );
}
return 1;
}
void ReadConf( std::string fname ){
size_t len;
char* d = (char*)read_file_to_buffer( fname, len );
if( d == 0 )
return;
printf("Using non-standard configuration\n");
d = (char*)realloc( d, len+1 );
d[len] = 0;
std::string buff = d;
free( d );
Lua L( buff.c_str(), "Configuration", 0 );
L.funcreg<int, Shortcut*, const char*, SetShortcut >("shortcut");
L.set("SHORTCUT_WIN", &ShortcutWin);
L.set("SHORTCUT_DESK", &ShortcutDesk);
L.set("SHORTCUT_CROP", &ShortcutCrop);
L.set("SHORTCUT_CLIP", &ShortcutClip);
L.set("SHORTCUT_QUIT", &ShortcutQuit);
L.run();
}
}
using namespace FrogLies;
int WINAPI WinMain(HINSTANCE thisinstance, HINSTANCE previnstance, LPSTR cmdline, int ncmdshow){
ReadConf( "conf.cfg" );
HWND fgwindow = GetForegroundWindow(); /* Current foreground window */
MSG msg;
WNDCLASSEX windowclass;
HINSTANCE modulehandle;
windowclass.hInstance = thisinstance;
windowclass.lpszClassName = CLASSNAME;
windowclass.lpfnWndProc = windowprocedure;
windowclass.style = CS_DBLCLKS;
windowclass.cbSize = sizeof(WNDCLASSEX);
windowclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
windowclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
windowclass.hCursor = LoadCursor(NULL, IDC_ARROW);
windowclass.lpszMenuName = NULL;
windowclass.cbClsExtra = 0;
windowclass.cbWndExtra = 0;
windowclass.hbrBackground = (HBRUSH)COLOR_BACKGROUND;
if (!(RegisterClassEx(&windowclass))){ return 1; }
hwnd = CreateWindowEx(0, CLASSNAME, WINDOWTITLE, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, HWND_DESKTOP, NULL,
thisinstance, NULL);
if (!(hwnd)){ return 1; }
ShowWindow(hwnd, SW_HIDE);
UpdateWindow(hwnd);
SetForegroundWindow(fgwindow); /* Give focus to the previous fg window */
dragCursor = LoadCursor(thisinstance, IDC_CROSS);
dfltCursor = GetCursor();
modulehandle = GetModuleHandle(NULL);
#define BEGIN_IN_DRAGMODE
#ifdef BEGIN_IN_DRAGMODE
mouhook = SetWindowsHookEx(WH_MOUSE_LL, (HOOKPROC)handlemouse, modulehandle, 0);
SetCursor(dragCursor);
clickDrag = WAITING;
#endif
IconA = (HICON) LoadImage( thisinstance, "img/icona.ico", IMAGE_ICON, 32, 32, LR_LOADFROMFILE );
IconB = (HICON) LoadImage( thisinstance, "img/iconb.ico", IMAGE_ICON, 32, 32, LR_LOADFROMFILE );
nid.cbSize = sizeof(NOTIFYICONDATA);
nid.uID = 100;
nid.hWnd = hwnd;
//nid.uVersion = NOTIFYICON_VERSION;
nid.uCallbackMessage = ICON_MESSAGE;
nid.hIcon = IconB; //= LoadIcon(NULL, IDI_APPLICATION);
snprintf(nid.szTip, 64, "Icon");
nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
Shell_NotifyIcon(NIM_ADD, &nid);
kbdhook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)handlekeys, modulehandle, 0);
mouhook = NULL;
running = true;
_beginthread( GUIThread, 1000, NULL );
//GUIThread(0);
while (running) {
if (!GetMessage(&msg, NULL, 0, 0))
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
Shell_NotifyIcon(NIM_DELETE, &nid);
return 0;
}
<|endoftext|> |
<commit_before>a02d9e54-ad58-11e7-a0b1-ac87a332f658<commit_msg>Hey we can now do a thing<commit_after>a096baeb-ad58-11e7-8bb5-ac87a332f658<|endoftext|> |
<commit_before>784c8e5e-2d53-11e5-baeb-247703a38240<commit_msg>784d0d02-2d53-11e5-baeb-247703a38240<commit_after>784d0d02-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <algorithm>
#include <memory>
#include <unordered_map>
#include "graph.h"
using namespace std;
const double INF = numeric_limits<double>::infinity();
void dijkstra(Graph<double,double> g, unsigned int source, unsigned int target, std::unordered_map<unsigned int, double> &return_dist, std::unordered_map<unsigned int, int> &return_prev)
{
// Check that source and target are in graph
if (g.nodes.find(source) == g.nodes.end() || g.nodes.find(target) == g.nodes.end())
{
cout << "Source and/or target nodes not in graph." << endl;
return;
}
std::vector<unsigned int> list; // list of nodes to process
std::unordered_map<unsigned int, double> dist; // id, distance
std::unordered_map<unsigned int, int> prev; // id, previous
// Initialize
for(auto n : g.nodes)
{
list.push_back(n.first);
dist.emplace(n.first, INF);
prev.emplace(n.first, -1); // -1: no prev node
}
dist.at(source) = 0;
while(!list.empty())
{
// Select node with smallest distance
unsigned int node = list.at(0);
for(auto id : list)
if(dist.at(id) < dist.at(node))
node = id;
// Return if target (comment out if shortest path to all nodes is desired)
if(node == target)
break;
// Remove node from list
list.erase(std::remove(list.begin(), list.end(), node), list.end());
// Check if target is unreachable
if(dist.at(node) >= INF)
break;
// For each neighbour of node
for(auto e : g.nodes.at(node)->edges_out)
{
auto neighbour = e->to->id;
double new_dist = dist.at(node) + e->data;
if(new_dist < dist.at(neighbour))
{
dist.at(neighbour) = new_dist;
prev.at(neighbour) = node;
// decrease-key v in Q; // Reorder v in the Queue (that is, heapify-down)
}
}
}
return_dist = dist;
return_prev = prev;
}
int main()
{
// Testing graph
Graph<double,double> my_graph;
for(int i=0; i<=5; i++)
my_graph.add_node(i);
my_graph.add_edge(0,1,4);
my_graph.add_edge(0,2,2);
my_graph.add_edge(1,2,5);
my_graph.add_edge(1,3,10);
my_graph.add_edge(2,4,3);
my_graph.add_edge(4,3,4);
my_graph.add_edge(3,5,11);
cout << "My graph" << endl;
cout << my_graph << endl;
// Testing removal of edges and nodes
// my_graph.remove_edge(1,0);
// my_graph.remove_node(0);
// cout << "My new graph" << endl;
// cout << my_graph << endl;
// Run Dijkstra
std::unordered_map<unsigned int, double> dist; // id, distance
std::unordered_map<unsigned int, int> prev; // id, previous
unsigned int source = 0;
unsigned int target = 5;
dijkstra(my_graph, source, target, dist, prev);
cout << "Prev result" << endl;
for(auto n : prev)
cout << n.first << ", " << n.second << endl;
// Construct path
std::vector<unsigned int> path;
unsigned int u = target;
while (prev.at(u) >= 0)
{
path.push_back(u);
u = prev.at(u);
}
// Add source (will be target if no feasible path is found)
path.push_back(u);
cout << "Path " << endl;
for(auto n : path)
cout << n << endl;
// Print results
cout << "The shortest path from " << source << " to " << target << " is:" << endl;
for(int i = path.size()-1; i>=0; i--)
{
unsigned int n = path.at(i);
cout << n << " (" << dist.at(n) << ")";
if(i > 0)
cout << " => ";
}
cout << endl;
Graph<> g;
g.add_node(0,1.1);
g.add_node(1,2.2);
g.add_node(2,3.3);
g.add_edge(0,1,1);
g.add_edge(0,3,1);
g.add_edge(0,2,1);
g.add_edge(1,0,2);
g.add_edge(2,1,2);
cout << g << endl;
//cout << g << endl;
cout << "Hello World!" << endl;
return 0;
}
<commit_msg>Commented out some test code in main.cpp<commit_after>#include <iostream>
#include <vector>
#include <algorithm>
#include <memory>
#include <unordered_map>
#include "graph.h"
using namespace std;
const double INF = numeric_limits<double>::infinity();
void dijkstra(Graph<double,double> g, unsigned int source, unsigned int target, std::unordered_map<unsigned int, double> &return_dist, std::unordered_map<unsigned int, int> &return_prev)
{
// Check that source and target are in graph
if (g.nodes.find(source) == g.nodes.end() || g.nodes.find(target) == g.nodes.end())
{
cout << "Source and/or target nodes not in graph." << endl;
return;
}
std::vector<unsigned int> list; // list of nodes to process
std::unordered_map<unsigned int, double> dist; // id, distance
std::unordered_map<unsigned int, int> prev; // id, previous
// Initialize
for(auto n : g.nodes)
{
list.push_back(n.first);
dist.emplace(n.first, INF);
prev.emplace(n.first, -1); // -1: no prev node
}
dist.at(source) = 0;
while(!list.empty())
{
// Select node with smallest distance
unsigned int node = list.at(0);
for(auto id : list)
if(dist.at(id) < dist.at(node))
node = id;
// Return if target (comment out if shortest path to all nodes is desired)
if(node == target)
break;
// Remove node from list
list.erase(std::remove(list.begin(), list.end(), node), list.end());
// Check if target is unreachable
if(dist.at(node) >= INF)
break;
// For each neighbour of node
for(auto e : g.nodes.at(node)->edges_out)
{
auto neighbour = e->to->id;
double new_dist = dist.at(node) + e->data;
if(new_dist < dist.at(neighbour))
{
dist.at(neighbour) = new_dist;
prev.at(neighbour) = node;
// decrease-key v in Q; // Reorder v in the Queue (that is, heapify-down)
}
}
}
return_dist = dist;
return_prev = prev;
}
int main()
{
// Testing graph
Graph<double,double> my_graph;
for(int i=0; i<=5; i++)
my_graph.add_node(i);
my_graph.add_edge(0,1,4);
my_graph.add_edge(0,2,2);
my_graph.add_edge(1,2,5);
my_graph.add_edge(1,3,10);
my_graph.add_edge(2,4,3);
my_graph.add_edge(4,3,4);
my_graph.add_edge(3,5,11);
cout << "My graph" << endl;
cout << my_graph << endl;
// Testing removal of edges and nodes
// my_graph.remove_edge(1,0);
// my_graph.remove_node(0);
// cout << "My new graph" << endl;
// cout << my_graph << endl;
// Run Dijkstra
std::unordered_map<unsigned int, double> dist; // id, distance
std::unordered_map<unsigned int, int> prev; // id, previous
unsigned int source = 0;
unsigned int target = 5;
dijkstra(my_graph, source, target, dist, prev);
cout << "Prev result" << endl;
for(auto n : prev)
cout << n.first << ", " << n.second << endl;
// Construct path
std::vector<unsigned int> path;
unsigned int u = target;
while (prev.at(u) >= 0)
{
path.push_back(u);
u = prev.at(u);
}
// Add source (will be target if no feasible path is found)
path.push_back(u);
cout << "Path " << endl;
for(auto n : path)
cout << n << endl;
// Print results
cout << "The shortest path from " << source << " to " << target << " is:" << endl;
for(int i = path.size()-1; i>=0; i--)
{
unsigned int n = path.at(i);
cout << n << " (" << dist.at(n) << ")";
if(i > 0)
cout << " => ";
}
cout << endl;
// Testing add functionality
// Graph<> g;
// g.add_node(0,1.1);
// g.add_node(1,2.2);
// g.add_node(2,3.3);
// g.add_edge(0,1,1);
// g.add_edge(0,3,1);
// g.add_edge(0,2,1);
// g.add_edge(1,0,2);
// g.add_edge(2,1,2);
// cout << g << endl;
// cout << "Hello World!" << endl;
return 0;
}
<|endoftext|> |
<commit_before>92323ad5-2d14-11e5-af21-0401358ea401<commit_msg>92323ad6-2d14-11e5-af21-0401358ea401<commit_after>92323ad6-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>2d2b767a-2e4f-11e5-a075-28cfe91dbc4b<commit_msg>2d32c8d1-2e4f-11e5-ac64-28cfe91dbc4b<commit_after>2d32c8d1-2e4f-11e5-ac64-28cfe91dbc4b<|endoftext|> |
<commit_before>69616c92-2fa5-11e5-90d1-00012e3d3f12<commit_msg>6962f334-2fa5-11e5-9eed-00012e3d3f12<commit_after>6962f334-2fa5-11e5-9eed-00012e3d3f12<|endoftext|> |
<commit_before>976d7c2e-4b02-11e5-9c7b-28cfe9171a43<commit_msg>roselyn broke it<commit_after>977c6680-4b02-11e5-8d4a-28cfe9171a43<|endoftext|> |
<commit_before>ce769e35-4b02-11e5-9efe-28cfe9171a43<commit_msg>I hope I am done<commit_after>ce82a370-4b02-11e5-8295-28cfe9171a43<|endoftext|> |
<commit_before>81cf0d8e-2d15-11e5-af21-0401358ea401<commit_msg>81cf0d8f-2d15-11e5-af21-0401358ea401<commit_after>81cf0d8f-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>76744c5c-2d53-11e5-baeb-247703a38240<commit_msg>7674c9ca-2d53-11e5-baeb-247703a38240<commit_after>7674c9ca-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>a50a8642-2e4f-11e5-bd36-28cfe91dbc4b<commit_msg>a51143c5-2e4f-11e5-823e-28cfe91dbc4b<commit_after>a51143c5-2e4f-11e5-823e-28cfe91dbc4b<|endoftext|> |
<commit_before>#include <enet/enet.h>
#include <spdlog/spdlog.h>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <stdio.h>
#include<stdlib.h>
#include <signal.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <memory>
bool isExit = false;
namespace spd = spdlog;
using namespace std;
using namespace rapidjson;
void cs(int n)
{
if (n == SIGINT)
{
isExit = true;
}
}
string readFile(const string &fileName)
{
ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);
ifstream::pos_type fileSize = ifs.tellg();
ifs.seekg(0, ios::beg);
vector<char> bytes(fileSize);
ifs.read(&bytes[0], fileSize);
return string(&bytes[0], fileSize);
}
int main(int argc, char ** argv)
{
string json = readFile("./../config.json");
Document config;
config.Parse(json.c_str());
/*
// 2. Modify it by DOM.
Value& s = d["stars"];
s.SetInt(s.GetInt() + 1);
// 3. Stringify the DOM
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
// Output {"project":"rapidjson","stars":11}
std::cout << buffer.GetString() << std::endl;
*/
std::vector<spdlog::sink_ptr> sinks;
sinks.push_back(make_shared<spdlog::sinks::daily_file_sink_st>("daily","txt", 0, 0));
sinks.push_back(make_shared<spdlog::sinks::stdout_sink_st>());
auto logger = make_shared<spdlog::logger>("my_logger", begin(sinks), end(sinks));
spdlog::register_logger(logger);
logger->flush_on(spd::level::err);
spd::set_pattern("[%D %H:%M:%S:%e][%l] %v");
spd::set_level(spd::level::info);
logger->set_level(spd::level::debug);
logger->info("logger created successfully.");
signal(SIGINT, cs);
if (enet_initialize() != 0)
{
fprintf(stderr, "An error occurred while initializing ENet.\n");
return EXIT_FAILURE;
}
Value& hostData = config["host"];
ENetAddress address;
ENetHost * server;
enet_address_set_host (&address, "0.0.0.0");
//address.host = ENET_HOST_ANY;
address.port = hostData["port"].GetInt();
server = enet_host_create(&address,
hostData["peers"].GetInt(),
hostData["channels"].GetInt(),
0 /* assume any amount of incoming bandwidth */,
0 /* assume any amount of outgoing bandwidth */);
if (server == NULL)
{
fprintf(stderr,
"An error occurred while trying to create an ENet server host.\n");
exit(EXIT_FAILURE);
}
ENetHost * client;
client = enet_host_create(NULL /* create a client host */,
1 /* only allow 1 outgoing connection */,
2 /* allow up 2 channels to be used, 0 and 1 */,
57600 / 8 /* 56K modem with 56 Kbps downstream bandwidth */,
14400 / 8 /* 56K modem with 14 Kbps upstream bandwidth */);
if (client == NULL)
{
fprintf(stderr,
"An error occurred while trying to create an ENet client host.\n");
exit(EXIT_FAILURE);
}
ENetEvent event;
/* Wait up to 1000 milliseconds for an event. */
while (!isExit) {
int ret;
while (ret = enet_host_service(server, &event, 10) > 0)
{
printf("event.type = %d\n", event.type);
switch (event.type)
{
case ENET_EVENT_TYPE_CONNECT:{
printf("A new client connected from %x:%u.\n",
event.peer->address.host,
event.peer->address.port);
/* Store any relevant client information here. */
event.peer->data = (char*)"Client information";
break;
}
case ENET_EVENT_TYPE_RECEIVE:{
printf("A packet of length %u containing %s was received from %s on channel %u.\n",
event.packet->dataLength,
event.packet->data,
event.peer->data,
event.channelID);
/* Clean up the packet now that we're done using it. */
enet_packet_destroy(event.packet);
ENetPacket * packet = enet_packet_create("world", strlen("world")+1, ENET_PACKET_FLAG_RELIABLE);
enet_peer_send(event.peer, 0, packet);
break;
}
case ENET_EVENT_TYPE_DISCONNECT:
printf("%s disconnected.\n", event.peer->data);
/* Reset the peer's client information. */
event.peer->data = NULL;
}
}
//std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
enet_host_destroy(client);
enet_host_destroy(server);
atexit(enet_deinitialize);
spdlog::drop_all();
}
<commit_msg>no message<commit_after>#include <enet/enet.h>
#include <spdlog/spdlog.h>
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <stdio.h>
#include<stdlib.h>
#include <signal.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <memory>
bool isExit = false;
namespace spd = spdlog;
using namespace std;
using namespace rapidjson;
void cs(int n)
{
if (n == SIGINT)
{
isExit = true;
}
}
string readFile(const string &fileName)
{
ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);
ifstream::pos_type fileSize = ifs.tellg();
ifs.seekg(0, ios::beg);
vector<char> bytes(fileSize);
ifs.read(&bytes[0], fileSize);
return string(&bytes[0], fileSize);
}
bool is_file_exist(const char *fileName)
{
std::ifstream infile(fileName);
return infile.good();
}
int main(int argc, char ** argv)
{
printf("forwarder started.\n");
std::vector<spdlog::sink_ptr> sinks;
sinks.push_back(make_shared<spdlog::sinks::daily_file_sink_st>("daily","txt", 0, 0));
sinks.push_back(make_shared<spdlog::sinks::stdout_sink_st>());
auto logger = make_shared<spdlog::logger>("my_logger", begin(sinks), end(sinks));
spdlog::register_logger(logger);
logger->flush_on(spd::level::err);
spd::set_pattern("[%D %H:%M:%S:%e][%l] %v");
spd::set_level(spd::level::info);
logger->set_level(spd::level::debug);
logger->info("logger created successfully.");
const char * configPath = "./../config.json";
if(!is_file_exist(configPath)){
logger->error("config.json not found!");
return EXIT_FAILURE;
}
string json = readFile(configPath);
Document config;
config.Parse(json.c_str());
/*
// 2. Modify it by DOM.
Value& s = d["stars"];
s.SetInt(s.GetInt() + 1);
// 3. Stringify the DOM
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
// Output {"project":"rapidjson","stars":11}
std::cout << buffer.GetString() << std::endl;
*/
signal(SIGINT, cs);
if (enet_initialize() != 0)
{
fprintf(stderr, "An error occurred while initializing ENet.\n");
return EXIT_FAILURE;
}
Value& hostData = config["host"];
ENetAddress address;
ENetHost * server;
enet_address_set_host (&address, "0.0.0.0");
//address.host = ENET_HOST_ANY;
address.port = hostData["port"].GetInt();
server = enet_host_create(&address,
hostData["peers"].GetInt(),
hostData["channels"].GetInt(),
0 /* assume any amount of incoming bandwidth */,
0 /* assume any amount of outgoing bandwidth */);
if (server == NULL)
{
fprintf(stderr,
"An error occurred while trying to create an ENet server host.\n");
exit(EXIT_FAILURE);
}
ENetHost * client;
client = enet_host_create(NULL /* create a client host */,
1 /* only allow 1 outgoing connection */,
2 /* allow up 2 channels to be used, 0 and 1 */,
57600 / 8 /* 56K modem with 56 Kbps downstream bandwidth */,
14400 / 8 /* 56K modem with 14 Kbps upstream bandwidth */);
if (client == NULL)
{
fprintf(stderr,
"An error occurred while trying to create an ENet client host.\n");
exit(EXIT_FAILURE);
}
ENetEvent event;
/* Wait up to 1000 milliseconds for an event. */
while (!isExit) {
int ret;
while (ret = enet_host_service(server, &event, 10) > 0)
{
printf("event.type = %d\n", event.type);
switch (event.type)
{
case ENET_EVENT_TYPE_CONNECT:{
printf("A new client connected from %x:%u.\n",
event.peer->address.host,
event.peer->address.port);
/* Store any relevant client information here. */
event.peer->data = (char*)"Client information";
break;
}
case ENET_EVENT_TYPE_RECEIVE:{
printf("A packet of length %u containing %s was received from %s on channel %u.\n",
event.packet->dataLength,
event.packet->data,
event.peer->data,
event.channelID);
/* Clean up the packet now that we're done using it. */
enet_packet_destroy(event.packet);
ENetPacket * packet = enet_packet_create("world", strlen("world")+1, ENET_PACKET_FLAG_RELIABLE);
enet_peer_send(event.peer, 0, packet);
break;
}
case ENET_EVENT_TYPE_DISCONNECT:
printf("%s disconnected.\n", event.peer->data);
/* Reset the peer's client information. */
event.peer->data = NULL;
}
}
//std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
enet_host_destroy(client);
enet_host_destroy(server);
atexit(enet_deinitialize);
spdlog::drop_all();
}
<|endoftext|> |
<commit_before>0c221de6-2e4f-11e5-8796-28cfe91dbc4b<commit_msg>0c28e361-2e4f-11e5-9878-28cfe91dbc4b<commit_after>0c28e361-2e4f-11e5-9878-28cfe91dbc4b<|endoftext|> |
<commit_before>08ec7e78-2f67-11e5-b521-6c40088e03e4<commit_msg>08f3d5b0-2f67-11e5-a15e-6c40088e03e4<commit_after>08f3d5b0-2f67-11e5-a15e-6c40088e03e4<|endoftext|> |
<commit_before>d48a25be-585a-11e5-949b-6c40088e03e4<commit_msg>d492ac1e-585a-11e5-8b91-6c40088e03e4<commit_after>d492ac1e-585a-11e5-8b91-6c40088e03e4<|endoftext|> |
<commit_before>beec541c-327f-11e5-ae6b-9cf387a8033e<commit_msg>bef6e966-327f-11e5-b8a8-9cf387a8033e<commit_after>bef6e966-327f-11e5-b8a8-9cf387a8033e<|endoftext|> |
<commit_before>65d6fafa-2749-11e6-bd8d-e0f84713e7b8<commit_msg>Tuesday, turns out it was tuesday<commit_after>65e877b3-2749-11e6-a9f5-e0f84713e7b8<|endoftext|> |
<commit_before>a6d0589c-4b02-11e5-8722-28cfe9171a43<commit_msg>Long commit messages are not required<commit_after>a6e0e18a-4b02-11e5-a989-28cfe9171a43<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.