blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e05c88f5476a832257d63a3e00b0b59e2fa0afce | 8476ceb52232150ef5359b631b942a417acc46e0 | /libs/ofxMapper/src/Mapper.cpp | 7d6b76b2464e16a4c3f3b437c2852ca01df0014e | [] | no_license | tobiasebsen/ofxMapper | 7b6835e08b2079de8fda58d47a89ab90b8ad9c2a | 09a5c55c32f06aed489897e27af5fe43f5562ea7 | refs/heads/master | 2020-08-28T00:30:38.212153 | 2020-06-24T11:28:20 | 2020-06-24T11:28:20 | 217,534,728 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,274 | cpp | #include "Mapper.h"
using namespace ofxMapper;
//--------------------------------------------------------------
void Mapper::setup() {
setup(ofGetWidth(), ofGetHeight());
}
//--------------------------------------------------------------
void Mapper::setup(int width, int height) {
setCompSize(width, height);
}
//--------------------------------------------------------------
void Mapper::begin() {
if (fbo.isAllocated()) {
fbo.begin();
ofClear(0, 0);
}
}
//--------------------------------------------------------------
void Mapper::end(bool doUpdate) {
if (fbo.isAllocated()) {
fbo.end();
if (doUpdate) {
update(fbo.getTexture());
}
}
}
//--------------------------------------------------------------
void Mapper::update(ofTexture & texture) {
updateBlendRects();
for (auto & screen : screens) {
screen->update(texture);
}
}
//--------------------------------------------------------------
void Mapper::draw() {
for (auto & screen : screens) {
if (screen->enabled) {
screen->draw();
}
}
}
//--------------------------------------------------------------
void Mapper::drawComp() {
fbo.draw(0, 0);
}
//--------------------------------------------------------------
void Mapper::drawInputRects(bool drawDisabled, bool drawDeselected) {
for (auto & screen : screens) {
size_t n = screen->getNumSlices();
for (size_t i = 0; i < n; i++) {
SlicePtr slice = screen->getSlice(i);
if ((slice->enabled || drawDisabled) && (!slice->selected || drawDeselected)) {
slice->drawInputRect();
}
}
}
}
//--------------------------------------------------------------
void Mapper::drawInputRectsSelected(bool drawDisabled) {
for (auto & screen : screens) {
size_t n = screen->getNumSlices();
for (size_t i = 0; i < n; i++) {
SlicePtr slice = screen->getSlice(i);
if ((slice->enabled || drawDisabled) && slice->selected) {
slice->drawInputRect();
}
}
}
}
//--------------------------------------------------------------
void Mapper::setCompSize(size_t width, size_t height) {
fbo.allocate(width, height, GL_RGBA);
compRect.set(0, 0, width, height);
}
//--------------------------------------------------------------
ofFbo & Mapper::getFbo() {
return fbo;
}
//--------------------------------------------------------------
ofRectangle Mapper::getCompRect() const {
return compRect;
}
//--------------------------------------------------------------
vector<ScreenPtr> & Mapper::getScreens() {
return screens;
}
//--------------------------------------------------------------
size_t Mapper::getNumScreens() const {
return screens.size();
}
//--------------------------------------------------------------
ScreenPtr Mapper::getScreen(size_t screenIndex) {
return screens[screenIndex];
}
//--------------------------------------------------------------
ScreenPtr Mapper::getScreen(string uniqueId) {
for (ScreenPtr screen : screens) {
if (screen->uniqueId == uniqueId)
return screen;
}
return NULL;
}
//--------------------------------------------------------------
ScreenPtr ofxMapper::Mapper::addScreen(int width, int height) {
return addScreen("Screen " + ofToString(screens.size()+1), width, height);
}
//--------------------------------------------------------------
ScreenPtr Mapper::addScreen(string name, int width, int height) {
int x = 0;
int y = 0;
if (getNumScreens() > 0) {
ofRectangle rect = getScreens().back()->getScreenRect();
x = rect.getRight();
y = rect.getTop();
}
screens.emplace_back(new Screen(x, y, width, height));
ScreenPtr screen = screens.back();
screen->name = name;
return screen;
}
//--------------------------------------------------------------
ScreenPtr Mapper::addScreen(string name, int x, int y, int width, int height) {
screens.emplace_back(new Screen(x, y, width, height));
ScreenPtr screen = screens.back();
screen->name = name;
return screen;
}
//--------------------------------------------------------------
void Mapper::removeScreen() {
for (auto it = screens.begin(); it != screens.end();) {
auto p = it[0];
if (p->remove) {
it = screens.erase(it);
}
else {
++it;
}
}
}
//--------------------------------------------------------------
void Mapper::removeScreen(ScreenPtr screen) {
for (auto it = screens.begin(); it != screens.end();) {
auto p = it[0];
if (p == screen) {
it = screens.erase(it);
}
else {
++it;
}
}
}
//--------------------------------------------------------------
void Mapper::clearScreens() {
screens.clear();
}
//--------------------------------------------------------------
void Mapper::deselectAll() {
for (ScreenPtr screen : screens) {
screen->deselectSlices();
screen->deselectMasks();
}
}
//--------------------------------------------------------------
void Mapper::deselectAllExcept(ScreenPtr except) {
for (ScreenPtr screen : screens) {
if (screen != except) {
screen->deselectSlices();
screen->deselectMasks();
}
}
}
//--------------------------------------------------------------
void Mapper::grabInputHandle(const glm::vec2 & p, float radius) {
for (auto & screen : screens) {
if (screen->enabled) {
if (screen->grabInputHandle(p, radius))
return;
}
}
for (auto & screen : screens) {
if (screen->enabled) {
screen->selectSliceInput(p);
}
}
}
//--------------------------------------------------------------
void ofxMapper::Mapper::snapInputHandle(const glm::vec2 & p, float distance) {
glm::vec2 q = p;
if (abs(q.x) < distance)
q.x = 0;
if (abs(q.x - compRect.width) < distance)
q.x = compRect.width;
if (abs(q.y) < distance)
q.y = 0;
if (abs(q.y - compRect.height) < distance)
q.y = compRect.height;
for (auto & screen : screens) {
if (screen->enabled) {
screen->snapInputHandle(q, distance);
}
}
}
//--------------------------------------------------------------
void ofxMapper::Mapper::dragInputHandle(const glm::vec2 & delta) {
for (auto & screen : screens) {
if (screen->enabled) {
screen->dragInputHandle(delta);
}
}
}
//--------------------------------------------------------------
void ofxMapper::Mapper::moveInputHandle(const glm::vec2 & delta) {
for (auto & screen : screens) {
if (screen->enabled) {
screen->moveInputHandle(delta);
}
}
}
//--------------------------------------------------------------
void ofxMapper::Mapper::releaseInputHandle() {
for (auto & screen : screens) {
if (screen->enabled) {
screen->releaseInputHandle();
}
}
}
//--------------------------------------------------------------
void Mapper::updateBlendRects() {
size_t n = getNumScreens();
for (size_t i = 0; i < n; i++) {
ScreenPtr screen1 = getScreen(i);
size_t m = screen1->getNumSlices();
for (size_t j = 0; j < m; j++) {
SlicePtr slice1 = screen1->getSlice(j);
ofRectangle inputRect1 = slice1->getInputRect();
slice1->clearBlendRects();
for (size_t k=0; k<n; k++) {
if (k != i) {
ScreenPtr screen2 = getScreen(k);
size_t h = screen2->getNumSlices();
for (size_t g=0; g<h; g++) {
SlicePtr slice2 = screen2->getSlice(g);
ofRectangle inputRect2 = slice2->getInputRect();
if (slice1->softEdgeEnabled && slice2->softEdgeEnabled) {
ofRectangle blendRect = inputRect1.getIntersection(inputRect2);
if (!blendRect.isEmpty() && blendRect.getArea() < inputRect1.getArea() * 0.9f) {
slice1->addBlendRect(blendRect);
}
}
}
}
}
}
}
}
//--------------------------------------------------------------
void Mapper::drawBlendRects() {
for (auto & screen : screens) {
size_t n = screen->getNumSlices();
for (size_t i = 0; i < n; i++) {
SlicePtr slice = screen->getSlice(i);
auto & blendRects = slice->getBlendRects();
for (auto & rect : blendRects) {
ofDrawRectangle(rect);
}
}
}
}
//--------------------------------------------------------------
void ofxMapper::Mapper::clear() {
compFilePath = "untitled.xml";
compFile.reset();
screens.clear();
}
//--------------------------------------------------------------
bool Mapper::load(string filePath) {
compFile = shared_ptr<ResolumeFile>(new ResolumeFile);
bool loaded = compFile->load(filePath);
if (!loaded) {
ofLogError("ofxMapper") << "Unable to load file: " << filePath;
compFile.reset();
return false;
}
if (!compFile->isValid("Resolume Arena") && !compFile->isValid("ofxMapper")) {
ofLogError("ofxMapper") << "File not valid: " << filePath;
compFile.reset();
return false;
}
// Composition
ofRectangle r = compFile->getCompositionSize();
setCompSize(r.width, r.height);
// Screens
screens.clear();
int nscreens = compFile->loadScreens();
for (int i = 0; i < nscreens; i++) {
ResolumeFile::Screen sc = compFile->getScreen(i);
ofRectangle res = sc.getSize();
ScreenPtr screen = addScreen(res.width, res.height);
screen->uniqueId = sc.getUniqueId();
screen->name = sc.getName();
screen->enabled = sc.getEnabled();
// Slices
int nslices = sc.getNumSlices();
for (int j = 0; j < nslices; j++) {
ResolumeFile::Slice sl = sc.getSlice(j);
string name = sl.getName();
ofRectangle inputRect = sl.getInputRect();
SlicePtr slice = screen->addSlice(name, inputRect);
slice->uniqueId = sl.getUniqueId();
slice->enabled = sl.getEnabled();
slice->softEdgeEnabled = sl.getSoftEdgeEnabled();
SoftEdge & softEdge = slice->getSoftEdge();
softEdge.power = sl.getSoftEdgePower(softEdge.power);
softEdge.luminance = sl.getSoftEdgeLuminance(softEdge.luminance);
softEdge.gamma = sl.getSoftEdgeGamma(softEdge.gamma);
slice->setInputRect(inputRect);
slice->bezierEnabled = sl.getWarperMode() == "PM_BEZIER";
int w = 0, h = 0;
sl.getWarperDim(w, h);
auto vertices = sl.getWarperVertices();
slice->setVertices(vertices, w, h);
}
// Masks
int nmasks = sc.getNumMasks();
for (int j = 0; j < nmasks; j++) {
ResolumeFile::Mask msk = sc.getMask(j);
string name = msk.getName();
auto points = msk.getPoints();
MaskPtr mask = screen->addMask(name);
mask->uniqueId = msk.getUniqueId();
mask->enabled = msk.getEnabled();
mask->closed = msk.getClosed();
mask->setPoints(points);
}
}
compFilePath = filePath;
return true;
}
//--------------------------------------------------------------
void ofxMapper::Mapper::save(string filePath) {
//ResolumeFile saver(xml);
if (!compFile) {
compFile = shared_ptr<ResolumeFile>(new ResolumeFile);
compFile->setVersion("ofxMapper");
}
compFile->setCompositionSize(compRect.width, compRect.height);
// Remove deleted screens
int nb_screens = compFile->loadScreens();
for (int i = 0; i < nb_screens; i++) {
ResolumeFile::Screen scr = compFile->getScreen(i);
string uniqueId = scr.getUniqueId();
if (getScreen(uniqueId) == NULL) {
compFile->removeScreen(uniqueId);
}
}
compFile->loadScreens();
for (auto & screen : screens) {
ResolumeFile::Screen scr = compFile->getScreen(screen->uniqueId);
scr.setName(screen->name);
scr.setEnabled(screen->enabled);
// Remove deleted slices
int nb_slices = scr.loadSlices();
for (int i = 0; i < nb_slices; i++) {
ResolumeFile::Slice slc = scr.getSlice(i);
string uniqueId = slc.getUniqueId();
if (screen->getSlice(uniqueId) == NULL) {
scr.removeSlice(uniqueId);
}
}
scr.loadSlices();
for (auto & slice : screen->getSlices()) {
ResolumeFile::Slice slc = scr.getSlice(slice->uniqueId);
slc.setName(slice->name);
slc.setEnabled(slice->enabled);
slc.setInputRect(slice->getInputRect());
slc.setWarperMode(slice->bezierEnabled ? "PM_BEZIER" : "PM_LINEAR");
slc.setWarperVertices(slice->getControlWidth(), slice->getControlHeight(), slice->getVertices());
}
// Remove deleted masks
int nb_masks = scr.loadMasks();
for (int i = 0; i < nb_masks; i++) {
ResolumeFile::Mask msk = scr.getMask(i);
string uniqueId = msk.getUniqueId();
if (screen->getMask(uniqueId) == NULL) {
scr.removeMask(uniqueId);
}
}
scr.loadMasks();
for (auto & mask : screen->getMasks()) {
ResolumeFile::Mask msk = scr.getMask(mask->uniqueId);
msk.setName(mask->name);
msk.setEnabled(mask->enabled);
msk.setInverted(mask->inverted);
vector<glm::vec2> points;
for (auto & h : mask->getHandles()) {
points.push_back(h.position);
}
msk.setPoints(points, mask->closed);
}
scr.setSize(screen->width, screen->height);
}
if (compFile->save(filePath))
compFilePath = filePath;
}
//--------------------------------------------------------------
void ofxMapper::Mapper::save() {
save(compFilePath);
}
//--------------------------------------------------------------
string Mapper::getFileName() const {
return ofFilePath::getFileName(compFilePath);
}
//--------------------------------------------------------------
string ofxMapper::Mapper::getFilePath() const {
return compFilePath;
}
| [
"tobiasebsen@gmail.com"
] | tobiasebsen@gmail.com |
caf0955bcd6c74a8d3cff94e545912e40af08e90 | 5b41e312db8aeb5532ba59498c93e2ec1dccd4ff | /EmailServer/EmailServer/cEmailServer_Server.h | 7aa2e9a4c37160b8cb6df608bf5385d7f7ddd948 | [] | no_license | frankilfrancis/KPO_HMI_vs17 | 10d96c6cb4aebffb83254e6ca38fe6d1033eba79 | de49aa55eccd8a7abc165f6057088a28426a1ceb | refs/heads/master | 2020-04-15T16:40:14.366351 | 2019-11-14T15:33:25 | 2019-11-14T15:33:25 | 164,845,188 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 645 | h | #if defined (_MSC_VER) && (_MSC_VER >= 1000)
#pragma once
#endif
#ifndef _INC_CEMAILSERVER_SERVER_41127C30015C_INCLUDED
#define _INC_CEMAILSERVER_41127C30015C_INCLUDED
#include <CBS_General.h>
#include <CBS_Tasks.h>
#include <CBS_StdAPI.h>
class cEmailServer_Comp;
class cEmailServer_Server
: public cCBS_StdServer
{
public:
cEmailServer_Comp* m_pComponent;
virtual ~cEmailServer_Server();
cEmailServer_Server(int argc, const char* argv[]);
//Abstract method. Should create the tasks that are part
//of this server.
virtual void createTasks();
private:
};
#endif /* _INC_CEMAILSERVER_SERVER_41127C30015C_INCLUDED */
| [
"52784069+FrankilPacha@users.noreply.github.com"
] | 52784069+FrankilPacha@users.noreply.github.com |
d98994ce1db5362f1af4f90342429624d7f9def3 | 63ee2797c86df97b808fc774cecf5012c3f0b9c0 | /SecondJeux/attaque.cpp | 748306714985ef119eccc36ebcd9293123388c8e | [] | no_license | GIacial/jeux-2 | 31fbc5c784b77a7e5951b78d66bf65d14685a1cd | 321eba5d34c92267a9e543d669f2cd69a2deb6e2 | refs/heads/master | 2020-05-29T08:46:10.064286 | 2016-09-29T13:18:42 | 2016-09-29T13:18:42 | 69,556,194 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,204 | cpp | #include "attaque.h"
//base
QString attaque::baseAttaque(Entite &lanceur, Entite &cible, int coef, bool magique, int mana, bool soin){
QString retour="";
if(cible.getVie()!=0){
retour= lanceur.attaque(cible,coef,magique,mana,soin);//cible coef magique mana soin
lanceur.finTour();//met a 0 la celerite et decompte les buff
}
else{
retour= "Impossible car "+cible.getNomEntite()+" est deja mort";
}
return retour;
}
QString attaque::baseAttaqueMultiCible(Entite &lanceur, QList<Entite *> cible, int coef, bool magique, int mana, bool soin){
QString retour="";
int taille=cible.size();
if(lanceur.useMana(mana)){
for(int i=0;i<taille;i++){
if(cible[i]->getVie()!=0){
retour+= (baseAttaque(lanceur,*cible[i],coef,magique,0,soin)+"\n");
}
}
}
else{
retour= lanceur.getNomEntite()+" incante mais rien ne se passe";
}
lanceur.finTour();//met a 0 la celerite et decompte les buff
return retour;
}
QString attaque::baseAjoutBuff(Entite &lanceur, Entite &cible, buff buffAjoute, int mana){
QString retour="";
if(cible.getVie()!=0){
if(lanceur.useMana(mana)){
retour=cible.ajoutBuff(buffAjoute);
}
else{
retour= lanceur.getNomEntite()+" incante mais rien ne se passe";
}
lanceur.finTour();//met a 0 la celerite et decompte les buff
}
else{
retour= "Impossible car "+cible.getNomEntite()+" est deja mort";
}
return retour;
}
QString attaque::baseAjoutBuffMultiCible(Entite &lanceur, QList<Entite *> cible, buff buffAjoute, int mana){
QString retour="";
if(lanceur.useMana(mana)){
for(int i=0;i<cible.size();i++){
if(cible[i]->getVie()!=0){
retour+= (baseAjoutBuff(lanceur,*cible[i],buffAjoute)+"\n");
}
}
}
else{
retour= lanceur.getNomEntite()+" incante mais rien ne se passe";
}
lanceur.finTour();//met a 0 la celerite et decompte les buff
return retour;
}
QString attaque::baseAttaqueBuff(Entite &lanceur, Entite &cible,buff buffAjout ,int coefAttaque, int chanceBuffAct,Entite& cibleBuff, bool magique, int mana, bool soin){
QString retour=baseAttaque(lanceur,cible,coefAttaque,magique,mana,soin);
if(rand()%100<=chanceBuffAct && !(retour.contains("rien ne se passe") || retour.contains("raté")|| retour.contains("mort"))){
retour+="\n" +cibleBuff.ajoutBuff(buffAjout);
}
return retour;
}
QString attaque::baseAttaqueBuffMultiCible(Entite &lanceur, QList<Entite *> cible, buff buffAjout, int coefAttaque, int chanceBuffAct, bool magique, int mana, bool soin){
QString retour="";
if(lanceur.useMana(mana)){
for(int i=0;i<cible.size();i++){
if(cible[i]->getVie()!=0){
retour+= (baseAttaqueBuff(lanceur,*cible[i],buffAjout,coefAttaque,chanceBuffAct,*cible[i],magique,mana,soin)+"\n");
}
}
}
else{
retour= lanceur.getNomEntite()+" incante mais rien ne se passe";
}
lanceur.finTour();//met a 0 la celerite et decompte les buff
return retour;
}
QString attaque::baseAttaqueVolMana(Entite &lanceur, Entite &cible, int manaVol, int coef, bool magique, int mana){
QString retour=baseAttaque(lanceur,cible,coef,magique,mana);
if(!(retour.contains("rien ne se passe") || retour.contains("raté")|| retour.contains("mort"))){
if(cible.useMana(manaVol)){
lanceur.useMana(-manaVol);
retour+="\n" +lanceur.getNomEntite()+" vole "+QString::number(manaVol)+" de mana à "+cible.getNomEntite();
}
else{
retour+="\n" +lanceur.getNomEntite()+" ne peut plus voler du mana à "+cible.getNomEntite();
}
}
return retour;
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//soin
QString attaque::soin(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise le sort Soin\n"+baseAttaque(lanceur,cible,5,true,5,true);//cible coef magique mana soin
}
QString attaque::soinAvance(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise le sort Soin Avancé\n"+baseAttaque(lanceur,cible,9,true,15,true);
}
QString attaque::soinPuissant(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise le sort Soin Puissant\n"+baseAttaque(lanceur,cible,18,true,45,true);
}
QString attaque::soinComplet(Entite &lanceur, Entite &cible){
QString retour=lanceur.getNomEntite()+" utilise le sort Soin Complet\n";
if(cible.getVie()!=0){
if(lanceur.useMana(150)){
retour+=cible.useSoin(0,true);
}
else{
retour+= lanceur.getNomEntite()+" incante mais rien ne se passe";
}
lanceur.finTour();
}
else{
retour= "Impossible car "+cible.getNomEntite()+" est deja mort";
}
return retour;
}
QString attaque::rappel(Entite &lanceur, Entite &cible){
QString retour= lanceur.getNomEntite()+" utilise Rappel\n";
if(cible.getVie()==0){
if(lanceur.useMana(100)){
retour+=cible.useSoin(0.5);
}
else{
retour+= lanceur.getNomEntite()+" incante mais rien ne se passe";
}
}
else{
retour+="Impossible de réanimer quelqu'un si il est vivant";
}
lanceur.finTour();
return retour;
}
QString attaque::ressurection(Entite &lanceur, Entite &cible){
QString retour= lanceur.getNomEntite()+" utilise Ressurection\n";
if(cible.getVie()==0){
if(lanceur.useMana(200)){
retour+=cible.useSoin(0,true);
}
else{
retour+= lanceur.getNomEntite()+" incante mais rien ne se passe";
}
}
else{
retour+="Impossible de réanimer quelqu'un si il est vivant";
}
lanceur.finTour();
return retour;
}
QString attaque::multisoin(Entite &lanceur, QList<Entite *> cible){
return lanceur.getNomEntite()+" utilise le sort Multisoin\n"+baseAttaqueMultiCible(lanceur,cible,10,true,150,true);
}
QString attaque::omnisoin(Entite &lanceur, QList<Entite *> cible){
QString retour=lanceur.getNomEntite()+" utilise le sort Omnisoin\n";
if(lanceur.useMana(500)){
for (int i=0; i<cible.size();i++){
if(cible[i]->getVie()!=0){
retour+=cible[i]->useSoin(0,true)+"\n";
}
else{
retour= "Impossible car "+cible[i]->getNomEntite()+" est deja mort";
}
}
}
else{
retour+= lanceur.getNomEntite()+" incante mais rien ne se passe";
}
lanceur.finTour();
return retour;
}
//buff
//magie
QString attaque::bouclier(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise le sort Bouclier\n"+baseAjoutBuff(lanceur,cible,BuffPredefini::getBuffBouclier(),20) ;
}
QString attaque::blindage(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise le sort Blindage\n"+baseAjoutBuff(lanceur,cible,BuffPredefini::getBuffBlindage(),30) ;
}
QString attaque::booster(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise le sort Booster\n"+baseAjoutBuff(lanceur,cible,BuffPredefini::getBuffBooster(),50);
}
QString attaque::deculpo(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise le sort Deculpo\n"+baseAjoutBuff(lanceur,cible,BuffPredefini::getBuffDeculpo(),25);
}
QString attaque::canalisationMagique(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise le sort Canalisation Magique\n"+baseAjoutBuff(lanceur,cible,BuffPredefini::getBuffCanalisationMagique(),40);
}
QString attaque::purification(Entite &lanceur, Entite &cible){
QString retour=lanceur.getNomEntite()+" utilise le sort Purification\n";
if(cible.getVie()!=0){
if(lanceur.useMana(10)){
cible.supprimeToutBuff();
retour+=cible.getNomEntite()+" perd tout ses effects";
}
else{
retour+= lanceur.getNomEntite()+" incante mais rien ne se passe";
}
lanceur.finTour();
}
else{
retour= "Impossible car "+cible.getNomEntite()+" est deja mort";
}
return retour;
}
//tech
QString attaque::defense(Entite &lanceur){
return lanceur.getNomEntite()+" se met en defense\n"+baseAjoutBuff(lanceur,lanceur,BuffPredefini::getBuffDefense());
}
QString attaque::superBouclier(Entite &lanceur, QList<Entite *> cible){
return lanceur.getNomEntite()+" lance SuperBouclier\n"+baseAjoutBuffMultiCible(lanceur,cible,BuffPredefini::getBuffBouclier(),125);
}
QString attaque::superBlindage(Entite &lanceur, QList<Entite *> cible){
return lanceur.getNomEntite()+" lance SuperBlindage\n"+baseAjoutBuffMultiCible(lanceur,cible,BuffPredefini::getBuffBlindage(),150);
}
QString attaque::superBooster(Entite &lanceur, QList<Entite *> cible){
return lanceur.getNomEntite()+" lance SuperBooster\n"+baseAjoutBuffMultiCible(lanceur,cible,BuffPredefini::getBuffBooster(),200);
}
//attaque
//magie
QString attaque::flamme(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise le sort Flamme\n"+baseAttaque(lanceur,cible,3,true,5);
}
QString attaque::superFlamme(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise le sort SuperFlamme\n"+baseAttaque(lanceur,cible,6,true,15);
}
QString attaque::megaFlamme(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise le sort MegaFlamme\n"+baseAttaque(lanceur,cible,12,true,25);
}
QString attaque::gigaFlamme(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise le sort GigaFlamme\n"+baseAttaque(lanceur,cible,14,true,50);
}
QString attaque::crame(Entite &lanceur, QList<Entite *> cible){
return lanceur.getNomEntite()+" utilise le sort Crame\n"+baseAttaqueMultiCible(lanceur,cible,2,true,8);
}
QString attaque::superCrame(Entite &lanceur, QList<Entite *> cible){
return lanceur.getNomEntite()+" utilise le sort SuperCrame\n"+baseAttaqueMultiCible(lanceur,cible,4,true,20);
}
QString attaque::megaCrame(Entite &lanceur, QList<Entite *> cible){
return lanceur.getNomEntite()+" utilise le sort MegaCrame\n"+baseAttaqueMultiCible(lanceur,cible,8,true,35);
}
QString attaque::gigaCrame(Entite &lanceur, QList<Entite *> cible){
return lanceur.getNomEntite()+" utilise le sort GigaCrame\n"+baseAttaqueMultiCible(lanceur,cible,12,true,60);
}
QString attaque::frappePuissante(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise la frappe Puissante\n"+baseAttaque(lanceur,cible,2,false,1);
}
QString attaque::briseCrane(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise Brise-Crane\n"+baseAttaqueBuff(lanceur,cible,buff ("Brise-Crane",-1,-1,0.8,-1,-1,3),3,75,cible);
}
QString attaque::ryuken(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise ryuken\n"+baseAttaqueVolMana(lanceur,cible,ceil((double)lanceur.calculDommageMagique(cible)/2),2,true);
}
QString attaque::frappeCirculaire(Entite &lanceur, QList<Entite *> cible){
return lanceur.getNomEntite()+" frappe en arc de cercle\n"+baseAttaqueMultiCible(lanceur,cible,2);
}
QString attaque::Seisme(Entite &lanceur, QList<Entite *> cible){
return lanceur.getNomEntite()+" provoque un séisme\n"+baseAttaqueMultiCible(lanceur,cible,4,false,25);
}
QString attaque::Analyse(Entite &lanceur, Entite &cible){
QString retour=lanceur.getNomEntite()+" analyse "+cible.getNomEntite()+"\n";
if(cible.getVie()!=0){
if(lanceur.useMana(5)){
cible.afficheStat();
}
else{
retour+= lanceur.getNomEntite()+" incante mais rien ne se passe";
}
lanceur.finTour();
}
else{
retour= cible.getNomEntite()+" est deja mort";
}
return retour;
}
QString attaque::deprime(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise deprime\n"+baseAttaqueBuff(lanceur,cible,buff("Déprime",-1,0.5,-1,-1,-1,3),2,80,cible);
}
QString attaque::lameEmpoisonner(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" frappe avec sa lame empoisonné\n"+baseAttaqueBuff(lanceur,cible,BuffPredefini::getBuffPoison("Poison",3,2+(cible.getStatBaseVie()/200)),1,75,cible );
}
QString attaque::FrappeRapide(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" frappe à la vitesse de l'éclair\n"+baseAttaqueBuff(lanceur,cible,buff("Rapidité",-1,-1,-1,-1,1.5,1),2,95,lanceur );
}
QString attaque::NuagePoison(Entite &lanceur, QList<Entite *> cible){
return lanceur.getNomEntite()+" lance un nuage de poison\n"+baseAttaqueBuffMultiCible(lanceur,cible,BuffPredefini::getBuffPoison("Poison",3,10),1,50);
}
QString attaque::FrappeAstral(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise la frappe Astral\n"+baseAttaque(lanceur,cible,7,false,10);
}
QString attaque::lameDragon(Entite &lanceur, Entite &cible){
return lanceur.getNomEntite()+" utilise la lame Dragon\n"+baseAttaque(lanceur,cible,10,false,20);
}
| [
"cristalsaga@hotmail.fr"
] | cristalsaga@hotmail.fr |
9e111124ed70263a525c72765d99f0e7fcea527e | f749703e3bcb0650bbf993816daf8ebcab3fdb1a | /Librarys/Bohge/Bohge/BaseShader.h | 2990ba3e1b31a5e90e55beb852e2de3695220c2e | [
"MIT"
] | permissive | isoundy000/Bohge_Engine | fd96267678ba1fd02a11a8497a39997dc517ff26 | 9924cb579be1abf310cea1b6c0c81f96ab516cc4 | refs/heads/master | 2020-03-23T01:26:14.162766 | 2014-04-01T11:38:29 | 2014-04-01T11:39:38 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,411 | h | //////////////////////////////////////////////////////////////////////////////////////
//
// The Bohge Engine License (BEL)
//
// Copyright (c) 2011-2014 Peng Zhao
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software. And the logo of
// Bohge Engine shall be displayed full screen for more than 3 seconds
// when the software is started. Copyright holders are allowed to develop
// game edit based on Bohge Engine, The edit must be released under the MIT
// open source license if it is going to be published. In no event shall
// copyright holders be prohibited from using any code of Bohge Engine
// to develop any other analogous game engines.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////
// 基本的shader框架和基类 //
//////////////////////////////////////////
#pragma once
#include "Predefine.h"
#include "VariableType.h"
#include <vector>
#include <string>
#include <list>
namespace BohgeEngine
{
class Attributes
{
public:
enum ShaderAttributes//shader内部数值的预设地址
{
ATTRIBUTE_POSITION = 0, // 0
ATTRIBUTE_BONEINDICES, // 1
ATTRIBUTE_BONEWEIGHTS, // 2
ATTRIBUTE_NORMAL, // 3
ATTRIBUTE_TANGENT, // 4
ATTRIBUTE_BINORMAL, // 5
ATTRIBUTE_TEXCOORD0, // 6
ATTRIBUTE_TEXCOORD1, // 7
ATTRIBUTE_COLOR0, // 8
ATTRIBUTE_COLOR1, // 9
ATTRIBUTE_MATIRX_COLUMN1, //pesudo geometry instance使用
ATTRIBUTE_MATIRX_COLUMN2,
ATTRIBUTE_MATIRX_COLUMN3,
ATTRIBUTE_MATIRX_COLUMN4,
ATTRIBUTE_USER_0,
ATTRIBUTE_USER_1,
ATTRIBUTE_USER_2,
ATTRIBUTE_USER_3,
ATTRIBUTE_USER_4,
ATTRIBUTE_USER_5,
ATTRIBUTE_USER_6,
ATTRIBUTE_USER_7,
ATTRIBUTE_COUNT,
};
private:
struct StrShaderAttributes //初始化shader内部attribuyes结构体
{
public:
std::string strName;
int nLocation;//实际的属性地址
ShaderAttributes AttributeName;//属性类型
StrShaderAttributes( const std::string& name, uint location, ShaderAttributes attr )
: strName(name),
nLocation(location),
AttributeName(attr)
{
}
StrShaderAttributes( const StrShaderAttributes& input )
: strName(input.strName),
nLocation(input.nLocation),
AttributeName(input.AttributeName)
{
}
};
typedef std::vector<StrShaderAttributes> AttributeList;
private:
int m_Location;
AttributeList m_AttributesList;
public:
Attributes()
:m_Location(0)
{
m_AttributesList.reserve( ATTRIBUTE_COUNT );
for ( int i = 0 ; i < ATTRIBUTE_COUNT ; i ++ )
{
m_AttributesList.push_back( StrShaderAttributes( "", -1, static_cast<ShaderAttributes>(i) ) );
}
}
BOHGE_FORCEINLINE void PushAttribute( const std::string& name, ShaderAttributes attr )
{
m_AttributesList[static_cast<int>(attr)] = StrShaderAttributes( name, m_Location, attr);
m_Location ++;
}
BOHGE_FORCEINLINE uint GetLocation(ShaderAttributes attr)
{
return m_AttributesList[static_cast<int>(attr)].nLocation;
}
BOHGE_FORCEINLINE uint GetLocation( int index )
{
return m_AttributesList[index].nLocation;
}
BOHGE_FORCEINLINE std::string& StringAttribute( int index )
{
return m_AttributesList[index].strName;
}
BOHGE_FORCEINLINE uint Size() const
{
return m_AttributesList.size();
}
};
//---------------------------------------------------------------------
class Shader
{
protected:
handle m_hShaderProgram;
Attributes m_Attributes;
private:
Shader( const Shader& s ){}//不能拷贝
Shader& operator = ( Shader& s ){}
protected:
/*使用这个shader设置shader所需要的全部属性和参数*/
virtual void _SetParameters() = 0;
public:
Shader();
virtual ~Shader();
/*初始化这个shader*/
virtual bool Initialization() = 0;
void UsingShader();
Attributes& GetAttributesMap()
{
return m_Attributes;
}
};
//---------------------------------------------------------------------
class IRenderNode;
class Material;
class MaterialShader : public Shader //一种为material准备的自动填写参数的shader
{
protected:
const Material* m_pMaterial;
public:
MaterialShader():m_pMaterial(NULL){}
virtual ~MaterialShader(){};
BOHGE_FORCEINLINE void SetParamNode(const Material* material)
{
m_pMaterial = material;
}
};
} | [
"bohge@163.com"
] | bohge@163.com |
d356e56e05882abd4b5e50f58a44730b5e16a2ec | da8c4077151f06a210e161c54b8bc3b97097ff61 | /알고리즘/Backjoon/일반/4539_반올림.cpp | 2017ca431301372308f0fbbf508dd1ea9b3179fc | [] | no_license | welshimeat/Self_Study | 79a02f4320dc68c1aa30974ce716b36dc1019278 | d21decf5530d729f02be19c5355337a1da18cde6 | refs/heads/master | 2021-04-24T03:05:24.964874 | 2021-03-12T16:29:00 | 2021-03-12T16:29:00 | 250,065,414 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 637 | cpp | #include <iostream>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, x;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x;
if (x > 10) {
x = (x + 5) / 10 * 10;
}
if (x > 100) {
x = (x + 50) / 100 * 100;
}
if (x > 1000) {
x = (x + 500) / 1000 * 1000;
}
if (x > 10000) {
x = (x + 5000) / 10000 * 10000;
}
if (x > 100000) {
x = (x + 50000) / 100000 * 100000;
}
if (x > 1000000) {
x = (x + 500000) / 1000000 * 1000000;
}
if (x > 10000000) {
x = (x + 5000000) / 10000000 * 10000000;
}
cout << x << endl;
}
return 0;
} | [
"kimsw1726@naver.com"
] | kimsw1726@naver.com |
2b57fe3a15a79e26a3b34e273fd48506d2c3f0e3 | 2c32342156c0bb00e3e1d1f2232935206283fd88 | /cam/src/shock/shkaicmd.cpp | f176132f5a53e9f101f4840b2fa33fe243603aaa | [] | no_license | infernuslord/DarkEngine | 537bed13fc601cd5a76d1a313ab4d43bb06a5249 | c8542d03825bc650bfd6944dc03da5b793c92c19 | refs/heads/master | 2021-07-15T02:56:19.428497 | 2017-10-20T19:37:57 | 2017-10-20T19:37:57 | 106,126,039 | 7 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,634 | cpp | ///////////////////////////////////////////////////////////////////////////////
// $Header: r:/t2repos/thief2/src/shock/shkaicmd.cpp,v 1.1 1999/06/18 22:07:20 JON Exp $
//
//
//
#include <shkaicmd.h>
#include <lg.h>
#include <appagg.h>
#include <aiapisnd.h>
#include <aidebug.h>
#include <aigoal.h>
#include <aisndtyp.h>
#include <creatext.h>
// Must be last header
#include <dbmem.h>
///////////////////////////////////////////////////////////////////////////////
//
// CLASS: cAICameraDeath
//
STDMETHODIMP_(const char *) cAICameraDeath::GetName()
{
return "CameraDeath";
}
//////////////////////////////////////
STDMETHODIMP_(void) cAICameraDeath::Init()
{
// Intentially not calling base -- want no goals or notifications by default
SetNotifications(kAICN_Death);
m_dying = FALSE;
}
//////////////////////////////////////
STDMETHODIMP_(void) cAICameraDeath::OnDeath(const sDamageMsg * pMsg)
{
// Halt all current sounds
if (m_pAI->AccessSoundEnactor())
m_pAI->AccessSoundEnactor()->HaltCurrent();
m_dying = TRUE;
SignalGoal();
AIWatch(Death, m_pAI->GetObjID(), "camera death");
}
//////////////////////////////////////
STDMETHODIMP cAICameraDeath::SuggestGoal(cAIGoal * pPrevious, cAIGoal ** ppGoal)
{
if (!m_dying)
{
*ppGoal = NULL;
return S_FALSE;
}
*ppGoal = new cAIDieGoal(this);
(*ppGoal)->priority= kAIP_VeryHigh;
SignalAction();
return S_OK;
}
///////////////////////////////////////
STDMETHODIMP cAICameraDeath::SuggestActions(cAIGoal * pGoal, const cAIActions & previous, cAIActions * pNew)
{
m_pAI->Kill();
return S_OK;
}
| [
"masterchaos.lord@gmail.com"
] | masterchaos.lord@gmail.com |
b4cd48f3945f6af28760dc3b7fa0b344675fc388 | 3ec39892999e781a57a3696d763ab1f4818b5bd8 | /csit836/assignment_5/tree.cpp | a46936bf4fbdae8c6df73445ef31d6336a2dbe7d | [] | no_license | ruizjorgealt/programming-assignments | 8df5f16fd3ada4c11b62bd4cdf5843bcf212cdc4 | d3271a394d367b85c8691a20db78d765d5d2c9fb | refs/heads/master | 2020-04-10T16:12:37.996629 | 2018-12-25T00:11:45 | 2018-12-25T00:11:45 | 161,137,282 | 0 | 0 | null | 2018-12-25T00:08:53 | 2018-12-10T07:49:17 | null | UTF-8 | C++ | false | false | 2,400 | cpp | #include <iostream>
#include "tree.h"
using namespace std;
PersonRec::PersonRec(char* n, int b, PersonRec* lC = NULL, PersonRec* rC = NULL){
strcpy(name,n);
bribe = b;
lChild = lC;
rChild = rC;
}
CTree::CTree(){
root = NULL;
}
CTree::~CTree(){
delete root;
}
void CTree::Add(){
char aName[40];
int aBribe;
cout << endl << "Enter the person's name: ";
cin >> aName;
cout<< endl << "Enter the person's contribution: ";
cin >> aBribe;
AddItem(root, aName, aBribe);
}
bool CTree::isEmpty(){
return root == NULL;
}
void CTree::View(){
if (isEmpty() == false){
cout << endl <<"Contributions" << endl;
cout << "_______________" << endl;
DisplayTree(root);
} else if (isEmpty() == true){
cout << endl << "The list is empty" << endl;
}
}
void CTree::DisplayTree(PersonRec* ptr){
static int var = 1;
if (ptr == NULL){
return;
} else {
DisplayTree(ptr->rChild);
cout << var << ' ' << ptr->name << " $" << ptr->bribe << endl;
var++;
DisplayTree(ptr->lChild);
}
}
void CTree::AddItem(PersonRec* &aPtr, char* name, int bribe){
if(isFull() == false){
if (aPtr == NULL){
aPtr = new PersonRec(name, bribe);
} else {
if (bribe > aPtr->bribe){
AppendRight(aPtr, name, bribe);
} else if (bribe < aPtr->bribe){
AppendLeft(aPtr, name, bribe);
} else {
return;
}
}
} else {
return;
}
}
void CTree::AppendLeft(PersonRec* aPtr, char* name, int bribe){
AddItem(aPtr->lChild, name, bribe);
}
void CTree::AppendRight(PersonRec* aPtr, char* name, int bribe){
AddItem(aPtr->rChild, name, bribe);
}
bool CTree::isFull(){
return false;
/* For this assignment, you can assume there is available memory in the
* free store. Therefore, this function always will return false.*/
}
/*The Functions below this comment will not be used*/
/*"You do not need to use all of these member functions."*/
// PersonRec* CTree::Root(){
// return root;
// /*You do not need to use all of these member functions*/
// }
// void CTree::BuildRoot(char* name, int bribe){
// //root = new PersonRec(name, bribe);
// /*You do not need to use all of these member functions*/
// } | [
"jorgearuiz@icloud.com"
] | jorgearuiz@icloud.com |
4498704548528ef195666e33f8aaf2a225a48e41 | e849efeec50fd305d01c14efc62f6f8d096898fb | /src/planning/trajectory_planner/src/trajectory_planner_nodelet.cpp | bb89ad099824ba0987539984e00c4312863a0143 | [
"BSD-3-Clause"
] | permissive | HuaiyuCai/lartkv5 | e069839976f0100d7eb6090927481dfcc4b0f30d | de7bcd416a1861e7ed19b35ff4258df370fbd07e | refs/heads/master | 2020-04-23T15:42:13.803955 | 2017-10-12T19:55:32 | 2017-10-12T19:55:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,355 | cpp | /**************************************************************************************************
Software License Agreement (BSD License)
Copyright (c) 2011-2013, LAR toolkit developers - University of Aveiro - http://lars.mec.ua.pt
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.
*Neither the name of the University of Aveiro 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 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.
***************************************************************************************************/
#ifndef _trajectory_planner_nodelet_CPP_
#define _trajectory_planner_nodelet_CPP_
/**
* @file trajectory_planner_nodelet.cpp
* @brief Uses the c-trajectory class, to publish trajectories and send the message to follow one of them
* @author Joel Pereira
* @version v0
* @date 2012-04-19
*/
#include "trajectory_planner_nodelet.h"
bool plan_trajectory=false;
bool have_plan=false;
geometry_msgs::PoseStamped pose_in;
geometry_msgs::PoseStamped pose_transformed;
std::vector< pcl::PointCloud<pcl::PointXYZ> > pc_v;
/**
* @brief Set attractor point coordinates
* @param trajectory_planner::coordinates msg
* @return void
*/
void set_coordinates(trajectory_planner::coordinates msg)
{
// cout<<"stat Message received!!!"<<endl;
// Change parameters
pose_in.pose.position.x=msg.x;
pose_in.pose.position.y=msg.y;
pose_in.pose.orientation.w=cos(msg.theta/2.0);
pose_in.pose.orientation.x=0.0;
pose_in.pose.orientation.y=0.0;
pose_in.pose.orientation.z=sin(msg.theta/2.0);
pose_in.header.frame_id="/world";
manage_vt->set_attractor_point(msg.x,msg.y,msg.theta);
plan_trajectory=true;
}
/**
* @brief Set mtt points
* @param mtt::TargetListPC msg
* @return void
*/
void mtt_callback(mtt::TargetListPC msg)
{
ROS_INFO("received mtt num obs=%ld num lines first obs =%d frame_id=%s",msg.id.size(), msg.obstacle_lines[0].width, msg.header.frame_id.c_str());
//copy to global variable
pc_v.erase(pc_v.begin(), pc_v.end());
for (size_t i=0; i<msg.id.size(); ++i)
{
pcl::PointCloud<pcl::PointXYZ> tmp;
pcl::fromROSMsg(msg.obstacle_lines[i], tmp);
tmp.header.frame_id=msg.header.frame_id;
// tmp.header.stamp=msg.header.stamp;
ROS_INFO("Obstacle %ld has %ld lines", i, tmp.points.size());
pc_v.push_back(tmp);
}
}
/**
* @brief Determine the speed vector
* @param c_trajectoryPtr t
* @return vector<double>
*/
vector<double> set_speed_vector(boost::shared_ptr<c_trajectory> t)
{
vector<double> speed_setted;
for(size_t i=0;i<_NUM_NODES_;++i)
{
if(i < (_NUM_NODES_ - 1))
{
if((t->arc[i])*(t->arc[i+1])<0.0)
{
speed_setted.push_back((t->arc[i]/fabs(t->arc[i]))*_SPEED_SAFFETY_); // This is the speed set to reverse/forward or forward/reverse
}
else
{
speed_setted.push_back((t->arc[i]/fabs(t->arc[i]))*_SPEED_REQUIRED_);
}
}
else
{
speed_setted.push_back((t->arc[i]/fabs(t->arc[i]))*_SPEED_REQUIRED_);
}
}
return speed_setted;
}
/**
* @brief Main code of the nodelet
* @details Publishes the trajectories message and the command message
* @param int argc
* @param char **argv
* @return int
*/
int main(int argc, char **argv)
{
ros::init(argc, argv, "trajectory_planner_nodelet");
ros::NodeHandle n("~");
p_n=&n;
//Define the publishers and subscribers
tf::TransformBroadcaster broadcaster;
tf::TransformListener listener;
p_listener = &listener;
ros::Publisher array_pub = n.advertise<visualization_msgs::MarkerArray>( "/array_of_markers", 1 );
ros::Subscriber sub = n.subscribe("/msg_coordinates", 1, set_coordinates);
ros::Subscriber mtt_sub = n.subscribe("/mtt_targets", 1, mtt_callback);
ros::Rate loop_rate(10);
// ___________________________________
// | |
// | Define the trajectories |
// |_________________________________|
//Declare the traj manager class
manage_vt = (c_manage_trajectoryPtr) new c_manage_trajectory();
//initialize attractor point
t_desired_coordinates AP;
AP.x=-1.0;
AP.y=0.0;
AP.theta=-M_PI/8;
manage_vt->set_attractor_point(AP.x, AP.y, AP.theta);
//initialize vehicle description
manage_vt->set_vehicle_description(_VEHICLE_WIDTH_, _VEHICLE_LENGHT_BACK_, _VEHICLE_LENGHT_FRONT_,
_VEHICLE_HEIGHT_TOP_, _VEHICLE_HEIGHT_BOTTOM_);
//initialize inter axis distance
manage_vt->set_inter_axis_distance(_D_);
//Compute the trajectory parameters
for (int i=0; i< _NUM_TRAJ_; i++)
{
vector<double> v_a;
vector<double> v_arc;
for (int j=0; j<_NUM_NODES_; ++j)
{
v_a.push_back(M_PI/180.*a[i][j]);
v_arc.push_back(arc[i][j]);
}
manage_vt->create_new_trajectory(v_a,v_arc,v_a);
}
// Choose trajectory (0 is trajectory 1)
int val = 0; // This will be commented
if (val>=(int)manage_vt->vt.size())
{
ROS_ERROR("Chosen trajectory does not exist");
exit(0);
}
manage_vt->set_chosen_traj(val);
//create the static visualisation markers
commandPublisher = n.advertise<trajectory_planner::traj_info>("/trajectory_information", 1000);
while(ros::ok())
{
if(plan_trajectory==true)
{
//aqui recebi um comando para defenir uma trajectoria
plan_trajectory = false;
ROS_INFO("Going to plan a trajectory");
// _________________________________
//| |
//| Set the parking view frame |
//|_________________________________|
bool have_transform=true;
//Set the frame where to draw the trajectories
try
{
p_listener->lookupTransform("/world","/vehicle_odometry",ros::Time(0), transformw);
}
catch (tf::TransformException ex)
{
ROS_ERROR("%s",ex.what());
have_transform=false;
}
if (have_transform)
{
ros::Time time=ros::Time::now();
broadcaster.sendTransform(tf::StampedTransform(transformw, time,"/world", "/parking_frame"));
ros::spinOnce();
broadcaster.sendTransform(tf::StampedTransform(transformw, time+ros::Duration(5),"/world", "/parking_frame"));
ros::spinOnce();
// cout<<"stat Publishing transform"<<endl;
ros::Duration(0.1).sleep();
// ___________________________________
// | |
// | Trajectory evaluation |
// |_________________________________|
//Transform attractor point to /parking_frame
tf::Transformer tt;
pose_in.header.stamp=time+ros::Duration(0.1);
p_listener->transformPose ("/parking_frame", pose_in, pose_transformed);
ROS_INFO("pose_in frame_id=%s pose_transformed frame_id=%s",pose_in.header.frame_id.c_str(), pose_transformed.header.frame_id.c_str());
//Set transformed attractor point
manage_vt->set_attractor_point(pose_transformed.pose.position.x,pose_transformed.pose.position.y,atan2(2.0*(pose_transformed.pose.orientation.w*pose_transformed.pose.orientation.z),1-(2*(pose_transformed.pose.orientation.z*pose_transformed.pose.orientation.z))));
//transform mtt to /parking_frame
pcl::PointCloud<pcl::PointXYZ> pct;
mtt::TargetListPC msg_transformed;
for (size_t i=0; i<pc_v.size(); ++i)
{
if (i==0)
{
try
{
// p_listener->lookupTransform(pc_v[i].header.frame_id,"/parking_frame", pc_v[i].header.stamp, transform_mtt);
}
catch (tf::TransformException ex)
{
ROS_ERROR("%s",ex.what());
}
}
ROS_INFO("pc_v[%ld] frame_id=%s pcp frame_id=%s",i, pc_v[i].header.frame_id.c_str(), pct.header.frame_id.c_str());
pcl_ros::transformPointCloud(pc_v[i],pct,transform_mtt.inverse());
sensor_msgs::PointCloud2 pc_msg;
pcl::toROSMsg(pct, pc_msg);
pc_msg.header.frame_id = "/parking_frame";
pc_msg.header.stamp = ros::Time::now();
msg_transformed.obstacle_lines.push_back(pc_msg);
}
manage_vt->set_obstacles(msg_transformed);
// ___________________________________
// | |
// | Draw |
// |_________________________________|
manage_vt->create_static_markers();
ros::Time st=ros::Time::now();
manage_vt->compute_trajectories_scores();
cout<<"Compute scores: "<<(ros::Time::now()-st).toSec();
ROS_INFO("manage_vt chosen traj= %d",manage_vt->chosen_traj.index);
trajectory_planner::traj_info info;
manage_vt->get_traj_info_msg_from_chosen(&info);
commandPublisher.publish(info);
visualization_msgs::MarkerArray marker_array;
manage_vt->compute_vis_marker_array(&marker_array);
array_pub.publish(marker_array);
cout<<"ja size:"<<marker_array.markers.size()<<endl;
have_plan=true;
}
}
if (have_plan==true)
{
// !!!! The previous 'if' must have a weight evaluation !!!! if ... && GlobalScore>=0.74
broadcaster.sendTransform(tf::StampedTransform(transformw, ros::Time::now(),"/world", "/parking_frame"));
cout<<"stat Publishing transform"<<endl;
}
//printf("CURRENT NODE-> %d\n",node);
//printf("Distance Travelled-> %f\n",base_status.distance_traveled);
loop_rate.sleep();
ros::spinOnce();
}
}
#endif
| [
"vsantos@mec.ua.pt"
] | vsantos@mec.ua.pt |
d1f1b5c33a1f4790668bc909a32a06e5ce8ef977 | c485cb363d29d81212427d3268df1ddcda64d952 | /dependencies/boost/boost/chrono/detail/inlined/run_timer.hpp | 1d2d5f448d795d1b2d7d49dc0137bc42f1fa66f0 | [
"BSL-1.0"
] | permissive | peplopez/El-Rayo-de-Zeus | 66e4ed24d7d1d14a036a144d9414ca160f65fb9c | dc6f0a98f65381e8280d837062a28dc5c9b3662a | refs/heads/master | 2021-01-22T04:40:57.358138 | 2013-10-04T01:19:18 | 2013-10-04T01:19:18 | 7,038,026 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,331 | hpp | // boost run_timer.cpp ---------------------------------------------------------------//
// Copyright Beman Dawes 1994, 2006, 2008
// Copyright 2009-2010 Vicente J. Botet Escriba
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
// See http://www.boost.org/libs/chrono for documentation.
//--------------------------------------------------------------------------------------//
#ifndef BOOST_CHRONO_DETAIL_INLINED_RUN_TIMER_HPP
#define BOOST_CHRONO_DETAIL_INLINED_RUN_TIMER_HPP
#include <boost/version.hpp>
#include <boost/chrono/process_times.hpp>
#include <boost/system/system_error.hpp>
#include <boost/throw_exception.hpp>
#include <boost/io/ios_state.hpp>
#include <cstring>
#include <boost/assert.hpp>
namespace boost
{
namespace chrono
{
namespace chrono_detail
{
BOOST_CHRONO_INLINE
const char * default_format() {
return "\nreal %rs, cpu %cs (%p%), user %us, system %ss\n";
}
BOOST_CHRONO_INLINE
void show_time( const boost::chrono::process_times & times,
const char * format, int places, std::ostream & os )
// NOTE WELL: Will truncate least-significant digits to LDBL_DIG, which may
// be as low as 10, although will be 15 for many common platforms.
{
if ( times.real < nanoseconds(0) ) return;
if ( places > 9 )
places = 9; // sanity check
else if ( places < 0 )
places = 0;
boost::io::ios_flags_saver ifs( os );
os.setf( std::ios_base::fixed, std::ios_base::floatfield );
boost::io::ios_precision_saver ips( os );
os.precision( places );
nanoseconds total = times.system + times.user;
for ( ; *format; ++format )
{
if ( *format != '%' || !*(format+1) || !std::strchr("rcpus", *(format+1)) )
os << *format;
else
{
++format;
switch ( *format )
{
case 'r':
os << duration<double>(times.real).count();
break;
case 'u':
os << duration<double>(times.user).count();
break;
case 's':
os << duration<double>(times.system).count();
break;
case 'c':
os << duration<double>(total).count();
break;
case 'p':
{
boost::io::ios_precision_saver ips( os );
os.precision( 1 );
if ( times.real.count() && total.count() )
os << duration<double>(total).count()
/duration<double>(times.real).count() * 100.0;
else
os << 0.0;
}
break;
default:
BOOST_ASSERT(0 && "run_timer internal logic error");
}
}
}
}
}
run_timer::run_timer( system::error_code & ec )
: m_places(m_default_places), m_os(m_cout()) { start(ec); }
run_timer::run_timer( std::ostream & os,
system::error_code & ec )
: m_places(m_default_places), m_os(os) { start(ec); }
run_timer::run_timer( const std::string & format,
system::error_code & ec )
: m_places(m_default_places), m_os(m_cout()), m_format(format) { start(ec); }
run_timer::run_timer( std::ostream & os, const std::string & format,
system::error_code & ec )
: m_places(m_default_places), m_os(os), m_format(format) { start(ec); }
run_timer::run_timer( const std::string & format, int places,
system::error_code & ec )
: m_places(places), m_os(m_cout()), m_format(format) { start(ec); }
run_timer::run_timer( std::ostream & os, const std::string & format,
int places, system::error_code & ec )
: m_places(places), m_os(os), m_format(format) { start(ec); }
run_timer::run_timer( int places,
system::error_code & ec )
: m_places(places), m_os(m_cout()) { start(ec); }
run_timer::run_timer( std::ostream & os, int places,
system::error_code & ec )
: m_places(places), m_os(os) { start(ec); }
run_timer::run_timer( int places, const std::string & format,
system::error_code & ec )
: m_places(places), m_os(m_cout()), m_format(format) { start(ec); }
run_timer::run_timer( std::ostream & os, int places, const std::string & format,
system::error_code & ec )
: m_places(places), m_os(os), m_format(format) { start(ec); }
// run_timer::report -------------------------------------------------------------//
void run_timer::report( system::error_code & ec )
{
m_reported = true;
if ( m_format.empty() ) m_format = chrono_detail::default_format();
process_times times;
elapsed( times, ec );
if (ec) return;
if ( BOOST_CHRONO_IS_THROWS(ec) )
{
chrono_detail::show_time( times, m_format.c_str(), m_places, m_os );
}
else // non-throwing
{
try
{
chrono_detail::show_time( times, m_format.c_str(), m_places, m_os );
if (!BOOST_CHRONO_IS_THROWS(ec))
{
ec.clear();
}
}
catch (...) // eat any exceptions
{
BOOST_ASSERT( 0 && "error reporting not fully implemented yet" );
if (BOOST_CHRONO_IS_THROWS(ec))
{
boost::throw_exception(
system::system_error(
errno,
BOOST_CHRONO_SYSTEM_CATEGORY,
"chrono::run_timer" ));
}
else
{
ec.assign(system::errc::success, BOOST_CHRONO_SYSTEM_CATEGORY);
}
}
}
}
// run_timer::test_report --------------------------------------------------------//
void run_timer::test_report( duration real_, duration user_, duration system_ )
{
if ( m_format.empty() ) m_format = chrono_detail::default_format();
process_times times;
times.real = real_;
times.user = user_;
times.system = system_;
chrono_detail::show_time( times, m_format.c_str(), m_places, m_os );
}
} // namespace chrono
} // namespace boost
#endif
| [
"fibrizo.raziel@gmail.com"
] | fibrizo.raziel@gmail.com |
96386c59299e1ef02e694343781a83b838d6c697 | 682ce86c118a1b6f12c5bd4a5b62d8403df34496 | /SRC/Geometry/source/headers/geometry/index/strtree/Boundable.h | 4866bdeac737ad4462c3130ffa8027be591041bd | [] | no_license | 15831944/applesales | 5596aca332384fe3210e03152b30334e48c344bd | 76aaf13d6b995ee59f8d83ecd9a1af155ed1911d | refs/heads/master | 2023-03-17T11:44:43.762650 | 2013-04-15T14:22:18 | 2013-04-15T14:22:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,773 | h | /**********************************************************************
* $Id: Boundable.h 1971 2007-02-07 00:34:26Z strk $
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2006 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************/
#ifndef GEOS_INDEX_STRTREE_BOUNDABLE_H
#define GEOS_INDEX_STRTREE_BOUNDABLE_H
namespace GEOMETRY {
namespace index { // GEOMETRY::index
namespace strtree { // GEOMETRY::index::strtree
/// A spatial object in an AbstractSTRtree.
class Boundable {
public:
/**
* Returns a representation of space that encloses this Boundable,
* preferably not much bigger than this Boundable's boundary yet
* fast to test for intersection with the bounds of other Boundables.
*
* The class of object returned depends
* on the subclass of AbstractSTRtree.
*
* @return an Envelope (for STRtrees), an Interval (for SIRtrees),
* or other object (for other subclasses of AbstractSTRtree)
*
* @see AbstractSTRtree::IntersectsOp
*/
virtual const void* getBounds() const=0;
virtual ~Boundable() {};
};
} // namespace GEOMETRY::index::strtree
} // namespace GEOMETRY::index
} // namespace GEOMETRY
#endif // GEOS_INDEX_STRTREE_BOUNDABLE_H
/**********************************************************************
* $Log$
* Revision 1.1 2006/03/21 10:47:34 strk
* indexStrtree.h split
*
**********************************************************************/
| [
"lordfm@163.com"
] | lordfm@163.com |
65fd2e902728f71358533a3bca29370372f67917 | 5ab5d59f187aa57f38c602cb274ea60375465df9 | /qkc/wobjs/SemaphoreW.cpp | 990bd2cff7bd81f296d8ad9b567427e73c016c3f | [] | no_license | wenfengsource/quark | 58293b7f437e40ee88094b83326d9932bf589fbb | 71ed73f74af05bd78f46f1bc23b03291fc1b2f2f | refs/heads/master | 2023-03-18T02:27:51.026823 | 2020-06-09T08:44:22 | 2020-06-09T08:44:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,152 | cpp |
#include "wobjs/SemaphoreW.h"
#include <errno.h>
namespace qkc {
Semaphore::Semaphore()
{
value_ = 1;
handle_ = ::CreateSemaphore(NULL , value_ , 65536 , NULL);
}
Semaphore::Semaphore(int value)
{
value_ = value;
handle_ = ::CreateSemaphore(NULL, value, 65536, NULL);
}
Semaphore::~Semaphore()
{
value_ = 0;
if (handle_ != NULL)
{
::CloseHandle(handle_);
handle_ = NULL;
}
}
void Semaphore::SetInfo()
{
OType(Object::kSemaphore);
}
int Semaphore::Post(int count)
{
if (::ReleaseSemaphore(handle_, (LONG)count, &value_) == TRUE)
return 0;
else
return -1;
}
int Semaphore::Wait()
{
if (::WaitForSingleObject(handle_, INFINITE) == WAIT_OBJECT_0)
return 0;
else
return -1;
}
int Semaphore::TimedWait(int timeout)
{
if (::WaitForSingleObject(handle_, timeout) == WAIT_OBJECT_0)
return 0;
DWORD errcode = ::GetLastError();
if (errcode == WAIT_TIMEOUT)
errno = ETIMEDOUT;
return -1;
}
int Semaphore::Value() const
{
return (int)::InterlockedCompareExchange((volatile LONG *)&value_, 0, 0);
}
}
| [
"romandion@163.com"
] | romandion@163.com |
6f448bba1973e7f8b4da19c4303242c23aa8ec17 | 6a3811783356805a362d5bd1542896f79c3d4947 | /chapter10/useaccnt01.cpp | 3e1f143792aba28ac0d93a22aa024adb12accbb1 | [] | no_license | GgooM94/cppPrimerPlus | 3efd624e6ec51dbfcfdab68d025bc1903a97044e | cf8379560ae5a84a705c30cbdd209edd4f950594 | refs/heads/master | 2021-09-07T23:03:04.828839 | 2018-03-02T17:11:58 | 2018-03-02T17:11:58 | 117,944,286 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 285 | cpp | #include<iostream>
#include"account01.h"
int main() {
using std::cout;
using std::cin;
Account myAccount("GgoooM94", "1002-1004_000", 0);
myAccount.show();
myAccount.deposit(1000);
myAccount.show();
myAccount.withdraw(500);
myAccount.show();
myAccount.deposit(-1000);
} | [
"cbg1541@gmail.com"
] | cbg1541@gmail.com |
3e946e32a5840389a6c52c0a1bea96d298ad9933 | 71501709864eff17c873abbb97ffabbeba4cb5e3 | /llvm13.0.0/libc/test/src/math/FDimTest.h | 1a5344006ff34a85fa7d5babd30c9c8dbdf84ea5 | [
"Apache-2.0",
"LLVM-exception",
"NCSA"
] | permissive | LEA0317/LLVM-VideoCore4 | d08ba6e6f26f7893709d3285bdbd67442b3e1651 | 7ae2304339760685e8b5556aacc7e9eee91de05c | refs/heads/master | 2022-06-22T15:15:52.112867 | 2022-06-09T08:45:24 | 2022-06-09T08:45:24 | 189,765,789 | 1 | 0 | NOASSERTION | 2019-06-01T18:31:29 | 2019-06-01T18:31:29 | null | UTF-8 | C++ | false | false | 2,761 | h | //===-- Utility class to test different flavors of fdim ---------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===---------------------------------------------------------------------===//
#include "utils/FPUtil/BasicOperations.h"
#include "utils/FPUtil/FPBits.h"
#include "utils/FPUtil/TestHelpers.h"
#include "utils/UnitTest/Test.h"
#include <math.h>
template <typename T>
class FDimTestTemplate : public __llvm_libc::testing::Test {
public:
using FuncPtr = T (*)(T, T);
using FPBits = __llvm_libc::fputil::FPBits<T>;
using UIntType = typename FPBits::UIntType;
void testNaNArg(FuncPtr func) {
EXPECT_FP_EQ(nan, func(nan, inf));
EXPECT_FP_EQ(nan, func(negInf, nan));
EXPECT_FP_EQ(nan, func(nan, zero));
EXPECT_FP_EQ(nan, func(negZero, nan));
EXPECT_FP_EQ(nan, func(nan, T(-1.2345)));
EXPECT_FP_EQ(nan, func(T(1.2345), nan));
EXPECT_FP_EQ(func(nan, nan), nan);
}
void testInfArg(FuncPtr func) {
EXPECT_FP_EQ(zero, func(negInf, inf));
EXPECT_FP_EQ(inf, func(inf, zero));
EXPECT_FP_EQ(zero, func(negZero, inf));
EXPECT_FP_EQ(inf, func(inf, T(1.2345)));
EXPECT_FP_EQ(zero, func(T(-1.2345), inf));
}
void testNegInfArg(FuncPtr func) {
EXPECT_FP_EQ(inf, func(inf, negInf));
EXPECT_FP_EQ(zero, func(negInf, zero));
EXPECT_FP_EQ(inf, func(negZero, negInf));
EXPECT_FP_EQ(zero, func(negInf, T(-1.2345)));
EXPECT_FP_EQ(inf, func(T(1.2345), negInf));
}
void testBothZero(FuncPtr func) {
EXPECT_FP_EQ(zero, func(zero, zero));
EXPECT_FP_EQ(zero, func(zero, negZero));
EXPECT_FP_EQ(zero, func(negZero, zero));
EXPECT_FP_EQ(zero, func(negZero, negZero));
}
void testInRange(FuncPtr func) {
constexpr UIntType count = 10000001;
constexpr UIntType step = UIntType(-1) / count;
for (UIntType i = 0, v = 0, w = UIntType(-1); i <= count;
++i, v += step, w -= step) {
T x = T(FPBits(v)), y = T(FPBits(w));
if (isnan(x) || isinf(x))
continue;
if (isnan(y) || isinf(y))
continue;
if (x > y) {
EXPECT_FP_EQ(x - y, func(x, y));
} else {
EXPECT_FP_EQ(zero, func(x, y));
}
}
}
private:
// constexpr does not work on FPBits yet, so we cannot have these constants as
// static.
const T nan = T(__llvm_libc::fputil::FPBits<T>::buildNaN(1));
const T inf = T(__llvm_libc::fputil::FPBits<T>::inf());
const T negInf = T(__llvm_libc::fputil::FPBits<T>::negInf());
const T zero = T(__llvm_libc::fputil::FPBits<T>::zero());
const T negZero = T(__llvm_libc::fputil::FPBits<T>::negZero());
};
| [
"kontoshi0317@gmail.com"
] | kontoshi0317@gmail.com |
552122a939c10be3f6e1575faf86e9e208a03163 | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir7941/dir29315/dir34756/file34824.cpp | d4f304f2ffd5122e991da0d321f1aa105e72f9ca | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | #ifndef file34824
#error "macro file34824 must be defined"
#endif
static const char* file34824String = "file34824"; | [
"tgeng@google.com"
] | tgeng@google.com |
6303bf676cca18bb7ef5c389f972929b075d269c | fcc88521f63a3c22c81a9242ae3b203f2ea888fd | /C++/1170-Compare-Strings-by-Frequency-of-the-Smallest-Character/soln.cpp | 53c0cf33d50e7375e651d73400b7892b3fc406a4 | [
"MIT"
] | permissive | wyaadarsh/LeetCode-Solutions | b5963e3427aa547d485d3a2cb24e6cedc72804fd | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | refs/heads/master | 2022-12-06T15:50:37.930987 | 2020-08-30T15:49:27 | 2020-08-30T15:49:27 | 291,811,790 | 0 | 1 | MIT | 2020-08-31T19:57:35 | 2020-08-31T19:57:34 | null | UTF-8 | C++ | false | false | 749 | cpp | class Solution {
public:
vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) {
vector<int> freqs;
transform(words.begin(), words.end(), back_inserter(freqs), Frequency);
sort(freqs.begin(), freqs.end());
vector<int> ans;
for(const string & query : queries) {
int f = Frequency(query);
ans.push_back(freqs.end() - upper_bound(freqs.begin(), freqs.end(), f));
}
return ans;
}
private:
static int Frequency(const string & word) {
int chars[26] = {0};
for(char ch : word) ++chars[ch - 'a'];
for(int i = 0; i < 26; ++i) {
if (chars[i]) return chars[i];
}
return 0;
}
};
| [
"zhang623@wisc.edu"
] | zhang623@wisc.edu |
a27cea31507fc43d46105a644d1dc318f042aa91 | 4cbd6b1a06042ad3dbfc70b56ce81b32a32f3806 | /practise.cpp | 8ec70c87d686c98939b82c885b13bd44099585c2 | [] | no_license | ShashwatShukla0/test | 3ae3fa768b0e3f9b5c9ca4605e939a014179a80a | 4f447b077f7d4cd93578dcbc0acd7cfd34d89d0e | refs/heads/main | 2023-07-15T04:21:39.649805 | 2021-09-06T07:02:57 | 2021-09-06T07:02:57 | 327,871,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 96 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
cout<<"Hello world";
return 0;
}
| [
"sskrish786@gmail.com"
] | sskrish786@gmail.com |
3d1fc5f89918be70be3f622ad30ecded92a551bd | a28058cbf3aaa12ed8ff1a16959c5ba3f7bdac8c | /src/visitors/dot_visitor.cpp | 99c4b287bd57a0668b2c5e1281cff25b2b63b654 | [] | no_license | migimunz/squid | 396de72141347ce7dfa471839269101bed408915 | 2f44cf5269fc743112f793c39744d751d235a80a | refs/heads/master | 2021-01-17T05:25:17.514851 | 2012-12-13T22:33:00 | 2012-12-13T22:33:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,064 | cpp | #include "dot_visitor.hpp"
#include <sstream>
#include <algorithm>
#include <boost/algorithm/string.hpp>
namespace squid
{
dot_node::dot_node(int id)
:attributes(),
id(id)
{
}
dot_node &dot_node::operator=(const dot_node &rhs)
{
if(this != &rhs)
{
attributes = rhs.attributes;
}
return *this;
}
dot_node &dot_node::operator=(const dot_node &&rhs)
{
if(this != &rhs)
{
attributes = std::move(rhs.attributes);
}
return *this;
}
dot_edge::dot_edge()
:parent_id(dot_edge::INVALID),
child_id(dot_edge::INVALID),
label()
{
}
dot_edge::dot_edge(int parent_id, int child_id, const std::string &label)
:parent_id(parent_id),
child_id(child_id),
label(label)
{
}
dot_edge &dot_edge::operator=(const dot_edge &rhs)
{
parent_id = rhs.parent_id;
child_id = rhs.child_id;
label = rhs.label;
return *this;
}
dot_visitor::dot_visitor()
:node_list(),
edge_list(),
prev_id(dot_edge::INVALID),
next_edge_label(""),
graph_label("")
{
}
dot_node &dot_visitor::create_node()
{
node_list.push_back(dot_node(node_list.size()));
dot_node &node = node_list.back();
if(prev_id != dot_edge::INVALID)
{
edge_list.push_back(dot_edge(prev_id, node.id, next_edge_label));
next_edge_label = "";
}
return node;
}
void dot_visitor::visit_child(int parent_id, ast_node_ptr node)
{
if(node)
{
prev_id = parent_id;
node->accept(*this);
}
}
IMPL_VISIT(dot_visitor, identifier, node)
{
dot_node &dnode = create_node();
dnode.attributes["label"] = node->text;
return node;
}
IMPL_VISIT(dot_visitor, binary_op, node)
{
dot_node &dnode = create_node();
dnode.attributes["label"] = node->get_operator_str();
dnode.attributes["shape"] = "oval";
visit_child(dnode.id, node->get_left());
visit_child(dnode.id, node->get_right());
return node;
}
IMPL_VISIT(dot_visitor, match, node)
{
dot_node &dnode = create_node();
dnode.attributes["label"] = node->get_operator_str();
dnode.attributes["shape"] = "oval";
visit_child(dnode.id, node->pattern);
visit_child(dnode.id, node->target);
return node;
}
IMPL_VISIT(dot_visitor, unary_op, node)
{
dot_node &dnode = create_node();
dnode.attributes["label"] = node->get_operator_str();
dnode.attributes["shape"] = "oval";
visit_child(dnode.id, node->get_operand());
return node;
}
IMPL_VISIT(dot_visitor, member_access, node)
{
dot_node &dnode = create_node();
dnode.attributes["label"] = ".";
dnode.attributes["shape"] = "oval";
visit_child(dnode.id, node->get_parent());
visit_child(dnode.id, node->get_child());
return node;
}
IMPL_VISIT(dot_visitor, number, node)
{
dot_node &dnode = create_node();
dnode.attributes["label"] = node->text;
return node;
}
IMPL_VISIT(dot_visitor, expression_list, node)
{
dot_node &dnode = create_node();
dnode.attributes["label"] = "expr list";
dnode.attributes["shape"] = "box";
auto& children = node->get_children();
for(auto iter = children.begin(); iter != children.end(); ++iter)
{
visit_child(dnode.id, *iter);
}
return node;
}
IMPL_VISIT(dot_visitor, function_def, node)
{
dot_node &dnode = create_node();
std::stringstream label;
label << "def " << node->name;
dnode.attributes["label"] = label.str();
dnode.attributes["shape"] = "box";
auto &args = node->args;
for(auto iter = args.begin(); iter != args.end(); ++iter)
{
next_edge_label = "arg";
visit_child(dnode.id, *iter);
}
next_edge_label = "body";
visit_child(dnode.id, node->body);
return node;
}
void dot_visitor::print_begin(std::ofstream &out)
{
out << "digraph AST\n"
<< "{\n"
<< "graph [fontname=Courier,fontsize=10.0,labeljust=l];\n"
<< "node [shape=box,width=0.2,height=0.2,fontname=Courier,fontsize=10.0,penwidth=0.5];\n"
<< "edge [weight=1.2,penwidth=0.5,fontname=Courier,fontsize=10.0,labeljust=c];\n"
<< "labelloc=\"t\";\n"
<< "label=\"" << graph_label << "\";\n";
}
void dot_visitor::print_end(std::ofstream &out)
{
out << "}";
}
void dot_visitor::print_node(std::ofstream &out, dot_node &node)
{
out << NODE_ID(node.id) << " [";
auto begin = node.attributes.begin();
for(auto iter = begin; iter != node.attributes.end(); ++iter)
{
if(iter != begin)
out << ",";
out << iter->first << "=\"" << iter->second << "\"";
}
out << "];\n";
}
void dot_visitor::print_edge(std::ofstream &out, dot_edge &edge)
{
out << NODE_ID(edge.parent_id) << " -> " << NODE_ID(edge.child_id);
if(!edge.label.empty())
out << "[label=\"" << edge.label << "\"]";
out << ";\n";
}
void dot_visitor::write_to_file(const char *fname)
{
std::ofstream out(fname);
if(out.fail())
return;
print_begin(out);
for(auto iter = node_list.begin(); iter != node_list.end(); ++iter)
{
print_node(out, *iter);
}
for(auto iter = edge_list.begin(); iter != edge_list.end(); ++iter)
{
print_edge(out, *iter);
}
print_end(out);
out.flush();
}
void dot_visitor::write_to_file(const char *fname, ast_node_ptr node, const std::string &graph_label)
{
dot_visitor visitor;
visitor.graph_label = graph_label;
boost::replace_all(visitor.graph_label, "\n", "\\l");
node->accept(visitor);
visitor.write_to_file(fname);
}
} | [
"migimunz@ivar.rs"
] | migimunz@ivar.rs |
854c37e11bc6e6083636d7050cedbe0f54fffe79 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14482/function14482_schedule_34/function14482_schedule_34.cpp | 6e5785dc16aa59c8d1b65bfc3fcfeeb6bcc9c455 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,200 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function14482_schedule_34");
constant c0("c0", 64), c1("c1", 64), c2("c2", 128), c3("c3", 64);
var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i3("i3", 0, c3), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06");
input input00("input00", {i0, i1, i3}, p_int32);
input input01("input01", {i3}, p_int32);
input input02("input02", {i0, i1, i3}, p_int32);
input input03("input03", {i0, i3}, p_int32);
input input04("input04", {i0}, p_int32);
input input05("input05", {i0, i1, i3}, p_int32);
input input06("input06", {i0, i3}, p_int32);
input input07("input07", {i1}, p_int32);
input input08("input08", {i2, i3}, p_int32);
computation comp0("comp0", {i0, i1, i2, i3}, input00(i0, i1, i3) - input01(i3) * input02(i0, i1, i3) + input03(i0, i3) + input04(i0) + input05(i0, i1, i3) + input06(i0, i3) - input07(i1) * input08(i2, i3));
comp0.tile(i1, i2, i3, 64, 64, 32, i01, i02, i03, i04, i05, i06);
comp0.parallelize(i0);
buffer buf00("buf00", {64, 64, 64}, p_int32, a_input);
buffer buf01("buf01", {64}, p_int32, a_input);
buffer buf02("buf02", {64, 64, 64}, p_int32, a_input);
buffer buf03("buf03", {64, 64}, p_int32, a_input);
buffer buf04("buf04", {64}, p_int32, a_input);
buffer buf05("buf05", {64, 64, 64}, p_int32, a_input);
buffer buf06("buf06", {64, 64}, p_int32, a_input);
buffer buf07("buf07", {64}, p_int32, a_input);
buffer buf08("buf08", {128, 64}, p_int32, a_input);
buffer buf0("buf0", {64, 64, 128, 64}, p_int32, a_output);
input00.store_in(&buf00);
input01.store_in(&buf01);
input02.store_in(&buf02);
input03.store_in(&buf03);
input04.store_in(&buf04);
input05.store_in(&buf05);
input06.store_in(&buf06);
input07.store_in(&buf07);
input08.store_in(&buf08);
comp0.store_in(&buf0);
tiramisu::codegen({&buf00, &buf01, &buf02, &buf03, &buf04, &buf05, &buf06, &buf07, &buf08, &buf0}, "../data/programs/function14482/function14482_schedule_34/function14482_schedule_34.o");
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
2f9dc0ad7afb384f1a6220926c82865f8f382d6e | 5ccdb058df19fc4e220b9bf7844ed9bbff956ffc | /p1766.cpp | 3dd2d3019e7d2dba7d767cd96034af457599c7f7 | [
"MIT"
] | permissive | sjnov11/Baekjoon-Online-Judge | 4db4253ba8df6923347ebdc33e920cfb1b2d8159 | a95df8a62e181d86a97d0e8969d139a3dae2be74 | refs/heads/master | 2020-04-02T09:00:30.235008 | 2018-12-03T10:05:52 | 2018-12-03T10:05:52 | 154,270,938 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 671 | cpp | #include <iostream>
#include <vector>
#include <queue>
#include <cstdio>
using namespace std;
vector<int> adj_list[32001];
int indegree[32001];
struct cmp {
bool operator()(int a, int b) {
return a > b;
}
};
int main() {
int N, M;
cin >> N >> M;
for (int i = 0; i < M; i++) {
int a, b;
cin >> a >> b;
adj_list[a].push_back(b);
indegree[b]++;
}
priority_queue<int, vector<int>, greater<int> > q;
for (int i = 1; i <= N; i++) {
if (indegree[i] == 0)
q.push(i);
}
while (!q.empty()) {
int n = q.top();
q.pop();
cout << n << " ";
for (int next : adj_list[n]) {
indegree[next]--;
if (indegree[next] == 0)
q.push(next);
}
}
} | [
"sjnov11@gmail.com"
] | sjnov11@gmail.com |
26208aba242e0823e34c7dabb307a8713e3d920e | 4d5f2cdc0b7120f74ba6f357b21dac063e71b606 | /star-ots/idl/CosTransactionsCurrent_skel.h | 18c9264bf89a1de8a62bc8979346e38049235917 | [
"BSD-2-Clause"
] | permissive | anjingbin/starccm | cf499238ceb1e4f0235421cb6f3cb823b932a2cd | 70db48004aa20bbb82cc24de80802b40c7024eff | refs/heads/master | 2021-01-11T19:49:04.306906 | 2017-01-19T02:02:50 | 2017-01-19T02:02:50 | 79,404,002 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 791 | h | // *************************************************************************
//
// This File Is Automatically Generated by the StarBusIDL-to-C++ Compiler !
//
// Copyright (c) 2003
// Network Information Security Institute,Computer College,NUDT.
// ChangSha,Hunan,PRC
//
// All Rights Reserved
//
// *************************************************************************
// Version: 5.0.0
#ifndef ___CosTransactionsCurrent_skel_h__
#define ___CosTransactionsCurrent_skel_h__
#include <CosTransactionsCurrent.h>
#include <STAR/SkelForServerRequest.h>
#include <STAR/Current_skel.h>
#include <CosTransactionsOTS_skel.h>
#include <CosTransactionsPolicy_skel.h>
//
// Module declare ::CosTransactions
//
namespace POA_CosTransactions
{
} // End of namespace POA_CosTransactions
#endif
| [
"anjb@qkjr.com.cn"
] | anjb@qkjr.com.cn |
b7e211e145a475d975d658ddad8600cd1c3aca87 | 34925da378f915aa67682e1fa7ae124c511f7d20 | /source/renderStats.cpp | ba90731508d0b2a0558f90b3b8c03c6e1da72235 | [] | no_license | leecloudvictor/orbisGlPerf | bbf39f64db72bef9552e67ef024d06172c98a73f | f369cfed3b5db99486357668ec47498eb4824c07 | refs/heads/master | 2020-04-13T07:31:25.587270 | 2018-12-24T19:04:35 | 2018-12-24T19:04:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 575 | cpp | #include <stdint.h>
struct RenderStats
{
uint32_t drawCalls;
uint32_t vertices;
uint32_t triangles;
};
static RenderStats stats;
void ResetRenderStats()
{
stats.vertices = 0;
stats.triangles = 0;
stats.drawCalls = 0;
}
void LogDrawCall(uint32_t vertices, uint32_t triangles)
{
stats.vertices += vertices;
stats.triangles += triangles;
stats.drawCalls++;
}
uint32_t GetVertexCount()
{
return stats.vertices;
}
uint32_t GetTriangleCount()
{
return stats.triangles;
}
uint32_t GetDrawCallCount()
{
return stats.drawCalls;
} | [
"psxdev@gmail.com"
] | psxdev@gmail.com |
6891df9e38f78254b5a0e1633526e0ac4ad7c7ab | dc4c1d2145f1ef7febf1f9fb0d64a13da0b6fc18 | /model/bp-orwar-router-changed-order.cc | cdfbaaca0db5c493c61fbd5c211eb8cc271e4fbd | [
"MIT"
] | permissive | liuqipei/ns3-dtn-mestrado | 0980bc92ef7786271f28d17bde1b6813fa3f8d4e | 3c92ffc1a4cb83a24e710cc61c7a5912be0bb255 | refs/heads/master | 2021-05-27T03:42:43.396383 | 2014-02-25T16:14:42 | 2014-02-25T16:14:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 51,162 | cc | /* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
#include <cmath>
#include <algorithm>
#include <limits>
#include <sstream>
#include "ns3/log.h"
#include "ns3/uinteger.h"
#include "ns3/address.h"
#include "ns3/mac48-address.h"
#include "ns3/mobility-model.h"
#include "ns3/trace-source-accessor.h"
#include "ns3/nstime.h"
#include "ns3/boolean.h"
#include "bp-orwar-router-changed-order.h"
#include "bp-header.h"
#include "bp-orwar-contact.h"
#include "bp-link-manager.h"
#include "bp-orwar-link-manager.h"
#include "bp-neighbourhood-detection-agent.h"
#include "bp-link.h"
NS_LOG_COMPONENT_DEFINE ("OrwarRouterChangedOrder");
namespace ns3 {
namespace bundleProtocol {
NS_OBJECT_ENSURE_REGISTERED (OrwarRouterChangedOrder);
TypeId
OrwarRouterChangedOrder::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::bundleProtocol::OrwarRouterChangedOrder")
.SetParent<BundleRouter> ()
.AddConstructor<OrwarRouterChangedOrder> ()
.AddAttribute ("ReplicationFactor",
"Sets the replication factor",
UintegerValue (6),
MakeUintegerAccessor (&OrwarRouterChangedOrder::m_replicationFactor),
MakeUintegerChecker<uint8_t> ())
.AddAttribute ("Delta",
"Sets the delta replication factor",
UintegerValue (2),
MakeUintegerAccessor (&OrwarRouterChangedOrder::m_deltaReplicationFactor),
MakeUintegerChecker<uint8_t> ())
.AddAttribute ("PauseTime",
"Sets the time a link should be paused",
TimeValue (Seconds (0.2)),
MakeTimeAccessor (&OrwarRouterChangedOrder::m_pauseTime),
MakeTimeChecker ())
.AddAttribute ("MaxRetries",
"Sets the maximum retries before closeing a bundle",
UintegerValue (3),
MakeUintegerAccessor (&OrwarRouterChangedOrder::m_maxRetries),
MakeUintegerChecker<uint32_t> ())
.AddAttribute ("EstimateContactWindow",
"Sets if contact window estimation shall be used or not.",
BooleanValue (true),
MakeBooleanAccessor (&OrwarRouterChangedOrder::m_estimateCw),
MakeBooleanChecker ())
.AddAttribute ("AlwaysSendHello",
"Sets if the router always should send hellos or only when it have something to send.",
BooleanValue (false),
MakeBooleanAccessor (&OrwarRouterChangedOrder::m_alwaysSendHello),
MakeBooleanChecker ())
.AddTraceSource ("CreatedRouterBundle", "A router message have been created.",
MakeTraceSourceAccessor (&OrwarRouterChangedOrder::m_createRouterLogger))
.AddTraceSource ("ContactSetup", "A contact setup has been finished.",
MakeTraceSourceAccessor (&OrwarRouterChangedOrder::m_contactSetupLogger))
.AddTraceSource ("RedundantRelay", "A message already held in the buffer has been received.",
MakeTraceSourceAccessor (&OrwarRouterChangedOrder::m_redundantRelayLogger))
.AddTraceSource ("ContactsOutOfSynch", "A message have been received out of order in the contact seutp.",
MakeTraceSourceAccessor (&OrwarRouterChangedOrder::m_outOfSynchLogger))
.AddTraceSource ("ContactSetupFailed", "A contact setup failed, no ack for router bundle.",
MakeTraceSourceAccessor (&OrwarRouterChangedOrder::m_contactSetupFailedLogger))
.AddTraceSource ("EstimatedCw", "The estimated contact window of a nodes contact.",
MakeTraceSourceAccessor (&OrwarRouterChangedOrder::m_estimatedCwLogger))
.AddTraceSource ("ContactOpp", ".",
MakeTraceSourceAccessor (&OrwarRouterChangedOrder::m_contactOppLogger))
.AddTraceSource ("ContactOppBetween", ".",
MakeTraceSourceAccessor (&OrwarRouterChangedOrder::m_contactOppBetweenLogger))
.AddTraceSource ("DeleteRouter", "A router bundle have been deleted",
MakeTraceSourceAccessor (&OrwarRouterChangedOrder::m_routerDeleteLogger))
;
return tid;
}
OrwarRouterChangedOrder::OrwarRouterChangedOrder ()
: BundleRouter (),
m_kdm ()
{}
OrwarRouterChangedOrder::~OrwarRouterChangedOrder ()
{
///cout << "%%%%% OrwarRouterChangedOrder::~OrwarRouterChangedOrder" << endl;
}
void
OrwarRouterChangedOrder::DoInit ()
{
if (m_alwaysSendHello)
{
m_nda->Start ();
}
}
void
OrwarRouterChangedOrder::DoDispose ()
{
m_kdm.Clear ();
BundleRouter::DoDispose ();
}
void
OrwarRouterChangedOrder::DoLinkClosed (Ptr<Link> link)
{
/*
if (m_node->GetId () == 49 && link->GetRemoteEndpointId ().GetId () == 21)
cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ")" << "OrwarRouterChangedOrder::DoLinkClosed" << endl;
*/
if (link->GetContact () != 0)
{
Ptr<OrwarContact> oc (dynamic_cast<OrwarContact *> (PeekPointer (link->GetContact ())));
if (oc->GetState () != READY)
{
m_contactSetupFailedLogger (1);
}
BundleList bundles = link->GetContact ()->GetQueuedBundles ();
for (BundleList::iterator iter = bundles.begin (); iter != bundles.end (); ++iter)
{
link->GetContact ()->DequeueBundle (*iter);
/*
if (m_node->GetId () == 49 && link->GetRemoteEndpointId ().GetId () == 21)
{
cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ")" << "CancelTransmission anropas av DoLinkClosed" << endl;
}
*/
CancelTransmission (*iter, link);
}
}
RemoveRouterSpecificBundles (link);
}
void
OrwarRouterChangedOrder::RemoveRouterSpecificBundles (Ptr<Link> link)
{
BundleList tmp;
for (BundleList::iterator iter = m_routerSpecificList.begin (); iter != m_routerSpecificList.end (); ++iter)
{
if (link->GetRemoteEndpointId () == (*iter)->GetDestinationEndpoint ())
{
tmp.push_back (*iter);
}
}
for (BundleList::iterator iter = tmp.begin (); iter != tmp.end (); ++iter)
{
RemoveRouterSpecificBundle (*iter, 1);
}
}
void
OrwarRouterChangedOrder::PauseLink (Ptr<Link> link)
{
if (link->GetState () == LINK_CONNECTED)
{
BundleList bundles = link->GetContact ()->GetQueuedBundles ();
for (BundleList::iterator iter = bundles.begin (); iter != bundles.end (); ++iter)
{
link->GetContact ()->DequeueBundle (*iter);
/*
if (m_node->GetId () == 49 && link->GetRemoteEndpointId ().GetId () == 21)
{
cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ")" << "CancelTransmission anropas av PauseLink" << endl;
}
*/
CancelTransmission (*iter, link);
}
link->ChangeState (LINK_PAUSED);
Ptr<OrwarContact> oc (dynamic_cast<OrwarContact *> (PeekPointer (link->GetContact ())));
if (oc->GetRetransmissions () >= m_maxRetries)
{
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") OrwarRouterChangedOrder::PauseLink Closes the link to (" << link->GetRemoteEndpointId ().GetId () << ") due to many retransmission attempts" << endl;
//Ptr<OrwarLinkManager> olm (dynamic_cast<OrwarLinkManager *> (PeekPointer (m_linkManager)));
Ptr<LinkManager> olm (dynamic_cast<LinkManager *> (PeekPointer (m_linkManager)));
olm->CloseLink (link);
}
else
{
oc->IncreaseRetransmissions ();
Simulator::Schedule (m_pauseTime, &OrwarRouterChangedOrder::UnPauseLink, this, link);
}
}
Simulator::ScheduleNow (&OrwarRouterChangedOrder::TryToStartSending, this);
}
void
OrwarRouterChangedOrder::UnPauseLink (Ptr<Link> link)
{
if (link->GetState () == LINK_PAUSED)
{
link->ChangeState (LINK_CONNECTED);
Simulator::ScheduleNow (&OrwarRouterChangedOrder::TryToStartSending, this);
}
}
void
OrwarRouterChangedOrder::DoLinkDiscovered (Ptr<Link> link)
{
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") OrwarRouterChangedOrder::DoLinkDiscovered Detected (" << link->GetRemoteEndpointId ().GetId () << ")" << endl;
m_contactOppLogger (1);
m_contactOppBetweenLogger (m_node->GetId (), link->GetRemoteEndpointId ().GetId ());
m_linkManager->OpenLink (link);
Ptr<OrwarContact> oc = dynamic_cast<OrwarContact *> (PeekPointer (link->GetContact ()));
oc->ChangeState (S_CREATED);
// Want to send my Kdm to the other node.
Simulator::ScheduleNow (&OrwarRouterChangedOrder::SendCwi, this, link, true);
}
void
OrwarRouterChangedOrder::DoBundleReceived (Ptr<Bundle> bundle)
{
Ptr<Link> link = m_linkManager->FindLink (bundle->GetReceivedFrom ().front ().GetEndpoint ());
if (link != 0)
{
link->UpdateLastHeardFrom ();
}
}
Ptr<Bundle>
OrwarRouterChangedOrder::DoSendBundle (Ptr<Link> link, Ptr<Bundle> bundle)
{
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") OrwarChangedOrder::SendBundle to " << link->GetRemoteEndpointId ().GetId () << endl;
link->GetContact ()->EnqueueBundle (bundle);
Ptr<Bundle> send = bundle->Copy ();
if (!IsRouterSpecific (bundle))
{
if (bundle->GetReplicationFactor () > 1)
{
send->SetReplicationFactor (ceil ((double) bundle->GetReplicationFactor () / 2.0));
}
}
return send;
}
void
OrwarRouterChangedOrder::DoBundleSent (const Address& address, const GlobalBundleIdentifier& gbid, bool finalDelivery)
{
NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::DoBundleSent");
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::DoBundleSent" << endl;
Mac48Address mac = Mac48Address::ConvertFrom (address);
Ptr<Link> link = m_linkManager->FindLink (mac);
Ptr<Bundle> bundle = GetBundle (gbid);
if (bundle != 0)
{
// I have received an ack for the sent bundle, so i have heard from the
// other node.
link->UpdateLastHeardFrom ();
if (link->GetState () == LINK_CONNECTED || link->GetState () == LINK_PAUSED)
{
link->GetContact ()->DequeueBundle (gbid);
link->GetContact ()->ResetRetransmissions ();
}
if (IsRouterSpecific (bundle))
{
SentRouterSpecific (link, bundle);
}
else
{
m_forwardLog.AddEntry (bundle, link);
if (finalDelivery)
{
BundleDelivered (bundle, true);
}
else
{
bundle->SetReplicationFactor (floor ((double)bundle->GetReplicationFactor () / 2.0));
}
Simulator::ScheduleNow (&OrwarRouterChangedOrder::TryToStartSending, this);
}
}
else
{
// FIXME: Hmm hur ska man ta hand om det h�r fallet...
// H�r vet jag enbbart gbid, men vet ej vilken typ av bundle det �r
// eller vad den har f�r ttl.
if (finalDelivery)
{
// This is a ugly hack utilitzing the fact that i know that
// the ttl is "inifinite".
Ptr<Bundle> bundle = Create<Bundle> ();
bundle->SetSourceEndpoint (gbid.GetSourceEid ());
bundle->SetCreationTimestamp (gbid.GetCreationTimestamp ());
bundle->SetLifetime (43000);
BundleDelivered (bundle, true);
Simulator::ScheduleNow (&OrwarRouterChangedOrder::TryToStartSending, this);
}
}
}
void
OrwarRouterChangedOrder::DoBundleTransmissionFailed (const Address& address, const GlobalBundleIdentifier& gbid)
{
NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::DoBundleTransmissionFailed");
Mac48Address mac = Mac48Address::ConvertFrom (address);
Ptr<Link> link = m_linkManager->FindLink (mac);
if (link->GetContact () != 0)
{
//link->GetContact ()->DequeueBundle (gbid);
}
PauseLink (link);
}
bool
OrwarRouterChangedOrder::DoAcceptBundle (Ptr<Bundle> bundle, bool fromApplication)
{
if (HasBundle (bundle))
{
m_redundantRelayLogger (bundle);
Ptr<Bundle> otherBundle = GetBundle (bundle->GetBundleId ());
otherBundle->AddReceivedFrom (bundle->GetReceivedFrom ().front ());
return false;
}
return CanMakeRoomForBundle (bundle);
}
bool
OrwarRouterChangedOrder::DoCanDeleteBundle (const GlobalBundleIdentifier& gbid)
{
return true;
}
void
OrwarRouterChangedOrder::DoInsert (Ptr<Bundle> bundle)
{
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::DoInsert bundle (" << bundle->GetPayload ()->GetSize () << ")" << endl;
// This is my extra thing, i always set the eid to current node holding the bundle.
bundle->SetCustodianEndpoint (m_eid);
m_bundleList.push_back (bundle);
sort (m_bundleList.begin (), m_bundleList.end (), UtilityPerBitCompare ());
// If this is the first bundle, I now want to begin sending hello messages announcing that
// I have something to send. If there is more than one bundle in the queue this means that
// I already have started sending hello messages.
if (m_nBundles == 1 && !m_alwaysSendHello)
{
m_nda->Start ();
}
Simulator::ScheduleNow (&OrwarRouterChangedOrder::TryToStartSending, this);
}
bool
OrwarRouterChangedOrder::CanMakeRoomForBundle (Ptr<Bundle> bundle)
{
if (bundle->GetSize () < m_maxBytes)
{
return true;
}
else
{
return false;
}
}
bool
OrwarRouterChangedOrder::MakeRoomForBundle (Ptr<Bundle> bundle)
{
if (bundle->GetSize () < m_maxBytes)
{
if (bundle->GetSize () < GetFreeBytes ())
{
return true;
}
for (BundleList::reverse_iterator iter = m_bundleList.rbegin (); iter != m_bundleList.rend ();)
{
Ptr<Bundle> currentBundle = *(iter++);
DeleteBundle (currentBundle,true);
if (bundle->GetSize () < GetFreeBytes ())
{
return true;
}
}
}
return false;
}
bool
OrwarRouterChangedOrder::DoDelete (const GlobalBundleIdentifier& gbid, bool drop)
{
// If this is the last bundle in the queue, stop sending Hello messages.
if (m_nBundles == 1 && !m_alwaysSendHello)
{
m_nda->Stop ();
}
return BundleRouter::DoDelete (gbid, drop);
}
void
OrwarRouterChangedOrder::DoCancelTransmission (Ptr<Bundle> bundle, Ptr<Link> link)
{
/*
if (m_node->GetId () == 49)
{
cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ")" << "DoCancelTransmission anropas p� bundlen" << endl;
cout << *bundle << endl;
}
*/
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::DoCancelTransmission");
}
void
OrwarRouterChangedOrder::DoTransmissionCancelled (const Address& address, const GlobalBundleIdentifier& gbid)
{
Mac48Address mac = Mac48Address::ConvertFrom (address);
Ptr<Link> link = m_linkManager->FindLink (mac);
if (link == 0)
{
cout << "This would just be strange" << endl;
}
/*
if (link->GetContact () == 0)
{
cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") OrwarRouterChangedOrder::BundleTransmissionCancelled Why does this happen..." << endl;
cout << *link << endl;
cout << gbid << endl;
}
*/
link->GetContact ()->DequeueBundle (gbid);
Simulator::ScheduleNow (&OrwarRouterChangedOrder::TryToStartSending, this);
}
uint8_t
OrwarRouterChangedOrder::DoCalculateReplicationFactor (const BundlePriority& priority) const
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::DoCalculateReplicationFactor");
switch (priority)
{
case BULK:
return m_replicationFactor - m_deltaReplicationFactor;
break;
case NORMAL:
return m_replicationFactor;
break;
case EXPEDITED:
return m_replicationFactor + m_deltaReplicationFactor;
break;
default:
return 1;
}
return 1;
}
// Orwar specific
void
OrwarRouterChangedOrder::TryToStartSending ()
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::TryToStartSending");
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::TryToStartSending" << endl;
RemoveExpiredBundles (true);
m_forwardLog.RemoveExpiredEntries ();
if (!IsSending () && ((GetNBundles () > 0) || (m_routerSpecificList.size () > 0)))
{
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << " Have something to send" << endl;
LinkBundle linkBundle = FindNextToSend ();
if (!linkBundle.IsNull ())
{
SendBundle (linkBundle.GetLink (), linkBundle.GetBundle ());
}
}
else
{
Ptr<OrwarLinkManager> olm (dynamic_cast<OrwarLinkManager *> (PeekPointer (m_linkManager)));
///cout << Simulator::Now ().GetSeconds () << " Could not start sending: " << endl;
///cout << Simulator::Now ().GetSeconds () << " !IsSending = " << !IsSending () << endl;
///cout << Simulator::Now ().GetSeconds () << " GetNBundles () = " << GetNBundles () << endl;
///cout << Simulator::Now ().GetSeconds () << " RouterSpecificBundles = " << m_routerSpecificList.size () << endl;
///cout << Simulator::Now ().GetSeconds () << " ReadyLinks = " << olm->GetReadyLinks ().size () << endl;
}
}
LinkBundle
OrwarRouterChangedOrder::FindNextToSend ()
{
NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::FindNextToSend");
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::FindNextToSend" << endl;
if (m_routerSpecificList.size () > 0)
{
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "Want to send a router bundle" << endl;
LinkBundle lb = GetNextRouterSpecific ();
if (!lb.IsNull ())
{
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "Found a router bundle to send" << endl;
return lb;
}
else
{
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "Could not find a suitable router bundle" << endl;
}
}
Ptr<LinkManager> olm (dynamic_cast<LinkManager *> (PeekPointer (m_linkManager)));
//Ptr<OrwarLinkManager> olm (dynamic_cast<OrwarLinkManager *> (PeekPointer (m_linkManager)));
//Ptr<OrwarLinkManager> olm ((OrwarLinkManager *) (PeekPointer (m_linkManager)));
if ((olm->GetReadyLinks ().size () > 0) && (GetNBundles () > 0))
{
LinkBundleList linkBundleList = GetAllDeliverableBundles ();
if (linkBundleList.empty ())
{
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "Want to forward a bundle" << endl;
linkBundleList = GetAllBundlesToAllLinks ();
}
else
{
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "Want to delivery a bundle" << endl;
}
if (!linkBundleList.empty ())
{
sort (linkBundleList.begin (), linkBundleList.end (), UtilityPerBitCompare2 ());
return linkBundleList.front ();
}
}
//cout << "GetNBundles () = " << GetNBundles () << endl;
//cout << "Doh kom hit utan att skicka n�got" << endl;
///cout << Simulator::Now ().GetSeconds () << " Failed to find a suitable bundle: " << endl;
///cout << Simulator::Now ().GetSeconds () << " GetNBundles () = " << GetNBundles () << endl;
///cout << Simulator::Now ().GetSeconds () << " RouterSpecificBundles = " << m_routerSpecificList.size () << endl;
///cout << Simulator::Now ().GetSeconds () << " ReadyLinks = " << olm->GetReadyLinks ().size () << endl;
return LinkBundle (0,0);
}
LinkBundle
OrwarRouterChangedOrder::GetNextRouterSpecific ()
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::GetNextRouterSpecific");
//cout << Simulator::Now ().GetSeconds () << "(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::GetNextRouterSpecific" << endl;
for (BundleList::iterator iter = m_routerSpecificList.begin ();
iter != m_routerSpecificList.end ();
++iter)
{
Ptr<Bundle> rsBundle = *iter;
Ptr<Link> link = m_linkManager->FindLink (rsBundle->GetDestinationEndpoint ());
CanonicalBundleHeader header = rsBundle->GetCanonicalHeaders ().front ();
if (header.GetBlockType () == KNOWN_DELIVERED_MESSAGES_BLOCK)
{
Ptr<OrwarContact> oc = dynamic_cast<OrwarContact *> (PeekPointer (link->GetContact ()));
double txTime = oc->GetDataRate ().CalculateTxTime (EstimateNeededBytes (rsBundle));
if (txTime <= oc->GetContactWindowDuration ().GetSeconds ())
{
return LinkBundle (link, rsBundle);
}
}
else
{
return LinkBundle (link, rsBundle);
}
}
return LinkBundle (0,0);
}
LinkBundleList
OrwarRouterChangedOrder::GetAllDeliverableBundles ()
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::GetAllDeliverableBundles");
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::GetAllDeliverableBundles" << endl;
//Ptr<OrwarLinkManager> olm (dynamic_cast<OrwarLinkManager *> (PeekPointer (m_linkManager)));
Ptr<LinkManager> olm (dynamic_cast<LinkManager *> (PeekPointer (m_linkManager)));
Links links = olm->GetReadyLinks ();
LinkBundleList result;
for (Links::iterator iter = links.begin (); iter != links.end (); ++iter)
{
Ptr<Link> link = *iter;
LinkBundleList linkBundleList = GetAllBundlesForLink (link);
result.insert (result.end (), linkBundleList.begin (), linkBundleList.end ());
}
return result;
}
LinkBundleList
OrwarRouterChangedOrder::GetAllBundlesForLink (Ptr<Link> link)
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder:: GetAllBundlesForLink");
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::GetAllBundlesForLink (" << link->GetRemoteEndpointId ().GetId () << ")" << endl;
LinkBundleList linkBundleList;
if (link->GetState () == LINK_CONNECTED)
{
Ptr<OrwarContact> oc = dynamic_cast<OrwarContact *> (PeekPointer (link->GetContact ()));
if (oc->GetState () == READY)
{
///cout << m_bundleList.size () << endl;
///cout << GetNBundles () << endl;
for (BundleList::iterator iter = m_bundleList.begin (); iter != m_bundleList.end (); ++iter)
{
Ptr<Bundle> bundle = *iter;
double txTime = oc->GetDataRate ().CalculateTxTime (EstimateNeededBytes (bundle));
/*
///cout << "The bundle: " << endl << *bundle << endl;
///cout << boolalpha;
///cout << "Txtime = " << txTime << endl;
///cout << "The contact window: " << oc->GetContactWindowDuration ().GetSeconds () << endl;
///cout << "Has RC: " << bundle->HasRetentionConstraint (RC_FORWARDING_PENDING) << endl;
///cout << "Enough time in contact window: " << (txTime <= oc->GetContactWindowDuration ().GetSeconds ()) << endl;
///cout << "Not been received from: " << !bundle->HaveBeenReceivedFrom (link) << endl;
///cout << "Replication factor > 1: " << (bundle->GetReplicationFactor () > 1) << endl;
///cout << "Forward log does not have an entry: " << !m_forwardLog.HasEntry (bundle, link) << endl;
///cout << noboolalpha;
*/
if (bundle->HasRetentionConstraint (RC_FORWARDING_PENDING) &&
txTime <= oc->GetContactWindowDuration ().GetSeconds () &&
!bundle->HaveBeenReceivedFrom (link) &&
(link->GetRemoteEndpointId () == bundle->GetDestinationEndpoint ()) &&
!m_forwardLog.HasEntry (bundle, link))
{
linkBundleList.push_back (LinkBundle (link, *iter));
}
}
}
}
return linkBundleList;
}
LinkBundleList
OrwarRouterChangedOrder::GetAllBundlesToAllLinks ()
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder:: GetAllBundlesToAllLinks");
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::GetAllBundlesToAllLinks" << endl;
//Ptr<OrwarLinkManager> olm (dynamic_cast<OrwarLinkManager *> (PeekPointer (m_linkManager)));
Ptr<LinkManager> olm (dynamic_cast<LinkManager *> (PeekPointer (m_linkManager)));
Links links = olm->GetReadyLinks ();
LinkBundleList linkBundleList;
for (Links::iterator iter = links.begin (); iter != links.end (); ++iter)
{
Ptr<Link> link = *iter;
Ptr<OrwarContact> oc = dynamic_cast<OrwarContact *> (PeekPointer (link->GetContact ()));
//Ptr<Contact> oc = dynamic_cast<Contact *> (PeekPointer (link->GetContact ()));
for (BundleList::iterator it = m_bundleList.begin (); it != m_bundleList.end (); ++it)
{
Ptr<Bundle> bundle = *it;
double txTime = oc->GetDataRate ().CalculateTxTime (EstimateNeededBytes (bundle));
/*
///cout << "The bundle: " << endl << *bundle << endl;
///cout << boolalpha;
///cout << "Txtime = " << txTime << endl;
///cout << "The contact window: " << oc->GetContactWindowDuration ().GetSeconds () << endl;
///cout << "Has RC: " << bundle->HasRetentionConstraint (RC_FORWARDING_PENDING) << endl;
///cout << "Enough time in contact window: " << (txTime <= oc->GetContactWindowDuration ().GetSeconds ()) << endl;
///cout << "Not been received from: " << !bundle->HaveBeenReceivedFrom (link) << endl;
///cout << "Replication factor > 1: " << (bundle->GetReplicationFactor () > 1) << endl;
///cout << "Forward log does not have an entry: " << !m_forwardLog.HasEntry (bundle, link) << endl;
///cout << noboolalpha;
*/
if (bundle->HasRetentionConstraint (RC_FORWARDING_PENDING) &&
txTime <= oc->GetContactWindowDuration ().GetSeconds () &&
!bundle->HaveBeenReceivedFrom (link) &&
bundle->GetReplicationFactor () > 1 &&
!m_forwardLog.HasEntry (bundle, link))
{
linkBundleList.push_back (LinkBundle (link, bundle));
}
}
}
return linkBundleList;
}
bool
OrwarRouterChangedOrder::DoIsRouterSpecific (Ptr<Bundle> bundle)
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::DoIsRouterSpecific");
CanonicalBundleHeader header = bundle->GetCanonicalHeaders ().front ();
return IsRouterSpecific (header.GetBlockType ());
}
bool
OrwarRouterChangedOrder::DoIsRouterSpecific (const BlockType& block)
{
switch (block)
{
case KNOWN_DELIVERED_MESSAGES_BLOCK:
case CONTACT_WINDOW_INFORMATION_BLOCK:
return true;
break;
default:
break;
}
return false;
}
void
OrwarRouterChangedOrder::SendRouterSpecific (Ptr<Link> link, Ptr<Bundle> bundle)
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::SendRouterSpecific");
}
void
OrwarRouterChangedOrder::SentRouterSpecific (Ptr<Link> link, const GlobalBundleIdentifier& gbid)
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::SentRouterSpecific");
//cout << Simulator::Now ().GetSeconds () << "(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::SentRouterSpecific" << endl;
Ptr<Bundle> bundle = GetBundle (gbid);
if (bundle != 0)
{
RemoveRouterSpecificBundle (bundle,0);
CanonicalBundleHeader header = bundle->GetCanonicalHeaders ().front ();
switch (header.GetBlockType ())
{
case KNOWN_DELIVERED_MESSAGES_BLOCK:
SentKdm (link);
break;
case CONTACT_WINDOW_INFORMATION_BLOCK:
SentCwi (link);
break;
default:
break;
}
}
else
{
Simulator::ScheduleNow (&OrwarRouterChangedOrder::TryToStartSending, this);
}
}
void
OrwarRouterChangedOrder::ReceiveRouterSpecific (Ptr<Bundle> bundle)
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::ReceiveRouterSpecific");
CanonicalBundleHeader header = bundle->GetCanonicalHeaders ().front ();
switch (header.GetBlockType ())
{
case KNOWN_DELIVERED_MESSAGES_BLOCK:
HandleKdm (bundle);
break;
case CONTACT_WINDOW_INFORMATION_BLOCK:
HandleCwi (bundle);
break;
default:
//cout << Doh this should not happen!! :/";
break;
}
}
void
OrwarRouterChangedOrder::AddRouterSpecificBundle (Ptr<Bundle> bundle)
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::AddRouterSpecificBundle");
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::AddRouterSpecificBundle" << endl;
m_routerSpecificList.push_back (bundle);
//cout << "(" << m_node->GetId () << ") " << "======== TryToStartSending anropat fr�n AddRouterSpecific ========" << endl;
Simulator::ScheduleNow (&OrwarRouterChangedOrder::TryToStartSending, this);
}
void
OrwarRouterChangedOrder::RemoveRouterSpecificBundle (const GlobalBundleIdentifier& gbid, uint8_t reason)
{
Ptr<Bundle> bundle = GetRouterSpecificBundle (gbid);
if (bundle != 0)
{
m_routerDeleteLogger (bundle, reason);
}
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::RemoveRouterSpecificBundle");
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::RemoveRouterSpecificBundle" << endl;
BundleList::iterator iter = remove_if (m_routerSpecificList.begin (), m_routerSpecificList.end (), MatchingGbid (gbid));
if (iter != m_routerSpecificList.end ())
{
m_routerSpecificList.erase (iter, m_routerSpecificList.end ());
}
}
bool
OrwarRouterChangedOrder::HasRouterSpecificBundle (const GlobalBundleIdentifier& gbid)
{
//NS_LOG_DEBUG' ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::HasRouterSpecificBundle");
return find_if (m_routerSpecificList.begin (), m_routerSpecificList.end (), MatchingGbid (gbid)) != m_routerSpecificList.end ();
}
Ptr<Bundle>
OrwarRouterChangedOrder::GetRouterSpecificBundle (const GlobalBundleIdentifier& gbid)
{
//NS_LOG_DEBUG' ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::GetRouterSpecificBundle");
BundleList::iterator iter = find_if (m_routerSpecificList.begin (), m_routerSpecificList.end (), MatchingGbid (gbid));
if (iter != m_routerSpecificList.end ())
{
return *iter;
}
else
{
return 0;
}
}
uint32_t
OrwarRouterChangedOrder::EstimateNeededBytes (Ptr<Bundle> bundle) const
{
//NS_LOG_DEBUG' ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::EstimateNeededBytes");
Ptr<ConvergenceLayerAgent> cla = m_node->GetObject<BundleProtocolAgent> ()->GetConvergenceLayerAgent ();
uint32_t overHeadPerFragment = 40;
uint16_t neededFragments = ceil ((double) bundle->GetSize () / (double) (cla->GetNetDevice ()->GetMtu () - overHeadPerFragment));
return bundle->GetSize () + overHeadPerFragment * neededFragments;
}
void
OrwarRouterChangedOrder::SendKdm (Ptr<Link> link, bool isInitiator)
{
NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::SendKdm " << "\t(" << m_node->GetId () << ")" << " >>>>>>>>>>>>>Kdm>>>>>>>>>>>>> " << "(" << link->GetRemoteEndpointId ().GetSsp () << ") contains " << m_kdm.NEntries () << " bundles");
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::SendKdm " << "\t(" << m_node->GetId () << ")" << " >>>>>>>>>>>>>Kdm>>>>>>>>>>>>> " << "(" << link->GetRemoteEndpointId ().GetSsp () << ") contains " << m_kdm.NEntries () << " bundles" << endl;
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::SendKdm " << "\t(" << m_node->GetId () << ")" << " >>>>>>>>>>>>>Kdm";
//if (isInitiator)
{
///cout << "*";
}
///cout << ">>>>>>>>>>>>> " << "(" << link->GetRemoteEndpointId ().GetSsp () << ") contains " << m_kdm.NEntries () << " bundles" << endl;
Ptr<Bundle> kdmBundle = GenerateKdm (link, isInitiator);
AddRouterSpecificBundle (kdmBundle);
}
void
OrwarRouterChangedOrder::SendCwi (Ptr<Link> link, bool isInitiator)
{
NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::SendCwi " << "\t(" << m_node->GetId () << ")" << " >>>>>>>>>>>>>Cwi>>>>>>>>>>>>> " << "(" << link->GetRemoteEndpointId ().GetSsp () << ")");
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::SendCwi " << "\t(" << m_node->GetId () << ")" << " >>>>>>>>>>>>>Cwi>>>>>>>>>>>>> " << "(" << link->GetRemoteEndpointId ().GetSsp () << ")" << endl;
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::SendCwi " << "\t(" << m_node->GetId () << ")" << " >>>>>>>>>>>>>Cwi";
//if (isInitiator)
///cout << "*";
///cout << ">>>>>>>>>>>>> " << "(" << link->GetRemoteEndpointId ().GetSsp () << ")" << endl;
Ptr<Bundle> cwiBundle = GenerateCwi (link, isInitiator);
AddRouterSpecificBundle (cwiBundle);
}
void
OrwarRouterChangedOrder::SentKdm (Ptr<Link> link)
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::SentKdm");
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::SentKdm" << endl;
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::SentKdm to (" << link->GetRemoteEndpointId ().GetId () << ")" << endl;
if (link->GetState () == LINK_CONNECTED)
{
Ptr<OrwarContact> oc (dynamic_cast<OrwarContact *> (PeekPointer (link->GetContact ())));
if (oc->GetState () == S_RECEIVED_CWI)
{
oc->ChangeState (S_WAITING_FOR_KDM);
}
else if (oc->GetState () == R_RECEIVED_KDM)
{
oc->ChangeState (READY);
}
else
{
NS_LOG_DEBUG ("Something is wrong!" << "(" << m_node->GetId () << ") ");
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "Something is wrong!" << endl;
}
}
//cout << "(" << m_node->GetId () << ") " << "======== TryToStartSending anropat fr�n SentKdm =========" << endl;
Simulator::ScheduleNow (&OrwarRouterChangedOrder::TryToStartSending, this);
}
void
OrwarRouterChangedOrder::SentCwi (Ptr<Link> link)
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::SentCwi");
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::SentCwi" << endl;
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::SentCwi to (" << link->GetRemoteEndpointId ().GetId () << ")" << endl;
if (link->GetState () == LINK_CONNECTED)
{
Ptr<OrwarContact> oc (dynamic_cast<OrwarContact *> (PeekPointer (link->GetContact ())));
if (oc->GetState () == S_CREATED)
{
//NS_LOG_INFO ("Sender: Sent kdm, waiting for kdm in response");
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "Sender: Sent kdm, waiting for kdm in response" << endl;
oc->ChangeState (S_WAITING_FOR_CWI);
}
else if (oc->GetState () == R_RECEIVED_CWI)
{
oc->ChangeState (R_WAITING_FOR_KDM);
}
else
{
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "Something is wrong!" << endl;
NS_LOG_DEBUG ("Something is wrong!" << "(" << m_node->GetId () << ") ");
}
}
//cout << "(" << m_node->GetId () << ") " << "======== TryToStartSending anropat fr�n SentCwi ========" << endl;
Simulator::ScheduleNow (&OrwarRouterChangedOrder::TryToStartSending, this);
}
void
OrwarRouterChangedOrder::HandleCwi (Ptr<Bundle> bundle)
{
NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::HandleCwi " << "\t(" << m_node->GetId () << ")" << " <<<<<<<<<<<<<Cwi<<<<<<<<<<<<< " << "(" << bundle->GetSourceEndpoint ().GetSsp () << ") ");
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::HandleCwi " << "\t(" << m_node->GetId () << ")" << " <<<<<<<<<<<<<Cwi<<<<<<<<<<<<< " << "(" << bundle->GetSourceEndpoint ().GetSsp () << ") " << endl;
Ptr<Packet> serializedCwi = bundle->GetPayload ();
uint8_t *buffer = new uint8_t [serializedCwi->GetSize ()];
serializedCwi->CopyData (buffer, serializedCwi->GetSize ());
ContactWindowInformation cwi = ContactWindowInformation::Deserialize (buffer);
delete [] buffer;
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::HandleCwi " << "\t(" << m_node->GetId () << ")" << " <<<<<<<<<<<<<Cwi";
// if (cwi.IsInitiator ())
///cout << "*";
///cout << "<<<<<<<<<<<<< " << "(" << bundle->GetSourceEndpoint ().GetSsp () << ") " << endl;
Ptr<Link> link = m_linkManager->FindLink (bundle->GetSourceEndpoint ());
if (link == 0)
{
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") Got a CWI and have no previous link" << endl;
EidAddress ea = bundle->GetReceivedFrom ().front ();
link = CreateLink (ea.GetEndpoint (), ea.GetAddress ());
m_linkManager->AddLink (link);
m_linkManager->OpenLink (link);
Ptr<OrwarContact> oc = dynamic_cast<OrwarContact *> (PeekPointer (link->GetContact ()));
oc->ChangeState (R_RECEIVED_CWI);
m_contactOppBetweenLogger (m_node->GetId (), link->GetRemoteEndpointId ().GetId ());
}
else if (link->GetState () == LINK_UNAVAILABLE)
{
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") Got a CWI and the link is unavailable" << endl;
m_linkManager->OpenLink (link);
Ptr<OrwarContact> oc = dynamic_cast<OrwarContact *> (PeekPointer (link->GetContact ()));
oc->ChangeState (R_RECEIVED_CWI);
m_contactOppBetweenLogger (m_node->GetId (), link->GetRemoteEndpointId ().GetId ());
}
if (link->GetState () == LINK_CONNECTED)
{
Ptr<OrwarContact> oc = dynamic_cast<OrwarContact *> (PeekPointer (link->GetContact ()));
if (oc->GetState () == S_WAITING_FOR_CWI && !cwi.IsInitiator ())
{
//cout << Simulator::Now ().GetSeconds () << " Sender: Got cwi while waiting for cwi " << endl;
Simulator::ScheduleNow (&OrwarRouterChangedOrder::SendKdm, this, link, true);
CalculateContactWindow (link, cwi);
oc->ChangeState (S_RECEIVED_CWI);
}
else if (oc->GetState () == R_RECEIVED_CWI && cwi.IsInitiator ())
{
//cout << Simulator::Now ().GetSeconds () << " Receiver: Got a cwi* want to send cwi as response" << endl;
Simulator::ScheduleNow (&OrwarRouterChangedOrder::SendCwi, this, link, false);
CalculateContactWindow (link, cwi);
}
else
{
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") HandleCwi" << " The contact is out of synch! Hmm the link is connected" << endl;
///cout << *link << endl;
m_outOfSynchLogger (1);
Simulator::ScheduleNow (&OrwarRouterChangedOrder::TryToStartSending, this);
}
}
else
{
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") HandleCwi" << " The contact is out of synch! Hmm the link is not connected" << endl;
///cout << *link << endl;
m_outOfSynchLogger (1);
Simulator::ScheduleNow (&OrwarRouterChangedOrder::TryToStartSending, this);
}
}
void
OrwarRouterChangedOrder::HandleKdm (Ptr<Bundle> bundle)
{
Ptr<Packet> serializedKdm = bundle->GetPayload ();
uint8_t *buffer = new uint8_t[serializedKdm->GetSize ()];
serializedKdm->CopyData (buffer, serializedKdm->GetSize ());
KnownDeliveredMessages kdm = KnownDeliveredMessages::Deserialize (buffer);
NS_LOG_DEBUG ("(" << m_node->GetId () << ") " <<"OrwarRouterChangedOrder::HandleKdm " << "\t(" << m_node->GetId () << ")" << " <<<<<<<<<<<<<Kdm<<<<<<<<<<<<< " << "(" << bundle->GetSourceEndpoint ().GetSsp () << ") contains " << kdm.NEntries () << " bundles");
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::HandleKdm " << "\t(" << m_node->GetId () << ")" << " <<<<<<<<<<<<<Kdm<<<<<<<<<<<<< " << "(" << bundle->GetSourceEndpoint ().GetSsp () << ") contains " << kdm.NEntries () << " bundles" << endl;
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::HandleKdm " << "\t(" << m_node->GetId () << ")" << " <<<<<<<<<<<<<Kdm";
//if (kdm.IsInitiator ())
///cout << "*";
///cout << "<<<<<<<<<<<<< " << "(" << bundle->GetSourceEndpoint ().GetSsp () << ") contains " << kdm.NEntries () << " bundles" << endl;
Ptr<Link> link = m_linkManager->FindLink (bundle->GetSourceEndpoint ());
if ((link == 0) || (link->GetState () != LINK_CONNECTED))
{
m_outOfSynchLogger (1);
Simulator::ScheduleNow (&OrwarRouterChangedOrder::TryToStartSending, this);
return;
}
Ptr<OrwarContact> oc (dynamic_cast<OrwarContact *> (PeekPointer (link->GetContact ())));
if (oc->GetState () == S_WAITING_FOR_KDM && !kdm.IsInitiator ())
{
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& OrwarRouterChangedOrder::HandleKdm The contact between" << " (" << m_node->GetId () << ") and" << " (" << link->GetRemoteEndpointId ().GetId () << ") has been finalized" << endl;
m_contactSetupLogger (0);
oc->ChangeState (READY);
}
else if (oc->GetState () == R_WAITING_FOR_KDM && kdm.IsInitiator ())
{
Simulator::ScheduleNow (&OrwarRouterChangedOrder::SendKdm, this, link, false);
oc->ChangeState (R_RECEIVED_KDM);
}
else
{
///cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") HandleKdm" << "The contact is out of synch!" << endl;
m_outOfSynchLogger (1);
Simulator::ScheduleNow (&OrwarRouterChangedOrder::TryToStartSending, this);
}
RemoveDeliveredBundles (kdm);
m_kdm.Merge (kdm);
delete [] buffer;
}
void
OrwarRouterChangedOrder::RemoveDeliveredBundles (const KnownDeliveredMessages& kdm)
{
NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::RemoveDelivered");
BundleList bl;
for (BundleList::iterator iter = m_bundleList.begin (); iter != m_bundleList.end (); ++iter)
{
Ptr<Bundle> bundle = *iter;
if (kdm.Has (bundle))
{
bl.push_back (bundle);
m_forwardLog.RemoveEntriesFor (bundle->GetBundleId ());
}
}
for (BundleList::iterator iter = bl.begin (); iter != bl.end (); ++iter)
{
DeleteBundle (*iter, false);
}
}
Ptr<Bundle>
OrwarRouterChangedOrder::GenerateCwi (Ptr<Link> link, bool isInitiator)
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::GenerateCwi");
Ptr<MobilityModel> mobility = m_node->GetObject<MobilityModel> ();
Ptr<ConvergenceLayerAgent> cla = m_node->GetObject<BundleProtocolAgent> ()->GetConvergenceLayerAgent ();
ContactWindowInformation cwi = ContactWindowInformation (mobility->GetPosition (), mobility->GetVelocity (), cla->GetTransmissionRange (), cla->GetTransmissionSpeed (), isInitiator);
uint8_t buffer[cwi.GetSerializedSize ()];
cwi.Serialize (buffer);
Ptr<Packet> adu = Create<Packet> (buffer, cwi.GetSerializedSize ());
PrimaryBundleHeader primaryHeader = PrimaryBundleHeader ();
primaryHeader.SetDestinationEndpoint (link->GetRemoteEndpointId ());
primaryHeader.SetSourceEndpoint (m_eid);
primaryHeader.SetCustodianEndpoint (m_eid);
primaryHeader.SetReplicationFactor (1);
primaryHeader.SetCreationTimestamp (CreationTimestamp ());
primaryHeader.SetLifetime (Seconds (60));
CanonicalBundleHeader canonicalHeader = CanonicalBundleHeader (CONTACT_WINDOW_INFORMATION_BLOCK);
canonicalHeader.SetMustBeReplicated (false);
canonicalHeader.SetStatusReport (false);
canonicalHeader.SetDeleteBundle (false);
canonicalHeader.SetLastBlock (true);
canonicalHeader.SetDiscardBlock (true);
canonicalHeader.SetForwarded (false);
canonicalHeader.SetContainsEid (false);
canonicalHeader.SetBlockLength (adu->GetSize ());
Ptr<Bundle> cwiBundle = Create<Bundle> ();
cwiBundle->SetPayload (adu);
cwiBundle->SetPrimaryHeader (primaryHeader);
cwiBundle->AddCanonicalHeader (canonicalHeader);
m_createRouterLogger (cwiBundle);
return cwiBundle;
}
Ptr<Bundle>
OrwarRouterChangedOrder::GenerateKdm (Ptr<Link> link, bool isInitiator)
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::GenerateKdm");
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::GenerateKdm" << endl;
m_kdm.RemoveExpiredBundles (); // Removes all expired bundles from the kdm, before createing the bundle to send.
m_kdm.SetIsInitiator (isInitiator);
uint8_t buffer[m_kdm.GetSerializedSize ()];
m_kdm.Serialize (buffer);
KnownDeliveredMessages test = KnownDeliveredMessages::Deserialize (buffer);
Ptr<Packet> adu = Create<Packet> (buffer, m_kdm.GetSerializedSize ());
PrimaryBundleHeader primaryHeader = PrimaryBundleHeader ();
primaryHeader.SetDestinationEndpoint (link->GetRemoteEndpointId ());
primaryHeader.SetSourceEndpoint (m_eid);
primaryHeader.SetCustodianEndpoint (m_eid);
primaryHeader.SetReplicationFactor (1);
primaryHeader.SetCreationTimestamp (CreationTimestamp ());
primaryHeader.SetLifetime (Seconds (60));
CanonicalBundleHeader canonicalHeader = CanonicalBundleHeader (KNOWN_DELIVERED_MESSAGES_BLOCK);
canonicalHeader.SetMustBeReplicated (false);
canonicalHeader.SetStatusReport (false);
canonicalHeader.SetDeleteBundle (false);
canonicalHeader.SetLastBlock (true);
canonicalHeader.SetDiscardBlock (true);
canonicalHeader.SetForwarded (false);
canonicalHeader.SetContainsEid (false);
canonicalHeader.SetBlockLength (adu->GetSize ());
Ptr<Bundle> kdm = Create<Bundle> ();
kdm->SetPayload (adu);
kdm->SetPrimaryHeader (primaryHeader);
kdm->AddCanonicalHeader (canonicalHeader);
m_createRouterLogger (kdm);
return kdm;
}
void
OrwarRouterChangedOrder::CalculateContactWindow (Ptr<Link> link, const ContactWindowInformation& cwi)
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::CalculateContactWindow");
Ptr<OrwarContact> oc (dynamic_cast<OrwarContact *> (PeekPointer (link->GetContact ())));
Ptr<MobilityModel> mobility = m_node->GetObject<MobilityModel> ();
Ptr<ConvergenceLayerAgent> cla = m_node->GetObject<BundleProtocolAgent> ()->GetConvergenceLayerAgent ();
Vector p1 = mobility->GetPosition ();
Vector v1 = mobility->GetVelocity ();
uint32_t r1 = cla->GetTransmissionRange ();
Vector p2 = cwi.GetPosition ();
Vector v2 = cwi.GetVelocity ();
uint32_t r2 = cwi.GetTransmissionRange ();
double minr = min (r1,r2);
double a = v2.y - v1.y;
double b = v1.x - v2.x;
double c = p2.y - p1.y;
double d = p1.x - p2.x;
double result;
if (a == 0 && b == 0)
{
result = numeric_limits<uint32_t>::max();
oc->SetCwMax (true);
}
else
{
double e = pow (a,2) + pow (b,2);
double f = c*b - a*d;
double s = pow (minr,2) * e - pow (f,2);
double numerator = -a*c + sqrt (s) - b*d;
result = numerator / e;
}
// This case exist beacuse the nodes transmission range is not exact, sometimes the nodes detects each other from a larger distance.
// This can result in a negative contact window if they according to their conectivity settings are moving away from each other.
// One solution could be to set result to zero if the distance between the nodes according to the coordinates is larger than minr,
// but this solution also sets
if (result < 0)
{
result = 0;
}
//debug << "### " << Simulator::Now ().GetSeconds () << " Contact between 0 and " << oc->GetLink ()->GetRemoteEndpointId ().GetId () << endl;
//debug << "p1=" << p1 << " v1=" << v1 << " r1=" << r1 << endl;
//debug << "p2=" << p2 << " v2=" << v2 << " r2=" << r2 << endl;
//debug << "result = " << result << endl;
//debug << "#############" << endl << endl;
//NS_LOG_INFO ("(" << m_node->GetId () << ") " << "Contact window estimated to: " << result);
oc->SetContactWindowDuration (Seconds (result));
oc->SetDataRate (cla->GetTransmissionSpeed ());
Ptr<OrwarLinkManager> olm (dynamic_cast<OrwarLinkManager *> (PeekPointer (m_linkManager)));
if (GetPointer(olm) != NULL) {
olm->FinishedSetup (link);
}
m_estimatedCwLogger (m_node->GetId (), link->GetRemoteEndpointId ().GetId (), oc->GetContactWindowDuration (), oc->GetCwMax ());
}
void
OrwarRouterChangedOrder::DoBundleDelivered (Ptr<Bundle> bundle, bool fromAck)
{
NS_LOG_DEBUG ("############################# " << "(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::DoBundleDelivered");
//cout << Simulator::Now ().GetSeconds () << " (" << m_node->GetId () << ") ############################# " << "OrwarRouterChangedOrder::DoBundleDelivered" << endl;
m_kdm.Insert (bundle);
if (fromAck)
{
RemoveDeliveredBundles (m_kdm);
}
}
Ptr<Link>
OrwarRouterChangedOrder::DoCreateLink (const BundleEndpointId& eid, const Address& address)
{
//NS_LOG_DEBUG ("(" << m_node->GetId () << ") " << "OrwarRouterChangedOrder::DoCreateLink");
Ptr<ConvergenceLayerAgent> cla = m_node->GetObject<BundleProtocolAgent> ()->GetConvergenceLayerAgent ();
Ptr<OrwarLink> link = CreateObject<OrwarLink> ();
link->SetLinkLostCallback (MakeCallback (&ConvergenceLayerAgent::LinkLost, cla));
link->SetHackFixmeCallback (MakeCallback (&ConvergenceLayerAgent::HackFixme, cla));
/*
Ptr<OrwarLinkManager> olm (dynamic_cast<OrwarLinkManager *> (PeekPointer (m_linkManager)));
link->m_expirationTimer.SetFunction (&OrwarLinkManager::CheckIfExpired, olm);
link->m_expirationTimer.SetArguments (link);
*/
link->SetRemoteEndpointId (eid);
link->SetRemoteAddress (address);
return link;
}
}} // namespace bundleProtocol, ns3
| [
"sergiosvieira@gmail.com"
] | sergiosvieira@gmail.com |
2f8c4e07f5f16e9b61649cefa8cf8ed06b723713 | 6e2f8b62a9977ae6c51c6bcbe41daccc92a87677 | /ParabellumEngine/ParabellumEngine/SystemInstance.h | d986d8559aadbff4c3545fc3f7ab515e215a312b | [
"MIT"
] | permissive | Qazwar/ParabellumFramework | 8a455ea5e1ac0dab9c466604d2f443317e2a57bd | 7b55003bb04e696a68f436b9ec98a05e026526fd | refs/heads/master | 2022-01-26T06:28:53.040419 | 2019-06-29T11:05:34 | 2019-06-29T11:05:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,550 | h | #ifndef _SYSTEMINSTANCE_H_
#define _SYSTEMINSTANCE_H_
//
// Predefs
//
#include "DLLIE.h"
#include <stdio.h>
#include "../ParabellumFramework/ResourceManager.h"
#include "../ParabellumFramework/GraphicsDevice.h"
#include "../ParabellumFramework/InputDevice.h"
//#include "Timer.h"
using namespace ParabellumFramework;
using namespace ParabellumFramework::Resources;
using namespace ParabellumFramework::Graphics;
using namespace ParabellumFramework::IO;
namespace ParabellumEngine
{
namespace System
{
class XYZ_API SystemInstance
{
private:
ResourceManager* m_resourceManager;
GraphicsDevice* m_graphicsDevice;
InputDevice* m_inputDevice;
//Timer* m_time;
public:
SystemInstance() {}
SystemInstance(SystemInstance&) {}
~SystemInstance() {}
virtual void Initialize() = 0;
virtual void Release() = 0;
virtual void Draw() = 0;
virtual void Update() = 0;
virtual EUINT32 Initialize(
_IO_ ResourceManager* pResource, _IO_ GraphicsDevice* pGraphics, _IN_ InputDevice* pInput) final
{
m_resourceManager = pResource;
m_graphicsDevice = pGraphics;
m_inputDevice = pInput;
//m_time = pTime;
Initialize();
return SystemCodes::SUCCESS;
}
protected:
ResourceManager* GetResourceManager()
{
return m_resourceManager;
}
GraphicsDevice* GetGraphicsDevice()
{
return m_graphicsDevice;
}
InputDevice* GetInputDevice()
{
return m_inputDevice;
}
/*
Timer* GetTime()
{
return m_time;
}
*/
};
}
}
#endif | [
"szuplak@gmail.com"
] | szuplak@gmail.com |
4498119b0f69cef176503716007c1d03e892b3a6 | a5880ede88b3dfe17c4e1213b27ebc7b2802e1e0 | /443.cpp | 0cdb5dea282cddb3485822ebe4521f8058b1b651 | [] | no_license | sblackstone/project_euler_solutions | 401a06924c63da8261272375683e037c2e96667c | 0146a384c8b7cee5f239d162bc0288cff6668359 | refs/heads/master | 2021-11-12T14:21:07.154788 | 2021-10-25T16:34:24 | 2021-10-25T16:34:24 | 5,906,334 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,300 | cpp | #include <iostream>
#include <bitset>
#include <cmath>
#include <vector>
#define ulong unsigned long long
using namespace std;
ulong gcd(ulong u, ulong v)
{
int shift;
/* GCD(0,v) == v; GCD(u,0) == u, GCD(0,0) == 0 */
if (u == 0) return v;
if (v == 0) return u;
/* Let shift := lg K, where K is the greatest power of 2
dividing both u and v. */
for (shift = 0; ((u | v) & 1) == 0; ++shift) {
u >>= 1;
v >>= 1;
}
while ((u & 1) == 0)
u >>= 1;
/* From here on, u is always odd. */
do {
/* remove all factors of 2 in v -- they are not common */
/* note: v is not zero, so while will terminate */
while ((v & 1) == 0) /* Loop X */
v >>= 1;
/* Now u and v are both odd. Swap if necessary so u <= v,
then set v = v - u (which is even). For bignums, the
swapping is just pointer movement, and the subtraction
can be done in-place. */
if (u > v) {
ulong t = v; v = u; u = t;} // Swap u and v.
v = v - u; // Here v >= u.
} while (v != 0);
/* restore common factors of 2 */
return u << shift;
}
int main() {
ulong gn = 12;
ulong n = 4;
while (n <= 1000000000) {
n++;
gn += gcd(n,gn);
}
cout << gn << endl;
} | [
"sblackstone@gmail.com"
] | sblackstone@gmail.com |
be81b738c4b5ea3de20880ac069cd650dacfdb1c | 0c6bec29bbeea5c6a8d88514dd271fd1a5dc1745 | /w1/at_home/graph.cpp | 9555502e98742a1c261fe6ca4317e6445930e9b1 | [] | no_license | chevashiIP/OOP244 | 8f9b1be2f049451d19b829b3bd7828c3addd4daf | e8edfbf32691aefbcf7c125cd0d9dffd5e55fbcf | refs/heads/main | 2023-03-13T18:50:11.350329 | 2021-03-05T20:37:26 | 2021-03-05T20:37:26 | 344,265,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,064 | cpp | #include <iostream>
#include "graph.h"
#include "tools.h"
using namespace std;
namespace sict {
void printGraph(int samples[], int noOfSamples) {
int max = findMax(samples, noOfSamples);
cout << "Graph:" << endl;
for (int i = 0; i < noOfSamples; i++) {
printBar(samples[i], max);
}
}
// prints a scaled bar relevant to the maximum value in samples array
void printBar(int val, int max) {
int i;
for (i = 0; i < 70 * val / max; i++) {
cout << "*";
}
cout << " " << val << endl;
}
// Fills the samples array with the statistic samples
void getSamples(int samples[], int noOfSamples) {
int i;
for (i = 0; i < noOfSamples; i++) {
cout << (i + 1) << "/" << noOfSamples << ": ";
samples[i] = getInt(1, 1000000);
}
}
// finds the largest sample in the samples array, if it is larger than 70,
// otherwise it will return 70.
int findMax(int samples[], int noOfSamples) {
int max = samples[0];
int i;
for (i = 1; i < noOfSamples; i++) {
if (max < samples[i]) max = samples[i];
}
return max < 70 ? 70 : max;
}
} | [
"32250543+SomeRandomDude456@users.noreply.github.com"
] | 32250543+SomeRandomDude456@users.noreply.github.com |
87203cc18ad415ec3f2052fba58b1282aa1268bc | e0290b81913feec28ba84d91290592db9677888d | /LeetCode/13_10.cc | c1371d5b1687071f710e0778ce1096c132e884d8 | [] | no_license | shashwatnayak/Codeforces | 24e84f1d9cf15cefbbfae378f982b00b508c3ef6 | 0f9c3e77038a5a1a6e17d18863427cad5615140d | refs/heads/master | 2023-08-19T03:11:56.320841 | 2021-06-09T16:31:39 | 2021-06-09T16:31:39 | 261,502,925 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,350 | cc | // is valid palindrome
class Solution {
public:
bool isPalindrome(string s) {
int l = 0;
int r = s.size()-1;
while(l < r){
if(!isalnum(s[l]))l++;
else if(!isalnum(s[r]))r--;
else if(tolower(s[l])!=tolower(s[r]))return false;
else{
l++;
r--;
}
}
return true;
}
};
// 3 sum - checks for duplicates as well
// one more method using hash
class Solution {
public:
vector<vector<int> > vvk;
vector<vector<int>> threeSum(vector<int>& nums) {
if(nums.size()<3){
return vvk;
}
sort(nums.begin(),nums.end());
int n = nums.size();
//int i = 0;
for(int i = 0;i<n-1;i++){
if(nums[i] > 0) break;
if(i>0 && nums[i] == nums[i-1])continue;
int l = i+1;
int r = n-1;
long int x = nums[i];
while(l<r){
if((x + nums[l] + nums[r])==0) {
vector<int>v3;
v3.push_back(x);
v3.push_back(nums[l]);
v3.push_back(nums[r]);
vvk.push_back(v3);
v3.clear();
while( l < r && nums[l] == nums[l+1])l++;
while( l <r && nums[r] == nums[r-1])r--;
l++;
r--;
}else if((x + nums[l] + nums[r]) < 0){
l++;
}else{
r--;
}
}
}
return vvk;
}
};
// if a straight line
class Solution {
public:
bool checkStraightLine(vector<vector<int>>& coordinates) {
int cz = coordinates.size();
if (cz == 1) return false; // One point only, not a straight line
if (cz == 2) return true; // Two points only, always a straight line
int x0 = coordinates[0][0], y0 = coordinates[0][1];
int dx = coordinates[1][0] - x0, dy = coordinates[1][1] - y0;
for (int i = 1; i < cz; i++) { // Checking two point formula for each point with the first point
int x = coordinates[i][0], y = coordinates[i][1];
if (dx * (y - y0) != dy * (x - x0)) // Two point formula of line, if (x2-x1)*(y1-y0) = (x1-x0)(y2-y1), then a straight line, otherwise not
return false;
}
return true;
}
};
//Reverse integer
// also checks integer overflows
class Solution {
public:
int reverse(int x) {
bool sign = false;
if(x<0){
sign = true;
x = abs(x);
}
long int rev = 0;
while(x!=0){
rev = rev*10 + (x%10);
x = x/10;
}
if(rev > INT_MAX || rev < INT_MIN){
return false;
}
if(sign){
return (-1)*rev;
}
return rev;
}
};
//Add Binary Number
class Solution {
public:
string addBinary(string a, string b) {
string ans = "";
int carry = 0;
int i = a.size() - 1;
int j = b.size() - 1;
while(i >= 0 || j>=0 || carry ){
if(i>=0 && a[i--] == '1')carry++;
if(j>=0 && b[j--] == '1')carry++;
if(carry%2 == 0){
ans.push_back('0');
}else{
ans.push_back('1');
}
carry = carry/2;
}
reverse(ans.begin(),ans.end());
return ans;
}
};
//Palindrome number
class Solution {
public:
bool isPalindrome(int x) {
long rev = 0;
int c = x;
if(x<0){
return false;
}
if(x==0){
return true;
}
if(x%10==0){
return false;
}
while(x!=0){
rev = rev*10 + (x%10);
x = x/10;
}
//cout<<rev<<endl<<x;
if(rev == c){
return true;
}
return false;
}
};
| [
"shashwatnayak@outlook.com"
] | shashwatnayak@outlook.com |
75236f8404822bf09b71df23fdd0dcfb0aff4b22 | c7ee01ea74cbfa2f663d284b986ed8e850bed660 | /Project1/Source.cpp | 9f68a183c09d24124d324ca87673b9d39b3da75a | [] | no_license | DenialKreso/PR1-Vjezbe2 | cb57077ab7105349c654da7c2c6d619490435416 | e4c66724fead1111e9ec3885a32587dbb88dbe06 | refs/heads/main | 2023-03-20T09:59:06.769086 | 2021-03-10T19:06:11 | 2021-03-10T19:06:11 | 346,457,840 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,422 | cpp | //Napisati program koji će omogućiti korisniku da unese veličinu n jednodimenzionalnog dinamičkog niza integer vrijednosti(n > 2).
//Napisati rekurzivnu funkciju koja će taj niz puniti serijom brojeva 1, 3, 3, 9, 27, ..., tako da je svaki slijedeći broj jednak umnosku dva prethodna broja(Prva dva elementa su 1 i 3.)
//Rekurzija se prekida kad se popuni cijeli niz ili kad se desi overflow na integer varijabli.
//Zatim napraviti drugu rekurzivnu funkciju koja će izračunati zbir svih elemenata tog niza(Voditi računa o tipu podataka zbog veličine broja).
//U ovom zadatku je zabranjeno indexirati elemente niza uglastim zagradama.Obavezno koristiti aritmetiku pokazivača
#include <iostream>
#include <cmath>
using namespace std;
int puniNiz(int* niz, int pocetak) {
int duzinaNiza = sizeof niz;
if (duzinaNiza == pocetak)
return 0;
niz[pocetak] = niz[pocetak - 1] * niz[pocetak - 2];
return puniNiz(niz, pocetak + 1);
}
int suma(int* niz, int vel) {
if (vel == 0)
{
return 0;
}
return niz[vel - 1] + suma(niz, vel - 1);
}
int y6main() {
int vel;
int* niz;
do
{
cout << "Broj mora biti veci od 2" << endl;
cin >> vel;
} while (vel <= 2);
niz = new int[vel];
niz[0] = 1;
niz[1] = 3;
puniNiz(niz, 2);
for (int i = 0; i < vel; i++)
{
cout << niz[i] << endl;
}
cout << "**************************" << endl;
cout << "Suma je : " << suma(niz, vel);
return 0;
} | [
"denialkreso@gmail.com"
] | denialkreso@gmail.com |
9c38d4227604d3da1b4becba290f8f890431e5bd | 42f9220fe969e13d0c9ecffdf19305029e68d40a | /bethe-xxz/generic.cc | eb0d22a3efdbd164fb492f40e77541da32f13483 | [
"MIT"
] | permissive | robhagemans/bethe-solver | 0eb9cb1c5af1de0faf52197c7f4c95d768594168 | 77b217c6cc23842b284ecd2d7b01fe28310cc32e | refs/heads/master | 2021-01-17T12:20:49.692478 | 2020-09-05T15:19:13 | 2020-09-05T15:19:13 | 24,987,052 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,354 | cc | #include "generic.h"
// monikers
const string mon_File = "v20105";
const string mon_Base = "base";
const string mon_Delta = "D";
const string mon_Length = "N";
const string mon_LeftDown = "M";
const string mon_RightDown = "R";
const string mon_Spinon = "s";
const string sep_Name = "_";
const string sep_Final = ".";
const string sep_Vector = "-";
const char* exc_Ferro = "ferromagnetic and XX0 chains not supported"; // generic contructors
const char* exc_InfiniteRaps = "only infinite rapidities for the isotropic chain";
const char* exc_NegativeAnisotropy = "negative or zero anisotropy"; //name()
const char* exc_BadName = "cannot parse the moniker";
const char* exc_ThresholdOne = "contribution threshold must be less than one";
const char* exc_NullPointer = "null pointer passed";
const char* exc_NotConverged = "bethe equations not converged"; //solve()
const char* exc_Deviated = "bethe strings deviated"; //solve()
/** generic construction **/
/** new chain **/
Chain* newChain (const double delta, const int chain_length, const int cutoff_types)
{
const string here = "newChain";
if (delta > 1.0) return new Gap_Chain (delta, chain_length, cutoff_types);
if (delta == 1.0) return new XXX_Chain (chain_length, cutoff_types);
if ((delta < 1.0) && (delta > 0.0)) return new XXZ_Chain (delta, chain_length);
throw Exception (here, exc_Ferro);
}
/** new base **/
Base* newBase (const Chain* const p_chain, const BaseData& base_data) {
const string here = "newBase";
if (p_chain->delta() == 1.0) return new XXX_Base (p_chain, base_data);
// if (number_infinite_rapidities) throw Exception (here, exc_InfiniteRaps);
if (p_chain->delta() > 1.0) return new Gap_Base (p_chain, base_data);
if ((p_chain->delta() < 1.0) && (p_chain->delta() > 0.0)) return new XXZ_Base (p_chain, base_data);
throw Exception (here, exc_Ferro);
}
Base* newBase (const Chain* const p_chain, const vector<int>& base_vec, const int number_spinons, const int number_infinite_rapidities)
{
const string here = "newBase";
if (p_chain->delta() == 1.0) return new XXX_Base (p_chain, base_vec, number_spinons, number_infinite_rapidities);
if (number_infinite_rapidities) throw Exception (here, exc_InfiniteRaps);
if (p_chain->delta() > 1.0) return new Gap_Base (p_chain, base_vec, number_spinons);
if ((p_chain->delta() < 1.0) && (p_chain->delta() > 0.0)) return new XXZ_Base (p_chain, base_vec, number_spinons);
throw Exception (here, exc_Ferro);
}
Base* newBase (const Chain* const p_chain, const int number_down, const vector<int>& base_vec, const int number_spinons, const int number_infinite_rapidities)
{
const string here = "newBase";
if (p_chain->delta() == 1.0) return new XXX_Base (p_chain, number_down, base_vec, number_spinons, number_infinite_rapidities);
if (number_infinite_rapidities) throw Exception (here, exc_InfiniteRaps);
if (p_chain->delta() > 1.0) return new Gap_Base (p_chain, number_down, base_vec, number_spinons);
if ((p_chain->delta() < 1.0) && (p_chain->delta() > 0.0)) return new XXZ_Base (p_chain, number_down, base_vec, number_spinons);
throw Exception (here, exc_Ferro);
}
Base* newGroundBase (const Chain* const p_chain, const int number_down)
{
const string here = "newGroundBase";
if (p_chain->delta() > 1.0) return new Gap_Base (p_chain, number_down);
if (p_chain->delta() == 1.0) return new XXX_Base (p_chain, number_down);
if ((p_chain->delta() < 1.0) && (p_chain->delta() > 0.0)) return new XXZ_Base (p_chain, number_down);
throw Exception (here, exc_Ferro);
}
/** new state **/
State* newGroundState (const Base* const p_base)
{
const string here = "newGroundState";
if (p_base->p_chain->delta() > 1.0) return new Gap_State (p_base);
if (p_base->p_chain->delta() == 1.0) return new XXX_State (p_base);
if ((p_base->p_chain->delta() < 1.0) && (p_base->p_chain->delta() > 0.0)) return new XXZ_State (p_base);
throw Exception (here, exc_Ferro);
}
State* newState (const Base* const p_base, const long long int id)
{
const string here = "newState";
if (p_base->p_chain->delta() > 1.0) return new Gap_State (p_base, id);
if (p_base->p_chain->delta() == 1.0) return new XXX_State (p_base, id);
if ((p_base->p_chain->delta() < 1.0) && (p_base->p_chain->delta() > 0.0)) return new XXZ_State (p_base, id);
throw Exception (here, exc_Ferro);
}
State* newState (const Base* const p_base, const vector<Young>& shifts)
{
const string here = "newState";
if (p_base->p_chain->delta() > 1.0) return new Gap_State (p_base, shifts);
if (p_base->p_chain->delta() == 1.0) return new XXX_State (p_base, shifts);
if ((p_base->p_chain->delta() < 1.0) && (p_base->p_chain->delta() > 0.0)) return new XXZ_State (p_base, shifts);
throw Exception (here, exc_Ferro);
}
/** clone **/
// TODO: replace by State::clone()
State* copy (State* const p_state)
{
const string here = "State* copy";
if (!p_state) throw Exception (here, exc_NullPointer);
if (p_state->p_chain->delta() > 1.0) return new Gap_State ( *( (Gap_State*) p_state ));
if (p_state->p_chain->delta() == 1.0) return new XXX_State ( *( (XXX_State*) p_state ));
if ((p_state->p_chain->delta() < 1.0) && (p_state->p_chain->delta() > 0.0)) return new XXZ_State ( *( (XXZ_State*) p_state ));
throw Exception (here, exc_Ferro);
}
/** file naming conventions **/
/** parse names **/
string nameFromValue (const string moniker, const REAL value)
{
stringstream namestream;
namestream << sep_Name << moniker << value;
return namestream.str();
}
string nameFromValue (const string moniker, const int value, const int width)
{
stringstream namestream;
namestream << sep_Name << moniker;
if (width) {
namestream.width (width);
namestream.fill('0');
}
namestream << value;
return namestream.str();
}
string nameFromValue (const string moniker, const vector<int>& value)
{
stringstream namestream;
namestream << sep_Name << moniker;
for (int i=0; i<value.size(); ++i) namestream << sep_Vector << value[i];
return namestream.str();
}
int intValueFromName(const string name, const string moniker)
{
const string here = "intValueFromName";
int length= moniker.length() + sep_Name.length();
// find anisotropy delta
int start = name.find(sep_Name + moniker, 0);
int finish = name.find(sep_Name, start+length); // number ends at an underscore
if (finish == string::npos) finish = name.find(sep_Final, start+length); // or at a dot
if ((start==string::npos) || (finish==string::npos)) throw Exception(here, exc_BadName, moniker);
return atoi(name.substr(start+length, finish-start-length).c_str());
}
REAL realValueFromName(const string name, const string moniker)
{
const string here = "realValueFromName";
int length = moniker.length() + sep_Name.length();
// find anisotropy delta
int start = name.find(sep_Name + moniker, 0);
int finish = name.find(sep_Name, start+length); // number ends at an underscore
if ((start==string::npos) || (finish==string::npos)) throw Exception(here, exc_BadName, moniker);
return atof(name.substr(start+length, finish-start-length).c_str());
}
string valueFromName(const string name, const string moniker)
{
const string here = "valueFromName";
int length = moniker.length() + sep_Name.length();
// find anisotropy delta
int start = name.find(sep_Name + moniker, 0);
int finish = name.find(sep_Name, start+length); // number ends at an underscore
if (finish == string::npos) finish = name.find(sep_Final, start+length); // or at a dot
if (finish == string::npos) finish = name.length(); // or at the end
if ((start==string::npos) || (finish==string::npos)) throw Exception(here, exc_BadName, moniker);
return name.substr(start+length, finish-start-length);
}
/** base name **/
string name(const BaseData& base_data)
{
stringstream the_name;
//the_name.precision(3);
the_name << nameFromValue(mon_RightDown, base_data.number_magnons) << nameFromValue(mon_Spinon, base_data.number_spinons) << nameFromValue(mon_Base, base_data.its_structure);
return the_name.str();
}
string name(const Base* const p_base)
{
stringstream the_name;
//the_name.precision(3);
the_name << nameFromValue(mon_RightDown, p_base->numberDown()) << nameFromValue(mon_Spinon, p_base->numberSpinons()) << nameFromValue(mon_Base, p_base->structure());
return the_name.str();
}
/** chain name **/
string name(const Chain* const p_chain, const int number_down)
{
const char* here = "name";
stringstream description;
description << sep_Name << mon_File;
if (p_chain->delta() <= 0) throw Exception (here, exc_NegativeAnisotropy);
if (p_chain->delta() == 1.0) description << "_xxx";
if (p_chain->delta() > 1.0) description << "_xxz-gap";
if (p_chain->delta() < 1.0) description << "_xxz";
description << nameFromValue(mon_Delta, p_chain->delta());
description << nameFromValue(mon_Length, p_chain->length());
if (number_down) description << nameFromValue (mon_LeftDown, number_down, fieldWidth(p_chain->length()) ); // all fields from 1 to N/2 equally wide
return description.str();
}
// convert a name into a chain
Chain* newChain (const string name, const int cutoff_types)
{
REAL delta = realValueFromName (name, mon_Delta);
int chain_length = intValueFromName (name, mon_Length);
return newChain (delta, chain_length, cutoff_types);
}
// convert a name into a base
Base* newBase (const string name, Chain*& p_chain)
{
const string here = "newBase";
// if no chain is defined, get our own (note: passing a literal zero for Chain* guarantees trouble, you need to keep the result!)
int right_number_down = intValueFromName(name, mon_RightDown); // number of down spins (right side) incl. infinite
int number_spinons = intValueFromName(name, mon_Spinon);
vector<string> base_elements = explode(valueFromName(name, mon_Base), sep_Vector);
// if necessary, create the chain
if (!p_chain) p_chain = newChain(name, base_elements.size()+1);
// find the number of infinite rapidities & create a base vector
int number_down_found=0;
vector<int> base_vec (base_elements.size());
for (int i=0; i<base_elements.size(); ++i) {
base_vec[i] = atoi(base_elements[i].c_str());
// this is only necessary due to the silly way I implemented the constructors.
number_down_found += base_vec[i] * p_chain->stringLength(i);
}
/// TODO: implement a contructor that takes base_vec on its word as a boy scout and calculates the number of infinite raps by itself from number_down.
return newBase(p_chain, right_number_down, base_vec, number_spinons, right_number_down - number_down_found);
}
/// BaseData constructor?
BaseData readBaseData (const string name) {
int right_number_down = intValueFromName(name, mon_RightDown); // number of down spins (right side) incl. infinite
int number_spinons = intValueFromName(name, mon_Spinon);
vector<string> base_elements = explode(valueFromName(name, mon_Base), sep_Vector);
int number_down_found=0;
vector<int> base_vec (base_elements.size());
for (int i=0; i<base_elements.size(); ++i) {
base_vec[i] = atoi(base_elements[i].c_str());
// this is only necessary due to the silly way I implemented the constructors.
// number_down_found += base_vec[i] * p_chain->stringLength(i);
}
return BaseData(right_number_down, base_vec, NOT_SET, number_spinons);
}
/** scan through bases, particle/spinon ordered **/
vector<BaseData> allNewBases (
const Chain* const p_chain, const int number_down,
const int max_string_length,
const int uptoinc_number_particles, const int uptoinc_number_spinons,
const int max_infinite
)
{
vector<BaseData> all_bases;
vector<int> basevec (1, 0); // set dummy first element
int number_particles = 0;
int last_type_increased = 0;
bool limits_exceeded = false;
//int max_infinite = (p_chain->delta() == 1.0) ?2 :0;
while (number_particles <= min(uptoinc_number_particles, number_down)) {
limits_exceeded = false;
// every higher excitation contributes itself as a particle
int number_higher_particles = 0;
for (int i=1; i < basevec.size(); ++i) number_higher_particles += basevec[i] ;
if (number_higher_particles > number_particles) limits_exceeded=true; // all particles must be higher particles
// we must fit the available number of particles exactly, so we need an even number of spinons+holes remaining.
else if (number_higher_particles == number_particles) {
for (int number_spinons = 0; number_spinons <= min(uptoinc_number_spinons, number_down); ++number_spinons ) {
for (int number_infinite=0; number_infinite <= max_infinite; ++number_infinite){
try {
// try to make a base, will throw if it can't
// NOTE: this constructor calculates the number of type-1 particles from the other info
Base* p_base = newBase(p_chain, number_down, basevec, number_spinons, number_infinite);
// but keep only the base data (as calculated by the constructor!)
BaseData base_data = *p_base;
all_bases.push_back(base_data);
}
catch (Exception exc) {
if (exc.error == exc_BlackburnLancashire
|| exc.error == exc_TooMany) {
// too many holes for this base , i.e. not enough space for spinons. ignore.
}
else throw;
}
}
}
}
// find out where to increase
int number_excited;
int type_to_increase = 1;
if (limits_exceeded) type_to_increase = last_type_increased +1;
if ((type_to_increase >= p_chain->numberTypes()) || (p_chain->stringLength(type_to_increase) > max_string_length )) {
// we're out of bases for this number of particles. increase and reset p_base->
++number_particles;
basevec.clear();
basevec.push_back(0); // set the dummy first element
type_to_increase = 0; // increase only the dummy element, aka start with the trivial p_base->
}
// increase.
for (int type=0; type < type_to_increase; ++type) basevec[type] = 0;
if (type_to_increase >= basevec.size()) basevec.push_back(0);
++basevec[type_to_increase];
last_type_increased = type_to_increase;
}
return all_bases;
}
/** generic solve **/
State* solve(
State* const p_state_in,
const REAL deviation_threshold,
const bool deviate
)
{
const char* here = "::solve()";
// don't clone, just copy
// cloning only necessary when deviating
// TODO: by separating id info from solving and roots, we could
// do this as fast and much more elegantly.
State* p_state = p_state_in;
// solve the Bethe Equations up to convergence
if (p_state->solve()) {
// our state has converged
REAL deviation = p_state->stringDeviation();
// our core business: calculate form factor
if (deviation < deviation_threshold) return p_state;
else if (deviate && p_state->p_chain->delta()==1.0) {
XXXDeviatedState* p_dev_state = new XXXDeviatedState ( *p_state );
if (!p_dev_state->solve()) {
// we haven't converged! (counts as deviated)
stringstream message;
message << "deviance not converged, convergence "<<p_dev_state->convergence<< " threshold "<< State::precision;
// clean up
delete p_dev_state;
throw Exception(here, exc_Deviated, message.str());
}
else return p_dev_state;
}
else {
stringstream message;
message << "non-deviable, deviation threshold "<<deviation_threshold;
throw Exception(here, exc_Deviated, message.str());
}
}
else {
stringstream message;
message << "convergence "<<p_state->convergence<< " threshold "<< State::precision;
throw Exception(here, exc_NotConverged, message.str());
}
}
| [
"robhagemans@users.noreply.github.com"
] | robhagemans@users.noreply.github.com |
2b8c3de018492b8c71b7c89f12265c8a0d067d82 | 76e6270c76bd52d8addf3ac88493a6760cacfdd9 | /libraries/tarhSensors/TPH_board.h | d82e0346ec623942f972559a4dc430f8702e1b0f | [] | no_license | Tarrask/Arduino | b5c2f358f6c646dff1cd9d26c90b2e40861fdcec | f15a59b731981594997db7f2eaba251771ce573a | refs/heads/master | 2020-04-27T18:24:12.452206 | 2015-08-03T09:01:00 | 2015-08-03T09:01:00 | 39,798,523 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 872 | h | #ifndef TPH_board_H
#define TPH_board_H
#include "Arduino.h"
struct TPH_data {
int16_t temperature;
int32_t pressure;
int16_t humidity;
};
class TPH_board {
public:
TPH_board();
void begin();
TPH_data readSensors();
private:
void beginSHT21();
void beginBMP180();
void startHumidityReading();
int16_t readTemperature();
int32_t readPressure();
int16_t readHumidity();
uint8_t checkCRC(uint8_t b1, uint8_t b2, uint8_t checksum);
int8_t read8(uint8_t address, uint8_t reg);
int16_t read16(uint8_t reg);
uint16_t read16u(uint8_t reg);
void write8u(uint8_t address, uint8_t reg, uint8_t value);
int32_t readData(uint8_t key);
int16_t ac1, ac2, ac3;
uint16_t ac4, ac5, ac6;
int16_t b1, b2;
int32_t b3, b5, b6;
uint32_t b4, b7;
int16_t mb, mc, md;
int32_t x1 , x2, x3;
};
#endif // TPH_board_H | [
"damien.plumettaz@bluewin.ch"
] | damien.plumettaz@bluewin.ch |
6374097258651be44381c1897949baeb735742ff | 44ab57520bb1a9b48045cb1ee9baee8816b44a5b | /Assist/Code/Toolset/CoreTools/ExportTest/CoreTools/Detail/CopyUnshared/AnimationCopyUnsharedMacroImpl.h | 05a3062013ef8f22e0ebdd482ce9899abbb25f53 | [
"BSD-3-Clause"
] | permissive | WuyangPeng/Engine | d5d81fd4ec18795679ce99552ab9809f3b205409 | 738fde5660449e87ccd4f4878f7bf2a443ae9f1f | refs/heads/master | 2023-08-17T17:01:41.765963 | 2023-08-16T07:27:05 | 2023-08-16T07:27:05 | 246,266,843 | 10 | 0 | null | null | null | null | GB18030 | C++ | false | false | 849 | h | /// Copyright (c) 2010-2023
/// Threading Core Render Engine
///
/// 作者:彭武阳,彭晔恩,彭晔泽
/// 联系作者:94458936@qq.com
///
/// 标准:std:c++20
/// 版本:0.9.1.2 (2023/07/28 15:19)
#ifndef EXPORT_TEST_ANIMATION_COPY_UNSHARED_MACRO_IMPL_H
#define EXPORT_TEST_ANIMATION_COPY_UNSHARED_MACRO_IMPL_H
#include "Animation/AnimationDll.h"
namespace Animation
{
class ANIMATION_HIDDEN_DECLARE AnimationCopyUnsharedMacroImpl final
{
public:
using ClassType = AnimationCopyUnsharedMacroImpl;
public:
explicit AnimationCopyUnsharedMacroImpl(int count) noexcept;
CLASS_INVARIANT_DECLARE;
NODISCARD int GetCount() const noexcept;
void SetCount(int aCount) noexcept;
private:
int count;
};
}
#endif // EXPORT_TEST_ANIMATION_COPY_UNSHARED_MACRO_IMPL_H | [
"94458936@qq.com"
] | 94458936@qq.com |
8651f5478d3a38b202b0d4397a887ab52b983fe8 | ec0be2417834e2ab2380912b25089b56c6b5e907 | /src/controller/driver/LXESP32DMX/LXHardwareSerial.cpp | e097622c39e3652d6adc7b52bc3cc5120fe961a5 | [] | no_license | bildspur/aben | 39a76a3f9eae1768bd30b5cb90864ce0c5e45f52 | aecfaebf3bf181a05002e0761fa87ae8be673913 | refs/heads/master | 2021-11-23T20:43:45.205091 | 2021-11-15T14:30:01 | 2021-11-15T14:30:01 | 158,379,496 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,903 | cpp | /**************************************************************************/
/*!
@file LXHardwareSerial.cpp
@author Claude Heintz
@license BSD (see LXESP32DMX.h)
@copyright 2017 by Claude Heintz
Exposes functionality in HardwareSerial class for LXESP32DMX driver
@section HISTORY
v1.0 - First release
*/
/**************************************************************************/
#include "LXHardwareSerial.h"
#include "freertos/portmacro.h"
#include "esp_task_wdt.h"
// uart_struct_t is also defined in esp32-hal-uart.c
// defined here because to access fields in uart_t* in the following mods
struct uart_struct_t {
uart_dev_t * dev;
#if !CONFIG_DISABLE_HAL_LOCKS
xSemaphoreHandle lock;
#endif
uint8_t num;
xQueueHandle queue;
intr_handle_t intr_handle;
};
#if CONFIG_DISABLE_HAL_LOCKS
#define UART_MUTEX_LOCK()
#define UART_MUTEX_UNLOCK()
#else
#define UART_MUTEX_LOCK() do {} while (xSemaphoreTake(uart->lock, portMAX_DELAY) != pdPASS)
#define UART_MUTEX_UNLOCK() xSemaphoreGive(uart->lock)
#endif
uint8_t testCtr = 0;
/***************************** privateDelayMicroseconds allows sendBreak to be called on non-main task/thread
*
* reason for private function is
* portENTER_CRITICAL_ISR has a spin lock
* delayMicroseconds() can only be called on main loop
* because micros() is called on main loop task
*
*/
portMUX_TYPE privateMicrosMux = portMUX_INITIALIZER_UNLOCKED;
unsigned long IRAM_ATTR privateMicros()
{
static unsigned long lccount = 0; //because this depends of these static variables does each task need a private micros()/delayMicroseconds()?
static unsigned long overflow = 0;
unsigned long ccount;
portENTER_CRITICAL_ISR(&privateMicrosMux);
__asm__ __volatile__ ( "rsr %0, ccount" : "=a" (ccount) );
if(ccount < lccount){
overflow += UINT32_MAX / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ;
}
lccount = ccount;
portEXIT_CRITICAL_ISR(&privateMicrosMux);
return overflow + (ccount / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ);
}
void IRAM_ATTR hardwareSerialDelayMicroseconds(uint32_t us) {
for(int k=0; k<us; k++) { // approximate delay, not a very portable solution
taskYIELD(); // this may or may not allow another task to run
}
// ccount appears to be CPU dependent and task might switch CPUs making Micros invalid
/*
uint32_t m = privateMicros();
if(us){
uint32_t e = (m + us);
if(m > e){ //overflow
while(privateMicros() > e){
NOP();
}
}
while(privateMicros() < e){
NOP();
}
}*/
}
// *****************************
// wait for FIFO to be empty
void IRAM_ATTR uartWaitFIFOEmpty(uart_t* uart) {
if ( uart == NULL ) {
return;
}
uint16_t timeout = 0;
while(uart->dev->status.txfifo_cnt != 0x00) {
timeout++;
if ( timeout > 20000 ) {
break;
}
hardwareSerialDelayMicroseconds(10);
}
}
void IRAM_ATTR uartWaitRxFIFOEmpty(uart_t* uart) {
if ( uart == NULL ) {
return;
}
uint16_t timeout = 0;
while(uart->dev->status.rxfifo_cnt != 0x00) {
timeout++;
if ( timeout > 20000 ) {
break;
}
hardwareSerialDelayMicroseconds(10);
}
}
void IRAM_ATTR uartWaitTXDone(uart_t* uart) {
if ( uart == NULL ) {
return;
}
uint16_t timeout = 0;
while (uart->dev->int_raw.tx_done == 0) {
timeout++;
if ( timeout > 20000 ) {
break;
}
hardwareSerialDelayMicroseconds(10);
}
uart->dev->int_clr.tx_done = 1;
}
void IRAM_ATTR uartWaitTXBrkDone(uart_t* uart) {
if ( uart == NULL ) {
return;
}
while (uart->dev->int_raw.tx_brk_idle_done == 0) {
hardwareSerialDelayMicroseconds(10);
}
uart->dev->int_clr.tx_brk_idle_done = 1;
}
void uartConfigureRS485(uart_t* uart, uint8_t en) {
UART_MUTEX_LOCK();
uart->dev->rs485_conf.en = en;
UART_MUTEX_UNLOCK();
}
void uartConfigureSendBreak(uart_t* uart, uint8_t en, uint8_t len, uint16_t idle) {
UART_MUTEX_LOCK();
uart->dev->conf0.txd_brk = en;
uart->dev->idle_conf.tx_brk_num=len;
uart->dev->idle_conf.tx_idle_num = idle;
UART_MUTEX_UNLOCK();
}
// ****************************************************
// uartConfigureTwoStopBits
// known issue with two stop bits now handled in IDF and Arduino Core
// see
// https://github.com/espressif/esp-idf/blob/master/components/driver/uart.c
// uart_set_stop_bits(), lines 118-127
// see also
// https://esp32.com/viewtopic.php?f=2&t=1431
void uartSetToTwoStopBits(uart_t* uart) {
UART_MUTEX_LOCK();
uart->dev->conf0.stop_bit_num = 1;
uart->dev->rs485_conf.dl1_en = 1;
UART_MUTEX_UNLOCK();
}
void uartEnableBreakDetect(uart_t* uart) {
UART_MUTEX_LOCK();
uart->dev->int_ena.brk_det = 1;
uart->dev->conf1.rxfifo_full_thrhd = 1;
uart->dev->auto_baud.val = 0;
UART_MUTEX_UNLOCK();
}
void uartDisableBreakDetect(uart_t* uart) {
UART_MUTEX_LOCK();
uart->dev->int_ena.brk_det = 0;
UART_MUTEX_UNLOCK();
}
void uartDisableInterrupts(uart_t* uart) {
UART_MUTEX_LOCK();
//uart->dev->conf1.val = 0;
uart->dev->int_ena.val = 0;
uart->dev->int_clr.val = 0xffffffff;
UART_MUTEX_UNLOCK();
}
void uartSetInterrupts(uart_t* uart, uint32_t value) {
UART_MUTEX_LOCK();
uart->dev->int_ena.val = value;
UART_MUTEX_UNLOCK();
}
void uartClearInterrupts(uart_t* uart) {
UART_MUTEX_LOCK();
uart->dev->int_clr.val = 0xffffffff;
UART_MUTEX_UNLOCK();
}
void uartLockMUTEX(uart_t* uart) {
UART_MUTEX_LOCK();
}
void uartUnlockMUTEX(uart_t* uart) {
UART_MUTEX_UNLOCK();
}
LXHardwareSerial::LXHardwareSerial(int uart_nr):HardwareSerial(uart_nr) {}
void LXHardwareSerial::end() {
uartDisableInterrupts(_uart);
if(uartGetDebug() == _uart_nr) {
uartSetDebug(0);
}
// todo: Implement this again with three arguments:
// https://github.com/claudeheintz/LXESP32DMX/issues/25
//uartEnd(_uart);
_uart = 0;
}
void LXHardwareSerial::waitFIFOEmpty() {
uartWaitFIFOEmpty(_uart);
}
void LXHardwareSerial::waitRxFIFOEmpty() {
uartWaitRxFIFOEmpty(_uart);
}
void LXHardwareSerial::waitTXDone() {
uartWaitTXDone(_uart);
}
void LXHardwareSerial::waitTXBrkDone() {
uartWaitTXBrkDone(_uart);
}
void LXHardwareSerial::sendBreak(uint32_t length) {
uint8_t gpioSig;
if( _uart_nr == 1 ) {
gpioSig = U1TXD_OUT_IDX;
} else if( _uart_nr == 2 ) {
gpioSig = U2TXD_OUT_IDX;
} else {
gpioSig = U0TXD_OUT_IDX;
}
//uint32_t save_interrupts = _uart->dev->int_ena.val;
//uartDisableInterrupts(_uart);
esp_intr_disable(_uart->intr_handle);
// detach
pinMatrixOutDetach(_tx_gpio_pin, false, false);
pinMode(_tx_gpio_pin, OUTPUT);
digitalWrite(_tx_gpio_pin, LOW);
hardwareSerialDelayMicroseconds(length);
digitalWrite(_tx_gpio_pin, HIGH);
//reattach
pinMatrixOutAttach(_tx_gpio_pin, gpioSig, false, false);
esp_intr_enable(_uart->intr_handle);
//uartSetInterrupts(_uart, save_interrupts);
}
void LXHardwareSerial::setBaudRate(uint32_t rate) {
uartSetBaudRate(_uart, rate);
}
void LXHardwareSerial::configureRS485(uint8_t en) {
uartConfigureRS485(_uart, en);
}
void LXHardwareSerial::configureSendBreak(uint8_t en, uint8_t len, uint16_t idle) {
uartConfigureSendBreak(_uart, en, len, idle);
}
void LXHardwareSerial::setToTwoStopBits() {
uartSetToTwoStopBits(_uart);
}
void LXHardwareSerial::enableBreakDetect() {
uartEnableBreakDetect(_uart);
}
void LXHardwareSerial::disableBreakDetect() {
uartDisableBreakDetect(_uart);
}
void LXHardwareSerial::clearInterrupts() {
uartClearInterrupts(_uart);
}
void LXHardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, int8_t txPin, bool invert) {
_tx_gpio_pin = txPin;
HardwareSerial::begin(baud, config, rxPin, txPin, invert);
}
| [
"florian@bildspur.ch"
] | florian@bildspur.ch |
cd57e5cfaa3f9e707129b0cb12d80b3fd6f7e5e3 | 85ee42ebd3f49481acafc9022bd372021117e5ee | /src/cpp/flann/algorithms/index_abstractions.h | a7721100615aac6992337253292d90e2b92afe8a | [
"BSD-3-Clause"
] | permissive | barbaraplume/flann | 2d7d0342aded034a86bd85227099e9ea989b2167 | 82f2b31e75cfbd17f2a6add4d2ae8f86d991350e | refs/heads/master | 2020-12-30T18:38:39.139969 | 2012-10-01T18:43:25 | 2012-10-01T18:43:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,271 | h | /***********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved.
* Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*************************************************************************/
#ifndef INDEX_ABSTRACTIONS_H
#define INDEX_ABSTRACTIONS_H
#include "flann/util/matrix.h"
#include "flann/util/params.h"
#include "flann/algorithms/dist.h"
namespace flann {
class IndexBase
{
public:
virtual ~IndexBase() {};
virtual void buildIndex() = 0;
virtual size_t veclen() const = 0;
virtual size_t size() const = 0;
virtual flann_algorithm_t getType() const = 0;
virtual int usedMemory() const = 0;
virtual IndexParams getParameters() const = 0;
virtual void loadIndex(FILE* stream) = 0;
virtual void saveIndex(FILE* stream) = 0;
};
template<typename ElementType_, typename DistanceType_ = typename Accumulator<ElementType_>::Type>
class TypedIndexBase : public IndexBase
{
public:
typedef ElementType_ ElementType;
typedef DistanceType_ DistanceType;
virtual void addPoints(const Matrix<ElementType>& points, float rebuild_threshold) = 0;
virtual void removePoint(size_t index) = 0;
virtual int knnSearch(const Matrix<ElementType>& queries,
Matrix<int>& indices,
Matrix<DistanceType>& dists,
size_t knn,
const SearchParams& params) = 0;
virtual int knnSearch(const Matrix<ElementType>& queries,
std::vector< std::vector<int> >& indices,
std::vector<std::vector<DistanceType> >& dists,
size_t knn,
const SearchParams& params) = 0;
virtual int radiusSearch(const Matrix<ElementType>& queries,
Matrix<int>& indices,
Matrix<DistanceType>& dists,
DistanceType radius,
const SearchParams& params) = 0;
virtual int radiusSearch(const Matrix<ElementType>& queries,
std::vector< std::vector<int> >& indices,
std::vector<std::vector<DistanceType> >& dists,
DistanceType radius,
const SearchParams& params) = 0;
};
/**
* Class that wraps an index and makes it a polymorphic object.
*/
template<typename Index>
class IndexWrapper : public TypedIndexBase<typename Index::ElementType, typename Index::DistanceType>
{
public:
typedef typename Index::ElementType ElementType;
typedef typename Index::DistanceType DistanceType;
IndexWrapper(Index* index) : index_(index)
{
};
virtual ~IndexWrapper()
{
delete index_;
}
void buildIndex()
{
index_->buildIndex();
}
void buildIndex(const Matrix<ElementType>& dataset)
{
index_->buildIndex(dataset);
}
void addPoints(const Matrix<ElementType>& points, float rebuild_threshold = 2)
{
index_->addPoints(points, rebuild_threshold);
}
void removePoint(size_t index)
{
index_->removePoint(index);
}
size_t veclen() const
{
return index_->veclen();
}
size_t size() const
{
return index_->size();
}
flann_algorithm_t getType() const
{
return index_->getType();
}
int usedMemory() const
{
return index_->usedMemory();
}
IndexParams getParameters() const
{
return index_->getParameters();
}
void loadIndex(FILE* stream)
{
index_->loadIndex(stream);
}
void saveIndex(FILE* stream)
{
index_->saveIndex(stream);
}
Index* getIndex() const
{
return index_;
}
int knnSearch(const Matrix<ElementType>& queries,
Matrix<int>& indices,
Matrix<DistanceType>& dists,
size_t knn,
const SearchParams& params)
{
return index_->knnSearch(queries, indices,dists, knn, params);
}
int knnSearch(const Matrix<ElementType>& queries,
std::vector< std::vector<int> >& indices,
std::vector<std::vector<DistanceType> >& dists,
size_t knn,
const SearchParams& params)
{
return index_->knnSearch(queries, indices,dists, knn, params);
}
int radiusSearch(const Matrix<ElementType>& queries,
Matrix<int>& indices,
Matrix<DistanceType>& dists,
DistanceType radius,
const SearchParams& params)
{
return index_->radiusSearch(queries, indices, dists, radius, params);
}
int radiusSearch(const Matrix<ElementType>& queries,
std::vector< std::vector<int> >& indices,
std::vector<std::vector<DistanceType> >& dists,
DistanceType radius,
const SearchParams& params)
{
return index_->radiusSearch(queries, indices, dists, radius, params);
}
private:
Index* index_;
};
}
#endif
| [
"mariusm@cs.ubc.ca"
] | mariusm@cs.ubc.ca |
7e381d028c06fb20be1dc85bbaf2d25cd7e071f4 | 28f416a282135d72b6a4e27a2b35945e13870e15 | /star.cpp | afa3dd3efbd616286748755208b1b5044d72028f | [] | no_license | elvissoares/ELcode | 94ab6fcd4f4034e23c4d2a3968e1c3f3c8307e0a | d5fca4af506032c1f2adb99e9d10b1b242571a1b | refs/heads/master | 2020-04-17T15:34:30.863280 | 2019-01-20T20:10:54 | 2019-01-20T20:10:54 | 166,704,115 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,774 | cpp | #include <iostream>
#include <vector>
#include <fstream>
#include <iomanip>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <limits>
#include <sstream>
#include <omp.h>
#include "star.hpp"
#include "stellar_structure_equations.hpp"
#include "util/tridag.hpp"
#include "util/nr.hpp"
#include "util/roots.hpp"
#include "util/odeint.hpp"
#include "util/mins_ndim.hpp"
using namespace std;
std::string Star::ConfigFileName = "star.cfg";
std::string Star::OutputFilePath = "output/";
std::string Star::InputFilePath = "input/";
std::string Star::OutputFileName = "output";
std::string Star::EndFileName = ".dat";
std::string Star::InitialConditionFileName = "white_dwarf";
//=====================================================================
// The Shells struct
//=====================================================================
void Shells::Set_Mass(const double &Mass){
M = Mass;
}
void Shells::Set_Temperature(const double &Temperature){
T = Temperature;
}
void Shells::Set_Abundance(const std::vector<double> &Xin){
X[0] = Xin[0];
X[1] = Xin[1];
X[2] = Xin[2];
X[3] = Xin[3];
X[4] = Xin[4];
X[5] = Xin[5];
X[6] = Xin[6];
}
void Shells::Set_Radius(const double &Radius, const double &dRadius){
Rout = Radius;
Rin = Radius - dRadius;
}
void Shells::Set_RadialVelocity(const double &RadialVelocity, const double &dRadialVelocity){
Rdot_out = RadialVelocity;
Rdot_in = RadialVelocity - dRadialVelocity;
}
void Shells::Calculate_Volume(){
using PhysConstants::four_pi_o3;
Vol = four_pi_o3 * (C(Rout) - C(Rin));
if (Vol < 0){
std::cerr << "ERROR: Shells::Calculate_Volume: Negative Volume!" << std::endl;
exit(0);
}
using PhysConstants::four_pi;
Voldot = four_pi*(Q(Rout) * Rdot_out - Q(Rin) * Rdot_in);
}
//=====================================================================
// Density within the Shell \[Rho] = M[i] / (4Pi R[i]^3/ 3)
//=====================================================================
void Shells::Calculate_Density(){
Rho = M / Vol;
Rhodot = -Rho * Voldot / Vol;
}
//=====================================================================
// Calculate the Artificial Viscosity within the Shells
//=====================================================================
void Shells::Calculate_ArtificialViscosity(){
double dR = (Rout-Rin);
const double alpha = 0.0, beta = 1.2;
if (Rhodot > 0.0 && Rin > 0){
double mu = dR*Rhodot/Rho;
Q = Rho*(alpha*cs*mu + beta*Q(mu)); // the bulk viscosity as in Monaghan 1983
}
else Q = 0.;
}
//=====================================================================
// Calculate the material Opacity within the Shells
//=====================================================================
void Shells::Calculate_Opacity(){
using PhysConstants::a;
using PhysConstants::c;
double rad = 0.2 + 1.e23*Rho*pow(T,-3.5) ;
double sigmacond, kappacond;
sigmacond = pow(10,cond.Evaluate_ThermalConductivity(log10(Rho),log10(T),X));
kappacond = 4*a*c*C(T)/(3*Rho*sigmacond);
kappa = 1./(1./kappacond+1./rad);
}
void Shells::Calculate_Ksi(){
ksi = Ksi(Rout,Rin);
ksidot = Ksidot(Rout,Rin,Rdot_out,Rdot_in);
}
//=====================================================================
// The Star struct
//=====================================================================
void Star::SetMass(const double &m){
Mass = m;
Distribute_Mass();
}
void Star::SetTemperature(const double &T){
Temperature = T;
Distribute_Temperature();
}
void Star::Distribute_Mass(){
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < shell.size(); j++)
shell[j].Set_Mass(Mass/Nshells);
}
void Star::Distribute_Radius(){
using PhysConstants::four_pi_o3;
shell[0].Rout = pow(shell[0].M/(four_pi_o3*Density),1/3.);
shell[0].Rin = 0.;
for (std::vector<int>::size_type j = 1; j < shell.size(); j++)
{
shell[j].Rin = shell[j-1].Rout;
shell[j].Rout = pow(C(shell[j].Rin) + shell[j].M/(four_pi_o3*Density),1/3.);
}
}
void Star::Distribute_Temperature(){
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < shell.size(); j++)
{
shell[j].Set_Temperature(Temperature);
}
}
void Star::Distribute_Abundance(){
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < shell.size(); j++)
{
shell[j].Set_Abundance(X);
}
}
void Star::Initial_RadialVelocity(){
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < shell.size(); j++)
{
shell[j].Set_RadialVelocity(0.,0.);
}
}
void Star::Update_Radius(){
shell[0].Rin = 0.;
#pragma omp parallel for
for (std::vector<int>::size_type j = 1; j < shell.size(); j++)
shell[j].Rin = shell[j-1].Rout;
}
void Star::Update_Velocity(){
shell[0].Rdot_in = 0.;
#pragma omp parallel for
for (std::vector<int>::size_type j = 1; j < shell.size(); j++){
shell[j].Rdot_in = shell[j-1].Rdot_out ;
}
}
void Star::Copy_InitialAbundance(){
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < shell.size(); j++){
shell[j].Xi = shell[j].X;
}
}
void Star::Calculate_Luminosity(){
using PhysConstants::four_pi;
using PhysConstants::a;
using PhysConstants::c;
shell[0].L = four_pi*Q(shell[0].Rout)*(4*a*c/3.)*(1/(shell[0].kappa*shell[0].Rho))*pow(shell[0].T,3)*(shell[1].T-shell[0].T)/(shell[0].Rout-0.);
#pragma omp parallel for
for (std::vector<int>::size_type j = 1; j < Nshells-1; j++)
{
shell[j].L = four_pi*Q(shell[j].Rout)*(4*a*c/3.)*(1/(shell[j].kappa*shell[j].Rho))*pow(shell[j].T,3)*(shell[j+1].T-shell[j].T)/(shell[j].Rout-shell[j].Rin) - four_pi*Q(shell[j-1].Rout)*(4*a*c/3.)*(1/(shell[j-1].kappa*shell[j-1].Rho))*pow(shell[j-1].T,3)*(shell[j].T-shell[j-1].T)/(shell[j-1].Rout-shell[j-1].Rin);
}
shell[Nshells-1].L = four_pi*Q(shell[Nshells-1].Rout)*(4*a*c/3.)*(1/(shell[Nshells-1].kappa*shell[Nshells-1].Rho))*pow(shell[Nshells-1].T,3)*(0.-shell[Nshells-1].T)/(shell[Nshells-1].Rout-shell[Nshells-1].Rin) - four_pi*Q(shell[Nshells-1].Rin)*(4*a*c/3.)*(1/(shell[Nshells-2].kappa*shell[Nshells-2].Rho))*pow(shell[Nshells-2].T,3)*(shell[Nshells-1].T-shell[Nshells-2].T)/(shell[Nshells-2].Rout-shell[Nshells-2].Rin);
Luminosity = - four_pi*Q(shell[Nshells-1].Rout)*(4*a*c/3.)*(1/(shell[Nshells-1].kappa*shell[Nshells-1].Rho))*pow(shell[Nshells-1].T,3)*(0.-shell[Nshells-1].T)/(shell[Nshells-1].Rout-shell[Nshells-1].Rin) ;
}
void Star::Update_Interior(){
Update_Radius();
Update_Velocity();
for (std::vector<int>::size_type j = 0; j < shell.size(); j++){
shell[j].Calculate_Ksi();
shell[j].Calculate_Volume();
shell[j].Calculate_Density();
eos.Evaluate(shell[j].Rho,shell[j].T,shell[j].X);
shell[j].P = eos.P;
shell[j].u = eos.u;
shell[j].cs = eos.cs;
shell[j].Cv = shell[j].M * fabs(eos.cv);
shell[j].Cp = shell[j].M * fabs(eos.cp);
shell[j].dUdrho = shell[j].M * eos.dudrho;
if (art_viscosity) shell[j].Calculate_ArtificialViscosity();
if (luminosity) shell[j].Calculate_Opacity();
}
if (luminosity) Calculate_Luminosity();
}
void Star::ReadConfigFile(){
string ReadFileName = InputFilePath + ConfigFileName;
ifstream InFile(ReadFileName.c_str());
std::cerr << "Reading configuration file: " << ConfigFileName << " ...";
if (!InFile.is_open()) {
std::cout << "The configuration file could not be opened (wrong filename?)" << std::endl;
exit(1);
}
else{
std::string line;
while(getline(InFile, line)){
// read all lines until end of configuration file is reached
if ( line[0]=='#' || line[0]==' ' || line[0]=='\n' ) {} /* Ignore lines beginning with empty space, #
or newline character. */
else{
if (line.find(" ")== std::string::npos) {
// if there are no empty spaces, we are done
}
else {
line = line.substr(0,line.find_first_of(" ")); // remove everything after first empty space
}
ProcessLine(&line); // use helper function to sort into respective variables
}
}
InFile.close();
}
InFile.clear();
std::cerr << "done."<< std::endl;
}
void Star::ProcessLine(std::string *line){
std::string pre = line->substr(0,line->find("=")); // part of the string in front of "="
std::string post = line->substr(line->find("=")+1); // part of the string after "="
if (pre == "Nshells") Nshells = atof(post.c_str()); // star initial temperature
if (pre == "eos") eos.id_eos = atoi(post.c_str());
if (pre == "Gravity") {
if (post == "yes") gravity = true;
else if (post == "no") gravity = false;
}
if (pre == "Reactions") {
if (post == "yes") reactions = true;
else if (post == "no") reactions = false;
}
if (pre == "Art_Viscosity") {
if (post == "yes") art_viscosity = true;
else if (post == "no") art_viscosity = false;
}
if (pre == "Luminosity") {
if (post == "yes") luminosity = true;
else if (post == "no") luminosity = false;
}
if (pre == "OutputFileName") OutputFileName = post;
if (pre == "OutputFilePath") OutputFilePath = post;
if (pre == "InitialConditionFileName") InitialConditionFileName = post;
}
void Star::Read_InitialCondition(){
string ReadFileName = InputFilePath + InitialConditionFileName;
ifstream InFile(ReadFileName.c_str());
std::cerr << "Reading the initial condition file: " << InitialConditionFileName << "...";
if (!InFile) {
std::cout << "The initial condition file could not be opened (wrong filename?)" << std::endl;
exit(1);
}
std::string line;
unsigned int j = 0;
if (InFile.is_open()){
getline(InFile, line); // read all lines until end of configuration file is reached
getline(InFile, line);
}
Mass = 0.;
while(!InFile.eof()){
InFile >> shell[j].M >> shell[j].Rout >> shell[j].Rdot_out >> shell[j].T >> shell[j].X[0] >> shell[j].X[1] >> shell[j].X[2] >> shell[j].X[3] >> shell[j].X[4] >> shell[j].X[5] >> shell[j].X[6];
j++;
Mass += shell[j].M;
}
InFile.close();
std::cerr << "done."<< std::endl;
}
//=====================================================================
// Função que calcula a energia gravitacional Vg total da estrela
// para uma dada configuração {R_i}
//=====================================================================
double Star::Gravitational_Energy(){
using PhysConstants::G;
const double three_teenths = 0.3;
std::vector<double> sum_Mass(Nshells-1); //Vetor para a soma das massas das camadas internas
sum_Mass[0] = shell[0].M;
for (std::vector<int>::size_type j = 1; j < Nshells-1; j++)
sum_Mass[j] = sum_Mass[j-1] + shell[j].M;
shell[0].Vg = -G*three_teenths * (shell[0].M / shell[0].Rout)
* (f(shell[0].ksi) * shell[0].M ); // For first shell
#pragma omp parallel for
for (std::vector<int>::size_type j = 1; j < Nshells; j++){
shell[j].Vg = -G*three_teenths * (shell[j].M / shell[j].Rout)
* (f(shell[j].ksi) * shell[j].M + g(shell[j].ksi) * (sum_Mass[j-1]));
}
double sum = 0.0;
for (std::vector<int>::size_type j = 0; j < Nshells; j++)
sum += shell[j].Vg;
sum_Mass.clear();
return (sum);
}
//=====================================================================
// Função que calcula a energia interna U_int total da estrela
// para uma dada configuração {R_i}
//=====================================================================
double Star::Internal_Energy() {
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < Nshells; j++){
shell[j].U = shell[j].u*shell[j].M;
}
double sum = 0.0;
for (std::vector<int>::size_type j = 0; j < Nshells; j++) {
sum += shell[j].U ;
}
return sum;
}
double Star::Nuclear_Energy() {
double sum = 0.;
for (std::vector<int>::size_type j = 0; j < Nshells; j++) {
sum += shell[j].M*shell[j].network.EnergyGeneratedIntegrated(shell[j].X,shell[j].Xi,1.);
}
return sum;
}
//=====================================================================
// Função que calcula a energia cinética K total da estrela
// para uma dada configuração {R_i,Rdot_i}
//=====================================================================
double Star::Kinetic_Energy() {
const double half = 0.5;
double K;
std::vector<double> Td(Nshells), Ts(Nshells);
T_matrix(Td,Ts);
if (Nshells==1) K = half*shell[0].Rdot_out*Td[0]*shell[0].Rdot_out;
else
{
double sum = 0.0;
for (std::vector<int>::size_type j = 0; j < Nshells-1; j++){
sum += Td[j]*Q(shell[j].Rdot_out) + 2*Ts[j]*shell[j].Rdot_out*shell[j+1].Rdot_out;
}
sum += Td[Nshells-1]*Q(shell[Nshells-1].Rdot_out);
K = half*sum;
}
Td.clear(); Ts.clear();
return K;
}
//=====================================================================
// Matriz tridiagonal de energia cinética n x n (T) a partir dos
// vetores a, b das diagonais
//=====================================================================
void Star::T_matrix(vector<double>& d, vector<double>& s)
{
if (Nshells==1) d[0] = T_22(shell[0].ksi, shell[0].M);
else{
// Create the a, b and c coefficients in the vectors
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < Nshells-1; j++)
{
d[j] = T_22(shell[j].ksi, shell[j].M) + T_11(shell[j+1].ksi, shell[j+1].M);
s[j] = T_12(shell[j+1].ksi, shell[j+1].M);
}
d[Nshells-1] = T_22(shell[Nshells-1].ksi, shell[Nshells-1].M);
s[Nshells-1] = 0.; // por definição de matriz tridiagonal simétrica
}
}
//=====================================================================
// Matriz tridiagonal de energia cinética n x n (Q) a partir dos
// vetores a, b e c das diagonais
//=====================================================================
void Star::Q_matrix(vector<double>& d, vector<double>& s)
{
if (Nshells==1) d[0] = Q_22(shell[0].ksi, shell[0].ksidot, shell[0].M);
else{
// Create the a, b and c coefficients in the vectors
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < shell.size()-1; j++)
{
d[j] = Q_22(shell[j].ksi, shell[j].ksidot, shell[j].M) + Q_11(shell[j+1].ksi, shell[j+1].ksidot, shell[j+1].M);
s[j] = Q_12(shell[j+1].ksi, shell[j+1].ksidot, shell[j+1].M);
}
d[Nshells-1] = Q_22(shell[Nshells-1].ksi, shell[Nshells-1].ksidot, shell[Nshells-1].M);
s[Nshells-1] = 0.; // por definição de matriz tridiagonal simétrica
}
}
//=====================================================================
// Vetor de força 1 x n (F)
//=====================================================================
void Star::F_vector(std::vector<double>& f)
{
using PhysConstants::four_pi;
if (gravity){
using PhysConstants::G;
if (Nshells==1) f[0] = four_pi*Q(shell[0].Rout)*( shell[0].P + shell[0].Q ) - (G/Q(shell[0].Rout))*( f_1(shell[0].ksi)*Q(shell[0].M) );
else{
std::vector<double> sumM(Nshells-1); //Vetor para a soma das massas das camadas internas
sumM[0] = shell[0].M;
for (std::vector<int>::size_type j = 1; j < shell.size()-1; j++)
sumM[j] = sumM[j-1] + shell[j].M;
f[0] = four_pi*Q(shell[0].Rout)*( (shell[0].P-shell[1].P) + (shell[0].Q-shell[1].Q) ) - (G/Q(shell[0].Rout))*( f_1(shell[0].ksi)*Q(shell[0].M) + f_2(shell[1].ksi)*Q(shell[1].M) + g_2(shell[1].ksi)*shell[1].M*sumM[0] );
// A seguir, calculamos as variáveis necessárias para o elemento F[i] dentro do loop
#pragma omp parallel for
for (std::vector<int>::size_type j = 1; j < shell.size()-1; j++)
{
f[j] = four_pi*Q(shell[j].Rout)*( (shell[j].P-shell[j+1].P) + (shell[j].Q-shell[j+1].Q) ) - (G/Q(shell[j].Rout))*( f_1(shell[j].ksi)*Q(shell[j].M) + f_2(shell[j+1].ksi)*Q(shell[j+1].M) + g_1(shell[j].ksi)*shell[j].M*sumM[j-1] + g_2(shell[j+1].ksi)*shell[j+1].M*sumM[j] );
}
// A seguir, calculamos as variáveis necessárias para o elemento F[N-1]
f[Nshells-1] = four_pi*Q(shell[Nshells-1].Rout)*(shell[Nshells-1].P + shell[Nshells-1].Q) - (G/Q(shell[Nshells-1].Rout))*( f_1(shell[Nshells-1].ksi)*Q(shell[Nshells-1].M) + g_1(shell[Nshells-1].ksi)*shell[Nshells-1].M*sumM[Nshells-2] );
sumM.clear();
}
}
else {
if (Nshells==1) f[0] = four_pi*Q(shell[0].Rout)*( shell[0].P + shell[0].Q );
else{
f[0] = four_pi*Q(shell[0].Rout)*( (shell[0].P-shell[1].P) + (shell[0].Q-shell[1].Q) );
// A seguir, calculamos as variáveis necessárias para o elemento F[i] dentro do loop
#pragma omp parallel for
for (std::vector<int>::size_type j = 1; j < shell.size()-1; j++)
{
f[j] = four_pi*Q(shell[j].Rout)*( (shell[j].P-shell[j+1].P) + (shell[j].Q-shell[j+1].Q) );
}
// A seguir, calculamos as variáveis necessárias para o elemento F[N-1]
f[Nshells-1] = four_pi*Q(shell[Nshells-1].Rout)*(shell[Nshells-1].P + shell[Nshells-1].Q);
}
}
}
//=====================================================================
// Retorna as derivadas dR/dt (Velocidade) para a dinâmica
//=====================================================================
void Star::dRdt()
{
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < shell.size(); j++)
shell[j].dRdt = shell[j].Rdot_out;
}
//=====================================================================
// Retorna as derivadas dRdot/dt (Aceleração) para a dinâmica
//=====================================================================
void Star::dRdotdt()
{
std::vector<double> Td(Nshells), Ts(Nshells);
std::vector<double> Qd(Nshells), Qs(Nshells);
std::vector<double> f(Nshells), aux(Nshells), fout(Nshells);
T_matrix(Td, Ts);
Q_matrix(Qd, Qs);
F_vector(f);
if (Nshells==1) fout[0] = shell[0].Rdot_out*Qd[0] + f[0];
else
{
aux[0] = shell[0].Rdot_out*Qd[0] + shell[1].Rdot_out*Qs[0] + f[0];
#pragma omp parallel for
for (std::vector<int>::size_type j = 1; j < shell.size()-1; j++)
aux[j] = shell[j-1].Rdot_out*Qs[j-1] + shell[j].Rdot_out*Qd[j] + shell[j+1].Rdot_out*Qs[j] + f[j];
aux[Nshells-1] = shell[Nshells-1].Rdot_out*Qd[Nshells-1] + shell[Nshells-2].Rdot_out*Qs[Nshells-2] + f[Nshells-1];
tridag_symm(Ts,Td,aux,fout);
}
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < shell.size(); j++)
shell[j].dRdotdt = fout[j];
Td.clear(); Ts.clear(); Qd.clear(); Qs.clear(); f.clear(); aux.clear(); fout.clear();
}
//=====================================================================
// Retorna as derivadas dT/dt para a dinâmica
//=====================================================================
void Star::ThermalConductionEquation()
{
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < shell.size(); j++){
if (tau > 0.0) shell[j].dTdt = (-shell[j].dUdrho*shell[j].Rhodot - shell[j].P*shell[j].Voldot +shell[j].Qd + shell[j].L ) /(shell[j].Cv);
else shell[j].dTdt = (-shell[j].dUdrho*shell[j].Rhodot - shell[j].P*shell[j].Voldot -shell[j].Q*shell[j].Voldot + shell[j].L + shell[j].Eps*shell[j].M + shell[j].dUdt) /(shell[j].Cv);
}
}
//=====================================================================
// Retorna as derivadas dQd/dt (calor retardado) para a dinâmica
//=====================================================================
void Star::dQddt()
{
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < shell.size(); j++){
shell[j].dQddt = (-shell[j].Q*shell[j].Voldot + shell[j].Eps*shell[j].M -shell[j].Qd)/tau;
}
}
//=====================================================================
// Funções para cálculo do equilíbrio hidrostático da estrela
//=====================================================================
struct Equilibrium {
Star *star_ptr;
void initial(std::vector<double> &x){
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < star_ptr->Nshells; j++){
x[j]= sqrt(star_ptr->shell[j].Rout - star_ptr->shell[j].Rin);
}
}
double operator()(std::vector<double> &x){
using PhysConstants::four_pi_o3;
const double onethird = 1.0/3.0;
star_ptr->shell[0].Rout = Q(x[0]);
star_ptr->shell[0].Rin = 0.;
for (std::vector<int>::size_type j = 1; j < star_ptr->Nshells; j++) {
star_ptr->shell[j].Rin = star_ptr->shell[j-1].Rout;
star_ptr->shell[j].Rout = star_ptr->shell[j].Rin + Q(x[j]);
}
star_ptr->Update_Interior();
std::cerr << "Energy = " << (star_ptr->Gravitational_Energy() + star_ptr->Internal_Energy()) << std::endl;
return (star_ptr->Gravitational_Energy() + star_ptr->Internal_Energy());
}
};
void Star::HydrostaticEquilibrium(const double &rtol){
std::vector<double> x(Nshells);
Equilibrium energy;
energy.star_ptr = this;
energy.initial(x);
Powell<Equilibrium> powell(energy,rtol);
x = powell.minimize(x);
x.clear();
}
struct Network: public Nuclear_Network {
double Rho, T;
void operator() (const double &t, const std::vector<double> &y, std::vector<double> &dydt)
{
Calculate_Derivatives(Rho,T,y,dydt);
}
void jacobian(const double &t, const std::vector<double> &y, std::vector<double> &dydt, std::vector< std::vector<double> > &dfdy)
{
Calculate_Jacobian(Rho,T,y,dfdy);
}
};
void Star::NuclearReactions(double &dtnet, const double &rtol, const double &tol){
double hmin = 0.0, h0 = 1.0e-9;
std::vector<int>::size_type j;
//#pragma omp parallel for private(j,hmin,h0,rtol,tol,dtnet)
for (j = 0; j < shell.size(); j++){
Network network;
std::vector<double> Xi = shell[j].X;
network.Rho = shell[j].Rho;
network.T = shell[j].T;
double dtNSE = pow(shell[j].Rho,0.2)*exp(1.797e11/shell[j].T-40.5);
double h = h0;
double t = 0.0;
// if (dtNSE <= dtnet){
// network.NuclearStatisticalEquilibrium(shell[j].Rho,shell[j].T,shell[j].X);
// }
//
// else{
Odeint<StepperSie<Network> > odenet(shell[j].X,t,dtnet,tol,rtol,h,hmin,network);
odenet.integrate();
// }
shell[j].Eps = network.EnergyGeneratedIntegrated(shell[j].X,Xi,dtnet);
Xi.clear();
}
}
void Star::Single_Step(const double &dt, const double &tol, const double &rtol){
Update_Interior();
dRdt();
dRdotdt();
ThermalConductionEquation();
if (tau > 0.0) dQddt();
}
double Star::TimeStep(unsigned int id_dynamics){
double dtf, dtR, dtacc, dtT, dtQd, dtz, dtcv, dtdyn, dtexpl;
if (id_dynamics == 1){
double dR = (shell[0].Rout-shell[0].Rin);
dtacc = sqrt(dR/fabs(shell[0].dRdotdt));
dtR = shell[0].Rout/fabs(shell[0].Rdot_out);
dtcv = dR/(shell[0].cs);
dtdyn = 446/sqrt(shell[0].Rho);
for (std::vector<int>::size_type j = 1; j < shell.size(); j++){
dR = (shell[j].Rout-shell[j].Rin);
dtR = MIN(dtR,shell[j].Rout/fabs(shell[j].Rdot_out));
dtacc = sqrt(dR/fabs(shell[j].dRdotdt));
dtdyn = 446/sqrt(shell[j].Rho);
dtcv = dR/(shell[j].cs+dR*fabs(shell[j].Rhodot/shell[j].Rho));
}
std::cerr << "dtR = " << dtR << std::endl;
std::cerr << "dtacc = " << dtacc << std::endl;
std::cerr << "dtdyn = " << dtdyn << std::endl;
std::cerr << "dtcv = " << dtcv << std::endl;
return 0.25*MIN(dtcv,MIN(dtdyn,MIN(dtR,dtacc)));
}
if (id_dynamics == 2){
dtT = fabs(shell[0].T/fabs(shell[0].dTdt));
dtexpl = fabs((shell[0].Cp*shell[0].T)/(shell[0].Eps*shell[0].M));
for (std::vector<int>::size_type j = 1; j < shell.size(); j++){
dtT = MIN(dtT,fabs(shell[j].T/shell[j].dTdt));
dtexpl = MIN(dtexpl,fabs((shell[j].Cp*shell[j].T)/(shell[j].Eps*shell[j].M)));
}
return 0.25*MIN(dtT,dtexpl);
}
if (id_dynamics > 2 ){
double dR = (shell[0].Rout-shell[0].Rin);
dtdyn = 446/sqrt(shell[0].Rho);
dtR = shell[0].Rout/fabs(shell[0].Rdot_out);
dtacc = sqrt(dR/fabs(shell[0].dRdotdt));
dtcv = dR/(shell[0].cs);
dtT = shell[0].T/fabs(shell[0].dTdt);
dtexpl = fabs((shell[0].Cp*shell[0].T)/(shell[0].Eps*shell[0].M));
double dtNSE = pow(shell[0].Rho,0.2)*exp(1.797e11/shell[0].T-40.5);
for (std::vector<int>::size_type j = 1; j < shell.size(); j++){
dR = (shell[j].Rout-shell[j].Rin);
dtdyn = MIN(dtdyn,446/sqrt(shell[j].Rho));
dtcv = MIN(dtcv,dR/(shell[j].cs));
dtexpl = MIN(dtexpl,fabs((shell[j].Cp*shell[j].T)/(shell[j].Eps*shell[j].M)));
dtR = MIN(dtR,shell[j].Rout/fabs(shell[j].Rdot_out));
dtacc = sqrt(dR/fabs(shell[j].dRdotdt));
dtT = MIN(dtT,shell[j].T/fabs(shell[j].dTdt));
dtNSE = MIN(dtNSE,pow(shell[j].Rho,0.2)*exp(1.797e11/shell[j].T-40.5));
}
std::cerr << "dtR = " << dtR << std::endl;
std::cerr << "dtT = " << dtT << std::endl;
std::cerr << "dtacc = " << dtacc << std::endl;
std::cerr << "dtdyn = " << dtdyn << std::endl;
std::cerr << "dtcv = " << dtcv << std::endl;
std::cerr << "dtexpl = " << dtexpl << std::endl;
std::cerr << "dtNSE = " << dtNSE << std::endl;
return 0.3*MIN(dtNSE,MIN(dtT,MIN(dtR,MIN(dtacc,MIN(dtexpl,MIN(dtdyn,dtcv))))));
}
}
struct Dynamics{
Star *starptr;
unsigned int id;
double ti;
void operator() (const double &t, const std::vector<double> &y, std::vector<double> &dydt)
{
unsigned int n = starptr->shell.size();
if (id == 1){
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < starptr->shell.size(); j++){
starptr->shell[j].Rout = y[j];
starptr->shell[j].Rdot_out = y[j+n];
}
starptr->Update_Interior();
starptr->dRdt();
starptr->dRdotdt();
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < starptr->shell.size(); j++){
dydt[j] = starptr->shell[j].dRdt;
dydt[j+n] = starptr->shell[j].dRdotdt;
}
}
if (id == 2){
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < starptr->shell.size(); j++){
starptr->shell[j].T = y[j];
}
starptr->Update_Interior();
starptr->ThermalConductionEquation();
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < starptr->shell.size(); j++){
dydt[j] = starptr->shell[j].dTdt;
}
}
if (id == 3){
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < starptr->shell.size(); j++){
starptr->shell[j].Rout = y[j];
starptr->shell[j].Rdot_out = y[j+n];
starptr->shell[j].T = y[j+2*n];
if (starptr->tau > 0.0) starptr->shell[j].Qd = y[j+3*n];
}
starptr->Update_Interior();
starptr->dRdt();
starptr->dRdotdt();
starptr->ThermalConductionEquation();
if (starptr->tau > 0.0) starptr->dQddt();
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < starptr->shell.size(); j++){
dydt[j] = starptr->shell[j].dRdt;
dydt[j+n] = starptr->shell[j].dRdotdt;
dydt[j+2*n] = starptr->shell[j].dTdt;
if (starptr->tau > 0.0) dydt[j+3*n] = starptr->shell[j].dQddt;
}
}
}
};
void Star::Time_Integration(double &ti, double &dt, const double &rtol, const double &tol, unsigned int id_dynamics){
double hmin = 0.;
double dtnet;
double tf = ti + dt;
Dynamics dynamics;
dynamics.starptr = this;
dynamics.id = id_dynamics;
dynamics.ti = ti;
const unsigned int n = shell.size();
if (id_dynamics == 1){
std::vector<double> y(2*n);
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < shell.size(); j++){
y[j] = shell[j].Rout;
y[j+n] = shell[j].Rdot_out;
}
Odeint<StepperFehlb<Dynamics> > ode(y,ti,tf,tol,rtol,dt_integrator,hmin,dynamics);
ode.integrate();
dt_integrator = ode.s.hnext; //Atualiza o tamanho do passo
y.clear();
}
if (id_dynamics == 2){
std::vector<double> y(n);
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < shell.size(); j++){
y[j] = shell[j].T;
}
Odeint<StepperFehlb<Dynamics> > ode(y,ti,tf,tol,rtol,dt_integrator,hmin,dynamics);
ode.integrate();
dt_integrator = ode.s.hnext; //Atualiza o tamanho do passo
y.clear();
}
if (id_dynamics == 3){
dtnet = dt;
Update_Interior();
if (reactions) NuclearReactions(dtnet,1.0e-6,1.0e-8);
std::vector<double> y(3*n);
if (tau > 0.0) y.resize(4*n);
#pragma omp parallel for
for (std::vector<int>::size_type j = 0; j < shell.size(); j++){
y[j] = shell[j].Rout;
y[j+n] = shell[j].Rdot_out;
y[j+2*n] = shell[j].T;
if (tau > 0.0) y[j+3*n] = shell[j].Qd;
}
Odeint<StepperFehlb<Dynamics> > ode(y,ti,tf,tol,rtol,dt_integrator,hmin,dynamics);
ode.integrate();
dt_integrator = ode.s.hnext; //Atualiza o tamanho do passo
y.clear();
}
dt = MIN(10*dt_integrator,TimeStep(id_dynamics));
std::cerr << "dt =" << dt << std::endl;
dt_integrator = MIN(dt_integrator,dt);
std::cerr << "dt_integrator = " << dt_integrator << std::endl;
ti = tf;
}
| [
"elvis@macbook-pro.home"
] | elvis@macbook-pro.home |
d87c9568faedc5907cc0d306965d2ca006761865 | 06cb71218ef207cee9f6be593613c30aa38ccf48 | /General Programs/Sorting & Searching (Array)/Binary Search (Ascending)/Sorted Array Search/Source.cpp | 087b1431f9bb166e635d39cbbae7ef0f473dead8 | [] | no_license | aurangzaib048/Cpp-programming | e2d4acb84c3c03dc3a1c5568023f7251b824e4ab | a28a9cf8ea08e90f212fcc2a4d611286aa42dea0 | refs/heads/master | 2020-04-03T06:27:22.430878 | 2018-10-28T14:26:47 | 2018-10-28T14:26:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,331 | cpp | /*
Program for Searching array of n entered numbers for a specific number (Sorted [Ascending] Array Search) using function
of return type bool.
Note:
If entered number is present at more than one index then the index of first occurence of entered number
in array will be displayed.
*/
#include<iostream>
using namespace std;
bool SortedSearch(int[], int, int &, int);
void AscendingOrder(int[], int);
void swap(int &, int &);
int main()
{
int size, num[50], key, index;
//For Inputting amount of numbers
do
{
cout << "How many numbers u want to sort (Max 50)?\t";
cin >> size;
if (size < 0 || size > 50)
cout << "Invalid Input.......\nEnter number again\n";
} while (size < 0 || size > 50);
//For inputting n Numbers
for (int i = 0; i < size; i++)
{
cout << "Enetr number at [" << i << "] index?\t";
cin >> num[i];
}
//for formatting output
for (int i = 0; i < 80; i++)
cout << "=";
AscendingOrder(num, size); //For sorting Array in Ascending order
//displays sorted array
cout << "Entered Numbers in ASCENDING Order are:\n\t";
for (int i = 0; i < size; i++)
{
cout << num[i];
if (i != size - 1)
cout << ", ";
}
//for formatting output
cout << endl;
for (int i = 0; i < 80; i++)
cout << "=";
//for inputting key-value
cout << "Enter number that you want to search?\t";
cin >> key;
//For Displaying Result
if (!SortedSearch(num, size, index, key))
cout << "\n" << key << " is not present in entered array.";
else
cout << "\n" << key << " is present in entered array at [" << index << "] index.";
cout << endl;
return 0;
}
//For Sorting array in ascending Order
void AscendingOrder(int num[], int n)
{
//For sorting in Ascending Order
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j<n; j++)
{
if (num[i] > num[j])
swap(num[i], num[j]);
}
}
}
//For swapping 2 numbers
void swap(int &a, int &b)
{
a = a + b;
b = a - b;
a = a - b;
}
//Function for searching entered number in array
bool SortedSearch(int num[], int size, int &index, int key)
{
int first = 0, last = size - 1, mid;
//For finding index of entered number if it exists
while (first <= last)
{
mid = (first + last) / 2;
if (num[mid] == key)
{
index = mid;
return 1;
}
else if (num[mid] < key)
first = mid + 1;
else
last = mid - 1;
}
return 0;
} | [
"aurangzaib048@gmail.com"
] | aurangzaib048@gmail.com |
8cb977ec28c93dc707daae33038d34f30d0316cd | 76ad6f592d3d971dde26896a3d602794750ce5e3 | /src/main.h | ece0d2639a7b7ca9f2810977d03784a3a23c3831 | [
"MIT"
] | permissive | futurepoints/futurepoints | 4e0b81b5c5b3b638db282999de27c2afb8955702 | fd9d084389627c033d1a9f270012c94272a11436 | refs/heads/master | 2021-01-10T11:06:36.980503 | 2016-01-24T09:53:30 | 2016-01-24T09:53:30 | 50,236,743 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,598 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_MAIN_H
#define BITCOIN_MAIN_H
#include "bignum.h"
#include "sync.h"
#include "net.h"
#include "script.h"
#include "scrypt.h"
#include "hashblock.h"
#include <list>
class CWallet;
class CBlock;
class CBlockIndex;
class CKeyItem;
class CReserveKey;
class COutPoint;
class CAddress;
class CInv;
class CRequestTracker;
class CNode;
static const unsigned int MAX_BLOCK_SIZE = 1000000;
static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
static const unsigned int MAX_INV_SZ = 50000;
static const int64 MIN_TX_FEE = 0.0 * CENT;
static const int64 MIN_RELAY_TX_FEE = 0 * CENT;
static const int64 MAX_MONEY = 360000000 * COIN; //
static const int64 CIRCULATION_MONEY = MAX_MONEY;
static const double TAX_PERCENTAGE = 0.00; //no tax
static const int64 MAX_CLOAK_PROOF_OF_STAKE = 0.01 * COIN; // 0.001% annual interest
static const int CUTOFF_POW_BLOCK = 5000;
static const int64 MIN_TXOUT_AMOUNT = 0.0 * CENT; //0 or MIN_TX_FEE;
inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
// Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp.
static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
#ifdef USE_UPNP
static const int fHaveUPnP = true;
#else
static const int fHaveUPnP = false;
#endif
static const uint256 hashGenesisBlockOfficial("0x00000001fe54c4deb5287b6c704a8bebf24779c5705c4425439512f1e3681cb6");
static const uint256 hashGenesisBlockTestNet ("0x865ab1be14fd34531a5a506f10032b0082a3b064b4af38fda77449e80971e627");
static const int64 nClockDriftSwitchHeight = 300;
static const int64 nMaxClockDriftOrig = 8 * 60;
static const int64 nMaxClockDrift = 8 * 60; // 8 minutes
inline int64 GetMaxClockDrift(int nHeight) { return nHeight > nClockDriftSwitchHeight ? nMaxClockDrift : nMaxClockDriftOrig; }
extern CScript COINBASE_FLAGS;
extern CCriticalSection cs_main;
extern std::map<uint256, CBlockIndex*> mapBlockIndex;
extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
extern uint256 hashGenesisBlock;
extern CBlockIndex* pindexGenesisBlock;
extern unsigned int nStakeMinAge;
extern int nCoinbaseMaturity;
extern int nBestHeight;
extern CBigNum bnBestChainTrust;
extern CBigNum bnBestInvalidTrust;
extern uint256 hashBestChain;
extern CBlockIndex* pindexBest;
extern unsigned int nTransactionsUpdated;
extern uint64 nLastBlockTx;
extern uint64 nLastBlockSize;
extern int64 nLastCoinStakeSearchInterval;
extern const std::string strMessageMagic;
extern double dHashesPerSec;
extern int64 nHPSTimerStart;
extern int64 nTimeBestReceived;
extern CCriticalSection cs_setpwalletRegistered;
extern std::set<CWallet*> setpwalletRegistered;
extern unsigned char pchMessageStart[4];
extern std::map<uint256, CBlock*> mapOrphanBlocks;
// Settings
extern int64 nTransactionFee;
// Minimum disk space required - used in CheckDiskSpace()
static const uint64 nMinDiskSpace = 52428800;
class CReserveKey;
class CTxDB;
class CTxIndex;
void RegisterWallet(CWallet* pwalletIn);
void UnregisterWallet(CWallet* pwalletIn);
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
bool ProcessBlock(CNode* pfrom, CBlock* pblock);
bool CheckDiskSpace(uint64 nAdditionalBytes=0);
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
FILE* AppendBlockFile(unsigned int& nFileRet);
bool LoadBlockIndex(bool fAllowNew=true);
void PrintBlockTree();
CBlockIndex* FindBlockByHeight(int nHeight);
bool ProcessMessages(CNode* pfrom);
bool SendMessages(CNode* pto, bool fSendTrickle);
bool LoadExternalBlockFile(FILE* fileIn);
void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake=false);
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
bool CheckProofOfWork(uint256 hash, unsigned int nBits);
int64 GetProofOfWorkReward(int nHeight, int64 nFees, uint256 prevHash);
int64 GetProofOfWorkReward(int nHeight, int64 nFees, const CBlockIndex* pindex);
int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTime, int nHeight);
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
unsigned int ComputeMinStake(unsigned int nBase, int64 nTime, unsigned int nBlockTime);
int GetNumBlocksOfPeers();
bool IsInitialBlockDownload();
std::string GetWarnings(std::string strFor);
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
uint256 WantedByOrphan(const CBlock* pblockOrphan);
const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
void BitcoinMiner(CWallet *pwallet, bool fProofOfStake);
void ResendWalletTransactions();
//PoW Height Ctrl
int GetPowHeight(const CBlockIndex* pindex);
int GetPosHeight(const CBlockIndex* pindex);
bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
/** Position on disk for a particular transaction. */
class CDiskTxPos
{
public:
unsigned int nFile;
unsigned int nBlockPos;
unsigned int nTxPos;
CDiskTxPos()
{
SetNull();
}
CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
{
nFile = nFileIn;
nBlockPos = nBlockPosIn;
nTxPos = nTxPosIn;
}
IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
void SetNull() { nFile = (unsigned int) -1; nBlockPos = 0; nTxPos = 0; }
bool IsNull() const { return (nFile == (unsigned int) -1); }
friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
{
return (a.nFile == b.nFile &&
a.nBlockPos == b.nBlockPos &&
a.nTxPos == b.nTxPos);
}
friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
{
return !(a == b);
}
std::string ToString() const
{
if (IsNull())
return "null";
else
return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", nFile, nBlockPos, nTxPos);
}
void print() const
{
printf("%s", ToString().c_str());
}
};
/** An inpoint - a combination of a transaction and an index n into its vin */
class CInPoint
{
public:
CTransaction* ptx;
unsigned int n;
CInPoint() { SetNull(); }
CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
void SetNull() { ptx = NULL; n = (unsigned int) -1; }
bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
};
/** An outpoint - a combination of a transaction hash and an index n into its vout */
class COutPoint
{
public:
uint256 hash;
unsigned int n;
COutPoint() { SetNull(); }
COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
void SetNull() { hash = 0; n = (unsigned int) -1; }
bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
friend bool operator<(const COutPoint& a, const COutPoint& b)
{
return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
}
friend bool operator==(const COutPoint& a, const COutPoint& b)
{
return (a.hash == b.hash && a.n == b.n);
}
friend bool operator!=(const COutPoint& a, const COutPoint& b)
{
return !(a == b);
}
std::string ToString() const
{
return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** An input of a transaction. It contains the location of the previous
* transaction's output that it claims and a signature that matches the
* output's public key.
*/
class CTxIn
{
public:
COutPoint prevout;
CScript scriptSig;
unsigned int nSequence;
CTxIn()
{
nSequence = std::numeric_limits<unsigned int>::max();
}
explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
{
prevout = prevoutIn;
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
{
prevout = COutPoint(hashPrevTx, nOut);
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(prevout);
READWRITE(scriptSig);
READWRITE(nSequence);
)
bool IsFinal() const
{
return (nSequence == std::numeric_limits<unsigned int>::max());
}
friend bool operator==(const CTxIn& a, const CTxIn& b)
{
return (a.prevout == b.prevout &&
a.scriptSig == b.scriptSig &&
a.nSequence == b.nSequence);
}
friend bool operator!=(const CTxIn& a, const CTxIn& b)
{
return !(a == b);
}
std::string ToStringShort() const
{
return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
}
std::string ToString() const
{
std::string str;
str += "CTxIn(";
str += prevout.ToString();
if (prevout.IsNull())
str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
else
str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
if (nSequence != std::numeric_limits<unsigned int>::max())
str += strprintf(", nSequence=%u", nSequence);
str += ")";
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** An output of a transaction. It contains the public key that the next input
* must be able to sign with to claim it.
*/
class CTxOut
{
public:
int64 nValue;
CScript scriptPubKey;
CTxOut()
{
SetNull();
}
CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
{
nValue = nValueIn;
scriptPubKey = scriptPubKeyIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(nValue);
READWRITE(scriptPubKey);
)
void SetNull()
{
nValue = -1;
scriptPubKey.clear();
}
bool IsNull()
{
return (nValue == -1);
}
void SetEmpty()
{
nValue = 0;
scriptPubKey.clear();
}
bool IsEmpty() const
{
return (nValue == 0 && scriptPubKey.empty());
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
friend bool operator==(const CTxOut& a, const CTxOut& b)
{
return (a.nValue == b.nValue &&
a.scriptPubKey == b.scriptPubKey);
}
friend bool operator!=(const CTxOut& a, const CTxOut& b)
{
return !(a == b);
}
std::string ToStringShort() const
{
return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
}
std::string ToString() const
{
if (IsEmpty()) return "CTxOut(empty)";
if (scriptPubKey.size() < 6)
return "CTxOut(error)";
return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
enum GetMinFee_mode
{
GMF_BLOCK,
GMF_RELAY,
GMF_SEND,
};
typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
/** The basic transaction that is broadcasted on the network and contained in
* blocks. A transaction can contain multiple inputs and outputs.
*/
class CTransaction
{
public:
static const int CURRENT_VERSION=2;
int nVersion;
unsigned int nTime;
std::vector<CTxIn> vin;
std::vector<CTxOut> vout;
unsigned int nLockTime;
// Denial-of-service detection:
mutable int nDoS;
bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
CTransaction()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(nTime);
READWRITE(vin);
READWRITE(vout);
READWRITE(nLockTime);
)
void SetNull()
{
nVersion = CTransaction::CURRENT_VERSION;
nTime = GetAdjustedTime();
vin.clear();
vout.clear();
nLockTime = 0;
nDoS = 0; // Denial-of-service prevention
}
bool IsNull() const
{
return (vin.empty() && vout.empty());
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
{
// Time based nLockTime implemented in 0.1.6
if (nLockTime == 0)
return true;
if (nBlockHeight == 0)
nBlockHeight = nBestHeight;
if (nBlockTime == 0)
nBlockTime = GetAdjustedTime();
if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
return true;
BOOST_FOREACH(const CTxIn& txin, vin)
if (!txin.IsFinal())
return false;
return true;
}
bool IsNewerThan(const CTransaction& old) const
{
if (vin.size() != old.vin.size())
return false;
for (unsigned int i = 0; i < vin.size(); i++)
if (vin[i].prevout != old.vin[i].prevout)
return false;
bool fNewer = false;
unsigned int nLowest = std::numeric_limits<unsigned int>::max();
for (unsigned int i = 0; i < vin.size(); i++)
{
if (vin[i].nSequence != old.vin[i].nSequence)
{
if (vin[i].nSequence <= nLowest)
{
fNewer = false;
nLowest = vin[i].nSequence;
}
if (old.vin[i].nSequence < nLowest)
{
fNewer = true;
nLowest = old.vin[i].nSequence;
}
}
}
return fNewer;
}
bool IsCoinBase() const
{
return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
}
bool IsCoinStake() const
{
// ppcoin: the coin stake transaction is marked with the first output empty
return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
}
bool IsCoinBaseOrStake() const
{
return (IsCoinBase() || IsCoinStake());
}
/** Check for standard transaction types
@return True if all outputs (scriptPubKeys) use only standard transaction forms
*/
bool IsStandard() const;
/** Check for standard transaction types
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return True if all inputs (scriptSigs) use only standard transaction forms
@see CTransaction::FetchInputs
*/
bool AreInputsStandard(const MapPrevTx& mapInputs) const;
/** Count ECDSA signature operations the old-fashioned (pre-0.6) way
@return number of sigops this transaction's outputs will produce when spent
@see CTransaction::FetchInputs
*/
unsigned int GetLegacySigOpCount() const;
/** Count ECDSA signature operations in pay-to-script-hash inputs.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return maximum number of sigops required to validate this transaction's inputs
@see CTransaction::FetchInputs
*/
unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
/** Amount of bitcoins spent by this transaction.
@return sum of all outputs (note: does not include fees)
*/
int64 GetValueOut() const
{
int64 nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, vout)
{
nValueOut += txout.nValue;
if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
}
return nValueOut;
}
/** Amount of bitcoins coming in to this transaction
Note that lightweight clients may not know anything besides the hash of previous transactions,
so may not be able to calculate this.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return Sum of value of all inputs (scriptSigs)
@see CTransaction::FetchInputs
*/
int64 GetValueIn(const MapPrevTx& mapInputs) const;
static bool AllowFree(double dPriority)
{
// Large (in bytes) low-priority (new, small-coin) transactions
// need a fee.
return dPriority > COIN * 2880 / 250;
}
int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=false, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
{
CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
// Read transaction
if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
return error("CTransaction::ReadFromDisk() : fseek failed");
try {
filein >> *this;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Return file pointer
if (pfileRet)
{
if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
return error("CTransaction::ReadFromDisk() : second fseek failed");
*pfileRet = filein.release();
}
return true;
}
friend bool operator==(const CTransaction& a, const CTransaction& b)
{
return (a.nVersion == b.nVersion &&
a.nTime == b.nTime &&
a.vin == b.vin &&
a.vout == b.vout &&
a.nLockTime == b.nLockTime);
}
friend bool operator!=(const CTransaction& a, const CTransaction& b)
{
return !(a == b);
}
std::string ToStringShort() const
{
std::string str;
str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
return str;
}
std::string ToString() const
{
std::string str;
str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d)\n",
GetHash().ToString().substr(0,10).c_str(),
nTime,
nVersion,
vin.size(),
vout.size(),
nLockTime
);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
void print() const
{
printf("%s", ToString().c_str());
}
bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
bool ReadFromDisk(COutPoint prevout);
bool DisconnectInputs(CTxDB& txdb);
/** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
@param[in] txdb Transaction database
@param[in] mapTestPool List of pending changes to the transaction index database
@param[in] fBlock True if being called to add a new best-block to the chain
@param[in] fMiner True if being called by CreateNewBlock
@param[out] inputsRet Pointers to this transaction's inputs
@param[out] fInvalid returns true if transaction is invalid
@return Returns true if all inputs are in txdb or mapTestPool
*/
bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
/** Sanity check previous transactions, then, if all checks succeed,
mark them as spent by this transaction.
@param[in] inputs Previous transactions (from FetchInputs)
@param[out] mapTestPool Keeps track of inputs that need to be updated on disk
@param[in] posThisTx Position of this transaction on disk
@param[in] pindexBlock
@param[in] fBlock true if called from ConnectBlock
@param[in] fMiner true if called from CreateNewBlock
@param[in] fStrictPayToScriptHash true if fully validating p2sh transactions
@return Returns true if all checks succeed
*/
bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash=true);
bool ClientConnectInputs();
bool CheckTransaction() const;
bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true, bool* pfMissingInputs=NULL);
bool GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const; // ppcoin: get transaction coin age
protected:
const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
};
/** A transaction with a merkle branch linking it to the block chain. */
class CMerkleTx : public CTransaction
{
public:
uint256 hashBlock;
std::vector<uint256> vMerkleBranch;
int nIndex;
// memory only
mutable bool fMerkleVerified;
CMerkleTx()
{
Init();
}
CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
{
Init();
}
void Init()
{
hashBlock = 0;
nIndex = -1;
fMerkleVerified = false;
}
IMPLEMENT_SERIALIZE
(
nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
nVersion = this->nVersion;
READWRITE(hashBlock);
READWRITE(vMerkleBranch);
READWRITE(nIndex);
)
int SetMerkleBranch(const CBlock* pblock=NULL);
int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
bool IsInMainChain() const { return GetDepthInMainChain() > 0; }
int GetBlocksToMaturity() const;
bool AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs=true);
bool AcceptToMemoryPool();
};
/** A txdb record that contains the disk location of a transaction and the
* locations of transactions that spend its outputs. vSpent is really only
* used as a flag, but having the location is very helpful for debugging.
*/
class CTxIndex
{
public:
CDiskTxPos pos;
std::vector<CDiskTxPos> vSpent;
CTxIndex()
{
SetNull();
}
CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
{
pos = posIn;
vSpent.resize(nOutputs);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(pos);
READWRITE(vSpent);
)
void SetNull()
{
pos.SetNull();
vSpent.clear();
}
bool IsNull()
{
return pos.IsNull();
}
friend bool operator==(const CTxIndex& a, const CTxIndex& b)
{
return (a.pos == b.pos &&
a.vSpent == b.vSpent);
}
friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
{
return !(a == b);
}
int GetDepthInMainChain() const;
};
/** Nodes collect new transactions into a block, hash them into a hash tree,
* and scan through nonce values to make the block's hash satisfy proof-of-work
* requirements. When they solve the proof-of-work, they broadcast the block
* to everyone and the block is added to the block chain. The first transaction
* in the block is a special one that creates a new coin owned by the creator
* of the block.
*
* Blocks are appended to blk0001.dat files on disk. Their location on disk
* is indexed by CBlockIndex objects in memory.
*/
class CBlock
{
public:
// header
static const int CURRENT_VERSION=4;
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
// network and disk
std::vector<CTransaction> vtx;
// ppcoin: block signature - signed by one of the coin base txout[N]'s owner
std::vector<unsigned char> vchBlockSig;
// memory only
mutable std::vector<uint256> vMerkleTree;
// Denial-of-service detection:
mutable int nDoS;
bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
CBlock()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
// ConnectBlock depends on vtx following header to generate CDiskTxPos
if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
{
READWRITE(vtx);
READWRITE(vchBlockSig);
}
else if (fRead)
{
const_cast<CBlock*>(this)->vtx.clear();
const_cast<CBlock*>(this)->vchBlockSig.clear();
}
)
void SetNull()
{
nVersion = CBlock::CURRENT_VERSION;
hashPrevBlock = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
vtx.clear();
vchBlockSig.clear();
vMerkleTree.clear();
nDoS = 0;
}
bool IsNull() const
{
return (nBits == 0);
}
uint256 GetHash() const
{
return Hash9(BEGIN(nVersion), END(nNonce));
}
int64 GetBlockTime() const
{
return (int64)nTime;
}
void UpdateTime(const CBlockIndex* pindexPrev);
// ppcoin: entropy bit for stake modifier if chosen by modifier
unsigned int GetStakeEntropyBit(unsigned int nHeight) const
{
// Take last bit of block hash as entropy bit
unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu);
if (fDebug && GetBoolArg("-printstakemodifier"))
printf("GetStakeEntropyBit: nHeight=%u hashBlock=%s nEntropyBit=%u\n", nHeight, GetHash().ToString().c_str(), nEntropyBit);
return nEntropyBit;
}
// ppcoin: two types of block: proof-of-work or proof-of-stake
bool IsProofOfStake() const
{
return (vtx.size() > 1 && vtx[1].IsCoinStake());
}
bool IsProofOfWork() const
{
return !IsProofOfStake();
}
std::pair<COutPoint, unsigned int> GetProofOfStake() const
{
return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
}
// ppcoin: get max transaction timestamp
int64 GetMaxTransactionTime() const
{
int64 maxTransactionTime = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
maxTransactionTime = std::max(maxTransactionTime, (int64)tx.nTime);
return maxTransactionTime;
}
uint256 BuildMerkleTree() const
{
vMerkleTree.clear();
BOOST_FOREACH(const CTransaction& tx, vtx)
vMerkleTree.push_back(tx.GetHash());
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
for (int i = 0; i < nSize; i += 2)
{
int i2 = std::min(i+1, nSize-1);
vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
}
j += nSize;
}
return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
}
std::vector<uint256> GetMerkleBranch(int nIndex) const
{
if (vMerkleTree.empty())
BuildMerkleTree();
std::vector<uint256> vMerkleBranch;
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]);
nIndex >>= 1;
j += nSize;
}
return vMerkleBranch;
}
static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{
if (nIndex == -1)
return 0;
BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
{
if (nIndex & 1)
hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
else
hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
nIndex >>= 1;
}
return hash;
}
bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
{
// Open history file to append
CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
if (!fileout)
return error("CBlock::WriteToDisk() : AppendBlockFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(*this);
fileout << FLATDATA(pchMessageStart) << nSize;
// Write block
long fileOutPos = ftell(fileout);
if (fileOutPos < 0)
return error("CBlock::WriteToDisk() : ftell failed");
nBlockPosRet = fileOutPos;
fileout << *this;
// Flush stdio buffers and commit to disk before returning
fflush(fileout);
if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
FileCommit(fileout);
return true;
}
bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
{
SetNull();
// Open history file to read
CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
if (!fReadTransactions)
filein.nType |= SER_BLOCKHEADERONLY;
// Read block
try {
filein >> *this;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Check the header
if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
return error("CBlock::ReadFromDisk() : errors in block header");
return true;
}
void print() const
{
printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n",
GetHash().ToString().c_str(),
nVersion,
hashPrevBlock.ToString().c_str(),
hashMerkleRoot.ToString().c_str(),
nTime, nBits, nNonce,
vtx.size(),
HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
for (unsigned int i = 0; i < vtx.size(); i++)
{
printf(" ");
vtx[i].print();
}
printf(" vMerkleTree: ");
for (unsigned int i = 0; i < vMerkleTree.size(); i++)
printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
printf("\n");
}
bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos);
bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true) const;
bool AcceptBlock();
bool GetCoinAge(uint64& nCoinAge) const; // ppcoin: calculate total coin age spent in block
bool SignBlock(const CKeyStore& keystore);
bool CheckBlockSignature() const;
private:
bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
};
/** The block chain is a tree shaped structure starting with the
* genesis block at the root, with each block potentially having multiple
* candidates to be the next block. pprev and pnext link a path through the
* main/longest chain. A blockindex may have multiple pprev pointing back
* to it, but pnext will only point forward to the longest branch, or will
* be null if the block is not part of the longest chain.
*/
class CBlockIndex
{
public:
const uint256* phashBlock;
CBlockIndex* pprev;
CBlockIndex* pnext;
unsigned int nFile;
unsigned int nBlockPos;
CBigNum bnChainTrust; // ppcoin: trust score of block chain
int nHeight;
int64 nMint;
int64 nMoneySupply;
unsigned int nFlags; // ppcoin: block index flags
enum
{
BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
};
uint64 nStakeModifier; // hash modifier for proof-of-stake
unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only
// proof-of-stake specific fields
COutPoint prevoutStake;
unsigned int nStakeTime;
uint256 hashProofOfStake;
// block header
int nVersion;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
CBlockIndex()
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nFile = 0;
nBlockPos = 0;
nHeight = 0;
bnChainTrust = 0;
nMint = 0;
nMoneySupply = 0;
nFlags = 0;
nStakeModifier = 0;
nStakeModifierChecksum = 0;
hashProofOfStake = 0;
prevoutStake.SetNull();
nStakeTime = 0;
nVersion = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
}
CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nFile = nFileIn;
nBlockPos = nBlockPosIn;
nHeight = 0;
bnChainTrust = 0;
nMint = 0;
nMoneySupply = 0;
nFlags = 0;
nStakeModifier = 0;
nStakeModifierChecksum = 0;
hashProofOfStake = 0;
if (block.IsProofOfStake())
{
SetProofOfStake();
prevoutStake = block.vtx[1].vin[0].prevout;
nStakeTime = block.vtx[1].nTime;
}
else
{
prevoutStake.SetNull();
nStakeTime = 0;
}
nVersion = block.nVersion;
hashMerkleRoot = block.hashMerkleRoot;
nTime = block.nTime;
nBits = block.nBits;
nNonce = block.nNonce;
}
CBlock GetBlockHeader() const
{
CBlock block;
block.nVersion = nVersion;
if (pprev)
block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
uint256 GetBlockHash() const
{
return *phashBlock;
}
int64 GetBlockTime() const
{
return (int64)nTime;
}
CBigNum GetBlockTrust() const;
bool IsInMainChain() const
{
return (pnext || this == pindexBest);
}
bool CheckIndex() const
{
return true;
}
enum { nMedianTimeSpan=11 };
int64 GetMedianTimePast() const
{
int64 pmedian[nMedianTimeSpan];
int64* pbegin = &pmedian[nMedianTimeSpan];
int64* pend = &pmedian[nMedianTimeSpan];
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
*(--pbegin) = pindex->GetBlockTime();
std::sort(pbegin, pend);
return pbegin[(pend - pbegin)/2];
}
int64 GetMedianTime() const
{
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan/2; i++)
{
if (!pindex->pnext)
return GetBlockTime();
pindex = pindex->pnext;
}
return pindex->GetMedianTimePast();
}
/**
* Returns true if there are nRequired or more blocks of minVersion or above
* in the last nToCheck blocks, starting at pstart and going backwards.
*/
static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
unsigned int nRequired, unsigned int nToCheck);
bool IsProofOfWork() const
{
return !(nFlags & BLOCK_PROOF_OF_STAKE);
}
bool IsProofOfStake() const
{
return (nFlags & BLOCK_PROOF_OF_STAKE);
}
void SetProofOfStake()
{
nFlags |= BLOCK_PROOF_OF_STAKE;
}
unsigned int GetStakeEntropyBit() const
{
return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
}
bool SetStakeEntropyBit(unsigned int nEntropyBit)
{
if (nEntropyBit > 1)
return false;
nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
return true;
}
bool GeneratedStakeModifier() const
{
return (nFlags & BLOCK_STAKE_MODIFIER);
}
void SetStakeModifier(uint64 nModifier, bool fGeneratedStakeModifier)
{
nStakeModifier = nModifier;
if (fGeneratedStakeModifier)
nFlags |= BLOCK_STAKE_MODIFIER;
}
std::string ToString() const
{
return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016"PRI64x", nStakeModifierChecksum=%08x, hashProofOfStake=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
pprev, pnext, nFile, nBlockPos, nHeight,
FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
nStakeModifier, nStakeModifierChecksum,
hashProofOfStake.ToString().c_str(),
prevoutStake.ToString().c_str(), nStakeTime,
hashMerkleRoot.ToString().c_str(),
GetBlockHash().ToString().c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** Used to marshal pointers into hashes for db storage. */
class CDiskBlockIndex : public CBlockIndex
{
public:
uint256 hashPrev;
uint256 hashNext;
CDiskBlockIndex()
{
hashPrev = 0;
hashNext = 0;
}
explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
{
hashPrev = (pprev ? pprev->GetBlockHash() : 0);
hashNext = (pnext ? pnext->GetBlockHash() : 0);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(hashNext);
READWRITE(nFile);
READWRITE(nBlockPos);
READWRITE(nHeight);
READWRITE(nMint);
READWRITE(nMoneySupply);
READWRITE(nFlags);
READWRITE(nStakeModifier);
if (IsProofOfStake())
{
READWRITE(prevoutStake);
READWRITE(nStakeTime);
READWRITE(hashProofOfStake);
}
else if (fRead)
{
const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
const_cast<CDiskBlockIndex*>(this)->hashProofOfStake = 0;
}
// block header
READWRITE(this->nVersion);
READWRITE(hashPrev);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
)
uint256 GetBlockHash() const
{
CBlock block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrev;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block.GetHash();
}
std::string ToString() const
{
std::string str = "CDiskBlockIndex(";
str += CBlockIndex::ToString();
str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
GetBlockHash().ToString().c_str(),
hashPrev.ToString().c_str(),
hashNext.ToString().c_str());
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** Describes a place in the block chain to another node such that if the
* other node doesn't have the same branch, it can find a recent common trunk.
* The further back it is, the further before the fork it may be.
*/
class CBlockLocator
{
protected:
std::vector<uint256> vHave;
public:
CBlockLocator()
{
}
explicit CBlockLocator(const CBlockIndex* pindex)
{
Set(pindex);
}
explicit CBlockLocator(uint256 hashBlock)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end())
Set((*mi).second);
}
CBlockLocator(const std::vector<uint256>& vHaveIn)
{
vHave = vHaveIn;
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vHave);
)
void SetNull()
{
vHave.clear();
}
bool IsNull()
{
return vHave.empty();
}
void Set(const CBlockIndex* pindex)
{
vHave.clear();
int nStep = 1;
while (pindex)
{
vHave.push_back(pindex->GetBlockHash());
// Exponentially larger steps back
for (int i = 0; pindex && i < nStep; i++)
pindex = pindex->pprev;
if (vHave.size() > 10)
nStep *= 2;
}
vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
}
int GetDistanceBack()
{
// Retrace how far back it was in the sender's branch
int nDistance = 0;
int nStep = 1;
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return nDistance;
}
nDistance += nStep;
if (nDistance > 10)
nStep *= 2;
}
return nDistance;
}
CBlockIndex* GetBlockIndex()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return pindex;
}
}
return pindexGenesisBlock;
}
uint256 GetBlockHash()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return hash;
}
}
return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
}
int GetHeight()
{
CBlockIndex* pindex = GetBlockIndex();
if (!pindex)
return 0;
return pindex->nHeight;
}
};
class CTxMemPool
{
public:
mutable CCriticalSection cs;
std::map<uint256, CTransaction> mapTx;
std::map<COutPoint, CInPoint> mapNextTx;
bool accept(CTxDB& txdb, CTransaction &tx,
bool fCheckInputs, bool* pfMissingInputs);
bool addUnchecked(const uint256& hash, CTransaction &tx);
bool remove(CTransaction &tx);
void clear();
void queryHashes(std::vector<uint256>& vtxid);
unsigned long size()
{
LOCK(cs);
return mapTx.size();
}
bool exists(uint256 hash)
{
return (mapTx.count(hash) != 0);
}
CTransaction& lookup(uint256 hash)
{
return mapTx[hash];
}
};
extern CTxMemPool mempool;
#endif
| [
"skypigr@gmail.com"
] | skypigr@gmail.com |
26f19277a57a8f728987b136ec2e065262cb762a | 336386125861896c0da96e9957943537138b9334 | /OpenEaagles/src/basicGL/MapPage.cpp | bbdd29623538bbddb2aed98087039eec597a7597 | [] | no_license | WarfareCode/afit-swarm-simulation | bd7cd1149ee2157f73a9ca8cc8f17a522211bd02 | 4f02483407f3fa0247cf7d22e53538090680de82 | refs/heads/master | 2020-06-03T07:37:10.079199 | 2016-04-01T15:49:58 | 2016-04-01T15:49:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,915 | cpp | #include "openeaagles/basicGL/MapPage.h"
#include "openeaagles/basic/PairStream.h"
#include "openeaagles/basicGL/Display.h"
#include "openeaagles/basic/Pair.h"
#include "openeaagles/basic/Number.h"
namespace Eaagles {
namespace BasicGL {
IMPLEMENT_SUBCLASS(MapPage,"MapPage")
EMPTY_SERIALIZER(MapPage)
EMPTY_DELETEDATA(MapPage)
//------------------------------------------------------------------------------
// Slot table
//------------------------------------------------------------------------------
BEGIN_SLOTTABLE(MapPage)
"outerRadius", // 1) radius (centered) of our outer circle (units)
"outerRadiusDecentered", // 2) radius (de-centered) of our outer arc (units)
"range", // 3) our range (NM) of our outer circle or arc
"displacement", // 4) how far to translate when we are decentered (units)
"centered", // 5) are we centered, or de-centered (default: centered)
"refLat", // 6) reference latitude (degs)
"refLon", // 7) reference longitude (degs)
"refHdg", // 8) reference heading (degs)
"northUp", // 9) north up mode
END_SLOTTABLE(MapPage)
BEGIN_SLOT_MAP(MapPage)
ON_SLOT(1, setSlotOuterRadius, Basic::Number)
ON_SLOT(2, setSlotOuterRadiusDC, Basic::Number)
ON_SLOT(3, setSlotRange, Basic::Number)
ON_SLOT(4, setSlotDisplacement, Basic::Number)
ON_SLOT(5, setSlotCentered, Basic::Number)
ON_SLOT(6, setSlotRefLat, Basic::Number)
ON_SLOT(7, setSlotRefLon, Basic::Number)
ON_SLOT(8, setSlotRefHdg, Basic::Number)
ON_SLOT(9, setSlotNorthUp, Basic::Number)
END_SLOT_MAP()
//------------------------------------------------------------------------------
// Event Handler
//------------------------------------------------------------------------------
BEGIN_EVENT_HANDLER(MapPage)
ON_EVENT_OBJ(UPDATE_VALUE, onUpdateRange, Basic::Number)
ON_EVENT_OBJ(UPDATE_VALUE2, onUpdateHeading, Basic::Number)
ON_EVENT_OBJ(UPDATE_VALUE3, onUpdateReferenceLat, Basic::Number)
ON_EVENT_OBJ(UPDATE_VALUE4, onUpdateReferenceLon, Basic::Number)
ON_EVENT_OBJ(UPDATE_VALUE5, onUpdateCentered, Basic::Number)
ON_EVENT_OBJ(UPDATE_VALUE6, onUpdateOuterRadius, Basic::Number)
ON_EVENT_OBJ(UPDATE_VALUE7, onUpdateOuterRadiusDC, Basic::Number)
ON_EVENT_OBJ(UPDATE_VALUE8, onUpdateDisplacement, Basic::Number)
END_EVENT_HANDLER()
//------------------------------------------------------------------------------
// Constructor(s)
//------------------------------------------------------------------------------
MapPage::MapPage()
{
STANDARD_CONSTRUCTOR()
initData();
}
void MapPage::initData()
{
heading = 0;
referenceLat = 0;
referenceLon = 0;
cosineLatReference = 1.0;
headingSin = 0;
headingCos = 1.0;
range = 1.0;
outerRadius = 1.0;
outerRadiusDC = 1.0;
nm2Screen = 1.0;
displacement = 0;
isCentered = true; // we are centered
northUp = true; // start in north up mode
}
//------------------------------------------------------------------------------
// copyData() -- copy member data
//------------------------------------------------------------------------------
void MapPage::copyData(const MapPage& org, const bool cc)
{
// copy base class stuff first
BaseClass::copyData(org);
if (cc) initData();
heading = org.heading;
headingSin = org.headingSin;
headingCos = org.headingCos;
referenceLat = org.referenceLat;
referenceLon = org.referenceLon;
cosineLatReference = org.cosineLatReference;
range = org.range;
outerRadius = org.outerRadius;
outerRadiusDC = org.outerRadiusDC;
nm2Screen = org.nm2Screen;
displacement = org.displacement;
isCentered = org.isCentered;
northUp = org.northUp;
}
//------------------------------------------------------------------------------
// updateData() - updates the values
//------------------------------------------------------------------------------
void MapPage::updateData(const LCreal dt)
{
// find our nearest map page above us and get the data from it!
MapPage* page = static_cast<MapPage*>(findContainerByType(typeid(MapPage)));
if (page != nullptr) {
setHeadingDeg(page->getHeadingDeg());
setDisplacement(page->getDisplacement());
setReferenceLatDeg(page->getReferenceLatDeg());
setReferenceLonDeg(page->getReferenceLonDeg());
setOuterRadius(page->getOuterRadius());
setOuterRadiusDC(page->getOuterRadiusDC());
setCentered(page->getCentered());
setRange(page->getRange());
setNorthUp(page->getNorthUp());
nm2Screen = page->getScale();
}
// if we are the top map page, we do the calculations ourself
else {
// determine if we are centered or not, and set our displacement and radius accordingly
if (isCentered) nm2Screen = outerRadius / range;
else nm2Screen = outerRadiusDC / range;
}
// update base class stuff
BaseClass::updateData(dt);
}
//------------------------------------------------------------------------------
// pixelsToLatLon() - determine our lat lon position from a pixel X/Y
//------------------------------------------------------------------------------
void MapPage::pixelsToLatLon(const int x, const int y, double &lat, double &lon)
{
double xpos = x;
double ypos = y;
// convert pixels position from top left to movement from center, so we
// can base our cals from the center.
if (getDisplay() != nullptr) {
double myLat = 0, myLon = 0;
double dLat = 0, dLon = 0;
GLsizei vpW = 0, vpH = 0;
getDisplay()->getViewportSize(&vpW, &vpH);
GLdouble tl = 0, tr = 0, tb = 0, tt = 0, tn = 0, tf = 0;
getDisplay()->getOrtho(tl, tr, tb, tt, tn, tf);
// determine the middle of our viewing screen
const double startX = (vpW / 2.0);
const double startY = (vpH / 2.0);
// find the position from our screen center (in pixels)
xpos -= startX;
ypos = startY - ypos;
// we have to find our units per pixel
const double unitsPerPixE = ((tr * 2) / vpW);
const double unitsPerPixN = ((tt * 2) / vpH);
// now from that we can determine our position in inches
xpos *= unitsPerPixE;
ypos *= unitsPerPixN;
if (!isCentered) ypos -= displacement;
// ok, now we can find our xpos and ypos in nautical miles
xpos /= nm2Screen;
ypos /= nm2Screen;
if (!getNorthUp()) {
LCreal acX = 0;
LCreal acY = 0;
earth2Aircraft( static_cast<LCreal>(xpos), static_cast<LCreal>(ypos), &acX, &acY);
xpos = acX;
ypos = acY;
}
// reference lat to figure off of (if centered())
myLat = referenceLat;
myLon = referenceLon;
// now convert to degree from our reference lat/lon
dLat = ypos / 60.0;
dLon = xpos / (60.0 * cosineLatReference);
myLat += dLat;
myLon += dLon;
lat = myLat;
lon = myLon;
}
}
//------------------------------------------------------------------------------
// Moves our reference lat lon based on the distance moved.
//------------------------------------------------------------------------------
void MapPage::moveMap(const int startX, const int startY, const int endX, const int endY)
{
double eLat = 0, eLon = 0, lat = 0, lon = 0, sLat = 0, sLon = 0, deltaLat = 0, deltaLon = 0;
// figure our lat/lon positioning
pixelsToLatLon(startX, startY, sLat, sLon);
pixelsToLatLon(endX, endY, eLat, eLon);
// get our delta movement
deltaLat = sLat - eLat;
deltaLon = sLon - eLon;
lat = getReferenceLatDeg();
lon = getReferenceLonDeg();
lat += deltaLat;
lon += deltaLon;
// As the world turns.... we need to flip the maps!
if (lon > 180) lon = -180;
else if (lon < -180) lon = 180;
if (lat > 90) lat = -90;
else if (lat < -90) lat = 90;
setReferenceLatDeg(lat);
setReferenceLonDeg(lon);
}
//------------------------------------------------------------------------------
// converts lat/lon to screen coordinates
//------------------------------------------------------------------------------
bool MapPage::latLon2Screen(const double lat, const double lon,
LCreal* const x, LCreal* const y) const
{
bool ok = false;
if (x != nullptr && y != nullptr) {
// Convert to nautical miles (NED) centered on ownship
const double earthX = ((lat - getReferenceLatDeg()) * 60.0);
const double earthY = ((lon - getReferenceLonDeg()) * 60.0 * getCosRefLat());
// Rotate to aircraft coordinates
double acX = 0;
double acY = 0;
if (getNorthUp()) {
acX = earthX;
acY = earthY;
}
else {
acX = (earthX * headingCos) + (earthY * headingSin);
acY = -(earthX * headingSin) + (earthY * headingCos);
}
// Scale from nautical miles to inches and
// transpose the X and Y from A/C to screen
double screenY = acX * getScale();
const double screenX = acY * getScale();
// Adjust for the decentered displayment
if ( !getCentered() ) screenY += getDisplacement();
*x = static_cast<LCreal>(screenX);
*y = static_cast<LCreal>(screenY);
ok = true;
}
return ok;
}
//------------------------------------------------------------------------------
// converts screen to lat/lon coordinates
//------------------------------------------------------------------------------
bool MapPage::screen2LatLon(const LCreal x, const LCreal y,
double* const lat, double* const lon) const
{
bool ok = false;
const double scale = getScale();
const double cosLat = getCosRefLat();
if (lat != nullptr && lon != nullptr && scale != 0 && cosLat != 0) {
// buffer the inputs
double screenX = x;
double screenY = y;
// Adjust for the decentered displayment
if ( !getCentered() ) screenY -= getDisplacement();
// Scale from screen (inches) to A/C (NM) and
// transpose the X and Y from screen to A/C
const double acX = screenY/scale;
const double acY = screenX/scale;
// Rotate A/C to NED
double earthX = 0.0;
double earthY = 0.0;
if (getNorthUp()) {
earthX = acX;
earthY = acY;
}
else {
earthX = (acX * headingCos) - (acY * headingSin);
earthY = (acX * headingSin) + (acY * headingCos);
}
// Convert nautical miles (NED) from ref point to lat/lon
*lat = (earthX/60.0) + getReferenceLatDeg();
*lon = (earthY/(60.0*cosLat)) + getReferenceLonDeg();
ok = true;
}
return ok;
}
//------------------------------------------------------------------------------
// aircraft2Screen() - converts real world coordinates to X, Y in inches.
//------------------------------------------------------------------------------
bool MapPage::aircraft2Screen(const LCreal acX, const LCreal acY, LCreal* const screenX, LCreal* const screenY) const
{
bool ok = false;
if (screenX != nullptr && screenY != nullptr) {
const double newX = (acX * nm2Screen);
const double newY = (acY * nm2Screen);
// now set the pointers to the new X and Y values
*screenX = static_cast<LCreal>(newY);
*screenY = static_cast<LCreal>(newX);
ok = true;
}
return ok;
}
//------------------------------------------------------------------------------
// earth2Aircraft() - converts earth coordinates to aircraft coordinates.
//------------------------------------------------------------------------------
bool MapPage::earth2Aircraft(const LCreal earthX, const LCreal earthY, LCreal* const acX, LCreal* const acY) const
{
bool ok = false;
if (acX != nullptr && acY != nullptr) {
const double x = (earthX * headingCos) + (earthY * headingSin);
const double y = -(earthX * headingSin) + (earthY * headingCos);
*acX = static_cast<LCreal>(x);
*acY = static_cast<LCreal>(y);
ok = true;
}
return ok;
}
//------------------------------------------------------------------------------
// latLonToEarth() - converts a latitude/longitude to earth coordinates.
//------------------------------------------------------------------------------
bool MapPage::latLon2Earth(const double lat, const double lon, LCreal* const earthX, LCreal* const earthY) const
{
bool ok = false;
if (earthX != nullptr && earthY != nullptr) {
*earthX = static_cast<LCreal>((lat - referenceLat) * 60.0);
*earthY = static_cast<LCreal>((lon - referenceLon) * 60.0 * cosineLatReference);
ok = true;
}
return ok;
}
//------------------------------------------------------------------------------
// event functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// onUpdateRange() - set our new range
//------------------------------------------------------------------------------
bool MapPage::onUpdateRange(const Basic::Number* const newR)
{
bool ok = false;
if (newR != nullptr) ok = setRange(newR->getReal());
return ok;
}
//------------------------------------------------------------------------------
// onUpdateHeading() - set our new heading
//------------------------------------------------------------------------------
bool MapPage::onUpdateHeading(const Basic::Number* const newH)
{
bool ok = false;
if (newH != nullptr) ok = setHeadingDeg(newH->getReal());
return ok;
}
//------------------------------------------------------------------------------
// onUpdateReferenceLat() - set our new reference latitude
//------------------------------------------------------------------------------
bool MapPage::onUpdateReferenceLat(const Basic::Number* const newOL)
{
bool ok = false;
if (newOL != nullptr) ok = setReferenceLatDeg(newOL->getDouble());
return ok;
}
//------------------------------------------------------------------------------
// onUpdateReferenceLon() - set our new reference longitude
//------------------------------------------------------------------------------
bool MapPage::onUpdateReferenceLon(const Basic::Number* const newOL)
{
bool ok = false;
if (newOL != nullptr) ok = setReferenceLonDeg(newOL->getDouble());
return ok;
}
//------------------------------------------------------------------------------
// onUpdateCentered() - set our centered / decentered flag
//------------------------------------------------------------------------------
bool MapPage::onUpdateCentered(const Basic::Number* const newC)
{
bool ok = false;
if (newC != nullptr) ok = setCentered(newC->getBoolean());
return ok;
}
//------------------------------------------------------------------------------
// onUpdateOuterRadius() - set our new outer map area
//------------------------------------------------------------------------------
bool MapPage::onUpdateOuterRadius(const Basic::Number* const newR)
{
bool ok = false;
if (newR != nullptr) ok = setOuterRadius(newR->getReal());
return ok;
}
//------------------------------------------------------------------------------
// onUpdateOuterRadiusDC() - set our new outer map area, decentered
//------------------------------------------------------------------------------
bool MapPage::onUpdateOuterRadiusDC(const Basic::Number* const newRDC)
{
bool ok = false;
if (newRDC != nullptr) ok = setOuterRadiusDC(newRDC->getReal());
return ok;
}
//------------------------------------------------------------------------------
// onUpdateDisplacement() - set our new displacement
//------------------------------------------------------------------------------
bool MapPage::onUpdateDisplacement(const Basic::Number* const newD)
{
bool ok = false;
if (newD != nullptr) ok = setDisplacement(newD->getReal());
return ok;
}
// SLOT FUNCTIONS
//------------------------------------------------------------------------------
// setSlotOuterRadius() - sets the outer radius of our compass rose, if we
// are centered
//------------------------------------------------------------------------------
bool MapPage::setSlotOuterRadius(const Basic::Number* const newRadius)
{
bool ok = false;
if (newRadius != nullptr) ok = setOuterRadius(newRadius->getReal());
return ok;
}
//------------------------------------------------------------------------------
// setSlotOuterRadiusDC() - sets the outer radius of our compass rose, if
// we are de-centered
//------------------------------------------------------------------------------
bool MapPage::setSlotOuterRadiusDC(const Basic::Number* const newDCRadius)
{
bool ok = false;
if (newDCRadius != nullptr) ok = setOuterRadiusDC(newDCRadius->getReal());
return ok;
}
//------------------------------------------------------------------------------
// setSlotRange() - sets the range of our viewing areas, in nautical miles
//------------------------------------------------------------------------------
bool MapPage::setSlotRange(const Basic::Number* const newR)
{
bool ok = false;
if (newR != nullptr) ok = setRange(newR->getReal());
return ok;
}
//------------------------------------------------------------------------------
// setSlotDisplacement() - sets how far we translate before we draw
//------------------------------------------------------------------------------
bool MapPage::setSlotDisplacement(const Basic::Number* const newD)
{
bool ok = false;
if (newD != nullptr) ok = setDisplacement(newD->getReal());
return ok;
}
//------------------------------------------------------------------------------
// setSlotCentered() - sets if we are centered or decentered
//------------------------------------------------------------------------------
bool MapPage::setSlotCentered(const Basic::Number* const newC)
{
bool ok = false;
if (newC != nullptr) ok = setCentered(newC->getBoolean());
return ok;
}
//------------------------------------------------------------------------------
// setSlotRefLat() - sets ref lat from slot
//------------------------------------------------------------------------------
bool MapPage::setSlotRefLat(const Basic::Number* const x)
{
bool ok = false;
if (x != nullptr) ok = setReferenceLatDeg(x->getDouble());
return ok;
}
//------------------------------------------------------------------------------
// setSlotRefLon() - sets ref lon from slot
//------------------------------------------------------------------------------
bool MapPage::setSlotRefLon(const Basic::Number* const x)
{
bool ok = false;
if (x != nullptr) ok = setReferenceLonDeg(x->getDouble());
return ok;
}
//------------------------------------------------------------------------------
// setSlotRefHdg() - sets ref heading from slot
//------------------------------------------------------------------------------
bool MapPage::setSlotRefHdg(const Basic::Number* const x)
{
bool ok = false;
if (x != nullptr) ok = setHeadingDeg(x->getReal());
return ok;
}
//------------------------------------------------------------------------------
// setSlotNorthUp() - sets north up / track up from slot
//------------------------------------------------------------------------------
bool MapPage::setSlotNorthUp(const Basic::Number* const x)
{
bool ok = false;
if (x != nullptr) ok = setNorthUp(x->getBoolean());
return ok;
}
//------------------------------------------------------------------------------
// getSlotByIndex() for MapPage
//------------------------------------------------------------------------------
Basic::Object* MapPage::getSlotByIndex(const int si)
{
return BaseClass::getSlotByIndex(si);
}
} // end of BasicGL namespace
} // end of Eaagles namespace
| [
"derek.worth@afit.edu"
] | derek.worth@afit.edu |
9bdef7ceae53c90d796cdc26b59d096b4533a310 | 51635684d03e47ebad12b8872ff469b83f36aa52 | /external/gcc-12.1.0/libstdc++-v3/testsuite/27_io/basic_stringstream/str/char/5.cc | 5ba3b6fe284f0803b19a1ee2bd8ea474f8b0f228 | [
"Zlib",
"LicenseRef-scancode-public-domain",
"LGPL-2.1-only",
"GPL-3.0-only",
"GCC-exception-3.1",
"GPL-2.0-only",
"LGPL-3.0-only",
"LGPL-2.0-or-later"
] | permissive | zhmu/ananas | 8fb48ddfe3582f85ff39184fc7a3c58725fe731a | 30850c1639f03bccbfb2f2b03361792cc8fae52e | refs/heads/master | 2022-06-25T10:44:46.256604 | 2022-06-12T17:04:40 | 2022-06-12T17:04:40 | 30,108,381 | 59 | 8 | Zlib | 2021-09-26T17:30:30 | 2015-01-31T09:44:33 | C | UTF-8 | C++ | false | false | 2,734 | cc | // Copyright (C) 2020-2022 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
// This library 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 this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 29.8.5.4 basic_stringstream member functions [stringstream.members]
// { dg-options "-std=gnu++2a" }
// { dg-do run { target c++2a } }
// { dg-require-effective-target cxx11_abi }
#include <sstream>
#include <testsuite_hooks.h>
#include <testsuite_allocator.h>
void test01()
{
const std::string s0 = "this is not a short string";
std::stringstream ss;
ss.str(s0);
VERIFY( ss.str() == s0 );
VERIFY( ss.str() == s0 );
using Alloc = __gnu_test::uneq_allocator<char>;
const Alloc a1(1);
std::basic_string<char, std::char_traits<char>, Alloc> s1 = ss.str(a1);
VERIFY( s1.get_allocator() == a1 );
VERIFY( ss.str(a1).get_allocator() == a1 );
VERIFY( ss.str(a1) == s1 );
VERIFY( std::move(ss).str(a1) == s1 );
VERIFY( std::move(ss).str(a1) == s1 );
const Alloc a2(2);
VERIFY( ss.str(a2).get_allocator() == a2 );
VERIFY( ss.str(a2) == s1 );
VERIFY( std::move(ss).str() == s0 );
VERIFY( std::move(ss).str().empty() );
VERIFY( ss.str().empty() );
VERIFY( ss.str(a1).empty() );
}
void test02()
{
std::stringstream ss("123");
std::string str = "ABCDEF";
ss << str;
VERIFY( ss.str() == str );
VERIFY( std::move(ss).str() == str );
VERIFY( std::move(ss).str().empty() );
}
void test03()
{
std::stringstream ss;
using Alloc = __gnu_test::tracker_allocator<char>;
using Str = std::basic_string<char, std::char_traits<char>, Alloc>;
Str s1 = "string that is not short, quite long even";
auto count1 = __gnu_test::tracker_allocator_counter::get_allocation_count();
ss.str(s1);
auto count2 = __gnu_test::tracker_allocator_counter::get_allocation_count();
VERIFY( count1 == count2 );
VERIFY( ss.str() == s1.c_str() );
}
void test04()
{
std::stringstream ss;
const std::string str = "Another quite long string, not at all short";
std::string str2 = str;
ss.str(std::move(str2));
VERIFY( str2.empty() );
VERIFY( ss.str() == str );
}
int main()
{
test01();
test02();
test03();
test04();
}
| [
"rink@rink.nu"
] | rink@rink.nu |
7aceffc000ed625df4fcbb47bf9f6e47a6bcefab | a470eefd60f183c535e3b99078da4faa83784de1 | /SDK/nncamsdk/extras/directshow/samples/demodshow/dshow.h | a76f7fe5a4d0370e43f7a6126b05337f0efda2ac | [] | no_license | tdwebste/bestscope_E3ISPM20000KPA_camera | 5d001f4f58e216f87293bf1d49650923584eda61 | 345c1428fbc6ba15c473cd974e92e5b1f5ea883e | refs/heads/master | 2022-12-11T23:35:01.532890 | 2020-09-08T22:43:33 | 2020-09-08T22:43:33 | 291,879,758 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,686 | h | #ifndef __dshow_h__
#define __dshow_h__
#include <vector>
#include <string>
#include <dshow.h>
#include <Dshowasf.h>
#include <wmsdk.h>
#include <InitGuid.h>
#include "toupcam_dshow.h"
#define SAFE_RELEASE(x) \
do{ \
if ((x)) \
{ \
(x)->Release(); \
(x) = NULL; \
} \
}while(0)
interface ISampleGrabberCB : public IUnknown
{
virtual STDMETHODIMP SampleCB(double SampleTime, IMediaSample *pSample) = 0;
virtual STDMETHODIMP BufferCB(double SampleTime, BYTE *pBuffer, long BufferLen) = 0;
};
static const IID IID_ISampleGrabberCB = { 0x0579154A, 0x2B53, 0x4994, { 0xB0, 0xD0, 0xE7, 0x73, 0x14, 0x8E, 0xFF, 0x85 } };
interface ISampleGrabber: public IUnknown
{
virtual HRESULT STDMETHODCALLTYPE SetOneShot(BOOL OneShot) = 0;
virtual HRESULT STDMETHODCALLTYPE SetMediaType(const AM_MEDIA_TYPE *pType) = 0;
virtual HRESULT STDMETHODCALLTYPE GetConnectedMediaType( AM_MEDIA_TYPE *pType) = 0;
virtual HRESULT STDMETHODCALLTYPE SetBufferSamples(BOOL BufferThem) = 0;
virtual HRESULT STDMETHODCALLTYPE GetCurrentBuffer(long *pBufferSize, long *pBuffer) = 0;
virtual HRESULT STDMETHODCALLTYPE GetCurrentSample(IMediaSample **ppSample) = 0;
virtual HRESULT STDMETHODCALLTYPE SetCallback(ISampleGrabberCB *pCallback, long WhichMethodToCallback) = 0;
};
#ifndef __ICaptureGraphBuilder2_INTERFACE_DEFINED__
#define __ICaptureGraphBuilder2_INTERFACE_DEFINED__
MIDL_INTERFACE("93E5A4E0-2D50-11d2-ABFA-00A0C9C6E38D")
ICaptureGraphBuilder2 : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE SetFiltergraph(
/* [in] */ IGraphBuilder *pfg) = 0;
virtual HRESULT STDMETHODCALLTYPE GetFiltergraph(
/* [out] */
__out IGraphBuilder **ppfg) = 0;
virtual HRESULT STDMETHODCALLTYPE SetOutputFileName(
/* [in] */ const GUID *pType,
/* [in] */ LPCOLESTR lpstrFile,
/* [out] */
__out IBaseFilter **ppf,
/* [out] */
__out IFileSinkFilter **ppSink) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE FindInterface(
/* [in] */
__in_opt const GUID *pCategory,
/* [in] */
__in_opt const GUID *pType,
/* [in] */ IBaseFilter *pf,
/* [in] */ REFIID riid,
/* [out] */
__out void **ppint) = 0;
virtual HRESULT STDMETHODCALLTYPE RenderStream(
/* [in] */
__in_opt const GUID *pCategory,
/* [in] */ const GUID *pType,
/* [in] */ IUnknown *pSource,
/* [in] */ IBaseFilter *pfCompressor,
/* [in] */ IBaseFilter *pfRenderer) = 0;
virtual HRESULT STDMETHODCALLTYPE ControlStream(
/* [in] */ const GUID *pCategory,
/* [in] */ const GUID *pType,
/* [in] */ IBaseFilter *pFilter,
/* [in] */
__in_opt REFERENCE_TIME *pstart,
/* [in] */
__in_opt REFERENCE_TIME *pstop,
/* [in] */ WORD wStartCookie,
/* [in] */ WORD wStopCookie) = 0;
virtual HRESULT STDMETHODCALLTYPE AllocCapFile(
/* [in] */ LPCOLESTR lpstr,
/* [in] */ DWORDLONG dwlSize) = 0;
virtual HRESULT STDMETHODCALLTYPE CopyCaptureFile(
/* [in] */
__in LPOLESTR lpwstrOld,
/* [in] */
__in LPOLESTR lpwstrNew,
/* [in] */ int fAllowEscAbort,
/* [in] */ IAMCopyCaptureFileProgress *pCallback) = 0;
virtual HRESULT STDMETHODCALLTYPE FindPin(
/* [in] */ IUnknown *pSource,
/* [in] */ PIN_DIRECTION pindir,
/* [in] */
__in_opt const GUID *pCategory,
/* [in] */
__in_opt const GUID *pType,
/* [in] */ BOOL fUnconnected,
/* [in] */ int num,
/* [out] */
__out IPin **ppPin) = 0;
};
#endif
static const IID IID_ISampleGrabber = { 0x6B652FFF, 0x11FE, 0x4fce, { 0x92, 0xAD, 0x02, 0x66, 0xB5, 0xD7, 0xC7, 0x8F } };
static const CLSID CLSID_SampleGrabber = { 0xC1F400A0, 0x3F08, 0x11d3, { 0x9F, 0x0B, 0x00, 0x60, 0x08, 0x03, 0x9E, 0x37 } };
static const CLSID CLSID_NullRenderer = { 0xC1F400A4, 0x3F08, 0x11d3, { 0x9F, 0x0B, 0x00, 0x60, 0x08, 0x03, 0x9E, 0x37 } };
class SampleGrabberCBImpl : public ISampleGrabberCB
{
bool bCapturing_;
ISampleGrabber* pISampleGrabber_;
std::wstring filename_;
public:
SampleGrabberCBImpl();
bool bCapturing()const { return bCapturing_; }
void start(const std::wstring& fn, ISampleGrabber* pISampleGrabber)
{
filename_ = fn;
bCapturing_ = true;
pISampleGrabber_ = pISampleGrabber;
}
virtual ULONG STDMETHODCALLTYPE AddRef() { return 2; }
virtual ULONG STDMETHODCALLTYPE Release() { return 1; }
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** ppvObject);
virtual STDMETHODIMP SampleCB(double SampleTime, IMediaSample* pSample);
virtual STDMETHODIMP BufferCB(double SampleTime, BYTE* pBuffer, long BufferLen);
};
class TDshowContext
{
const std::wstring m_devname;
const HWND m_hParent;
const HWND m_hOwner;
const UINT m_NotifyMsg;
std::wstring m_strFullPath;
IMoniker* m_pVideoMoniker;
ICaptureGraphBuilder2* m_pBuilder;
IVideoWindow* m_pVW;
IMediaEventEx* m_pME;
IAMVfwCaptureDialogs* m_pDlg;
IAMStreamConfig* m_pAMStreamConfig; // for video cap
IBaseFilter* m_pRender;
IBaseFilter* m_pSource;
IGraphBuilder* m_pFg;
IBaseFilter* m_pSampleGrabber;
IAMVideoControl* m_pStillImageVideoControl;
IPin* m_pStillImagePin;
IBaseFilter* m_pStillSampleGrabber;
IAMStreamConfig* m_pStillImageAMStreamConfig;
int m_iVCapDialogPos;
int m_iVCapCapturePinDialogPos;
int m_iVStillImagePinDialogPos;
BOOL m_fPreviewGraphBuilt;
BOOL m_fPreviewing;
BOOL m_fCaptureGraphBuilt;
BOOL m_fCapturing;
BOOL m_bFullscreen;
SampleGrabberCBImpl m_SampleGrabberCBImpl;
public:
TDshowContext(const std::wstring& devname, HWND hParent, HWND hOwner, IMoniker* pVideoMoniker, UINT NotifyMsg);
public:
BOOL IsCapturing()const { return m_fCapturing; }
BOOL IsPreviewing()const { return m_fPreviewing; }
public:
HRESULT start(HMENU hMenuSub1, UINT pos, UINT times, UINT cmdID);
void stop();
HRESULT startcapture(const wchar_t* szFullPath);
void stopcapture();
void on_notify();
void on_dialog(int id);
BOOL video_size(LONG* lWidth, LONG* lHeight);
void resize_window();
BOOL full_screen();
void move_window();
double get_framerate();
BOOL preview_snapshot(const wchar_t* filename);
BOOL stillimage_supported();
BOOL stillimage_snapshot(const wchar_t* filename);
HRESULT queryinterface(const IID& riid, void **ppvObj);
private:
BOOL MakeBuilder();
BOOL MakeGraph();
HRESULT BuildPreviewGraph();
BOOL BuildCaptureGraph();
BOOL StartPreview();
BOOL StartCapture();
BOOL RenderStillPin();
HRESULT InitCapFilters();
BOOL StopPreview();
BOOL StopCapture();
void TearDownGraph();
void FreeCapFilters();
void NukeDownstream(IBaseFilter* pf);
void MakeMenuOptions(BOOL bAdd, HMENU hMenuSub1, UINT pos, UINT times, UINT cmdID);
BOOL snapshot(IBaseFilter* pSampleGrabber, const wchar_t* filename);
};
typedef struct
{
std::wstring DisplayName;
std::wstring FriendlyName;
}TDshowDevice;
extern std::vector<TDshowDevice> dscap_enum_device();
extern TDshowContext* NewDshowContext(HWND hParent, HWND hOwner, const std::wstring& devname, UINT NotifyMsg);
extern BOOL savebitmap(const BITMAPINFOHEADER* pHeader, const char* data, long nSize, const wchar_t* filename);
#endif
| [
"tdwebste@gmail.com"
] | tdwebste@gmail.com |
189991a69f8c4d32103fe61489915a030b5564fc | 019b085ac8ef4594fb43a1566b8e984cd34fac16 | /platforms/nuttx/NuttX/apps/graphics/NxWidgets/UnitTests/CGlyphButton/cglyphbuttontest.hxx | 3db97111229c128ddd72569eb6cd0b2f76e202d0 | [
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | JJRnumrous/Firmware | fffabcee637b5fe00f374b6849894ae518b8c8af | 7c3505dffa465be7bcef4602976df853d587e467 | refs/heads/master | 2020-08-17T20:26:09.876510 | 2019-10-17T05:22:09 | 2019-10-17T05:22:09 | 150,714,296 | 0 | 0 | BSD-3-Clause | 2018-09-28T09:06:12 | 2018-09-28T09:06:12 | null | UTF-8 | C++ | false | false | 6,073 | hxx | /////////////////////////////////////////////////////////////////////////////
// apps/graphics/NxWidgets/UnitTests/CGlyphButton/cglyphbuttontest.hxx
//
// Copyright (C) 2012 Gregory Nutt. All rights reserved.
// Author: Gregory Nutt <gnutt@nuttx.org>
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
// 3. Neither the name NuttX, NxWidgets, nor the names of its contributors
// me 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef __UNITTESTS_CGLYPHBUTTON_CGLYPHBUTTONTEST_HXX
#define __UNITTESTS_CGLYPHBUTTON_CGLYPHBUTTONTEST_HXX
/////////////////////////////////////////////////////////////////////////////
// Included Files
/////////////////////////////////////////////////////////////////////////////
#include <nuttx/config.h>
#include <nuttx/init.h>
#include <cstdio>
#include <semaphore.h>
#include <debug.h>
#include <nuttx/nx/nx.h>
#include "nxwidgets/nxconfig.hxx"
#include "nxwidgets/cwidgetcontrol.hxx"
#include "nxwidgets/ccallback.hxx"
#include "nxwidgets/cbgwindow.hxx"
#include "nxwidgets/cnxserver.hxx"
#include "nxwidgets/cnxfont.hxx"
#include "nxwidgets/cnxstring.hxx"
#include "nxwidgets/cglyphbutton.hxx"
#include "nxwidgets/cbitmap.hxx"
/////////////////////////////////////////////////////////////////////////////
// Definitions
/////////////////////////////////////////////////////////////////////////////
// Configuration ////////////////////////////////////////////////////////////
#ifndef CONFIG_HAVE_CXX
# error "CONFIG_HAVE_CXX must be defined"
#endif
#ifndef CONFIG_CGLYPHBUTTONTEST_BGCOLOR
# define CONFIG_CGLYPHBUTTONTEST_BGCOLOR CONFIG_NXWIDGETS_DEFAULT_BACKGROUNDCOLOR
#endif
#ifndef CONFIG_CGLYPHBUTTONTEST_FONTCOLOR
# define CONFIG_CGLYPHBUTTONTEST_FONTCOLOR CONFIG_NXWIDGETS_DEFAULT_FONTCOLOR
#endif
// Helper macros
#ifndef MAX
# define MAX(a,b) ((a) > (b) ? (a) : (b))
#endif
/////////////////////////////////////////////////////////////////////////////
// Public Classes
/////////////////////////////////////////////////////////////////////////////
using namespace NXWidgets;
class CGlyphButtonTest : public CNxServer
{
private:
CWidgetControl *m_widgetControl; // The controlling widget for the window
CBgWindow *m_bgWindow; // Background window instance
struct nxgl_point_s m_center; // X, Y position the center of the button
public:
// Constructor/destructors
CGlyphButtonTest();
~CGlyphButtonTest();
// Initializer/unitializer. These methods encapsulate the basic steps for
// starting and stopping the NX server
bool connect(void);
void disconnect(void);
// Create a window. This method provides the general operations for
// creating a window that you can draw within.
//
// Those general operations are:
// 1) Create a dumb CWigetControl instance
// 2) Pass the dumb CWidgetControl instance to the window constructor
// that inherits from INxWindow. This will "smarten" the CWidgetControl
// instance with some window knowlede
// 3) Call the open() method on the window to display the window.
// 4) After that, the fully smartened CWidgetControl instance can
// be used to generate additional widgets by passing it to the
// widget constructor
bool createWindow(void);
// Create a CGlyphButton instance. This method will show you how to create
// a CGlyphButton widget
CGlyphButton *createButton(FAR const struct SBitmap *clickGlyph,
FAR const struct SBitmap *unClickedGlyph);
// Draw the button. This method illustrates how to draw the CGlyphButton widget.
void showButton(CGlyphButton *button);
// Perform a simulated mouse click on the button. This method injects
// the mouse click through the NX heirarchy just as would real mouse
// hardward.
void click(void);
// The counterpart to click. This simulates a button release through
// the same mechanism.
void release(void);
// Widget events are normally handled in a model loop (by calling goModel()).
// However, for this case we know when there should be press and release
// events so we don't have to poll. We can just perform a one pass poll
// then check if the event was processed corredly.
bool poll(CGlyphButton *button);
};
/////////////////////////////////////////////////////////////////////////////
// Public Data
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Public Function Prototypes
/////////////////////////////////////////////////////////////////////////////
#endif // __UNITTESTS_CGLYPHBUTTON_CGLYPHBUTTONTEST_HXX
| [
"18231349@sun.ac.za"
] | 18231349@sun.ac.za |
d6e71bcad0f2a7925d2a7ad37080b6f091728cf6 | adff020269314e7c714566fb5a943a883958dd28 | /MP3/camera.h | 2d31bc7dc70a95bfc00ebfc4bce4d85944dca891 | [] | no_license | fgoyal/CS419 | 386eaf0d84c01a47912ece15656ee63338b53d02 | 449aff0ea79fd2596e760a204d0dee04bec31b1d | refs/heads/main | 2023-04-07T01:08:23.989707 | 2021-04-08T02:16:34 | 2021-04-08T02:16:34 | 336,934,774 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 997 | h | #ifndef CAMERA_H
#define CAMERA_H
#include "vec3.h"
#include "ray.h"
#include <iostream>
class camera {
public:
camera(point3 eye, vec3 view, vec3 up, double d, int image_width, int image_height, double s) {
eyepoint = eye;
dir = d;
// calculate orthonormal basis
w = unit_vector(eyepoint - view);
u = unit_vector(cross(up, w));
v = cross(w, u);
}
ray get_ray(vec3 coordinate) const;
private:
point3 eyepoint;
double dir;
vec3 w;
vec3 u;
vec3 v;
};
/**
* Calculates a ray through the coordinate in world space coordinates
* @param coordinate coordinate in local camera space
* @return a ray that can intersect objects in the world space system
*/
ray camera::get_ray(vec3 coordinate) const {
vec3 pv = coordinate - eyepoint - vec3(0.0, 0.0, dir);
vec3 pw = u * pv.x() + v * pv.y() + w * pv.z();
return ray(eyepoint, pw);
}
#endif | [
"fgoyal2@illinois.edu"
] | fgoyal2@illinois.edu |
d54f1910c97c5b0132aba24cd8730d05ab6c8df7 | 1a02028ff7ac8516603b61386f521072b30c1e89 | /EmployeeTets.cpp | b937287ea85338236795a6ec6eb1ddd47fac6e2c | [] | no_license | yk92/EmployeeProgram | 007564e87ea1b6af004baff20447fc64c19ef138 | 9289e839e5d13f1bbc1ca92738a654ab9d493841 | refs/heads/master | 2021-01-17T20:39:47.243155 | 2016-06-18T22:54:06 | 2016-06-18T22:54:06 | 61,452,202 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 357 | cpp | #include <iostream>
#include "Employee.h"
using namespace std;
using namespace Records;
int main() {
cout << "testing the Employee class." << endl;
Employee emp;
emp.setFirstName("Yuval");
emp.setLastName("Klein");
emp.setEmployeeNumber(13);
emp.setSalary(134000);
emp.promote();
emp.promote(5050);
emp.hire();
emp.display();
return 0;
} | [
"yk92@njit.edu"
] | yk92@njit.edu |
90dc97ee1905e09dd4d2fd631aaa50c67d75d97b | 4edf2d108a8c00a04f31dbabead74baec4fdcb5c | /Beginner Contest 175/a.cpp | c74ba423b2b00ecc6bdd8c6542f9860d27d25832 | [] | no_license | bsdoshi01/AtCoder | 4b8c91fbd9eea06dd8cd090b9c1d178ee62e6b62 | 7166b7f1ad3707eee526ef6d628afe593f64337e | refs/heads/master | 2022-12-13T14:22:57.307955 | 2020-09-01T05:00:26 | 2020-09-01T05:00:26 | 287,719,937 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 339 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
void solve() {
char s[3];
int num = 0, max = 0;
cin >> s;
for (int i = 0; i < 3; ++i) {
if (s[i] == 'R') {
num++;
if (max < num)
max = num;
} else {
num = 0;
}
}
cout << max << endl;
}
int main() {
solve();
return 0;
} | [
"bsdoshi01@gmail.com"
] | bsdoshi01@gmail.com |
e83bba226c495be0299d6695d492d78c076ac82d | f76acf8c3e9b68a06d51e7ebef7da08225606b34 | /cppcen-html/prog14.cpp | bf1f7d53a2094eaf20f77ce11309b8d7e4c5961d | [] | no_license | Zaxcoding/c-to-cpp | 88156abd96a8f9ad34e1b6eb4eb98c855c7c1f0f | 4fa9674ca1ec510e4c06c7e71984711484c4f06d | refs/heads/master | 2020-04-19T18:15:30.417944 | 2012-12-19T00:57:46 | 2012-12-19T00:57:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,364 | cpp | // a truly new concept - operator overloading
// you can change the meaning of operators
// like *, +, <<, >>, ++, +=, []
// as they affect certain structs
// the '<<' in particular is very cool
using namespace std;
#include <iostream>
struct simple_array {
double x;
double y;
};
simple_array operator * (double scale_by, simple_array to_change) {
simple_array temp;
temp.x = scale_by * to_change.x;
temp.y = scale_by * to_change.y;
return temp;
}
ostream& operator << (ostream& out, simple_array to_display) {
out << "{" << to_display.x << ", " << to_display.y << "}";
return out;
}
int main() {
simple_array k, m;
k.x = 2;
k.y = -1;
cout << "So I made 2 'simple_array's.\n"
<< "The first is initialized to {2, -1}, and the second"
<< " is 5 * the first.\n";
m = 5 * k;
cout << "So now the first is {" << k.x << ", " << k.y << "}\n"
<< "and the second is {" << m.x << ", " << m.y << "}\n";
cout << "\nImportantly, this is not a commutative operator;\n"
<< "double * simple_array is defined, but not vice versa.\n";
cout << "One more cool trick - if you define:\n"
<< "\"ostream& operator << (ostream& out, TYPE name)\"\n"
<< "Then you can do this:\n"
<< "\"simple_array k = \" << k << endl\"\n"
<< "like so:\n"
<< "simple_array k = " << k
<< "\nThat right there is nifty.\n";
return 0;
} | [
"zaxcoding@gmail.com"
] | zaxcoding@gmail.com |
c319848a8859ada38cc0f0f955ddc40529bb12fd | 157fd7fe5e541c8ef7559b212078eb7a6dbf51c6 | /TRiAS/TRiASDB/TRiASMI/TRiASMIGeoFeatures.cpp | 99d416b237583da7a2581d00cc89f86ecf47e593 | [] | no_license | 15831944/TRiAS | d2bab6fd129a86fc2f06f2103d8bcd08237c49af | 840946b85dcefb34efc219446240e21f51d2c60d | refs/heads/master | 2020-09-05T05:56:39.624150 | 2012-11-11T02:24:49 | 2012-11-11T02:24:49 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 4,586 | cpp | // $Header: $
// Copyright© 1998-2000 TRiAS GmbH Potsdam, All rights reserved
// Created: 14.09.2000 21:21:48
//
// This file was generated by the TRiASDB Data Server Wizard V1.02.103 (#HK000729)
//
// @doc
// @module TRiASMIGeoFeatures.cpp | Implementation of the <c CTRiASMIGeoFeatures> class
#include "stdafx.h"
#include "Strings.h"
#include "TRiASMI.h"
#include "TRiASMIGeoFeatures.h"
#include "MiTabLayer.h"
#if defined(_DEBUG)
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif // _DEBUG
/////////////////////////////////////////////////////////////////////////////
// CTRiASMIGeoFeatures
STDMETHODIMP CTRiASMIGeoFeatures::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_ITRiASFeatures,
};
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
///////////////////////////////////////////////////////////////////////////////
// ITRiASFeaturesCallback
STDMETHODIMP CTRiASMIGeoFeatures::get_DefaultType (BSTR *pbstrType)
{
CHECKOUTPOINTER(pbstrType);
CIID Guid (CLSID_TRiASSimpleGeoFeature); // DefaultType der _Elemente_ !
CComBSTR bstrType (Guid.ProgID().c_str());
*pbstrType = bstrType.Detach();
return S_OK;
}
// eine neue Objekteigenschaft soll erzeugt werden
STDMETHODIMP CTRiASMIGeoFeatures::OnCreate (VARIANT NameOrHandle, BSTR Type, FEATURETYPE rgType, ITRiASFeature **ppIFeat)
{
// wird z.Zt. nicht gerufen (TRiAS unterstützt lediglich eine Geometrie je Objektklasse)
_ASSERTE(FALSE);
return E_NOTIMPL;
}
/////////////////////////////////////////////////////////////////////////////
//
STDMETHODIMP CTRiASMIGeoFeatures::OnChanging(CHANGEDFEATURES rgWhat, VARIANT vNewValue, VARIANT_BOOL *pDisAllow)
{
CHECKOUTPOINTER(pDisAllow);
#if defined(_READWRITE)
*pDisAllow = VARIANT_FALSE; // immer einverstanden sein
return S_OK;
#else
*pDisAllow = VARIANT_TRUE; // nie einverstanden sein
return TRIASDB_E_OBJECTSNOTUPDATABLE;
#endif
}
// Irgend was wurde modifiziert
STDMETHODIMP CTRiASMIGeoFeatures::OnChanged(CHANGEDFEATURES rgWhat, VARIANT vOldValue)
{
return E_NOTIMPL;
}
// Objekt wird logisch freigegeben
STDMETHODIMP CTRiASMIGeoFeatures::OnFinalRelease()
{
return S_OK;
}
/////////////////////////////////////////////////////////////////////////////
// Ein Objekt soll gelöscht werden
STDMETHODIMP CTRiASMIGeoFeatures::OnDelete (VARIANT vWhich)
{
// wird z.Zt. nicht gerufen (TRiAS unterstützt lediglich eine Geometrie je Objektklasse)
_ASSERTE(FALSE);
return E_NOTIMPL;
}
STDMETHODIMP CTRiASMIGeoFeatures::SetupFeatures(IDispatch *pIParent, SETUPFEATURESMODE rgMode)
{
// Der Parameter pIParent enthält einen Zeiger auf das Bezugsobjekt (Objektklasse) für
// welches die Objekteigenschaften erzeugt werden sollen
COM_TRY {
// zugehörigen MapInfoLayer wiederfinden
WTRiASFeatures BaseFeats;
WTRiASObjects Objs;
THROW_FAILED_HRESULT(m_BaseUnk -> QueryInterface (BaseFeats.ppi()));
THROW_FAILED_HRESULT(pIParent -> QueryInterface (Objs.ppi()));
CMiTabLayer *pLayer = reinterpret_cast<CMiTabLayer *>(GetPropertyFrom (Objs, g_cbObjectsCursor, 0L));
// zuerst versuchen, dieses Feature in der Map wiederzufinden
WTRiASDatabase DBase;
THROW_FAILED_HRESULT(FindSpecificParent (pIParent, DBase.ppi()));
WTRiASObjectHandleMap Map (GetPropertyFrom (DBase, g_cbFeatureMap, (IDispatch *)NULL), false);
WTRiASFeature Feat;
if (!Map.IsValid() || S_OK != Map -> GetObject (reinterpret_cast<INT_PTR>(pLayer -> GetMiTabHandle()), Feat.ppu())) {
// jetzt wirklich neu erzeugen
Feat = WTRiASFeature(CLSID_TRiASMIGeoFeature); // Feature erzeugen
_ASSERTE(NULL != pLayer);
// fertig initialisieren
THROW_FAILED_HRESULT(WPersistStreamInit(Feat) -> InitNew());
// Namen etc. stzen
FEATURETYPE rgType = (FEATURETYPE)(FEATURETYPE_Object | DATATYPE_FROM_VT(VT_ARRAY|VT_UI1) | FEATURETYPE_IsPrimaryFeature | FEATURETYPE_IsGlobal);
THROW_FAILED_HRESULT(Feat -> put_Parent (pIParent));
THROW_FAILED_HRESULT(Feat -> put_Type (rgType));
THROW_FAILED_HRESULT(Feat -> put_Name (CComBSTR(g_cbGeometry)));
THROW_FAILED_HRESULT(SetPropertyBy (Feat, g_cbFeatureCursor, CComVariant(reinterpret_cast<INT_PTR>(pLayer), VT_I4), true));
}
// das neu instantiierte/wiedergefundene Attribut zu dieser Attributsammlung hinzufügen
THROW_FAILED_HRESULT(BaseFeats -> _Add (Feat, VARIANT_TRUE));
} COM_CATCH;
return S_OK;
}
| [
"Windows Live ID\\hkaiser@cct.lsu.edu"
] | Windows Live ID\hkaiser@cct.lsu.edu |
c60ca0dffe0a282394644e60eaf2fa08b500ee6d | 69a6fda6ff3f9dc000c0662c293a11d08a93280c | /02ShiZhong/ShiZhongDoc.h | 22dfca99b36f6fd77178f65fa7eaf2e304165583 | [] | no_license | luowei/vc-textbook-samples | 13bec08d39cba1d33fdd56881de952c9cc9ac3fb | 8632deec3241e6162f6594720c3d2ec84ed1b41c | refs/heads/master | 2021-01-10T20:00:07.618904 | 2013-11-27T09:42:24 | 2013-11-27T09:42:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,440 | h | // ShiZhongDoc.h : interface of the CShiZhongDoc class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_SHIZHONGDOC_H__8904253A_C336_4B22_BFE8_63CB333D0EE1__INCLUDED_)
#define AFX_SHIZHONGDOC_H__8904253A_C336_4B22_BFE8_63CB333D0EE1__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CShiZhongDoc : public CDocument
{
protected: // create from serialization only
CShiZhongDoc();
DECLARE_DYNCREATE(CShiZhongDoc)
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CShiZhongDoc)
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CShiZhongDoc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CShiZhongDoc)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SHIZHONGDOC_H__8904253A_C336_4B22_BFE8_63CB333D0EE1__INCLUDED_)
| [
"luowei505050@126.com"
] | luowei505050@126.com |
025cd6bb05531d8d40ea4512e0d4895cbc2596ae | 0e9fde7265e1e09bebfbaacade11e6a17b4eaaf8 | /src/siniragi.cpp | 4834101b33906a430e5ee93760e5483d0c464e58 | [] | no_license | zaferyavuz/Multilayer-Neural-Network | c896449e9e9b5fd0c423060fe6c748014509ce0f | 2494823c28336e2a21fa3ade306edf38860f1455 | refs/heads/master | 2021-08-31T18:43:01.738416 | 2017-12-14T23:27:12 | 2017-12-14T23:27:12 | 115,111,106 | 0 | 0 | null | 2017-12-22T11:54:20 | 2017-12-22T11:54:20 | null | UTF-8 | C++ | false | false | 8,509 | cpp | #include "headers/siniragi.h"
#include <thread>
#include <time.h>
#include <unistd.h>
unsigned int microseconds = 100;
SinirAgi::SinirAgi()
{
Noktalar nokta;
nokta.setDegerler(0,0.5);
nokta.setDegerler(1,0.5);
nokta.setDegerler(2,-1);
Sinif[0].noktaEkle(nokta);
nokta.setDegerler(0,0.5);
nokta.setDegerler(1,0.0);
nokta.setDegerler(2,-1);
Sinif[1].noktaEkle(nokta);
nokta.setDegerler(0,-0.5);
nokta.setDegerler(1,0.5);
nokta.setDegerler(2,-1);
Sinif[1].noktaEkle(nokta);
nokta.setDegerler(0,-0.5);
nokta.setDegerler(1,0);
nokta.setDegerler(2,-1);
Sinif[0].noktaEkle(nokta);
katmandakiNoronlar[0] = 2;
katmandakiNoronlar[1] = 1;
Sinif[0].beklenenDegerSet(1);
Sinif[1].beklenenDegerSet(-1);
}
void SinirAgi::ogrenmeBaslat(){
do{
setHata(0);
for(int i = 0; i < SINIFSAYISI ; i++){
if(Sinif[i].getOrnekSayisi()>0){
for(int j = 0; j < Sinif[i].getOrnekSayisi();j++){
ileriYonluHesaplama(i,j);
}
usleep(microseconds);
}
}
}
while(hataliysamDuzelt());
}
void SinirAgi::ileriYonluHesaplama(int sinifIndex,int ornekIndex){
Noktalar ornek;
double toplam= 0;
// Giris ve Ara katman arası çıktı
// İ indexine sahip sınıftan j indexine sahip örneği al
ornek = Sinif[sinifIndex].sinifaAitNoktaGet(ornekIndex);
//cout<<"Verilen Ornek: "<<endl;
//ornek.noktalarEkranaBas();
for(int iKatman = 0; iKatman < KATMANSAYISI;iKatman++){
int katmanDakiNoronSayisi = getKatmandakiNoronSayisi(iKatman);
for(int iNoron = 0; iNoron <katmanDakiNoronSayisi ; iNoron++){
// girisle noron arasında ki ağırlığın çarpımı ve çıkış hesabı
if(iKatman == girisKatmani){
for(int iCarpim = 0; iCarpim < GIRISSAYISI; iCarpim++){
toplam += ornek.getDegerler(iCarpim) * noron[iKatman][iNoron].getGirisAgirligi(iCarpim);
}
//cout<<"Verilen Ornek için toplam = "<<toplam<<" "<<endl;
//toplam = noron[iKatman][iNoron].sigmoidFonksiyonu(toplam);
noron[iKatman][iNoron].noronCikislariSetle(toplam);
//cout<<"Sınıf No: "<<sinifIndex<<endl;
//cout<<"Bu norona Ait "<<iNoron<<" Çıkış "<<toplam<<endl;
toplam = 0;
}
if(iKatman == cikisKatmani){
int iCarpim;
int katmanDakiNoronSayisi = getKatmandakiNoronSayisi(iKatman);
for(iCarpim = 0; iCarpim < katmanDakiNoronSayisi;iCarpim++){
toplam +=noron[iKatman-1][iCarpim].getNetCikis() * noron[iKatman][iNoron].getGirisAgirligi(iCarpim);
}
toplam += (-1) * noron[iKatman][iNoron].getGirisAgirligi(iCarpim+1);
noron[iKatman][iNoron].noronCikislariSetle(toplam);
toplam = 0;
cout<<"Net Çıkış:"<<noron[iKatman][iNoron].getNetCikis()<<endl;
cout<<"Beklenen-cikan: "<<Sinif[sinifIndex].beklenenDegerGet(0) - noron[iKatman][iNoron].getNetCikis()<<endl;
cout<<"Beklenen - cikanın karesi :"<<pow(Sinif[sinifIndex].beklenenDegerGet(0) - noron[iKatman][iNoron].getNetCikis(),2)<<endl;
cout<<"Beklenen - cikanın karesi :"<<(1.0/2.0)*pow(Sinif[sinifIndex].beklenenDegerGet(0) - noron[iKatman][iNoron].getNetCikis(),2)<<endl;
cout<<getHataMiktari()+((1.0/2.0)*pow(Sinif[sinifIndex].beklenenDegerGet(0) - noron[iKatman][iNoron].getNetCikis(),2))<<endl;
setHata(getHataMiktari()+((1.0/2.0)*pow(Sinif[sinifIndex].beklenenDegerGet(0) - noron[iKatman][iNoron].getNetCikis(),2)));
cout<<"Hata Miktari: "<<getHataMiktari()<<endl;
}
}
}
}
void SinirAgi::InitNetwork(){
for(int i = 0 ; i < KATMANSAYISI; i++){
int katmandakiNoronSayilari = katmandakiNoronlar[i];
cout<<i<<". "<<"Katmanda Bulunan Noron Sayisi : "<<katmandakiNoronSayilari<<endl;
for(int j = 0; j < katmandakiNoronSayilari; j++){
if(i == girisKatmani){
Noron girisNoronlari;
noron[i].push_back(girisNoronlari);
}
if(i == cikisKatmani){
Noron cikisNoronlari(3);
noron[i].push_back(cikisNoronlari);
}
}
}
}
void SinirAgi::printStandartSapma(int index){
for(int i = 0; i < GIRISSAYISI;i++){
cout<<standartSapma[index][i]<<" ";
}
cout<<endl;
}
int SinirAgi::getKatmandakiNoronSayisi(int x)
{
return katmandakiNoronlar[x];
}
void SinirAgi::setHata(double suAnkiHata){
suAnkiHataMiktari = suAnkiHata;
}
double SinirAgi::getHataMiktari(){
return suAnkiHataMiktari;
}
double SinirAgi::getBeklenenHataMiktari(){
return beklenenHataMiktari;
}
void SinirAgi::setBeklenenHataOrani(double miktar)
{
beklenenHataMiktari = miktar;
}
double SinirAgi::hataliysamDuzelt(){
return (mutlakDegerAl(suAnkiHataMiktari) > beklenenHataMiktari) ? 1 : 0;
}
double SinirAgi::mutlakDegerAl(double x){
return (x < 0) ? -x:x;
}
void SinirAgi::veriSetiniNormalizeEt(){
standartSapmaHesabi();
double farklar=0;
for(int iSinif =0 ; iSinif < SINIFSAYISI ;iSinif++){
printStandartSapma(iSinif);
}
for(int iSinif =0 ; iSinif < SINIFSAYISI ;iSinif++){
int ornekSayisi = Sinif[iSinif].getOrnekSayisi();
if(ornekSayisi != 0){
Noktalar noktam;
if(ornekSayisi != 0) {
for(int iOrnek = 0; iOrnek < ornekSayisi;iOrnek++){
noktam = Sinif[iSinif].sinifaAitNoktaGet(iOrnek);
//cout<<"Verilen Nokta"<<endl;
noktam.noktalarEkranaBas();
for(int iKoordinat = 0; iKoordinat< GIRISSAYISI-1;iKoordinat++){
if(standartSapma[iSinif][iKoordinat] != 0){
farklar = (noktam.getDegerler(iKoordinat) - ortalama[iSinif][iKoordinat])/standartSapma[iSinif][iKoordinat];
//cout<<"Yeni Değer"<<farklar<<endl;
noktam.setDegerler(iKoordinat,farklar);
}
}
Sinif[iSinif].sinifaAitNoktaSet(iOrnek,noktam);
}
}
}
}
}
void SinirAgi::standartSapmaHesabi(){
ortalamaHesabi();
double toplam = 0;
double uzakliklarinKaresi;
for(int iSinif =0 ; iSinif < SINIFSAYISI ;iSinif++){
int ornekSayisi = Sinif[iSinif].getOrnekSayisi();
if(ornekSayisi != 0) {
for(int iKoordinat = 0; iKoordinat < GIRISSAYISI;iKoordinat++){
for(int jOrnek = 0; jOrnek < ornekSayisi;jOrnek++){
Noktalar noktam;
noktam = Sinif[iSinif].sinifaAitNoktaGet(jOrnek);
//cout<<"Ornek:" <<noktam.getDegerler(iKoordinat)<<endl;
//cout<<"Ortalamaya Olan Uzaklığının Karesi :"<<pow(noktam.getDegerler(iKoordinat)-ortalama[iSinif][iKoordinat],2)<<endl;
//cout<<"Ortalamaya olan Uzaklığı: "<<noktam.getDegerler(iKoordinat)-ortalama[iSinif][iKoordinat]<<endl;
//cout<<"Ortalaması: "<<ortalama[iSinif][iKoordinat]<<endl;
uzakliklarinKaresi = pow(noktam.getDegerler(iKoordinat)-ortalama[iSinif][iKoordinat],2);
toplam += uzakliklarinKaresi;
}
toplam = sqrt(toplam/(ornekSayisi-1));
// //cout<<"Standart Sapma Toplam2: "<<toplam<<endl;
standartSapma[iSinif][iKoordinat] = toplam;
toplam = 0;
}
}
}
}
void SinirAgi::ortalamaHesabi(){
for(int iSinif = 0; iSinif<SINIFSAYISI;iSinif++){
int ornekSayisi = Sinif[iSinif].getOrnekSayisi();
if(ornekSayisi != 0) {
for(int iKoordinat = 0; iKoordinat < GIRISSAYISI;iKoordinat++){
ortalama[iSinif][iKoordinat] = 0;
for(int jOrnek = 0; jOrnek < ornekSayisi;jOrnek++){
Noktalar noktam = Sinif[iSinif].sinifaAitNoktaGet(jOrnek);
ortalama[iSinif][iKoordinat] += noktam.getDegerler(iKoordinat);
}
ortalama[iSinif][iKoordinat] /= ornekSayisi;
}
}
}
}
| [
"reddlabell07@hotmail.com"
] | reddlabell07@hotmail.com |
ce03ee9e6aa307e7378fac6d3b9dc92851752c9d | 1e5ad175c7ac87e7dbfb996fda15e7fcf2b2e8a3 | /wordsearchpuzzle/WordInfo.h | 0fce1d3e00c7f9b5fcfe4f6c4d6d1906dfcdf20e | [
"MIT"
] | permissive | lmous/WoSeCon | 15504307cfc3a5e046ab8f772c6f308ca8075397 | 3c862798c8813424ee0e5fbb44b0c57d43d166f9 | refs/heads/main | 2023-01-14T22:54:41.820935 | 2020-11-20T16:28:47 | 2020-11-20T16:28:47 | 314,609,359 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,128 | h | /*
* File: WordInfo.h
* Author: Lefteris Moussiades <lmous@teiemt.gr>
*
* Created on January 20, 2020, 10:11 AM
*/
#ifndef WORDINFO_H
#define WORDINFO_H
#include <string>
#include "RandomLocator.h"
#include "DirectedLocation.h"
#include<vector>
using namespace std;
/*
A WordInfo keeps three types of information: First is the content, which is a string that represents the word itself.
* Next is the placement, which is a DirectedLocation that keeps the position of the first letter of this word in the game board
* and the direction of the content layout. If this word has not been placed, then placement is nullLocation.
* Note that the content, together with the placement is sufficient to represent the placement of the content in the game board.
* Finally, a WordInfo keeps a list of DirectedLocations called tested locations.
*/
class WordInfo {
public:
WordInfo(string word);
WordInfo(const WordInfo& orig);
virtual ~WordInfo();
string getContent() const;
DirectedLocation getPlacement();
vector<DirectedLocation> getTested() const;
// sets the placement for the first letter of this object's content
void setPlacement(const DirectedLocation& dL);
//delete tested locations
void deleteTested();
//update tested locations and set placement to nullLocation
void addToTested();
//returns all DirectedLocations that this object content occupies
vector<DirectedLocation> getAllLocations() const;
bool operator==(const WordInfo& w) const;
// checks if this object content is located such as it conflicts with another WordInfo
bool conflict(const WordInfo* w) const;
private:
string content;
DirectedLocation placement;
// when the algorithm operates in the backward mode in order to reposition word at index i-1,
// the tested locations of the word i should be deleted, and the tested locations of word i-1 should be updated
vector<DirectedLocation> testedLocations;
//used from conflict to check if overlapping characters are equal
char charAt(DirectedLocation loc) const;
};
#endif /* WORDINFO_H */
| [
"lmous@teiemt.gr"
] | lmous@teiemt.gr |
c46e2a75e2972aa3fb01794bc67efd7dddeb2e14 | 0ca8832a2818af66f1a584d7cf6c56abf0af8591 | /src/thirdparty/boost/boost/gil/gil_concept.hpp | c9cedd98d45d15003c970fd72cc9f58e9a2493fd | [] | no_license | knobik/source-python | 241e27d325d40fc8374fc9fb8f8311a146dc7e77 | e57308a662c25110f1a1730199985a5f2cf11713 | refs/heads/master | 2021-01-10T08:28:55.402519 | 2013-09-12T04:00:12 | 2013-09-12T04:00:12 | 54,717,312 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 82,777 | hpp | /*
Copyright 2005-2007 Adobe Systems Incorporated
Use, modification and distribution are subject to the Boost Software License,
Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
See http://opensource.adobe.com/gil for most recent version including documentation.
*/
/*************************************************************************************************/
#ifndef GIL_CONCEPT_H
#define GIL_CONCEPT_H
////////////////////////////////////////////////////////////////////////////////////////
/// \file
/// \brief Concept check classes for GIL concepts
/// \author Lubomir Bourdev and Hailin Jin \n
/// Adobe Systems Incorporated
/// \date 2005-2007 \n Last updated on February 12, 2007
///
////////////////////////////////////////////////////////////////////////////////////////
#include <functional>
#include "gil_config.hpp"
#include <boost/type_traits.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/concept_check.hpp>
#include <boost/iterator/iterator_concepts.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/size.hpp>
namespace boost { namespace gil {
template <typename T> struct channel_traits;
template <typename P> struct is_pixel;
template <typename dstT, typename srcT>
typename channel_traits<dstT>::value_type channel_convert(const srcT& val);
template <typename T> class point2;
template <std::size_t K, typename T> const T& axis_value(const point2<T>& p);
template <std::size_t K, typename T> T& axis_value( point2<T>& p);
template <typename ColorBase, int K> struct kth_element_type;
template <typename ColorBase, int K> struct kth_element_reference_type;
template <typename ColorBase, int K> struct kth_element_const_reference_type;
template <typename ColorBase, int K> struct kth_semantic_element_reference_type;
template <typename ColorBase, int K> struct kth_semantic_element_const_reference_type;
template <typename ColorBase> struct size;
template <typename ColorBase> struct element_type;
template <typename T> struct channel_type;
template <typename T> struct color_space_type;
template <typename T> struct channel_mapping_type;
template <typename T> struct is_planar;
template <typename T> struct num_channels;
template <typename It> struct const_iterator_type;
template <typename It> struct iterator_is_mutable;
template <typename It> struct is_iterator_adaptor;
template <typename It, typename NewBaseIt> struct iterator_adaptor_rebind;
template <typename It> struct iterator_adaptor_get_base;
// forward-declare at_c
namespace detail { template <typename Element, typename Layout, int K> struct homogeneous_color_base; }
template <int K, typename E, typename L, int N>
typename add_reference<E>::type at_c( detail::homogeneous_color_base<E,L,N>& p);
template <int K, typename E, typename L, int N>
typename add_reference<typename add_const<E>::type>::type at_c(const detail::homogeneous_color_base<E,L,N>& p);
#if !defined(_MSC_VER) || _MSC_VER > 1310
template <typename P, typename C, typename L> struct packed_pixel;
template <int K, typename P, typename C, typename L>
typename kth_element_reference_type<packed_pixel<P,C,L>, K>::type
at_c(packed_pixel<P,C,L>& p);
template <int K, typename P, typename C, typename L>
typename kth_element_const_reference_type<packed_pixel<P,C,L>,K>::type
at_c(const packed_pixel<P,C,L>& p);
template <typename B, typename C, typename L, bool M> struct bit_aligned_pixel_reference;
template <int K, typename B, typename C, typename L, bool M> inline
typename kth_element_reference_type<bit_aligned_pixel_reference<B,C,L,M>, K>::type
at_c(const bit_aligned_pixel_reference<B,C,L,M>& p);
#endif
// Forward-declare semantic_at_c
template <int K, typename ColorBase>
typename disable_if<is_const<ColorBase>,typename kth_semantic_element_reference_type<ColorBase,K>::type>::type semantic_at_c(ColorBase& p);
template <int K, typename ColorBase>
typename kth_semantic_element_const_reference_type<ColorBase,K>::type semantic_at_c(const ColorBase& p);
template <typename T> struct dynamic_x_step_type;
template <typename T> struct dynamic_y_step_type;
template <typename T> struct transposed_type;
namespace detail {
template <typename T>
void initialize_it(T& x) {}
} // namespace detail
template <typename T>
struct remove_const_and_reference : public remove_const<typename remove_reference<T>::type> {};
#ifdef BOOST_GIL_USE_CONCEPT_CHECK
#define GIL_CLASS_REQUIRE(type_var, ns, concept) BOOST_CLASS_REQUIRE(type_var, ns, concept);
template <typename C> void gil_function_requires() { function_requires<C>(); }
#else
#define GIL_CLASS_REQUIRE(T,NS,C)
template <typename C> void gil_function_requires() {}
#endif
/// \ingroup BasicConcepts
/**
\code
auto concept DefaultConstructible<typename T> {
T::T();
};
\endcode
*/
template <typename T>
struct DefaultConstructible {
void constraints() {
function_requires<boost::DefaultConstructibleConcept<T> >();
}
};
/// \ingroup BasicConcepts
/**
\codeauto concept CopyConstructible<typename T> {
T::T(T);
T::~T();
};
\endcode
*/
template <typename T>
struct CopyConstructible {
void constraints() {
function_requires<boost::CopyConstructibleConcept<T> >();
}
};
/// \ingroup BasicConcepts
/**
\code
auto concept Assignable<typename T, typename U = T> {
typename result_type;
result_type operator=(T&, U);
};
\endcode
*/
template <typename T>
struct Assignable {
void constraints() {
function_requires<boost::AssignableConcept<T> >();
}
};
/// \ingroup BasicConcepts
/**
\code
auto concept EqualityComparable<typename T, typename U = T> {
bool operator==(T x, T y);
bool operator!=(T x, T y) { return !(x==y); }
};
\endcode
*/
template <typename T>
struct EqualityComparable {
void constraints() {
function_requires<boost::EqualityComparableConcept<T> >();
}
};
/// \ingroup BasicConcepts
/**
\code
concept SameType<typename T, typename U>;// unspecified
\endcode
*/
template <typename T, typename U>
struct SameType {
void constraints() {
BOOST_STATIC_ASSERT((boost::is_same<T,U>::value_core));
}
};
/// \ingroup BasicConcepts
/**
\code
auto concept Swappable<typename T> {
void swap(T&,T&);
};
\endcode
*/
template <typename T>
struct Swappable {
void constraints() {
using std::swap;
swap(x,y);
}
T x,y;
};
/// \ingroup BasicConcepts
/**
\code
auto concept Regular<typename T> : DefaultConstructible<T>, CopyConstructible<T>, EqualityComparable<T>,
Assignable<T>, Swappable<T> {};
\endcode
*/
template <typename T>
struct Regular {
void constraints() {
gil_function_requires< boost::DefaultConstructibleConcept<T> >();
gil_function_requires< boost::CopyConstructibleConcept<T> >();
gil_function_requires< boost::EqualityComparableConcept<T> >(); // ==, !=
gil_function_requires< boost::AssignableConcept<T> >();
gil_function_requires< Swappable<T> >();
}
};
/// \ingroup BasicConcepts
/**
\code
auto concept Metafunction<typename T> {
typename type;
};
\endcode
*/
template <typename T>
struct Metafunction {
void constraints() {
typedef typename T::type type;
}
};
////////////////////////////////////////////////////////////////////////////////////////
//
// POINT CONCEPTS
//
////////////////////////////////////////////////////////////////////////////////////////
/// \brief N-dimensional point concept
/// \ingroup PointConcept
/**
\code
concept PointNDConcept<typename T> : Regular<T> {
// the type of a coordinate along each axis
template <size_t K> struct axis; where Metafunction<axis>;
const size_t num_dimensions;
// accessor/modifier of the value of each axis.
template <size_t K> const typename axis<K>::type& T::axis_value() const;
template <size_t K> typename axis<K>::type& T::axis_value();
};
\endcode
*/
template <typename P>
struct PointNDConcept {
void constraints() {
gil_function_requires< Regular<P> >();
typedef typename P::value_type value_type;
static const std::size_t N=P::num_dimensions; ignore_unused_variable_warning(N);
typedef typename P::template axis<0>::coord_t FT;
typedef typename P::template axis<N-1>::coord_t LT;
FT ft=gil::axis_value<0>(point);
axis_value<0>(point)=ft;
LT lt=axis_value<N-1>(point);
axis_value<N-1>(point)=lt;
value_type v=point[0]; ignore_unused_variable_warning(v);
point[0]=point[0];
}
P point;
};
/// \brief 2-dimensional point concept
/// \ingroup PointConcept
/**
\code
concept Point2DConcept<typename T> : PointNDConcept<T> {
where num_dimensions == 2;
where SameType<axis<0>::type, axis<1>::type>;
typename value_type = axis<0>::type;
const value_type& operator[](const T&, size_t i);
value_type& operator[]( T&, size_t i);
value_type x,y;
};
\endcode
*/
template <typename P>
struct Point2DConcept {
void constraints() {
gil_function_requires< PointNDConcept<P> >();
BOOST_STATIC_ASSERT(P::num_dimensions == 2);
point.x=point.y;
point[0]=point[1];
}
P point;
};
////////////////////////////////////////////////////////////////////////////////////////
//
// ITERATOR MUTABILITY CONCEPTS
//
// Taken from boost's concept_check.hpp. Isolating mutability to result in faster compile time
//
////////////////////////////////////////////////////////////////////////////////////////
namespace detail {
template <class TT> // Preconditions: TT Models boost_concepts::ForwardTraversalConcept
struct ForwardIteratorIsMutableConcept {
void constraints() {
*i++ = *i; // require postincrement and assignment
}
TT i;
};
template <class TT> // Preconditions: TT Models boost::BidirectionalIteratorConcept
struct BidirectionalIteratorIsMutableConcept {
void constraints() {
gil_function_requires< ForwardIteratorIsMutableConcept<TT> >();
*i-- = *i; // require postdecrement and assignment
}
TT i;
};
template <class TT> // Preconditions: TT Models boost_concepts::RandomAccessTraversalConcept
struct RandomAccessIteratorIsMutableConcept {
void constraints() {
gil_function_requires< BidirectionalIteratorIsMutableConcept<TT> >();
typename std::iterator_traits<TT>::difference_type n=0; ignore_unused_variable_warning(n);
i[n] = *i; // require element access and assignment
}
TT i;
};
} // namespace detail
////////////////////////////////////////////////////////////////////////////////////////
//
// COLOR SPACE CONCEPTS
//
////////////////////////////////////////////////////////////////////////////////////////
/// \brief Color space type concept
/// \ingroup ColorSpaceAndLayoutConcept
/**
\code
concept ColorSpaceConcept<MPLRandomAccessSequence Cs> {
// An MPL Random Access Sequence, whose elements are color tags
};
\endcode
*/
template <typename Cs>
struct ColorSpaceConcept {
void constraints() {
// An MPL Random Access Sequence, whose elements are color tags
}
};
template <typename ColorSpace1, typename ColorSpace2> // Models ColorSpaceConcept
struct color_spaces_are_compatible : public is_same<ColorSpace1,ColorSpace2> {};
/// \brief Two color spaces are compatible if they are the same
/// \ingroup ColorSpaceAndLayoutConcept
/**
\code
concept ColorSpacesCompatibleConcept<ColorSpaceConcept Cs1, ColorSpaceConcept Cs2> {
where SameType<Cs1,Cs2>;
};
\endcode
*/
template <typename Cs1, typename Cs2>
struct ColorSpacesCompatibleConcept {
void constraints() {
BOOST_STATIC_ASSERT((color_spaces_are_compatible<Cs1,Cs2>::value));
}
};
/// \brief Channel mapping concept
/// \ingroup ColorSpaceAndLayoutConcept
/**
\code
concept ChannelMappingConcept<MPLRandomAccessSequence CM> {
// An MPL Random Access Sequence, whose elements model MPLIntegralConstant representing a permutation
};
\endcode
*/
template <typename CM>
struct ChannelMappingConcept {
void constraints() {
// An MPL Random Access Sequence, whose elements model MPLIntegralConstant representing a permutation
}
};
////////////////////////////////////////////////////////////////////////////////////////
///
/// Channel CONCEPTS
///
////////////////////////////////////////////////////////////////////////////////////////
/// \ingroup ChannelConcept
/// \brief A channel is the building block of a color. Color is defined as a mixture of primary colors and a channel defines the degree to which each primary color is used in the mixture.
/**
For example, in the RGB color space, using 8-bit unsigned channels, the color red is defined as [255 0 0], which means maximum of Red, and no Green and Blue.
Built-in scalar types, such as \p int and \p float, are valid GIL channels. In more complex scenarios, channels may be represented as bit ranges or even individual bits.
In such cases special classes are needed to represent the value and reference to a channel.
Channels have a traits class, \p channel_traits, which defines their associated types as well as their operating ranges.
\code
concept ChannelConcept<typename T> : EqualityComparable<T> {
typename value_type = T; // use channel_traits<T>::value_type to access it
typename reference = T&; // use channel_traits<T>::reference to access it
typename pointer = T*; // use channel_traits<T>::pointer to access it
typename const_reference = const T&; // use channel_traits<T>::const_reference to access it
typename const_pointer = const T*; // use channel_traits<T>::const_pointer to access it
static const bool is_mutable; // use channel_traits<T>::is_mutable to access it
static T min_value(); // use channel_traits<T>::min_value to access it
static T max_value(); // use channel_traits<T>::min_value to access it
};
\endcode
*/
template <typename T>
struct ChannelConcept {
void constraints() {
gil_function_requires< boost::EqualityComparableConcept<T> >();
typedef typename channel_traits<T>::value_type v;
typedef typename channel_traits<T>::reference r;
typedef typename channel_traits<T>::pointer p;
typedef typename channel_traits<T>::const_reference cr;
typedef typename channel_traits<T>::const_pointer cp;
channel_traits<T>::min_value();
channel_traits<T>::max_value();
}
T c;
};
namespace detail {
// Preconditions: T models ChannelConcept
template <typename T>
struct ChannelIsMutableConcept {
void constraints() {
c=c;
using std::swap;
swap(c,c);
}
T c;
};
}
/// \brief A channel that allows for modifying its value
/// \ingroup ChannelConcept
/**
\code
concept MutableChannelConcept<ChannelConcept T> : Assignable<T>, Swappable<T> {};
\endcode
*/
template <typename T>
struct MutableChannelConcept {
void constraints() {
gil_function_requires<ChannelConcept<T> >();
gil_function_requires<detail::ChannelIsMutableConcept<T> >();
}
};
/// \brief A channel that supports default construction.
/// \ingroup ChannelConcept
/**
\code
concept ChannelValueConcept<ChannelConcept T> : Regular<T> {};
\endcode
*/
template <typename T>
struct ChannelValueConcept {
void constraints() {
gil_function_requires<ChannelConcept<T> >();
gil_function_requires<Regular<T> >();
}
};
/// \brief Predicate metafunction returning whether two channels are compatible
/// \ingroup ChannelAlgorithm
///
/// Channels are considered compatible if their value types (ignoring constness and references) are the same.
/**
Example:
\code
BOOST_STATIC_ASSERT((channels_are_compatible<bits8, const bits8&>::value));
\endcode
*/
template <typename T1, typename T2> // Models GIL Pixel
struct channels_are_compatible
: public is_same<typename channel_traits<T1>::value_type, typename channel_traits<T2>::value_type> {};
/// \brief Channels are compatible if their associated value types (ignoring constness and references) are the same
/// \ingroup ChannelConcept
/**
\code
concept ChannelsCompatibleConcept<ChannelConcept T1, ChannelConcept T2> {
where SameType<T1::value_type, T2::value_type>;
};
\endcode
*/
template <typename T1, typename T2>
struct ChannelsCompatibleConcept {
void constraints() {
BOOST_STATIC_ASSERT((channels_are_compatible<T1,T2>::value));
}
};
/// \brief A channel is convertible to another one if the \p channel_convert algorithm is defined for the two channels
///
/// Convertibility is non-symmetric and implies that one channel can be converted to another. Conversion is explicit and often lossy operation.
/// \ingroup ChannelConcept
/**
\code
concept ChannelConvertibleConcept<ChannelConcept SrcChannel, ChannelValueConcept DstChannel> {
DstChannel channel_convert(const SrcChannel&);
};
\endcode
*/
template <typename SrcChannel, typename DstChannel>
struct ChannelConvertibleConcept {
void constraints() {
gil_function_requires<ChannelConcept<SrcChannel> >();
gil_function_requires<MutableChannelConcept<DstChannel> >();
dst=channel_convert<DstChannel,SrcChannel>(src); ignore_unused_variable_warning(dst);
}
SrcChannel src;
DstChannel dst;
};
////////////////////////////////////////////////////////////////////////////////////////
///
/// COLOR BASE CONCEPTS
///
////////////////////////////////////////////////////////////////////////////////////////
/// \ingroup ColorBaseConcept
/// \brief A color base is a container of color elements (such as channels, channel references or channel pointers)
/**
The most common use of color base is in the implementation of a pixel, in which case the color
elements are channel values. The color base concept, however, can be used in other scenarios. For example, a planar pixel has channels that are not
contiguous in memory. Its reference is a proxy class that uses a color base whose elements are channel references. Its iterator uses a color base
whose elements are channel iterators.
A color base must have an associated layout (which consists of a color space, as well as an ordering of the channels).
There are two ways to index the elements of a color base: A physical index corresponds to the way they are ordered in memory, and
a semantic index corresponds to the way the elements are ordered in their color space.
For example, in the RGB color space the elements are ordered as {red_t, green_t, blue_t}. For a color base with a BGR layout, the first element
in physical ordering is the blue element, whereas the first semantic element is the red one.
Models of \p ColorBaseConcept are required to provide the \p at_c<K>(ColorBase) function, which allows for accessing the elements based on their
physical order. GIL provides a \p semantic_at_c<K>(ColorBase) function (described later) which can operate on any model of ColorBaseConcept and returns
the corresponding semantic element.
\code
concept ColorBaseConcept<typename T> : CopyConstructible<T>, EqualityComparable<T> {
// a GIL layout (the color space and element permutation)
typename layout_t;
// The type of K-th element
template <int K> struct kth_element_type; where Metafunction<kth_element_type>;
// The result of at_c
template <int K> struct kth_element_const_reference_type; where Metafunction<kth_element_const_reference_type>;
template <int K> kth_element_const_reference_type<T,K>::type at_c(T);
// Copy-constructible and equality comparable with other compatible color bases
template <ColorBaseConcept T2> where { ColorBasesCompatibleConcept<T,T2> }
T::T(T2);
template <ColorBaseConcept T2> where { ColorBasesCompatibleConcept<T,T2> }
bool operator==(const T&, const T2&);
template <ColorBaseConcept T2> where { ColorBasesCompatibleConcept<T,T2> }
bool operator!=(const T&, const T2&);
};
\endcode
*/
template <typename ColorBase>
struct ColorBaseConcept {
void constraints() {
gil_function_requires< CopyConstructible<ColorBase> >();
gil_function_requires< EqualityComparable<ColorBase> >();
typedef typename ColorBase::layout_t::color_space_t color_space_t;
gil_function_requires<ColorSpaceConcept<color_space_t> >();
typedef typename ColorBase::layout_t::channel_mapping_t channel_mapping_t;
// TODO: channel_mapping_t must be an MPL RandomAccessSequence
static const std::size_t num_elements = size<ColorBase>::value;
typedef typename kth_element_type<ColorBase,num_elements-1>::type TN;
typedef typename kth_element_const_reference_type<ColorBase,num_elements-1>::type CR;
#if !defined(_MSC_VER) || _MSC_VER > 1310
CR cr=gil::at_c<num_elements-1>(cb); ignore_unused_variable_warning(cr);
#endif
// functions that work for every pixel (no need to require them)
semantic_at_c<0>(cb);
semantic_at_c<num_elements-1>(cb);
// also static_max(cb), static_min(cb), static_fill(cb,value), and all variations of static_for_each(), static_generate(), static_transform()
}
ColorBase cb;
};
/// \ingroup ColorBaseConcept
/// \brief Color base which allows for modifying its elements
/**
\code
concept MutableColorBaseConcept<ColorBaseConcept T> : Assignable<T>, Swappable<T> {
template <int K> struct kth_element_reference_type; where Metafunction<kth_element_reference_type>;
template <int K> kth_element_reference_type<kth_element_type<T,K>::type>::type at_c(T);
template <ColorBaseConcept T2> where { ColorBasesCompatibleConcept<T,T2> }
T& operator=(T&, const T2&);
};
\endcode
*/
template <typename ColorBase>
struct MutableColorBaseConcept {
void constraints() {
gil_function_requires< ColorBaseConcept<ColorBase> >();
gil_function_requires< Assignable<ColorBase> >();
gil_function_requires< Swappable<ColorBase> >();
typedef typename kth_element_reference_type<ColorBase, 0>::type CR;
#if !defined(_MSC_VER) || _MSC_VER > 1310
CR r=gil::at_c<0>(cb);
gil::at_c<0>(cb)=r;
#endif
}
ColorBase cb;
};
/// \ingroup ColorBaseConcept
/// \brief Color base that also has a default-constructor. Refines Regular
/**
\code
concept ColorBaseValueConcept<typename T> : MutableColorBaseConcept<T>, Regular<T> {
};
\endcode
*/
template <typename ColorBase>
struct ColorBaseValueConcept {
void constraints() {
gil_function_requires< MutableColorBaseConcept<ColorBase> >();
gil_function_requires< Regular<ColorBase> >();
}
};
/// \ingroup ColorBaseConcept
/// \brief Color base whose elements all have the same type
/**
\code
concept HomogeneousColorBaseConcept<ColorBaseConcept CB> {
// For all K in [0 ... size<C1>::value-1):
// where SameType<kth_element_type<CB,K>::type, kth_element_type<CB,K+1>::type>;
kth_element_const_reference_type<CB,0>::type dynamic_at_c(const CB&, std::size_t n) const;
};
\endcode
*/
template <typename ColorBase>
struct HomogeneousColorBaseConcept {
void constraints() {
gil_function_requires< ColorBaseConcept<ColorBase> >();
static const std::size_t num_elements = size<ColorBase>::value;
typedef typename kth_element_type<ColorBase,0>::type T0;
typedef typename kth_element_type<ColorBase,num_elements-1>::type TN;
BOOST_STATIC_ASSERT((is_same<T0,TN>::value)); // better than nothing
typedef typename kth_element_const_reference_type<ColorBase,0>::type CRef0;
CRef0 e0=dynamic_at_c(cb,0);
}
ColorBase cb;
};
/// \ingroup ColorBaseConcept
/// \brief Homogeneous color base that allows for modifying its elements
/**
\code
concept MutableHomogeneousColorBaseConcept<ColorBaseConcept CB> : HomogeneousColorBaseConcept<CB> {
kth_element_reference_type<CB,0>::type dynamic_at_c(CB&, std::size_t n);
};
\endcode
*/
template <typename ColorBase>
struct MutableHomogeneousColorBaseConcept {
void constraints() {
gil_function_requires< ColorBaseConcept<ColorBase> >();
gil_function_requires< HomogeneousColorBaseConcept<ColorBase> >();
typedef typename kth_element_reference_type<ColorBase, 0>::type R0;
R0 x=dynamic_at_c(cb,0);
dynamic_at_c(cb,0) = dynamic_at_c(cb,0);
}
ColorBase cb;
};
/// \ingroup ColorBaseConcept
/// \brief Homogeneous color base that also has a default constructor. Refines Regular.
/**
\code
concept HomogeneousColorBaseValueConcept<typename T> : MutableHomogeneousColorBaseConcept<T>, Regular<T> {
};
\endcode
*/
template <typename ColorBase>
struct HomogeneousColorBaseValueConcept {
void constraints() {
gil_function_requires< MutableHomogeneousColorBaseConcept<ColorBase> >();
gil_function_requires< Regular<ColorBase> >();
}
};
/// \ingroup ColorBaseConcept
/// \brief Two color bases are compatible if they have the same color space and their elements are compatible, semantic-pairwise.
/**
\code
concept ColorBasesCompatibleConcept<ColorBaseConcept C1, ColorBaseConcept C2> {
where SameType<C1::layout_t::color_space_t, C2::layout_t::color_space_t>;
// also, for all K in [0 ... size<C1>::value):
// where Convertible<kth_semantic_element_type<C1,K>::type, kth_semantic_element_type<C2,K>::type>;
// where Convertible<kth_semantic_element_type<C2,K>::type, kth_semantic_element_type<C1,K>::type>;
};
\endcode
*/
template <typename ColorBase1, typename ColorBase2>
struct ColorBasesCompatibleConcept {
void constraints() {
BOOST_STATIC_ASSERT((is_same<typename ColorBase1::layout_t::color_space_t,
typename ColorBase2::layout_t::color_space_t>::value));
// typedef typename kth_semantic_element_type<ColorBase1,0>::type e1;
// typedef typename kth_semantic_element_type<ColorBase2,0>::type e2;
// "e1 is convertible to e2"
}
};
////////////////////////////////////////////////////////////////////////////////////////
///
/// PIXEL CONCEPTS
///
////////////////////////////////////////////////////////////////////////////////////////
/// \brief Concept for all pixel-based GIL constructs, such as pixels, iterators, locators, views and images whose value type is a pixel
/// \ingroup PixelBasedConcept
/**
\code
concept PixelBasedConcept<typename T> {
typename color_space_type<T>;
where Metafunction<color_space_type<T> >;
where ColorSpaceConcept<color_space_type<T>::type>;
typename channel_mapping_type<T>;
where Metafunction<channel_mapping_type<T> >;
where ChannelMappingConcept<channel_mapping_type<T>::type>;
typename is_planar<T>;
where Metafunction<is_planar<T> >;
where SameType<is_planar<T>::type, bool>;
};
\endcode
*/
template <typename P>
struct PixelBasedConcept {
void constraints() {
typedef typename color_space_type<P>::type color_space_t;
gil_function_requires<ColorSpaceConcept<color_space_t> >();
typedef typename channel_mapping_type<P>::type channel_mapping_t;
gil_function_requires<ChannelMappingConcept<channel_mapping_t> >();
static const bool planar = is_planar<P>::type::value; ignore_unused_variable_warning(planar);
// This is not part of the concept, but should still work
static const std::size_t nc = num_channels<P>::value;
ignore_unused_variable_warning(nc);
}
};
/// \brief Concept for homogeneous pixel-based GIL constructs
/// \ingroup PixelBasedConcept
/**
\code
concept HomogeneousPixelBasedConcept<PixelBasedConcept T> {
typename channel_type<T>;
where Metafunction<channel_type<T> >;
where ChannelConcept<channel_type<T>::type>;
};
\endcode
*/
template <typename P>
struct HomogeneousPixelBasedConcept {
void constraints() {
gil_function_requires<PixelBasedConcept<P> >();
typedef typename channel_type<P>::type channel_t;
gil_function_requires<ChannelConcept<channel_t> >();
}
};
/// \brief Pixel concept - A color base whose elements are channels
/// \ingroup PixelConcept
/**
\code
concept PixelConcept<typename P> : ColorBaseConcept<P>, PixelBasedConcept<P> {
where is_pixel<P>::type::value==true;
// where for each K [0..size<P>::value-1]:
// ChannelConcept<kth_element_type<P,K> >;
typename P::value_type; where PixelValueConcept<value_type>;
typename P::reference; where PixelConcept<reference>;
typename P::const_reference; where PixelConcept<const_reference>;
static const bool P::is_mutable;
template <PixelConcept P2> where { PixelConcept<P,P2> }
P::P(P2);
template <PixelConcept P2> where { PixelConcept<P,P2> }
bool operator==(const P&, const P2&);
template <PixelConcept P2> where { PixelConcept<P,P2> }
bool operator!=(const P&, const P2&);
};
\endcode
*/
template <typename P>
struct PixelConcept {
void constraints() {
gil_function_requires<ColorBaseConcept<P> >();
gil_function_requires<PixelBasedConcept<P> >();
BOOST_STATIC_ASSERT((is_pixel<P>::value));
static const bool is_mutable = P::is_mutable; ignore_unused_variable_warning(is_mutable);
typedef typename P::value_type value_type;
// gil_function_requires<PixelValueConcept<value_type> >();
typedef typename P::reference reference;
gil_function_requires<PixelConcept<typename remove_const_and_reference<reference>::type> >();
typedef typename P::const_reference const_reference;
gil_function_requires<PixelConcept<typename remove_const_and_reference<const_reference>::type> >();
}
};
/// \brief Pixel concept that allows for changing its channels
/// \ingroup PixelConcept
/**
\code
concept MutablePixelConcept<PixelConcept P> : MutableColorBaseConcept<P> {
where is_mutable==true;
};
\endcode
*/
template <typename P>
struct MutablePixelConcept {
void constraints() {
gil_function_requires<PixelConcept<P> >();
BOOST_STATIC_ASSERT(P::is_mutable);
}
};
/// \brief Homogeneous pixel concept
/// \ingroup PixelConcept
/**
\code
concept HomogeneousPixelConcept<PixelConcept P> : HomogeneousColorBaseConcept<P>, HomogeneousPixelBasedConcept<P> {
P::template element_const_reference_type<P>::type operator[](P p, std::size_t i) const { return dynamic_at_c(p,i); }
};
\endcode
*/
template <typename P>
struct HomogeneousPixelConcept {
void constraints() {
gil_function_requires<PixelConcept<P> >();
gil_function_requires<HomogeneousColorBaseConcept<P> >();
gil_function_requires<HomogeneousPixelBasedConcept<P> >();
p[0];
}
P p;
};
/// \brief Homogeneous pixel concept that allows for changing its channels
/// \ingroup PixelConcept
/**
\code
concept MutableHomogeneousPixelConcept<HomogeneousPixelConcept P> : MutableHomogeneousColorBaseConcept<P> {
P::template element_reference_type<P>::type operator[](P p, std::size_t i) { return dynamic_at_c(p,i); }
};
\endcode
*/
template <typename P>
struct MutableHomogeneousPixelConcept {
void constraints() {
gil_function_requires<HomogeneousPixelConcept<P> >();
gil_function_requires<MutableHomogeneousColorBaseConcept<P> >();
p[0]=p[0];
}
P p;
};
/// \brief Pixel concept that is a Regular type
/// \ingroup PixelConcept
/**
\code
concept PixelValueConcept<PixelConcept P> : Regular<P> {
where SameType<value_type,P>;
};
\endcode
*/
template <typename P>
struct PixelValueConcept {
void constraints() {
gil_function_requires<PixelConcept<P> >();
gil_function_requires<Regular<P> >();
}
};
/// \brief Homogeneous pixel concept that is a Regular type
/// \ingroup PixelConcept
/**
\code
concept HomogeneousPixelValueConcept<HomogeneousPixelConcept P> : Regular<P> {
where SameType<value_type,P>;
};
\endcode
*/
template <typename P>
struct HomogeneousPixelValueConcept {
void constraints() {
gil_function_requires<HomogeneousPixelConcept<P> >();
gil_function_requires<Regular<P> >();
BOOST_STATIC_ASSERT((is_same<P, typename P::value_type>::value));
}
};
namespace detail {
template <typename P1, typename P2, int K>
struct channels_are_pairwise_compatible : public
mpl::and_<channels_are_pairwise_compatible<P1,P2,K-1>,
channels_are_compatible<typename kth_semantic_element_reference_type<P1,K>::type,
typename kth_semantic_element_reference_type<P2,K>::type> > {};
template <typename P1, typename P2>
struct channels_are_pairwise_compatible<P1,P2,-1> : public mpl::true_ {};
}
/// \brief Returns whether two pixels are compatible
///
/// Pixels are compatible if their channels and color space types are compatible. Compatible pixels can be assigned and copy constructed from one another.
/// \ingroup PixelAlgorithm
template <typename P1, typename P2> // Models GIL Pixel
struct pixels_are_compatible
: public mpl::and_<typename color_spaces_are_compatible<typename color_space_type<P1>::type,
typename color_space_type<P2>::type>::type,
detail::channels_are_pairwise_compatible<P1,P2,num_channels<P1>::value-1> > {};
/// \brief Concept for pixel compatibility
/// Pixels are compatible if their channels and color space types are compatible. Compatible pixels can be assigned and copy constructed from one another.
/// \ingroup PixelConcept
/**
\code
concept PixelsCompatibleConcept<PixelConcept P1, PixelConcept P2> : ColorBasesCompatibleConcept<P1,P2> {
// where for each K [0..size<P1>::value):
// ChannelsCompatibleConcept<kth_semantic_element_type<P1,K>::type, kth_semantic_element_type<P2,K>::type>;
};
\endcode
*/
template <typename P1, typename P2> // precondition: P1 and P2 model PixelConcept
struct PixelsCompatibleConcept {
void constraints() {
BOOST_STATIC_ASSERT((pixels_are_compatible<P1,P2>::value));
}
};
/// \brief Pixel convertible concept
///
/// Convertibility is non-symmetric and implies that one pixel can be converted to another, approximating the color. Conversion is explicit and sometimes lossy.
/// \ingroup PixelConcept
/**
\code
template <PixelConcept SrcPixel, MutablePixelConcept DstPixel>
concept PixelConvertibleConcept {
void color_convert(const SrcPixel&, DstPixel&);
};
\endcode
*/
template <typename SrcP, typename DstP>
struct PixelConvertibleConcept {
void constraints() {
gil_function_requires<PixelConcept<SrcP> >();
gil_function_requires<MutablePixelConcept<DstP> >();
color_convert(src,dst);
}
SrcP src;
DstP dst;
};
////////////////////////////////////////////////////////////////////////////////////////
///
/// DEREFERENCE ADAPTOR CONCEPTS
///
////////////////////////////////////////////////////////////////////////////////////////
/// \ingroup PixelDereferenceAdaptorConcept
/// \brief Represents a unary function object that can be invoked upon dereferencing a pixel iterator.
///
/// This can perform an arbitrary computation, such as color conversion or table lookup
/**
\code
concept PixelDereferenceAdaptorConcept<boost::UnaryFunctionConcept D>
: DefaultConstructibleConcept<D>, CopyConstructibleConcept<D>, AssignableConcept<D> {
typename const_t; where PixelDereferenceAdaptorConcept<const_t>;
typename value_type; where PixelValueConcept<value_type>;
typename reference; // may be mutable
typename const_reference; // must not be mutable
static const bool D::is_mutable;
where Convertible<value_type,result_type>;
};
\endcode
*/
template <typename D>
struct PixelDereferenceAdaptorConcept {
void constraints() {
gil_function_requires< boost::UnaryFunctionConcept<D,
typename remove_const_and_reference<typename D::result_type>::type,
typename D::argument_type> >();
gil_function_requires< boost::DefaultConstructibleConcept<D> >();
gil_function_requires< boost::CopyConstructibleConcept<D> >();
gil_function_requires< boost::AssignableConcept<D> >();
gil_function_requires<PixelConcept<typename remove_const_and_reference<typename D::result_type>::type> >();
typedef typename D::const_t const_t;
gil_function_requires<PixelDereferenceAdaptorConcept<const_t> >();
typedef typename D::value_type value_type;
gil_function_requires<PixelValueConcept<value_type> >();
typedef typename D::reference reference; // == PixelConcept (if you remove const and reference)
typedef typename D::const_reference const_reference; // == PixelConcept (if you remove const and reference)
const bool is_mutable=D::is_mutable; ignore_unused_variable_warning(is_mutable);
}
D d;
};
template <typename P>
struct PixelDereferenceAdaptorArchetype : public std::unary_function<P, P> {
typedef PixelDereferenceAdaptorArchetype const_t;
typedef typename remove_reference<P>::type value_type;
typedef typename add_reference<P>::type reference;
typedef reference const_reference;
static const bool is_mutable=false;
P operator()(P x) const { throw; }
};
////////////////////////////////////////////////////////////////////////////////////////
///
/// Pixel ITERATOR CONCEPTS
///
////////////////////////////////////////////////////////////////////////////////////////
/// \brief Concept for iterators, locators and views that can define a type just like the given iterator/locator/view, except it supports runtime specified step along the X navigation
/// \ingroup PixelIteratorConcept
/**
\code
concept HasDynamicXStepTypeConcept<typename T> {
typename dynamic_x_step_type<T>;
where Metafunction<dynamic_x_step_type<T> >;
};
\endcode
*/
template <typename T>
struct HasDynamicXStepTypeConcept {
void constraints() {
typedef typename dynamic_x_step_type<T>::type type;
}
};
/// \brief Concept for locators and views that can define a type just like the given locator or view, except it supports runtime specified step along the Y navigation
/// \ingroup PixelLocatorConcept
/**
\code
concept HasDynamicYStepTypeConcept<typename T> {
typename dynamic_y_step_type<T>;
where Metafunction<dynamic_y_step_type<T> >;
};
\endcode
*/
template <typename T>
struct HasDynamicYStepTypeConcept {
void constraints() {
typedef typename dynamic_y_step_type<T>::type type;
}
};
/// \brief Concept for locators and views that can define a type just like the given locator or view, except X and Y is swapped
/// \ingroup PixelLocatorConcept
/**
\code
concept HasTransposedTypeConcept<typename T> {
typename transposed_type<T>;
where Metafunction<transposed_type<T> >;
};
\endcode
*/
template <typename T>
struct HasTransposedTypeConcept {
void constraints() {
typedef typename transposed_type<T>::type type;
}
};
/// \defgroup PixelIteratorConceptPixelIterator PixelIteratorConcept
/// \ingroup PixelIteratorConcept
/// \brief STL iterator over pixels
/// \ingroup PixelIteratorConceptPixelIterator
/// \brief An STL random access traversal iterator over a model of PixelConcept.
/**
GIL's iterators must also provide the following metafunctions:
- \p const_iterator_type<Iterator>: Returns a read-only equivalent of \p Iterator
- \p iterator_is_mutable<Iterator>: Returns whether the given iterator is read-only or mutable
- \p is_iterator_adaptor<Iterator>: Returns whether the given iterator is an adaptor over another iterator. See IteratorAdaptorConcept for additional requirements of adaptors.
\code
concept PixelIteratorConcept<typename Iterator> : boost_concepts::RandomAccessTraversalConcept<Iterator>, PixelBasedConcept<Iterator> {
where PixelValueConcept<value_type>;
typename const_iterator_type<It>::type;
where PixelIteratorConcept<const_iterator_type<It>::type>;
static const bool iterator_is_mutable<It>::type::value;
static const bool is_iterator_adaptor<It>::type::value; // is it an iterator adaptor
};
\endcode
*/
template <typename Iterator>
struct PixelIteratorConcept {
void constraints() {
gil_function_requires<boost_concepts::RandomAccessTraversalConcept<Iterator> >();
gil_function_requires<PixelBasedConcept<Iterator> >();
typedef typename std::iterator_traits<Iterator>::value_type value_type;
gil_function_requires<PixelValueConcept<value_type> >();
typedef typename const_iterator_type<Iterator>::type const_t;
static const bool is_mut = iterator_is_mutable<Iterator>::type::value; ignore_unused_variable_warning(is_mut);
const_t const_it(it); ignore_unused_variable_warning(const_it); // immutable iterator must be constructible from (possibly mutable) iterator
check_base(typename is_iterator_adaptor<Iterator>::type());
}
void check_base(mpl::false_) {}
void check_base(mpl::true_) {
typedef typename iterator_adaptor_get_base<Iterator>::type base_t;
gil_function_requires<PixelIteratorConcept<base_t> >();
}
Iterator it;
};
namespace detail {
template <typename Iterator> // Preconditions: Iterator Models PixelIteratorConcept
struct PixelIteratorIsMutableConcept {
void constraints() {
gil_function_requires<detail::RandomAccessIteratorIsMutableConcept<Iterator> >();
typedef typename remove_reference<typename std::iterator_traits<Iterator>::reference>::type ref;
typedef typename element_type<ref>::type channel_t;
gil_function_requires<detail::ChannelIsMutableConcept<channel_t> >();
}
};
}
/// \brief Pixel iterator that allows for changing its pixel
/// \ingroup PixelIteratorConceptPixelIterator
/**
\code
concept MutablePixelIteratorConcept<PixelIteratorConcept Iterator> : MutableRandomAccessIteratorConcept<Iterator> {};
\endcode
*/
template <typename Iterator>
struct MutablePixelIteratorConcept {
void constraints() {
gil_function_requires<PixelIteratorConcept<Iterator> >();
gil_function_requires<detail::PixelIteratorIsMutableConcept<Iterator> >();
}
};
namespace detail {
// Iterators that can be used as the base of memory_based_step_iterator require some additional functions
template <typename Iterator> // Preconditions: Iterator Models boost_concepts::RandomAccessTraversalConcept
struct RandomAccessIteratorIsMemoryBasedConcept {
void constraints() {
std::ptrdiff_t bs=memunit_step(it); ignore_unused_variable_warning(bs);
it=memunit_advanced(it,3);
std::ptrdiff_t bd=memunit_distance(it,it); ignore_unused_variable_warning(bd);
memunit_advance(it,3);
// for performace you may also provide a customized implementation of memunit_advanced_ref
}
Iterator it;
};
}
/// \defgroup PixelIteratorConceptStepIterator StepIteratorConcept
/// \ingroup PixelIteratorConcept
/// \brief Iterator that advances by a specified step
/// \brief Concept of a random-access iterator that can be advanced in memory units (bytes or bits)
/// \ingroup PixelIteratorConceptStepIterator
/**
\code
concept MemoryBasedIteratorConcept<boost_concepts::RandomAccessTraversalConcept Iterator> {
typename byte_to_memunit<Iterator>; where metafunction<byte_to_memunit<Iterator> >;
std::ptrdiff_t memunit_step(const Iterator&);
std::ptrdiff_t memunit_distance(const Iterator& , const Iterator&);
void memunit_advance(Iterator&, std::ptrdiff_t diff);
Iterator memunit_advanced(const Iterator& p, std::ptrdiff_t diff) { Iterator tmp; memunit_advance(tmp,diff); return tmp; }
Iterator::reference memunit_advanced_ref(const Iterator& p, std::ptrdiff_t diff) { return *memunit_advanced(p,diff); }
};
\endcode
*/
template <typename Iterator>
struct MemoryBasedIteratorConcept {
void constraints() {
gil_function_requires<boost_concepts::RandomAccessTraversalConcept<Iterator> >();
gil_function_requires<detail::RandomAccessIteratorIsMemoryBasedConcept<Iterator> >();
}
};
/// \brief Step iterator concept
///
/// Step iterators are iterators that have a set_step method
/// \ingroup PixelIteratorConceptStepIterator
/**
\code
concept StepIteratorConcept<boost_concepts::ForwardTraversalConcept Iterator> {
template <Integral D> void Iterator::set_step(D step);
};
\endcode
*/
template <typename Iterator>
struct StepIteratorConcept {
void constraints() {
gil_function_requires<boost_concepts::ForwardTraversalConcept<Iterator> >();
it.set_step(0);
}
Iterator it;
};
/// \brief Step iterator that allows for modifying its current value
///
/// \ingroup PixelIteratorConceptStepIterator
/**
\code
concept MutableStepIteratorConcept<Mutable_ForwardIteratorConcept Iterator> : StepIteratorConcept<Iterator> {};
\endcode
*/
template <typename Iterator>
struct MutableStepIteratorConcept {
void constraints() {
gil_function_requires<StepIteratorConcept<Iterator> >();
gil_function_requires<detail::ForwardIteratorIsMutableConcept<Iterator> >();
}
};
/// \defgroup PixelIteratorConceptIteratorAdaptor IteratorAdaptorConcept
/// \ingroup PixelIteratorConcept
/// \brief Adaptor over another iterator
/// \ingroup PixelIteratorConceptIteratorAdaptor
/// \brief Iterator adaptor is a forward iterator adapting another forward iterator.
/**
In addition to GIL iterator requirements, GIL iterator adaptors must provide the following metafunctions:
- \p is_iterator_adaptor<Iterator>: Returns \p mpl::true_
- \p iterator_adaptor_get_base<Iterator>: Returns the base iterator type
- \p iterator_adaptor_rebind<Iterator,NewBase>: Replaces the base iterator with the new one
The adaptee can be obtained from the iterator via the "base()" method.
\code
concept IteratorAdaptorConcept<boost_concepts::ForwardTraversalConcept Iterator> {
where SameType<is_iterator_adaptor<Iterator>::type, mpl::true_>;
typename iterator_adaptor_get_base<Iterator>;
where Metafunction<iterator_adaptor_get_base<Iterator> >;
where boost_concepts::ForwardTraversalConcept<iterator_adaptor_get_base<Iterator>::type>;
typename another_iterator;
typename iterator_adaptor_rebind<Iterator,another_iterator>::type;
where boost_concepts::ForwardTraversalConcept<another_iterator>;
where IteratorAdaptorConcept<iterator_adaptor_rebind<Iterator,another_iterator>::type>;
const iterator_adaptor_get_base<Iterator>::type& Iterator::base() const;
};
\endcode
*/
template <typename Iterator>
struct IteratorAdaptorConcept {
void constraints() {
gil_function_requires<boost_concepts::ForwardTraversalConcept<Iterator> >();
typedef typename iterator_adaptor_get_base<Iterator>::type base_t;
gil_function_requires<boost_concepts::ForwardTraversalConcept<base_t> >();
BOOST_STATIC_ASSERT(is_iterator_adaptor<Iterator>::value);
typedef typename iterator_adaptor_rebind<Iterator, void*>::type rebind_t;
base_t base=it.base(); ignore_unused_variable_warning(base);
}
Iterator it;
};
/// \brief Iterator adaptor that is mutable
/// \ingroup PixelIteratorConceptIteratorAdaptor
/**
\code
concept MutableIteratorAdaptorConcept<Mutable_ForwardIteratorConcept Iterator> : IteratorAdaptorConcept<Iterator> {};
\endcode
*/
template <typename Iterator>
struct MutableIteratorAdaptorConcept {
void constraints() {
gil_function_requires<IteratorAdaptorConcept<Iterator> >();
gil_function_requires<detail::ForwardIteratorIsMutableConcept<Iterator> >();
}
};
////////////////////////////////////////////////////////////////////////////////////////
///
/// LOCATOR CONCEPTS
///
////////////////////////////////////////////////////////////////////////////////////////
/// \defgroup LocatorNDConcept RandomAccessNDLocatorConcept
/// \ingroup PixelLocatorConcept
/// \brief N-dimensional locator
/// \defgroup Locator2DConcept RandomAccess2DLocatorConcept
/// \ingroup PixelLocatorConcept
/// \brief 2-dimensional locator
/// \defgroup PixelLocator2DConcept PixelLocatorConcept
/// \ingroup PixelLocatorConcept
/// \brief 2-dimensional locator over pixel data
/// \ingroup LocatorNDConcept
/// \brief N-dimensional locator over immutable values
/**
\code
concept RandomAccessNDLocatorConcept<Regular Loc> {
typename value_type; // value over which the locator navigates
typename reference; // result of dereferencing
typename difference_type; where PointNDConcept<difference_type>; // return value of operator-.
typename const_t; // same as Loc, but operating over immutable values
typename cached_location_t; // type to store relative location (for efficient repeated access)
typename point_t = difference_type;
static const size_t num_dimensions; // dimensionality of the locator
where num_dimensions = point_t::num_dimensions;
// The difference_type and iterator type along each dimension. The iterators may only differ in
// difference_type. Their value_type must be the same as Loc::value_type
template <size_t D> struct axis {
typename coord_t = point_t::axis<D>::coord_t;
typename iterator; where RandomAccessTraversalConcept<iterator>; // iterator along D-th axis.
where iterator::value_type == value_type;
};
// Defines the type of a locator similar to this type, except it invokes Deref upon dereferencing
template <PixelDereferenceAdaptorConcept Deref> struct add_deref {
typename type; where RandomAccessNDLocatorConcept<type>;
static type make(const Loc& loc, const Deref& deref);
};
Loc& operator+=(Loc&, const difference_type&);
Loc& operator-=(Loc&, const difference_type&);
Loc operator+(const Loc&, const difference_type&);
Loc operator-(const Loc&, const difference_type&);
reference operator*(const Loc&);
reference operator[](const Loc&, const difference_type&);
// Storing relative location for faster repeated access and accessing it
cached_location_t Loc::cache_location(const difference_type&) const;
reference operator[](const Loc&,const cached_location_t&);
// Accessing iterators along a given dimension at the current location or at a given offset
template <size_t D> axis<D>::iterator& Loc::axis_iterator();
template <size_t D> axis<D>::iterator const& Loc::axis_iterator() const;
template <size_t D> axis<D>::iterator Loc::axis_iterator(const difference_type&) const;
};
\endcode
*/
template <typename Loc>
struct RandomAccessNDLocatorConcept {
void constraints() {
gil_function_requires< Regular<Loc> >();
typedef typename Loc::value_type value_type;
typedef typename Loc::reference reference; // result of dereferencing
typedef typename Loc::difference_type difference_type; // result of operator-(pixel_locator, pixel_locator)
typedef typename Loc::cached_location_t cached_location_t; // type used to store relative location (to allow for more efficient repeated access)
typedef typename Loc::const_t const_t; // same as this type, but over const values
typedef typename Loc::point_t point_t; // same as difference_type
static const std::size_t N=Loc::num_dimensions; ignore_unused_variable_warning(N);
typedef typename Loc::template axis<0>::iterator first_it_type;
typedef typename Loc::template axis<N-1>::iterator last_it_type;
gil_function_requires<boost_concepts::RandomAccessTraversalConcept<first_it_type> >();
gil_function_requires<boost_concepts::RandomAccessTraversalConcept<last_it_type> >();
// point_t must be an N-dimensional point, each dimension of which must have the same type as difference_type of the corresponding iterator
gil_function_requires<PointNDConcept<point_t> >();
BOOST_STATIC_ASSERT(point_t::num_dimensions==N);
BOOST_STATIC_ASSERT((is_same<typename std::iterator_traits<first_it_type>::difference_type, typename point_t::template axis<0>::coord_t>::value));
BOOST_STATIC_ASSERT((is_same<typename std::iterator_traits<last_it_type>::difference_type, typename point_t::template axis<N-1>::coord_t>::value));
difference_type d;
loc+=d;
loc-=d;
loc=loc+d;
loc=loc-d;
reference r1=loc[d]; ignore_unused_variable_warning(r1);
reference r2=*loc; ignore_unused_variable_warning(r2);
cached_location_t cl=loc.cache_location(d); ignore_unused_variable_warning(cl);
reference r3=loc[d]; ignore_unused_variable_warning(r3);
first_it_type fi=loc.template axis_iterator<0>();
fi=loc.template axis_iterator<0>(d);
last_it_type li=loc.template axis_iterator<N-1>();
li=loc.template axis_iterator<N-1>(d);
typedef PixelDereferenceAdaptorArchetype<typename Loc::value_type> deref_t;
typedef typename Loc::template add_deref<deref_t>::type dtype;
//gil_function_requires<RandomAccessNDLocatorConcept<dtype> >(); // infinite recursion
}
Loc loc;
};
/// \ingroup Locator2DConcept
/// \brief 2-dimensional locator over immutable values
/**
\code
concept RandomAccess2DLocatorConcept<RandomAccessNDLocatorConcept Loc> {
where num_dimensions==2;
where Point2DConcept<point_t>;
typename x_iterator = axis<0>::iterator;
typename y_iterator = axis<1>::iterator;
typename x_coord_t = axis<0>::coord_t;
typename y_coord_t = axis<1>::coord_t;
// Only available to locators that have dynamic step in Y
//Loc::Loc(const Loc& loc, y_coord_t);
// Only available to locators that have dynamic step in X and Y
//Loc::Loc(const Loc& loc, x_coord_t, y_coord_t, bool transposed=false);
x_iterator& Loc::x();
x_iterator const& Loc::x() const;
y_iterator& Loc::y();
y_iterator const& Loc::y() const;
x_iterator Loc::x_at(const difference_type&) const;
y_iterator Loc::y_at(const difference_type&) const;
Loc Loc::xy_at(const difference_type&) const;
// x/y versions of all methods that can take difference type
x_iterator Loc::x_at(x_coord_t, y_coord_t) const;
y_iterator Loc::y_at(x_coord_t, y_coord_t) const;
Loc Loc::xy_at(x_coord_t, y_coord_t) const;
reference operator()(const Loc&, x_coord_t, y_coord_t);
cached_location_t Loc::cache_location(x_coord_t, y_coord_t) const;
bool Loc::is_1d_traversable(x_coord_t width) const;
y_coord_t Loc::y_distance_to(const Loc& loc2, x_coord_t x_diff) const;
};
\endcode
*/
template <typename Loc>
struct RandomAccess2DLocatorConcept {
void constraints() {
gil_function_requires<RandomAccessNDLocatorConcept<Loc> >();
BOOST_STATIC_ASSERT(Loc::num_dimensions==2);
typedef typename dynamic_x_step_type<Loc>::type dynamic_x_step_t;
typedef typename dynamic_y_step_type<Loc>::type dynamic_y_step_t;
typedef typename transposed_type<Loc>::type transposed_t;
typedef typename Loc::cached_location_t cached_location_t;
gil_function_requires<Point2DConcept<typename Loc::point_t> >();
typedef typename Loc::x_iterator x_iterator;
typedef typename Loc::y_iterator y_iterator;
typedef typename Loc::x_coord_t x_coord_t;
typedef typename Loc::y_coord_t y_coord_t;
x_coord_t xd=0; ignore_unused_variable_warning(xd);
y_coord_t yd=0; ignore_unused_variable_warning(yd);
typename Loc::difference_type d;
typename Loc::reference r=loc(xd,yd); ignore_unused_variable_warning(r);
dynamic_x_step_t loc2(dynamic_x_step_t(), yd);
dynamic_x_step_t loc3(dynamic_x_step_t(), xd, yd);
typedef typename dynamic_y_step_type<typename dynamic_x_step_type<transposed_t>::type>::type dynamic_xy_step_transposed_t;
dynamic_xy_step_transposed_t loc4(loc, xd,yd,true);
bool is_contiguous=loc.is_1d_traversable(xd); ignore_unused_variable_warning(is_contiguous);
loc.y_distance_to(loc, xd);
loc=loc.xy_at(d);
loc=loc.xy_at(xd,yd);
x_iterator xit=loc.x_at(d);
xit=loc.x_at(xd,yd);
xit=loc.x();
y_iterator yit=loc.y_at(d);
yit=loc.y_at(xd,yd);
yit=loc.y();
cached_location_t cl=loc.cache_location(xd,yd); ignore_unused_variable_warning(cl);
}
Loc loc;
};
/// \ingroup PixelLocator2DConcept
/// \brief GIL's 2-dimensional locator over immutable GIL pixels
/**
\code
concept PixelLocatorConcept<RandomAccess2DLocatorConcept Loc> {
where PixelValueConcept<value_type>;
where PixelIteratorConcept<x_iterator>;
where PixelIteratorConcept<y_iterator>;
where x_coord_t == y_coord_t;
typename coord_t = x_coord_t;
};
\endcode
*/
template <typename Loc>
struct PixelLocatorConcept {
void constraints() {
gil_function_requires< RandomAccess2DLocatorConcept<Loc> >();
gil_function_requires< PixelIteratorConcept<typename Loc::x_iterator> >();
gil_function_requires< PixelIteratorConcept<typename Loc::y_iterator> >();
typedef typename Loc::coord_t coord_t;
BOOST_STATIC_ASSERT((is_same<typename Loc::x_coord_t, typename Loc::y_coord_t>::value));
}
Loc loc;
};
namespace detail {
template <typename Loc> // preconditions: Loc Models RandomAccessNDLocatorConcept
struct RandomAccessNDLocatorIsMutableConcept {
void constraints() {
gil_function_requires<detail::RandomAccessIteratorIsMutableConcept<typename Loc::template axis<0>::iterator> >();
gil_function_requires<detail::RandomAccessIteratorIsMutableConcept<typename Loc::template axis<Loc::num_dimensions-1>::iterator> >();
typename Loc::difference_type d; initialize_it(d);
typename Loc::value_type v;initialize_it(v);
typename Loc::cached_location_t cl=loc.cache_location(d);
*loc=v;
loc[d]=v;
loc[cl]=v;
}
Loc loc;
};
template <typename Loc> // preconditions: Loc Models RandomAccess2DLocatorConcept
struct RandomAccess2DLocatorIsMutableConcept {
void constraints() {
gil_function_requires<detail::RandomAccessNDLocatorIsMutableConcept<Loc> >();
typename Loc::x_coord_t xd=0; ignore_unused_variable_warning(xd);
typename Loc::y_coord_t yd=0; ignore_unused_variable_warning(yd);
typename Loc::value_type v; initialize_it(v);
loc(xd,yd)=v;
}
Loc loc;
};
}
/// \ingroup LocatorNDConcept
/// \brief N-dimensional locator over mutable pixels
/**
\code
concept MutableRandomAccessNDLocatorConcept<RandomAccessNDLocatorConcept Loc> {
where Mutable<reference>;
};
\endcode
*/
template <typename Loc>
struct MutableRandomAccessNDLocatorConcept {
void constraints() {
gil_function_requires<RandomAccessNDLocatorConcept<Loc> >();
gil_function_requires<detail::RandomAccessNDLocatorIsMutableConcept<Loc> >();
}
};
/// \ingroup Locator2DConcept
/// \brief 2-dimensional locator over mutable pixels
/**
\code
concept MutableRandomAccess2DLocatorConcept<RandomAccess2DLocatorConcept Loc> : MutableRandomAccessNDLocatorConcept<Loc> {};
\endcode
*/
template <typename Loc>
struct MutableRandomAccess2DLocatorConcept {
void constraints() {
gil_function_requires< RandomAccess2DLocatorConcept<Loc> >();
gil_function_requires<detail::RandomAccess2DLocatorIsMutableConcept<Loc> >();
}
};
/// \ingroup PixelLocator2DConcept
/// \brief GIL's 2-dimensional locator over mutable GIL pixels
/**
\code
concept MutablePixelLocatorConcept<PixelLocatorConcept Loc> : MutableRandomAccess2DLocatorConcept<Loc> {};
\endcode
*/
template <typename Loc>
struct MutablePixelLocatorConcept {
void constraints() {
gil_function_requires<PixelLocatorConcept<Loc> >();
gil_function_requires<detail::RandomAccess2DLocatorIsMutableConcept<Loc> >();
}
};
////////////////////////////////////////////////////////////////////////////////////////
///
/// IMAGE VIEW CONCEPTS
///
////////////////////////////////////////////////////////////////////////////////////////
/// \defgroup ImageViewNDConcept ImageViewNDLocatorConcept
/// \ingroup ImageViewConcept
/// \brief N-dimensional range
/// \defgroup ImageView2DConcept ImageView2DConcept
/// \ingroup ImageViewConcept
/// \brief 2-dimensional range
/// \defgroup PixelImageViewConcept ImageViewConcept
/// \ingroup ImageViewConcept
/// \brief 2-dimensional range over pixel data
/// \ingroup ImageViewNDConcept
/// \brief N-dimensional view over immutable values
/**
\code
concept RandomAccessNDImageViewConcept<Regular View> {
typename value_type;
typename reference; // result of dereferencing
typename difference_type; // result of operator-(iterator,iterator) (1-dimensional!)
typename const_t; where RandomAccessNDImageViewConcept<View>; // same as View, but over immutable values
typename point_t; where PointNDConcept<point_t>; // N-dimensional point
typename locator; where RandomAccessNDLocatorConcept<locator>; // N-dimensional locator.
typename iterator; where RandomAccessTraversalConcept<iterator>; // 1-dimensional iterator over all values
typename reverse_iterator; where RandomAccessTraversalConcept<reverse_iterator>;
typename size_type; // the return value of size()
// Equivalent to RandomAccessNDLocatorConcept::axis
template <size_t D> struct axis {
typename coord_t = point_t::axis<D>::coord_t;
typename iterator; where RandomAccessTraversalConcept<iterator>; // iterator along D-th axis.
where SameType<coord_t, iterator::difference_type>;
where SameType<iterator::value_type,value_type>;
};
// Defines the type of a view similar to this type, except it invokes Deref upon dereferencing
template <PixelDereferenceAdaptorConcept Deref> struct add_deref {
typename type; where RandomAccessNDImageViewConcept<type>;
static type make(const View& v, const Deref& deref);
};
static const size_t num_dimensions = point_t::num_dimensions;
// Create from a locator at the top-left corner and dimensions
View::View(const locator&, const point_type&);
size_type View::size() const; // total number of elements
reference operator[](View, const difference_type&) const; // 1-dimensional reference
iterator View::begin() const;
iterator View::end() const;
reverse_iterator View::rbegin() const;
reverse_iterator View::rend() const;
iterator View::at(const point_t&);
point_t View::dimensions() const; // number of elements along each dimension
bool View::is_1d_traversable() const; // can an iterator over the first dimension visit each value? I.e. are there gaps between values?
// iterator along a given dimension starting at a given point
template <size_t D> View::axis<D>::iterator View::axis_iterator(const point_t&) const;
reference operator()(View,const point_t&) const;
};
\endcode
*/
template <typename View>
struct RandomAccessNDImageViewConcept {
void constraints() {
gil_function_requires< Regular<View> >();
typedef typename View::value_type value_type;
typedef typename View::reference reference; // result of dereferencing
typedef typename View::difference_type difference_type; // result of operator-(1d_iterator,1d_iterator)
typedef typename View::const_t const_t; // same as this type, but over const values
typedef typename View::point_t point_t; // N-dimensional point
typedef typename View::locator locator; // N-dimensional locator
typedef typename View::iterator iterator;
typedef typename View::reverse_iterator reverse_iterator;
typedef typename View::size_type size_type;
static const std::size_t N=View::num_dimensions;
gil_function_requires<RandomAccessNDLocatorConcept<locator> >();
gil_function_requires<boost_concepts::RandomAccessTraversalConcept<iterator> >();
gil_function_requires<boost_concepts::RandomAccessTraversalConcept<reverse_iterator> >();
typedef typename View::template axis<0>::iterator first_it_type;
typedef typename View::template axis<N-1>::iterator last_it_type;
gil_function_requires<boost_concepts::RandomAccessTraversalConcept<first_it_type> >();
gil_function_requires<boost_concepts::RandomAccessTraversalConcept<last_it_type> >();
// BOOST_STATIC_ASSERT((typename std::iterator_traits<first_it_type>::difference_type, typename point_t::template axis<0>::coord_t>::value));
// BOOST_STATIC_ASSERT((typename std::iterator_traits< last_it_type>::difference_type, typename point_t::template axis<N-1>::coord_t>::value));
// point_t must be an N-dimensional point, each dimension of which must have the same type as difference_type of the corresponding iterator
gil_function_requires<PointNDConcept<point_t> >();
BOOST_STATIC_ASSERT(point_t::num_dimensions==N);
BOOST_STATIC_ASSERT((is_same<typename std::iterator_traits<first_it_type>::difference_type, typename point_t::template axis<0>::coord_t>::value));
BOOST_STATIC_ASSERT((is_same<typename std::iterator_traits<last_it_type>::difference_type, typename point_t::template axis<N-1>::coord_t>::value));
point_t p;
locator lc;
iterator it;
reverse_iterator rit;
difference_type d; detail::initialize_it(d); ignore_unused_variable_warning(d);
View(p,lc); // view must be constructible from a locator and a point
p=view.dimensions();
lc=view.pixels();
size_type sz=view.size(); ignore_unused_variable_warning(sz);
bool is_contiguous=view.is_1d_traversable(); ignore_unused_variable_warning(is_contiguous);
it=view.begin();
it=view.end();
rit=view.rbegin();
rit=view.rend();
reference r1=view[d]; ignore_unused_variable_warning(r1); // 1D access
reference r2=view(p); ignore_unused_variable_warning(r2); // 2D access
// get 1-D iterator of any dimension at a given pixel location
first_it_type fi=view.template axis_iterator<0>(p); ignore_unused_variable_warning(fi);
last_it_type li=view.template axis_iterator<N-1>(p); ignore_unused_variable_warning(li);
typedef PixelDereferenceAdaptorArchetype<typename View::value_type> deref_t;
typedef typename View::template add_deref<deref_t>::type dtype;
}
View view;
};
/// \ingroup ImageView2DConcept
/// \brief 2-dimensional view over immutable values
/**
\code
concept RandomAccess2DImageViewConcept<RandomAccessNDImageViewConcept View> {
where num_dimensions==2;
typename x_iterator = axis<0>::iterator;
typename y_iterator = axis<1>::iterator;
typename x_coord_t = axis<0>::coord_t;
typename y_coord_t = axis<1>::coord_t;
typename xy_locator = locator;
x_coord_t View::width() const;
y_coord_t View::height() const;
// X-navigation
x_iterator View::x_at(const point_t&) const;
x_iterator View::row_begin(y_coord_t) const;
x_iterator View::row_end (y_coord_t) const;
// Y-navigation
y_iterator View::y_at(const point_t&) const;
y_iterator View::col_begin(x_coord_t) const;
y_iterator View::col_end (x_coord_t) const;
// navigating in 2D
xy_locator View::xy_at(const point_t&) const;
// (x,y) versions of all methods taking point_t
View::View(x_coord_t,y_coord_t,const locator&);
iterator View::at(x_coord_t,y_coord_t) const;
reference operator()(View,x_coord_t,y_coord_t) const;
xy_locator View::xy_at(x_coord_t,y_coord_t) const;
x_iterator View::x_at(x_coord_t,y_coord_t) const;
y_iterator View::y_at(x_coord_t,y_coord_t) const;
};
\endcode
*/
template <typename View>
struct RandomAccess2DImageViewConcept {
void constraints() {
gil_function_requires<RandomAccessNDImageViewConcept<View> >();
BOOST_STATIC_ASSERT(View::num_dimensions==2);
// TODO: This executes the requirements for RandomAccessNDLocatorConcept again. Fix it to improve compile time
gil_function_requires<RandomAccess2DLocatorConcept<typename View::locator> >();
typedef typename dynamic_x_step_type<View>::type dynamic_x_step_t;
typedef typename dynamic_y_step_type<View>::type dynamic_y_step_t;
typedef typename transposed_type<View>::type transposed_t;
typedef typename View::x_iterator x_iterator;
typedef typename View::y_iterator y_iterator;
typedef typename View::x_coord_t x_coord_t;
typedef typename View::y_coord_t y_coord_t;
typedef typename View::xy_locator xy_locator;
x_coord_t xd=0; ignore_unused_variable_warning(xd);
y_coord_t yd=0; ignore_unused_variable_warning(yd);
x_iterator xit;
y_iterator yit;
typename View::point_t d;
View(xd,yd,xy_locator()); // constructible with width, height, 2d_locator
xy_locator lc=view.xy_at(xd,yd);
lc=view.xy_at(d);
typename View::reference r=view(xd,yd); ignore_unused_variable_warning(r);
xd=view.width();
yd=view.height();
xit=view.x_at(d);
xit=view.x_at(xd,yd);
xit=view.row_begin(xd);
xit=view.row_end(xd);
yit=view.y_at(d);
yit=view.y_at(xd,yd);
yit=view.col_begin(xd);
yit=view.col_end(xd);
}
View view;
};
/// \ingroup PixelImageViewConcept
/// \brief GIL's 2-dimensional view over immutable GIL pixels
/**
\code
concept ImageViewConcept<RandomAccess2DImageViewConcept View> {
where PixelValueConcept<value_type>;
where PixelIteratorConcept<x_iterator>;
where PixelIteratorConcept<y_iterator>;
where x_coord_t == y_coord_t;
typename coord_t = x_coord_t;
std::size_t View::num_channels() const;
};
\endcode
*/
template <typename View>
struct ImageViewConcept {
void constraints() {
gil_function_requires<RandomAccess2DImageViewConcept<View> >();
// TODO: This executes the requirements for RandomAccess2DLocatorConcept again. Fix it to improve compile time
gil_function_requires<PixelLocatorConcept<typename View::xy_locator> >();
BOOST_STATIC_ASSERT((is_same<typename View::x_coord_t, typename View::y_coord_t>::value));
typedef typename View::coord_t coord_t; // 1D difference type (same for all dimensions)
std::size_t num_chan = view.num_channels(); ignore_unused_variable_warning(num_chan);
}
View view;
};
namespace detail {
template <typename View> // Preconditions: View Models RandomAccessNDImageViewConcept
struct RandomAccessNDImageViewIsMutableConcept {
void constraints() {
gil_function_requires<detail::RandomAccessNDLocatorIsMutableConcept<typename View::locator> >();
gil_function_requires<detail::RandomAccessIteratorIsMutableConcept<typename View::iterator> >();
gil_function_requires<detail::RandomAccessIteratorIsMutableConcept<typename View::reverse_iterator> >();
gil_function_requires<detail::RandomAccessIteratorIsMutableConcept<typename View::template axis<0>::iterator> >();
gil_function_requires<detail::RandomAccessIteratorIsMutableConcept<typename View::template axis<View::num_dimensions-1>::iterator> >();
typename View::difference_type diff; initialize_it(diff); ignore_unused_variable_warning(diff);
typename View::point_t pt;
typename View::value_type v; initialize_it(v);
view[diff]=v;
view(pt)=v;
}
View view;
};
template <typename View> // preconditions: View Models RandomAccessNDImageViewConcept
struct RandomAccess2DImageViewIsMutableConcept {
void constraints() {
gil_function_requires<detail::RandomAccessNDImageViewIsMutableConcept<View> >();
typename View::x_coord_t xd=0; ignore_unused_variable_warning(xd);
typename View::y_coord_t yd=0; ignore_unused_variable_warning(yd);
typename View::value_type v; initialize_it(v);
view(xd,yd)=v;
}
View view;
};
template <typename View> // preconditions: View Models ImageViewConcept
struct PixelImageViewIsMutableConcept {
void constraints() {
gil_function_requires<detail::RandomAccess2DImageViewIsMutableConcept<View> >();
}
};
}
/// \ingroup ImageViewNDConcept
/// \brief N-dimensional view over mutable values
/**
\code
concept MutableRandomAccessNDImageViewConcept<RandomAccessNDImageViewConcept View> {
where Mutable<reference>;
};
\endcode
*/
template <typename View>
struct MutableRandomAccessNDImageViewConcept {
void constraints() {
gil_function_requires<RandomAccessNDImageViewConcept<View> >();
gil_function_requires<detail::RandomAccessNDImageViewIsMutableConcept<View> >();
}
};
/// \ingroup ImageView2DConcept
/// \brief 2-dimensional view over mutable values
/**
\code
concept MutableRandomAccess2DImageViewConcept<RandomAccess2DImageViewConcept View> : MutableRandomAccessNDImageViewConcept<View> {};
\endcode
*/
template <typename View>
struct MutableRandomAccess2DImageViewConcept {
void constraints() {
gil_function_requires<RandomAccess2DImageViewConcept<View> >();
gil_function_requires<detail::RandomAccess2DImageViewIsMutableConcept<View> >();
}
};
/// \ingroup PixelImageViewConcept
/// \brief GIL's 2-dimensional view over mutable GIL pixels
/**
\code
concept MutableImageViewConcept<ImageViewConcept View> : MutableRandomAccess2DImageViewConcept<View> {};
\endcode
*/
template <typename View>
struct MutableImageViewConcept {
void constraints() {
gil_function_requires<ImageViewConcept<View> >();
gil_function_requires<detail::PixelImageViewIsMutableConcept<View> >();
}
};
/// \brief Returns whether two views are compatible
///
/// Views are compatible if their pixels are compatible. Compatible views can be assigned and copy constructed from one another.
template <typename V1, typename V2> // Model ImageViewConcept
struct views_are_compatible : public pixels_are_compatible<typename V1::value_type, typename V2::value_type> {};
/// \brief Views are compatible if they have the same color spaces and compatible channel values. Constness and layout are not important for compatibility
/// \ingroup ImageViewConcept
/**
\code
concept ViewsCompatibleConcept<ImageViewConcept V1, ImageViewConcept V2> {
where PixelsCompatibleConcept<V1::value_type, P2::value_type>;
};
\endcode
*/
template <typename V1, typename V2>
struct ViewsCompatibleConcept {
void constraints() {
BOOST_STATIC_ASSERT((views_are_compatible<V1,V2>::value));
}
};
////////////////////////////////////////////////////////////////////////////////////////
///
/// IMAGE CONCEPTS
///
////////////////////////////////////////////////////////////////////////////////////////
/// \ingroup ImageConcept
/// \brief N-dimensional container of values
/**
\code
concept RandomAccessNDImageConcept<typename Img> : Regular<Img> {
typename view_t; where MutableRandomAccessNDImageViewConcept<view_t>;
typename const_view_t = view_t::const_t;
typename point_t = view_t::point_t;
typename value_type = view_t::value_type;
typename allocator_type;
Img::Img(point_t dims, std::size_t alignment=1);
Img::Img(point_t dims, value_type fill_value, std::size_t alignment);
void Img::recreate(point_t new_dims, std::size_t alignment=1);
void Img::recreate(point_t new_dims, value_type fill_value, std::size_t alignment);
const point_t& Img::dimensions() const;
const const_view_t& const_view(const Img&);
const view_t& view(Img&);
};
\endcode
*/
template <typename Img>
struct RandomAccessNDImageConcept {
void constraints() {
gil_function_requires<Regular<Img> >();
typedef typename Img::view_t view_t;
gil_function_requires<MutableRandomAccessNDImageViewConcept<view_t> >();
typedef typename Img::const_view_t const_view_t;
typedef typename Img::value_type pixel_t;
typedef typename Img::point_t point_t;
gil_function_requires<PointNDConcept<point_t> >();
const_view_t cv = const_view(img); ignore_unused_variable_warning(cv);
view_t v = view(img); ignore_unused_variable_warning(v);
pixel_t fill_value;
point_t pt=img.dimensions();
Img im1(pt);
Img im2(pt,1);
Img im3(pt,fill_value,1);
img.recreate(pt);
img.recreate(pt,1);
img.recreate(pt,fill_value,1);
}
Img img;
};
/// \ingroup ImageConcept
/// \brief 2-dimensional container of values
/**
\code
concept RandomAccess2DImageConcept<RandomAccessNDImageConcept Img> {
typename x_coord_t = const_view_t::x_coord_t;
typename y_coord_t = const_view_t::y_coord_t;
Img::Img(x_coord_t width, y_coord_t height, std::size_t alignment=1);
Img::Img(x_coord_t width, y_coord_t height, value_type fill_value, std::size_t alignment);
x_coord_t Img::width() const;
y_coord_t Img::height() const;
void Img::recreate(x_coord_t width, y_coord_t height, std::size_t alignment=1);
void Img::recreate(x_coord_t width, y_coord_t height, value_type fill_value, std::size_t alignment);
};
\endcode
*/
template <typename Img>
struct RandomAccess2DImageConcept {
void constraints() {
gil_function_requires<RandomAccessNDImageConcept<Img> >();
typedef typename Img::x_coord_t x_coord_t;
typedef typename Img::y_coord_t y_coord_t;
typedef typename Img::value_type value_t;
gil_function_requires<MutableRandomAccess2DImageViewConcept<typename Img::view_t> >();
x_coord_t w=img.width();
y_coord_t h=img.height();
value_t fill_value;
Img im1(w,h);
Img im2(w,h,1);
Img im3(w,h,fill_value,1);
img.recreate(w,h);
img.recreate(w,h,1);
img.recreate(w,h,fill_value,1);
}
Img img;
};
/// \ingroup ImageConcept
/// \brief 2-dimensional image whose value type models PixelValueConcept
/**
\code
concept ImageConcept<RandomAccess2DImageConcept Img> {
where MutableImageViewConcept<view_t>;
typename coord_t = view_t::coord_t;
};
\endcode
*/
template <typename Img>
struct ImageConcept {
void constraints() {
gil_function_requires<RandomAccess2DImageConcept<Img> >();
gil_function_requires<MutableImageViewConcept<typename Img::view_t> >();
typedef typename Img::coord_t coord_t;
BOOST_STATIC_ASSERT(num_channels<Img>::value == mpl::size<typename color_space_type<Img>::type>::value);
BOOST_STATIC_ASSERT((is_same<coord_t, typename Img::x_coord_t>::value));
BOOST_STATIC_ASSERT((is_same<coord_t, typename Img::y_coord_t>::value));
}
Img img;
};
} } // namespace boost::gil
#endif
| [
"satoon101@gmail.com"
] | satoon101@gmail.com |
7afe9575d603542b6381a463d252cf7a8386594c | c234331232f227e0cdfb567a54ecaa5460aaa064 | /src/core/NEON/kernels/NESoftmaxLayerKernel.cpp | 648dac46c0476e1add7249636b7dde08e462cf63 | [
"MIT"
] | permissive | 10imaging/ComputeLibrary | fd0bd4b7c14c1a8da97ac95f9d5bf01461c31356 | e6bbd2b302eb9d229554ec3a02ceb20901459d8c | refs/heads/master | 2021-01-20T02:41:37.634109 | 2017-10-02T19:37:33 | 2017-10-02T19:37:33 | 89,437,773 | 2 | 0 | null | 2017-10-02T19:37:34 | 2017-04-26T04:27:53 | C++ | UTF-8 | C++ | false | false | 29,465 | cpp | /*
* Copyright (c) 2017 ARM Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "arm_compute/core/NEON/kernels/NESoftmaxLayerKernel.h"
#include "arm_compute/core/AccessWindowStatic.h"
#include "arm_compute/core/Error.h"
#include "arm_compute/core/Helpers.h"
#include "arm_compute/core/ITensor.h"
#include "arm_compute/core/NEON/NEFixedPoint.h"
#include "arm_compute/core/NEON/NEMath.h"
#include "arm_compute/core/TensorInfo.h"
#include "arm_compute/core/Utils.h"
#include "arm_compute/core/Validate.h"
#include "arm_compute/core/Window.h"
#include <algorithm>
#include <arm_neon.h>
#include <cfloat>
using namespace arm_compute;
namespace
{
void logits_1d_max_qs8(const ITensor *in, ITensor *out, const Window &window)
{
Window in_slice = window.first_slice_window_1D();
Window window_max(window);
window_max.set(Window::DimX, Window::Dimension(0, 0, 0));
Window max_slice = window_max.first_slice_window_1D();
do
{
Iterator input(in, in_slice);
Iterator output(out, max_slice);
qint8x16_t vec_max = vdupq_n_s8(std::numeric_limits<qint8_t>::lowest());
execute_window_loop(in_slice, [&](const Coordinates & id)
{
const auto in_ptr = reinterpret_cast<const qint8_t *>(input.ptr());
const qint8x16_t current_value = vld1q_qs8(in_ptr);
vec_max = vmaxq_qs8(vec_max, current_value);
},
input);
qint8x8_t carry_max = vpmax_qs8(vget_high_s8(vec_max), vget_low_s8(vec_max));
carry_max = vpmax_qs8(carry_max, carry_max);
carry_max = vpmax_qs8(carry_max, carry_max);
carry_max = vpmax_qs8(carry_max, carry_max);
*(reinterpret_cast<qint8_t *>(output.ptr())) = vget_lane_s8(carry_max, 0);
}
while(window.slide_window_slice_1D(in_slice) && window.slide_window_slice_1D(max_slice));
}
void logits_1d_max_qs16(const ITensor *in, ITensor *out, const Window &window)
{
Window in_slice = window.first_slice_window_1D();
Window window_max(window);
window_max.set(Window::DimX, Window::Dimension(0, 0, 0));
Window max_slice = window_max.first_slice_window_1D();
do
{
Iterator input(in, in_slice);
Iterator output(out, max_slice);
qint16x8_t vec_max = vdupq_n_qs16(std::numeric_limits<qint16_t>::lowest());
execute_window_loop(in_slice, [&](const Coordinates & id)
{
const auto in_ptr = reinterpret_cast<const qint16_t *>(input.ptr());
const qint16x8_t current_value = vld1q_qs16(in_ptr);
vec_max = vmaxq_qs16(vec_max, current_value);
},
input);
qint16x4_t carry_max = vpmax_qs16(vget_high_qs16(vec_max), vget_low_qs16(vec_max));
carry_max = vpmax_qs16(carry_max, carry_max);
carry_max = vpmax_qs16(carry_max, carry_max);
*(reinterpret_cast<qint16_t *>(output.ptr())) = vget_lane_s16(carry_max, 0);
}
while(window.slide_window_slice_1D(in_slice) && window.slide_window_slice_1D(max_slice));
}
#ifdef ARM_COMPUTE_ENABLE_FP16
void logits_1d_max_f16(const ITensor *in, ITensor *out, const Window &window)
{
Window in_slice = window.first_slice_window_1D();
Window window_max(window);
window_max.set(Window::DimX, Window::Dimension(0, 0, 0));
Window max_slice = window_max.first_slice_window_1D();
do
{
Iterator input(in, in_slice);
Iterator output(out, max_slice);
float16x8_t vec_max = vdupq_n_f16(std::numeric_limits<float16_t>::lowest());
execute_window_loop(in_slice, [&](const Coordinates & id)
{
const auto in_ptr = reinterpret_cast<const float16_t *>(input.ptr());
const float16x8_t current_value = vld1q_f16(in_ptr);
vec_max = vmaxq_f16(vec_max, current_value);
},
input);
float16x4_t carry_max = vpmax_f16(vget_high_f16(vec_max), vget_low_f16(vec_max));
carry_max = vpmax_f16(carry_max, carry_max);
carry_max = vpmax_f16(carry_max, carry_max);
*(reinterpret_cast<float16_t *>(output.ptr())) = vget_lane_f16(carry_max, 0);
}
while(window.slide_window_slice_1D(in_slice) && window.slide_window_slice_1D(max_slice));
}
#endif /* ARM_COMPUTE_ENABLE_FP16 */
void logits_1d_max_f32(const ITensor *in, ITensor *out, const Window &window)
{
Window in_slice = window.first_slice_window_1D();
Window window_max(window);
window_max.set(Window::DimX, Window::Dimension(0, 0, 0));
Window max_slice = window_max.first_slice_window_1D();
do
{
Iterator input(in, in_slice);
Iterator output(out, max_slice);
float32x4_t vec_max = vdupq_n_f32(-FLT_MAX);
execute_window_loop(in_slice, [&](const Coordinates & id)
{
const auto in_ptr = reinterpret_cast<const float *>(input.ptr());
const float32x4_t current_value = vld1q_f32(in_ptr);
vec_max = vmaxq_f32(vec_max, current_value);
},
input);
float32x2_t carry_max = vpmax_f32(vget_high_f32(vec_max), vget_low_f32(vec_max));
carry_max = vpmax_f32(carry_max, carry_max);
*(reinterpret_cast<float *>(output.ptr())) = vget_lane_f32(carry_max, 0);
}
while(window.slide_window_slice_1D(in_slice) && window.slide_window_slice_1D(max_slice));
}
} // namespace
NELogits1DMaxKernel::NELogits1DMaxKernel()
: _func(nullptr), _border_size()
{
}
BorderSize NELogits1DMaxKernel::border_size() const
{
return _border_size;
}
void NELogits1DMaxKernel::configure(const ITensor *input, ITensor *output)
{
ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::QS8, DataType::QS16, DataType::F16, DataType::F32);
ARM_COMPUTE_ERROR_ON_NULLPTR(output);
// Softmax across the x dimension
TensorShape output_shape{ input->info()->tensor_shape() };
output_shape.set(0, 1);
// Output auto initialization if not yet initialized
auto_init_if_empty(*output->info(), output_shape, 1, input->info()->data_type(), input->info()->fixed_point_position());
ARM_COMPUTE_ERROR_ON_MISMATCHING_DATA_TYPES(input, output);
ARM_COMPUTE_ERROR_ON_MISMATCHING_FIXED_POINT_POSITION(input, output);
ARM_COMPUTE_ERROR_ON_MISMATCHING_DIMENSIONS(output->info()->tensor_shape(), output_shape);
const int input_width = input->info()->valid_region().shape.x();
unsigned int num_elems_processed_per_iteration = 16 / data_size_from_type(input->info()->data_type());
switch(input->info()->data_type())
{
case DataType::QS8:
_func = &logits_1d_max_qs8;
break;
case DataType::QS16:
_func = &logits_1d_max_qs16;
break;
case DataType::F32:
_func = &logits_1d_max_f32;
break;
case DataType::F16:
#ifdef ARM_COMPUTE_ENABLE_FP16
_func = &logits_1d_max_f16;
break;
#endif /* ARM_COMPUTE_ENABLE_FP16 */
default:
ARM_COMPUTE_ERROR("Unsupported data type.");
}
_input = input;
_output = output;
_border_size = BorderSize(0, num_elems_processed_per_iteration - (input_width % num_elems_processed_per_iteration), 0, 0);
// Configure kernel window
constexpr unsigned int num_elems_written_per_row = 1;
Window win = calculate_max_window(*input->info(), Steps(num_elems_processed_per_iteration));
AccessWindowHorizontal input_access(input->info(), 0, num_elems_processed_per_iteration);
AccessWindowHorizontal output_access(output->info(), 0, num_elems_written_per_row, 1.f / input_width);
update_window_and_padding(win, input_access, output_access);
output_access.set_valid_region(win, ValidRegion(Coordinates(), output->info()->tensor_shape()));
INEKernel::configure(win);
}
void NELogits1DMaxKernel::run(const Window &window, const ThreadInfo &info)
{
ARM_COMPUTE_UNUSED(info);
ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(INEKernel::window(), window);
ARM_COMPUTE_ERROR_ON(_func == nullptr);
(*_func)(_input, _output, window);
}
namespace
{
void logits_1d_shift_exp_sum_qs8(const ITensor *in, const ITensor *max, ITensor *out, ITensor *sum, const Window &window)
{
Window window_max(window);
window_max.set(Window::DimX, Window::Dimension(0, 0, 0));
Window max_slice = window_max.first_slice_window_1D();
Window in_slice = window.first_slice_window_1D();
constexpr int step = 8;
const int long_steps = in->info()->valid_region().shape.x() / step;
const int small_steps = in->info()->valid_region().shape.x() % step;
const int fixed_point_position = in->info()->fixed_point_position();
do
{
Iterator input(in, in_slice);
Iterator exp(out, in_slice);
Iterator _max(max, max_slice);
Iterator _sum(sum, max_slice);
// Get pointers
auto in_ptr = reinterpret_cast<const qint8_t *>(input.ptr());
auto exp_ptr = reinterpret_cast<qint8_t *>(exp.ptr());
// Init sum to zero
qint16x8_t vec_sum_value = vdupq_n_qs16(0);
// Get max value
const auto max_ptr = reinterpret_cast<const qint8_t *>(_max.ptr());
const qint8x8_t vec_max = vdup_n_qs8(*max_ptr);
// Run neon loop
for(int i = 0; i < long_steps; ++i)
{
qint8x8_t vec_elements = vld1_qs8(in_ptr);
vec_elements = vqsub_qs8(vec_elements, vec_max);
vec_elements = vqexp_qs8(vec_elements, fixed_point_position);
vst1_qs8(exp_ptr, vec_elements);
vec_sum_value = vqaddq_qs16(vec_sum_value, vmovl_s8(vec_elements));
in_ptr += step;
exp_ptr += step;
}
// Reduce sum
const qint16x4_t sum_red = vqadd_qs16(vget_low_s16(vec_sum_value), vget_high_s16(vec_sum_value));
const qint16_t sum0 = sqadd_qs16(vget_lane_s16(sum_red, 0), vget_lane_s16(sum_red, 1));
const qint16_t sum1 = sqadd_qs16(vget_lane_s16(sum_red, 2), vget_lane_s16(sum_red, 3));
qint16_t sum = sqadd_qs16(sum0, sum1);
// Run remaining elements
for(int i = 0; i < small_steps; ++i)
{
qint8_t element = sqexp_qs8(sqsub_qs8(in_ptr[i], *max_ptr), fixed_point_position);
exp_ptr[i] = element;
sum = sqadd_qs16(sum, element);
}
*(reinterpret_cast<qint8_t *>(_sum.ptr())) = sqmovn_qs16(sum);
}
while(window.slide_window_slice_1D(in_slice) && window.slide_window_slice_1D(max_slice));
}
void logits_1d_shift_exp_sum_qs16(const ITensor *in, const ITensor *max, ITensor *out, ITensor *sum, const Window &window)
{
Window window_max(window);
window_max.set(Window::DimX, Window::Dimension(0, 0, 0));
Window max_slice = window_max.first_slice_window_1D();
Window in_slice = window.first_slice_window_1D();
constexpr int step = 4;
const int long_steps = in->info()->valid_region().shape.x() / step;
const int small_steps = in->info()->valid_region().shape.x() % step;
const int fixed_point_position = in->info()->fixed_point_position();
do
{
Iterator input(in, in_slice);
Iterator exp(out, in_slice);
Iterator _max(max, max_slice);
Iterator _sum(sum, max_slice);
// Get pointers
auto in_ptr = reinterpret_cast<const qint16_t *>(input.ptr());
auto exp_ptr = reinterpret_cast<qint16_t *>(exp.ptr());
// Init sum to zero
qint32x4_t vec_sum_value = vdupq_n_qs32(0);
// Get max value
const auto max_ptr = reinterpret_cast<const qint16_t *>(_max.ptr());
const qint16x4_t vec_max = vdup_n_qs16(*max_ptr);
// Run neon loop
for(int i = 0; i < long_steps; ++i)
{
qint16x4_t vec_elements = vld1_qs16(in_ptr);
vec_elements = vqsub_qs16(vec_elements, vec_max);
vec_elements = vqexp_qs16(vec_elements, fixed_point_position);
vst1_qs16(exp_ptr, vec_elements);
vec_sum_value = vqaddq_qs32(vec_sum_value, vmovl_s16(vec_elements));
in_ptr += step;
exp_ptr += step;
}
// Reduce sum
qint32x2_t carry_addition = vqadd_qs32(vget_high_s32(vec_sum_value), vget_low_s32(vec_sum_value));
qint32_t sum = vget_lane_s32(carry_addition, 0) + vget_lane_s32(carry_addition, 1);
// Run remaining elements
for(int i = 0; i < small_steps; ++i)
{
qint16_t element = sqexp_qs16(sqsub_qs16(in_ptr[i], *max_ptr), fixed_point_position);
exp_ptr[i] = element;
sum = sqadd_qs32(sum, element);
}
*(reinterpret_cast<qint16_t *>(_sum.ptr())) = sqmovn_qs32(sum);
}
while(window.slide_window_slice_1D(in_slice) && window.slide_window_slice_1D(max_slice));
}
#ifdef ARM_COMPUTE_ENABLE_FP16
void logits_1d_shift_exp_sum_f16(const ITensor *in, const ITensor *max, ITensor *out, ITensor *sum, const Window &window)
{
Window window_max(window);
window_max.set(Window::DimX, Window::Dimension(0, 0, 0));
Window max_slice = window_max.first_slice_window_1D();
Window in_slice = window.first_slice_window_1D();
constexpr int step = 8;
const int long_steps = in->info()->valid_region().shape.x() / step;
const int small_steps = in->info()->valid_region().shape.x() % step;
do
{
Iterator input(in, in_slice);
Iterator exp(out, in_slice);
Iterator _max(max, max_slice);
Iterator _sum(sum, max_slice);
// Get pointers
auto in_ptr = reinterpret_cast<const float16_t *>(input.ptr());
auto exp_ptr = reinterpret_cast<float16_t *>(exp.ptr());
// Init sum to zero
float16x8_t vec_sum_value = vdupq_n_f16(0);
// Get max value
const auto max_ptr = reinterpret_cast<const float16_t *>(_max.ptr());
const float16x8_t vec_max = vdupq_n_f16(*max_ptr);
// Run neon loop
for(int i = 0; i < long_steps; ++i)
{
float16x8_t vec_elements = vld1q_f16(in_ptr);
vec_elements = vsubq_f16(vec_elements, vec_max);
vec_elements = vexpq_f16(vec_elements);
vst1q_f16(exp_ptr, vec_elements);
vec_sum_value = vaddq_f16(vec_sum_value, vec_elements);
in_ptr += step;
exp_ptr += step;
}
// Reduce sum
const float16x4_t sum_red = vadd_f16(vget_low_f16(vec_sum_value), vget_high_f16(vec_sum_value));
const float16x4_t carry_addition = vpadd_f16(sum_red, sum_red);
float16_t sum = vget_lane_f16(carry_addition, 0) + vget_lane_f16(carry_addition, 1);
// Run remaining elements
for(int i = 0; i < small_steps; ++i)
{
const float16_t element = std::exp(static_cast<float>(in_ptr[i] - *max_ptr));
exp_ptr[i] = element;
sum += element;
}
*(reinterpret_cast<float16_t *>(_sum.ptr())) = sum;
}
while(window.slide_window_slice_1D(in_slice) && window.slide_window_slice_1D(max_slice));
}
#endif /* ARM_COMPUTE_ENABLE_FP16 */
void logits_1d_shift_exp_sum_f32(const ITensor *in, const ITensor *max, ITensor *out, ITensor *sum, const Window &window)
{
Window window_max(window);
window_max.set(Window::DimX, Window::Dimension(0, 0, 0));
Window max_slice = window_max.first_slice_window_1D();
Window in_slice = window.first_slice_window_1D();
constexpr int step = 4;
const int long_steps = in->info()->valid_region().shape.x() / step;
const int small_steps = in->info()->valid_region().shape.x() % step;
do
{
Iterator input(in, in_slice);
Iterator exp(out, in_slice);
Iterator _max(max, max_slice);
Iterator _sum(sum, max_slice);
// Get pointers
auto in_ptr = reinterpret_cast<const float *>(input.ptr());
auto exp_ptr = reinterpret_cast<float *>(exp.ptr());
// Init sum to zero
float32x4_t vec_sum_value = vdupq_n_f32(0.0f);
// Get max value
const auto max_ptr = reinterpret_cast<const float *>(_max.ptr());
const float32x4_t vec_max = vdupq_n_f32(*max_ptr);
// Run neon loop
for(int i = 0; i < long_steps; ++i)
{
float32x4_t vec_elements = vld1q_f32(in_ptr);
vec_elements = vsubq_f32(vec_elements, vec_max);
vec_elements = vexpq_f32(vec_elements);
vst1q_f32(exp_ptr, vec_elements);
vec_sum_value = vaddq_f32(vec_elements, vec_sum_value);
in_ptr += step;
exp_ptr += step;
}
// Reduce sum
float32x2_t carry_addition = vpadd_f32(vget_high_f32(vec_sum_value), vget_low_f32(vec_sum_value));
carry_addition = vpadd_f32(carry_addition, carry_addition);
float sum = vget_lane_f32(carry_addition, 0);
// Run remaining elements
for(int i = 0; i < small_steps; ++i)
{
float element = std::exp(in_ptr[i] - *max_ptr);
exp_ptr[i] = element;
sum += element;
}
*(reinterpret_cast<float *>(_sum.ptr())) = sum;
}
while(window.slide_window_slice_1D(in_slice) && window.slide_window_slice_1D(max_slice));
}
} //namespace
NELogits1DShiftExpSumKernel::NELogits1DShiftExpSumKernel()
: _func(nullptr), _input(nullptr), _max(nullptr), _output(nullptr), _sum(nullptr)
{
}
void NELogits1DShiftExpSumKernel::configure(const ITensor *input, const ITensor *max, ITensor *output, ITensor *sum)
{
ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::QS8, DataType::QS16, DataType::F16, DataType::F32);
ARM_COMPUTE_ERROR_ON_NULLPTR(max, sum, output);
// Output auto initialization if not yet initialized
auto_init_if_empty(*sum->info(), max->info()->tensor_shape(), 1, input->info()->data_type(), input->info()->fixed_point_position());
auto_init_if_empty(*output->info(), input->info()->tensor_shape(), 1, input->info()->data_type(), input->info()->fixed_point_position());
ARM_COMPUTE_ERROR_ON_MISMATCHING_DATA_TYPES(input, output, max, sum);
ARM_COMPUTE_ERROR_ON_MISMATCHING_FIXED_POINT_POSITION(input, output, max, sum);
ARM_COMPUTE_ERROR_ON_MISMATCHING_SHAPES(input, output);
ARM_COMPUTE_ERROR_ON_MISMATCHING_SHAPES(max, sum);
unsigned int num_elems_processed_per_iteration = input->info()->valid_region().shape.x();
switch(input->info()->data_type())
{
case DataType::QS8:
_func = &logits_1d_shift_exp_sum_qs8;
break;
case DataType::QS16:
_func = &logits_1d_shift_exp_sum_qs16;
break;
case DataType::F32:
_func = &logits_1d_shift_exp_sum_f32;
break;
case DataType::F16:
#ifdef ARM_COMPUTE_ENABLE_FP16
_func = &logits_1d_shift_exp_sum_f16;
break;
#endif /* ARM_COMPUTE_ENABLE_FP16 */
default:
ARM_COMPUTE_ERROR("Unsupported data type.");
break;
}
_input = input;
_max = max;
_output = output;
_sum = sum;
// Configure kernel window
Window win = calculate_max_window(*input->info(), Steps(num_elems_processed_per_iteration));
AccessWindowHorizontal input_access(input->info(), 0, num_elems_processed_per_iteration);
AccessWindowHorizontal max_access(max->info(), 0, 1);
AccessWindowHorizontal output_access(output->info(), 0, num_elems_processed_per_iteration);
AccessWindowHorizontal sum_access(sum->info(), 0, 1);
update_window_and_padding(win, input_access, max_access, output_access, sum_access);
output_access.set_valid_region(win, input->info()->valid_region());
sum_access.set_valid_region(win, ValidRegion(Coordinates(), sum->info()->tensor_shape()));
INEKernel::configure(win);
}
void NELogits1DShiftExpSumKernel::run(const Window &window, const ThreadInfo &info)
{
ARM_COMPUTE_UNUSED(info);
ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(INEKernel::window(), window);
ARM_COMPUTE_ERROR_ON(_func == nullptr);
(*_func)(_input, _max, _output, _sum, window);
}
namespace
{
void logits_1d_norm_qs8(const ITensor *in, const ITensor *sum, ITensor *out, const Window &window)
{
Window window_sum(window);
window_sum.set(Window::DimX, Window::Dimension(0, 0, 0));
Window sum_slice = window_sum.first_slice_window_1D();
Window in_slice = window.first_slice_window_1D();
const int fixed_point_position = in->info()->fixed_point_position();
do
{
Iterator input(in, in_slice);
Iterator _sum(sum, sum_slice);
Iterator output(out, in_slice);
const int8_t sum_value = *reinterpret_cast<const qint8_t *>(_sum.ptr());
const qint8x16_t vec_sum_inversed = vqrecipq_qs8(vdupq_n_qs8(sum_value), fixed_point_position);
execute_window_loop(in_slice, [&](const Coordinates & id)
{
const auto in_ptr = reinterpret_cast<const qint8_t *>(input.ptr());
const auto out_ptr = reinterpret_cast<qint8_t *>(output.ptr());
const qint8x16_t vec_in = vld1q_qs8(in_ptr);
const qint8x16_t normalized_value = vqmulq_qs8(vec_in, vec_sum_inversed, fixed_point_position);
vst1q_qs8(out_ptr, normalized_value);
},
input, output);
}
while(window.slide_window_slice_1D(in_slice) && window.slide_window_slice_1D(sum_slice));
}
void logits_1d_norm_qs16(const ITensor *in, const ITensor *sum, ITensor *out, const Window &window)
{
Window window_sum(window);
window_sum.set(Window::DimX, Window::Dimension(0, 0, 0));
Window sum_slice = window_sum.first_slice_window_1D();
Window in_slice = window.first_slice_window_1D();
const int fixed_point_position = in->info()->fixed_point_position();
do
{
Iterator input(in, in_slice);
Iterator _sum(sum, sum_slice);
Iterator output(out, in_slice);
const int16_t sum_value = *reinterpret_cast<const qint16_t *>(_sum.ptr());
const qint16x8_t vec_sum_inversed = vqrecipq_qs16(vdupq_n_qs16(sum_value), fixed_point_position);
execute_window_loop(in_slice, [&](const Coordinates & id)
{
const auto in_ptr = reinterpret_cast<const qint16_t *>(input.ptr());
const auto out_ptr = reinterpret_cast<qint16_t *>(output.ptr());
const qint16x8_t vec_in = vld1q_qs16(in_ptr);
const qint16x8_t normalized_value = vqmulq_qs16(vec_in, vec_sum_inversed, fixed_point_position);
vst1q_qs16(out_ptr, normalized_value);
},
input, output);
}
while(window.slide_window_slice_1D(in_slice) && window.slide_window_slice_1D(sum_slice));
}
#ifdef ARM_COMPUTE_ENABLE_FP16
void logits_1d_norm_f16(const ITensor *in, const ITensor *sum, ITensor *out, const Window &window)
{
Window window_sum(window);
window_sum.set(Window::DimX, Window::Dimension(0, 0, 0));
Window sum_slice = window_sum.first_slice_window_1D();
Window in_slice = window.first_slice_window_1D();
do
{
Iterator input(in, in_slice);
Iterator _sum(sum, sum_slice);
Iterator output(out, in_slice);
const float16_t sum_value = *reinterpret_cast<const qint16_t *>(_sum.ptr());
const float16x8_t vec_sum_inversed = vdupq_n_f16(1.0f / sum_value);
execute_window_loop(in_slice, [&](const Coordinates & id)
{
const auto in_ptr = reinterpret_cast<const float16_t *>(input.ptr());
const auto out_ptr = reinterpret_cast<float16_t *>(output.ptr());
const float16x8_t vec_in = vld1q_f16(in_ptr);
const float16x8_t normalized_value = vmulq_f16(vec_in, vec_sum_inversed);
vst1q_f16(out_ptr, normalized_value);
},
input, output);
}
while(window.slide_window_slice_1D(in_slice) && window.slide_window_slice_1D(sum_slice));
}
#endif /* ARM_COMPUTE_ENABLE_FP16 */
void logits_1d_norm_f32(const ITensor *in, const ITensor *sum, ITensor *out, const Window &window)
{
Window window_sum(window);
window_sum.set(Window::DimX, Window::Dimension(0, 0, 0));
Window sum_slice = window_sum.first_slice_window_1D();
Window in_slice = window.first_slice_window_1D();
do
{
Iterator input(in, in_slice);
Iterator _sum(sum, sum_slice);
Iterator output(out, in_slice);
const float sum_value = *reinterpret_cast<const float *>(_sum.ptr());
const float32x4_t vec_sum_inversed = vdupq_n_f32(1.0f / sum_value);
execute_window_loop(in_slice, [&](const Coordinates & id)
{
const auto in_ptr = reinterpret_cast<const float *>(input.ptr());
const auto out_ptr = reinterpret_cast<float *>(output.ptr());
const float32x4_t vec_in = vld1q_f32(in_ptr);
const float32x4_t normalized_value = vmulq_f32(vec_in, vec_sum_inversed);
vst1q_f32(out_ptr, normalized_value);
},
input, output);
}
while(window.slide_window_slice_1D(in_slice) && window.slide_window_slice_1D(sum_slice));
}
} // namespace
NELogits1DNormKernel::NELogits1DNormKernel()
: _func(nullptr), _input(nullptr), _sum(nullptr), _output(nullptr)
{
}
void NELogits1DNormKernel::configure(const ITensor *input, const ITensor *sum, ITensor *output)
{
ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::QS8, DataType::QS16, DataType::F16, DataType::F32);
ARM_COMPUTE_ERROR_ON_NULLPTR(sum, output);
// Output auto initialization if not yet initialized
auto_init_if_empty(*output->info(), input->info()->tensor_shape(), 1, input->info()->data_type(), input->info()->fixed_point_position());
ARM_COMPUTE_ERROR_ON_MISMATCHING_DATA_TYPES(input, sum, output);
ARM_COMPUTE_ERROR_ON_MISMATCHING_FIXED_POINT_POSITION(input, sum, output);
ARM_COMPUTE_ERROR_ON_MISMATCHING_SHAPES(input, output);
_input = input;
_sum = sum;
_output = output;
// Configure kernel window
unsigned int num_elems_processed_per_iteration = 16 / data_size_from_type(input->info()->data_type());
switch(input->info()->data_type())
{
case DataType::QS8:
_func = &logits_1d_norm_qs8;
break;
case DataType::QS16:
_func = &logits_1d_norm_qs16;
break;
case DataType::F32:
_func = &logits_1d_norm_f32;
break;
case DataType::F16:
#ifdef ARM_COMPUTE_ENABLE_FP16
_func = &logits_1d_norm_f16;
break;
#endif /* ARM_COMPUTE_ENABLE_FP16 */
default:
ARM_COMPUTE_ERROR("Unsupported data type.");
break;
}
Window win = calculate_max_window(*input->info(), Steps(num_elems_processed_per_iteration));
AccessWindowHorizontal input_access(input->info(), 0, num_elems_processed_per_iteration);
AccessWindowStatic sum_access(sum->info(), 0, 0, 1, sum->info()->dimension(1));
AccessWindowHorizontal output_access(output->info(), 0, num_elems_processed_per_iteration);
update_window_and_padding(win, input_access, sum_access, output_access);
output_access.set_valid_region(win, input->info()->valid_region());
INEKernel::configure(win);
}
void NELogits1DNormKernel::run(const Window &window, const ThreadInfo &info)
{
ARM_COMPUTE_UNUSED(info);
ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(INEKernel::window(), window);
ARM_COMPUTE_ERROR_ON(_func == nullptr);
(*_func)(_input, _sum, _output, window);
}
| [
"anthony.barbier@arm.com"
] | anthony.barbier@arm.com |
9c44d62daddd5adfabb4a7e0b62c9220b5eaadd4 | dc70e81f857273f14469300b4e04c55668b89478 | /CP/Assignment1-STL/Vinay/pair.cpp | 97a3c8286700e65af1aaa90113a15fdd5b036a10 | [] | no_license | vinayrk/SummerProjects18 | f1a240832eb9cd1db195fb35b9042eed595fb154 | 8611b47ddb01d3da56067e98d563a58546eba602 | refs/heads/master | 2020-03-16T01:51:51.543082 | 2018-05-11T14:36:21 | 2018-05-11T14:36:21 | 132,450,455 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 845 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int c, x, y, z, j, n, i;
array<pair<int, int>, 1000> a;
for (int i = 0; i < 1000; i++)
{
a.at(i) = make_pair(0, 0);
}
cin >> n;
for (i = 0; i < n; i++)
{
cin >> c;
if (c == 1)
{
cin >> x >> y >> z;
a.at(x) = make_pair(y, z);
}
else
if (c == 2)
{
cin >> x;
if (x == 1)
{
sort(a.begin(), a.end());
}
else
if (x == 2)
sort(a.begin(), a.end(), [](const pair<int, int> &lhs, const pair<int, int> &rhs) {
return lhs.second < rhs.second;
});
}
else
if (c == 3)
{
for (j = 0; j < n; j++)
{
cout << "(" << a.at(i).first << "," << a.at(i).second << ")";
}
}
}
return 0;
} | [
"beingvinay.rk1999@gmail.com"
] | beingvinay.rk1999@gmail.com |
f1d87ea43402bc9eef796c3dad4526d6902867f5 | 78a5af6d7778847e93385d1e00ad8f773f1d0fba | /DataStructuresAndAlgorithms/Assignment2/Tests/ExtendedTest.cpp | b54855afa06b70d6b12560972bf6d3e32f9fe159 | [] | no_license | vladvlad23/UBBComputerScienceBachelor | 099596a139c8aa5460c705b6d51fb86608015687 | d99a26dbcd9b629f5b3f38ff814cab42837365ed | refs/heads/master | 2023-05-08T23:49:32.737144 | 2021-05-27T19:06:56 | 2021-05-27T19:06:56 | 280,646,572 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,825 | cpp | #include <assert.h>
#include <exception>
#include <iostream>
#include "ExtendedTest.h"
#include "ShortTest.h"
#include "../SortedSet/SortedSet.h"
#include "../SortedSet/SortedSetIterator.h"
using namespace std;
bool rGreater(TComp e1, TComp e2) {
if (e1 > e2) {
return true;
}
else {
return false;
}
}
bool rLessEqual(TComp e1, TComp e2) {
if (e1 <= e2) {
return true;
}
else {
return false;
}
}
void testCreate(Relation r) {
SortedSet s(r);
assert(s.size() == 0);
assert(s.isEmpty() == true);
for (int i = -10; i < 10; i++) {
assert(s.search(i) == false);
}
for (int i = -10; i < 10; i++) {
assert(s.remove(i) == false);
}
SortedSetIterator it = s.iterator();
assert(it.valid() == false);
try {
it.next();
assert(false);
}
catch (exception&) {
assert (true);
}
try {
it.getCurrent();
assert(false);
}
catch (exception&) {
assert(true);
}
}
void testAdd() {
int vverif[10];
int iverif;
SortedSet s2(rGreater);
for (int i = 0; i <= 3; i++) {
s2.add(i);
}
for (int i = 5; i > 3; i--) {
s2.add(i);
}
SortedSetIterator it2 = s2.iterator();
iverif = 0;
while (it2.valid()) {
vverif[iverif++] = it2.getCurrent();
it2.next();
}
assert((vverif[0] == 5) && (vverif[1] == 4) && (vverif[2] == 3) && (vverif[3] == 2) && (vverif[4] == 1) && (vverif[5] == 0));
assert(s2.isEmpty() == false);
assert(s2.size() == 6);
SortedSet s(rLessEqual);
for (int i = 0; i <= 3; i++) {
s.add(i);
}
for (int i = 5; i > 3; i--) {
s.add(i);
}
SortedSetIterator it = s.iterator();
iverif = 0;
while (it.valid()) {
vverif[iverif++] = it.getCurrent();
it.next();
}
assert((vverif[0] == 0) && (vverif[1] == 1) && (vverif[2] == 2) && (vverif[3] == 3) && (vverif[4] == 4) && (vverif[5] == 5));
assert(s.isEmpty() == false);
assert(s.size() == 6);
for (int i = -10; i < 20; i++) {
s.add(i);
}
assert(s.isEmpty() == false);
assert(s.size() == 30);
for (int i = 100; i > -100; i--) {
s.add(i);
}
assert(s.isEmpty() == false);
assert(s.size() == 200);
for (int i = -200; i < 200; i++) {
if (i <= -100) {
assert(s.search(i) == false);
}
else if (i < 0) {
assert(s.search(i) == true);
}
else if (i <= 100) {
assert(s.search(i) == true);
}
else {
assert(s.search(i) == false);
}
}
for (int i = 10000; i > -10000; i--) {
s.add(i);
}
assert(s.size() == 20000);
}
void testRemove(Relation r) {
SortedSet s(r);
for (int i = -100; i < 100; i++) {
assert(s.remove(i) == false);
}
assert(s.size() == 0);
for (int i = -100; i < 100; i = i + 2) {
s.add(i);
}
for (int i = -100; i < 100; i++) {
if (i % 2 == 0) {
assert(s.remove(i) == true);
}
else {
assert(s.remove(i) == false);
}
}
assert(s.size() == 0);
for (int i = -100; i <= 100; i = i + 2) {
s.add(i);
}
for (int i = 100; i > -100; i--) {
if (i % 2 == 0) {
assert(s.remove(i) == true);
}
else {
assert(s.remove(i) == false);
}
}
assert(s.size() == 1);
s.remove(-100);
assert(s.size() == 0);
for (int i = -100; i < 100; i++) {
s.add(i);
s.add(i);
s.add(i);
s.add(i);
s.add(i);
}
assert(s.size() == 200);
for (int i = -200; i < 200; i++) {
if (i < -100 || i >= 100) {
assert(s.remove(i) == false);
}
else {
assert(s.remove(i) == true);
assert(s.remove(i) == false);
}
}
assert(s.size() == 0);
}
void testIterator(Relation r) {
SortedSet s(r);
SortedSetIterator it = s.iterator();
assert(it.valid() == false);
for (int i = 0; i < 100; i++) {
s.add(33);
}
assert(s.size() == 1);
SortedSetIterator it2 = s.iterator();
assert(it2.valid() == true);
TElem elem = it2.getCurrent();
assert(elem == 33);
it2.next();
assert(it2.valid() == false);
try {
it2.next();
assert(false);
}
catch (exception&) {
assert(true);
}
try {
it2.getCurrent();
assert(false);
}
catch (exception&) {
assert(true);
}
it2.first();
assert(it2.valid() == true);
SortedSet s2(r);
for (int i = -100; i < 100; i++) {
s2.add(i);
s2.add(i);
s2.add(i);
}
SortedSetIterator it3 = s2.iterator();
assert(it3.valid() == true);
for (int i = 0; i < 200; i++) {
it3.next();
}
assert(it3.valid() == false);
it3.first();
assert(it3.valid() == true);
SortedSet s3(r);
for (int i = 0; i < 200; i = i + 4) {
s3.add(i);
}
SortedSetIterator it4 = s3.iterator();
assert(it4.valid() == true);
int count = 0;
while (it4.valid()) {
TElem e = it4.getCurrent();
assert(e % 4 == 0);
it4.next();
count++;
}
assert(count == 50);
}
void testQuantity(Relation r) {
SortedSet s(r);
for (int i = 10; i >= 1; i--) {
for (int j = -30000; j < 30000; j = j + i) {
s.add(j);
}
}
std::cout<<"Addition from quantity is ok\n";
assert(s.size() == 60000);
SortedSetIterator it = s.iterator();
assert(it.valid() == true);
for (int i = 0; i < s.size(); i++) {
it.next();
}
std::cout<<"Validation of iterator from quantity is ok\n";
it.first();
while (it.valid()) {
TElem e = it.getCurrent();
assert(s.search(e) == true);
it.next();
}
std::cout<<"Searching all elements from quantity is oki\n";
assert(it.valid() == false);
for (int i = 0; i < 10; i++) {
for (int j = 40000; j >= -40000; j--) {
s.remove(j);
}
}
std::cout<<"Removing everything form quantity is oki\n";
assert(s.size() == 0);
}
void testAllExtended() {
testCreate(rLessEqual);
std::cout<<"Test create works\n";
testAdd();
std::cout<<"Test add works\n";
testRemove(rLessEqual);
std::cout<<"Test remove works\n";
testRemove(rGreater);
std::cout<<"Test remove2 works\n";
testIterator(rLessEqual);
std::cout<<"Test iterator works\n";
testIterator(rGreater);
std::cout<<"Test iterator2 works\n";
testQuantity(rLessEqual);
std::cout<<"Test quantity works\n";
testQuantity(rGreater);
std::cout<<"Test quantity 2 works\n";
}
| [
"ungureanu.vlad1@gmail.com"
] | ungureanu.vlad1@gmail.com |
43348df38c39678600c3ad4664c2967860394c38 | f4fe4d3bb84cf8c6ae4b648120c13cd77c592673 | /obi/algoritmos/bfs.cpp | 541ff078fabfde8c69ed6a460ffe59acd17dbb2d | [] | no_license | Thor99/OldAndMaybeNewThingz | 5ab975574b9a545a1b61de8102d91897c13cbf10 | 0569eec3c522f3f75cf8fdb305ef91d48f6c65d5 | refs/heads/master | 2020-04-02T01:38:05.913850 | 2018-10-20T04:09:59 | 2018-10-20T04:13:45 | 153,866,904 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,360 | cpp | #include <cstdio>
#include <queue>
#define MAXV 15 // Dizemos que o numero maximo de vertices é 15
/* Achar distancia minima de todos os vertices de um grafo com arestas de pesos iguais, para um vertice qualquer */
using namespace std;
queue<int> Q;
int peso = 1;
int dist[MAXV];
int INF = 16;
vector<vector<int> > listAdj(MAXV);
void bfs(int v){
dist[v] = 0; // Distancia dele para ele mesmo
Q.push(v);
while(!(Q.empty())){ // Enquanto tiver ainda algum adjacente para ver a distancia
int atual = Q.front();
Q.pop();
for(int i = 0; i < listAdj[atual].size(); ++i){ // Atualiza as distancias de todos os vizinhos do listAdj[atual], se a mesma estiver como INF
if(dist[listAdj[atual][i]] == INF){
dist[listAdj[atual][i]] = dist[atual] + peso;
Q.push(listAdj[atual][i]);
}
}
}
}
int main(){
int nVertices, nArestas;
int verticeParaAnalisar;
scanf("%d %d", &nVertices, &nArestas);
/* Inicializa todos os elemento de dist como "infinito"((peso * nArestas) + 1) */
for(int i = 0; i < MAXV; i++){
dist[i] = INF;
}
for(int i = 0; i < nArestas; i++){
int ini, fim;
scanf("%d %d", &ini, &fim);
listAdj[ini].push_back(fim);
listAdj[fim].push_back(ini);
}
scanf("%d", &verticeParaAnalisar);
bfs(verticeParaAnalisar);
for(int i = 1; i <= nVertices; ++i){
printf("Distancia para %d: %d\n", i, dist[i]);
}
}
| [
"thor.garcia@pagar.me"
] | thor.garcia@pagar.me |
5b967ddd10c2c491deb0b889ff76f32cfaf47c7d | a62342d6359a88b0aee911e549a4973fa38de9ea | /0.6.0.3/External/SDK/BTTask_GoToKing_functions.cpp | 6c327efe957ace3be27c5f7fc4b2a8f918d7bde4 | [] | no_license | zanzo420/Medieval-Dynasty-SDK | d020ad634328ee8ee612ba4bd7e36b36dab740ce | d720e49ae1505e087790b2743506921afb28fc18 | refs/heads/main | 2023-06-20T03:00:17.986041 | 2021-07-15T04:51:34 | 2021-07-15T04:51:34 | 386,165,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,214 | cpp | // Name: Medieval Dynasty, Version: 0.6.0.3
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function BTTask_GoToKing.BTTask_GoToKing_C.ReceiveExecuteAI
// (Event, Protected, BlueprintEvent)
// Parameters:
// class AAIController* OwnerController (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
// class APawn* ControlledPawn (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UBTTask_GoToKing_C::ReceiveExecuteAI(class AAIController* OwnerController, class APawn* ControlledPawn)
{
static auto fn = UObject::FindObject<UFunction>("Function BTTask_GoToKing.BTTask_GoToKing_C.ReceiveExecuteAI");
UBTTask_GoToKing_C_ReceiveExecuteAI_Params params;
params.OwnerController = OwnerController;
params.ControlledPawn = ControlledPawn;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BTTask_GoToKing.BTTask_GoToKing_C.ExecuteUbergraph_BTTask_GoToKing
// (Final, HasDefaults)
// Parameters:
// int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
void UBTTask_GoToKing_C::ExecuteUbergraph_BTTask_GoToKing(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function BTTask_GoToKing.BTTask_GoToKing_C.ExecuteUbergraph_BTTask_GoToKing");
UBTTask_GoToKing_C_ExecuteUbergraph_BTTask_GoToKing_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UBTTask_GoToKing_C::AfterRead()
{
UBTTask_BlueprintBase::AfterRead();
}
void UBTTask_GoToKing_C::BeforeDelete()
{
UBTTask_BlueprintBase::BeforeDelete();
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
8718eefec4813d83747687e9be7f403877381240 | f644afe912cbf51f8a9f29986f76d51f0ee6ff9e | /none_university_code/c++/cryptography/finding_AES_ECB_string.cpp | aa215caaa4c25f5ae6d0a410df12dfed09a1acf9 | [] | no_license | Denis-Sylenko/code_examples | 59379aea307eb01b0a9a85943289866456079151 | 88c4b6a70230afb2136934c2737e5a3fe0c5d659 | refs/heads/master | 2022-11-13T12:25:32.428322 | 2020-07-06T15:37:11 | 2020-07-06T15:37:11 | 277,548,902 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,374 | cpp | // The task is to find the AES ECB string form "crypto.txt" file
#include "pch.h"//Для VS
#include <iostream>
#include <vector>
#include <set>
#include <string>
#include <fstream>
using namespace std;
void ReadFromFileToVector(vector<vector<string>>& vector_of_vector_of_strings, string&& file) { // Прочитаем все строки из файла и каждую из них поделим на строки по 16 байт (128 бит)
ifstream is(move(file)); //Поскольку размер блока AES равен 128 бит == 16 байт
string line;
size_t count = 0;
if (is) {
while (getline(is, line)) {
vector_of_vector_of_strings.push_back({});
for (size_t i = 0; i < line.length(); i += 16) {
vector_of_vector_of_strings[count].push_back( line.substr(i, 16) );
}
++count;
}
}
else {
std::cout << "Can't find that file!" << std::endl;
}
};
int AmountOfRepeat(vector<string>& vector_of_strings) { //В режиме ECB одинаковым блокам данным соответствуют одинаковые блоки шифрокода.
set<string> tmp_set; //Соответственно, необходимо определить строку, в которой будут присутствовать одинаковые шифроблоки
for (auto a : vector_of_strings) {
tmp_set.insert(a); //Я решил это реализовать с использованием дополнительной памяти в виде контейнера set, элементы в котором не повторяются
} //Можно было бы не использовать дополнительную память, а использовать vector.count(), но я посчитал, что так мы будем иметь квадратическую сложность алгоритма, поскольку count() необходимо было бы выполнить для каждого элемента
return vector_of_strings.size() - tmp_set.size(); //Эта разница определяет, были ли в векторе повторяющиеся элементы
}
int IndexOfMaximumRepetitionString(vector<vector<string>>& vector_of_vector_of_strings) {//Находим строку с наибольшим колличеством повторений
int maximum = 0, index = 0;
for (int i = 0; i < vector_of_vector_of_strings.size(); ++i) {
int amount = AmountOfRepeat(vector_of_vector_of_strings[i]);
if (maximum < amount) {
maximum = amount;
index = i;
};
}
return index; //Вернем ее индекс
}
int main()
{
vector<vector<string>> vector_of_ciphertexts;
ReadFromFileToVector(vector_of_ciphertexts, "crypto.txt");//Расположение файла, который был дан в задании. Переименовал его для удобства
int index_of_AES_ECB_string = IndexOfMaximumRepetitionString(vector_of_ciphertexts);
std::cout << index_of_AES_ECB_string << std::endl;
for (const string& a : vector_of_ciphertexts[index_of_AES_ECB_string]) {
std::cout << a << " "; // Вывод строки, разбитой пробелами для наглядной демонстрации повторяющихся блоков
}
std::cout << endl;
return 0;
}
| [
"eforgit898@gmail.com"
] | eforgit898@gmail.com |
a6336424674a1eb958ffb0baf3aad6b13130659e | aab7eafab5efae62cb06c3a2b6c26fe08eea0137 | /PIDeff_myowntuples/PIDeff_myowntuples_OPTI/src/usefulFunctions.cpp | c3d0f053a2323abe8f9cf182bd6af8cd02616c77 | [] | no_license | Sally27/B23MuNu_backup | 397737f58722d40e2a1007649d508834c1acf501 | bad208492559f5820ed8c1899320136406b78037 | refs/heads/master | 2020-04-09T18:12:43.308589 | 2018-12-09T14:16:25 | 2018-12-09T14:16:25 | 160,504,958 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 28,502 | cpp | #include "usefulFunctions.hpp"
#include "RooFitResult.h"
#include "TTreeFormula.h"
#include "TObjArray.h"
#include "TTree.h"
#include "TH3D.h"
#include "TH2D.h"
#include "TAxis.h"
TH2D *GoodBinning(TH2D *hold, int ngroup, string name)
{
// create a clone of the old histogram
// TH2D *hnew = (TH2D*)hold->Clone();
TAxis *not_chan = hold->GetXaxis();//not changing
Int_t nbins_notchan = not_chan->GetNbins();
cout<<"Number of x bins to start with"<< nbins_notchan <<endl;
TAxis *xold = hold->GetYaxis();
int nbins = xold->GetNbins();
cout<<"Number of y bins to start with"<< nbins <<endl;
Double_t xmin = xold->GetXmin();
Double_t xmax = xold->GetXmax();
cout<<" ymin and y max: "<<xold->GetXmin()<<" "<<xold->GetXmax()<<endl;
vector<double> binningx = binx();
vector<double> binningy = biny();
// vector<double> binningz = binz();
Double_t* xedges = &binningx[0];
Double_t* yedges = &binningy[0];
// Double_t* zedges = &binningz[0];
const Int_t XBINS = nbins_notchan;
const Int_t YBINS = ngroup;
// const Int_t ZBINS = 4;
TH2D* hnew = new TH2D((name).c_str(), (name).c_str(), XBINS, xedges, YBINS, yedges);
Double_t bincont(0);
Double_t binerr(0);
hnew->SetBinContent(0,0,0);
hnew->SetBinError(0,0,0);
for (Int_t binx(1);binx<=nbins_notchan;binx++) {
for (Int_t bin(1);bin<=nbins;bin++) {
for (int i(1);i<=ngroup;i++) {
cout<<"Bin cont:"<<bincont<<endl;
bincont = hold->GetBinContent(binx,bin);
binerr = hold->GetBinError(binx,bin);
cout<<"Bin err:"<<binerr<<endl;
hnew->SetBinContent(binx,i,bincont);
hnew->SetBinError(binx,i,binerr);
cout<<"ngroup: "<<ngroup<<endl;
cout<<"Bin x idex:"<<binx<<endl;
cout<<"Bin y idex:"<<i<<endl;
cout<<"Bin cont 2:"<<bincont<<" bin x "<<binx<<" bin y "<< i<<endl;
cout<<"Bin err 2:"<<binerr<<endl;
}
cout<<"Finished with y bin "<<bin<<endl;
}
cout<<"Finished with x bin "<<binx<<endl;
}
cout<<"Out of loop"<<endl;
TAxis* xAxis = hnew->GetXaxis();
TAxis* yAxis = hnew->GetYaxis();
for (int i(1); i<=hnew->GetNbinsX();i++ ){
for (int j(1); j<=hnew->GetNbinsY();j++ ){
//cout<<"In bin "<<binx<<" and "<<biny<<" number of sig events"<< after->GetBinContent(binx+1,biny+1)<<endl;
cout<<"Efficiency "<<xAxis->GetBinLowEdge(i)<<" & "<<xAxis->GetBinUpEdge(i)<<" & "<<yAxis->GetBinLowEdge(j)<<" & "<<yAxis->GetBinUpEdge(j)<<" & "<<hnew->GetBinContent(i,j)<<" \\\\ " <<endl;
// cout<<"After "<<xAxis->GetBinLowEdge(i)<<" & "<<xAxis->GetBinUpEdge(i)<<" & "<<yAxis->GetBinLowEdge(j)<<" & "<<yAxis->GetBinUpEdge(j)<<" & "<< after->GetBinContent(i,j)<<" \\\\ " <<endl;
// values.push_back(hnew->GetBinContent(i,j));
}
}
cout<<"Out of loop 2"<<endl;
return hnew;
}
TH2D *Rebin(TH2D *hold, int ngroup, string name)
{
// example of ROOT macro to rebin a 1-D histogram hold
// Method:
// a new temporary histogram hnew is created and return to the caller
// The parameter ngroup indicates how many bins of hold have to me
// merged
// into one bin of hnew
// Errors are not taken into account
//
// Usage:
// Root > .L rebin.C; //load this macro
// Root > TH1F *hnew = Rebin(hold,2); //to rebin hold grouping 2 bins
// in one
//
// This macro will become a new TH1 function (taking care of errors)
// TH1 *TH1::Rebin(const Int_t ngroup)
TAxis *not_chan = hold->GetXaxis();//not changing
Int_t nbins_notchan = not_chan->GetNbins();
cout<<"Number of x bins to start with"<< nbins_notchan <<endl;
TAxis *xold = hold->GetYaxis();
int nbins = xold->GetNbins();
cout<<"Number of y bins to start with"<< nbins <<endl;
Double_t xmin = xold->GetXmin();
Double_t xmax = xold->GetXmax();
cout<<" ymin and y max: "<<xold->GetXmin()<<" "<<xold->GetXmax()<<endl;
if ((ngroup <= 0)) {
printf("ERROR in Rebin. Illegal value of ngroup=%d\n",ngroup);
return 0;
}
// Int_t newbins = nbins/ngroup;
// create a clone of the old histogram
TH2D *hnew = (TH2D*)hold->Clone();
// change name and axis specs
hnew->SetName(name.c_str());
TAxis *xnew = hnew->GetYaxis();
xnew->Set(ngroup,xmin,xmax);
hnew->Set((nbins_notchan*(ngroup+2)));
cout<<"Number of bins in my new: "<<xnew->GetNbins()<<endl;
// copy merged bin contents (ignore under/overflows)
Double_t bincont(0);
Double_t binerr(0);
hnew->SetBinContent(0,0,0);
hnew->SetBinError(0,0,0);
for (Int_t binx(1);binx<=nbins_notchan;binx++) {
for (Int_t bin(1);bin<=nbins;bin++) {
for (int i(1);i<=ngroup;i++) {
cout<<"Bin cont:"<<bincont<<endl;
bincont = hold->GetBinContent(binx,bin);
binerr = hold->GetBinError(binx,bin);
cout<<"Bin err:"<<binerr<<endl;
hnew->SetBinContent(binx,i,bincont);
hnew->SetBinError(binx,i,binerr);
cout<<"ngroup: "<<ngroup<<endl;
cout<<"Bin x idex:"<<binx<<endl;
cout<<"Bin y idex:"<<i<<endl;
cout<<"Bin cont 2:"<<hnew->GetBinContent(binx,i,bincont)<<" bin x "<<binx<<" bin y "<< i<<endl;
cout<<"Bin err 2:"<<binerr<<endl;
}
cout<<"Finished with y bin "<<bin<<endl;
}
cout<<"Finished with x bin "<<binx<<endl;
}
cout<<"Out of loop"<<endl;
TAxis* xAxis = hnew->GetXaxis();
TAxis* yAxis = hnew->GetYaxis();
for (int i(1); i<=hnew->GetNbinsX();i++ ){
for (int j(1); j<=hnew->GetNbinsY();j++ ){
//cout<<"In bin "<<binx<<" and "<<biny<<" number of sig events"<< after->GetBinContent(binx+1,biny+1)<<endl;
cout<<"Efficiency "<<xAxis->GetBinLowEdge(i)<<" & "<<xAxis->GetBinUpEdge(i)<<" & "<<yAxis->GetBinLowEdge(j)<<" & "<<yAxis->GetBinUpEdge(j)<<" & "<<hnew->GetBinContent(i,j)<<" \\\\ " <<endl;
// cout<<"After "<<xAxis->GetBinLowEdge(i)<<" & "<<xAxis->GetBinUpEdge(i)<<" & "<<yAxis->GetBinLowEdge(j)<<" & "<<yAxis->GetBinUpEdge(j)<<" & "<< after->GetBinContent(i,j)<<" \\\\ " <<endl;
// values.push_back(hnew->GetBinContent(i,j));
}
}
cout<<"Out of loop 2"<<endl;
return hnew;
}
double s2d(string str)
{
double ret;
istringstream is(str);
is >> ret;
return ret;
}
string d2s(double d)
{
string ret;
ostringstream os;
os<<d;
return os.str();
}
string d2s(double nbr, int nfixed )
{
stringstream ss;
//if(nfixed>=1) ss<<fixed<<setprecision(nfixed)<<nbr;
//else ss<<nbr;
ss<<nbr;
return ss.str();
}
string i2s(int i)
{
string ret;
ostringstream os;
os<<i;
return os.str();
}
vector<double> binxjack(){
vector<double> PArr;
PArr.push_back(3000.0);
PArr.push_back(6000.0);
PArr.push_back(9300.0);
PArr.push_back(10000.0);
PArr.push_back(12600.0);
PArr.push_back(15600.0);
PArr.push_back(17500.0);
PArr.push_back(21500.0);
PArr.push_back(27000.0);
PArr.push_back(32000.0);
PArr.push_back(40000.0);
PArr.push_back(60000.0);
PArr.push_back(70000.0);
PArr.push_back(100000.0);
const int p = 13;
for(int j(0); j<(p+1); ++j)
{
cout<<" "<<PArr.at(j)<<",";
}
cout<<"."<<endl;
return PArr;
}
vector<double> binx(){
vector<double> PArr;
PArr.push_back(3000.0);
PArr.push_back(9300.0);
PArr.push_back(15600.0);
PArr.push_back(19000.0);
const int p = 18;
for(int j(4); j<(p+1); ++j)
{
PArr.push_back(PArr.at(j-1) + 5400.0);
}
cout<<"P binning: ";
for(int j(0); j<(p+1); ++j)
{
cout<<" "<<PArr.at(j)<<",";
}
cout<<"."<<endl;
return PArr;
}
vector<double> binycourse(){
vector<double> EtaArr;
const int eta=1;
EtaArr.push_back(1.5);
EtaArr.push_back(5.0);
cout<<"ETA binning: ";
for(int j(0); j<(eta+1); ++j)
{
cout<<" "<<EtaArr.at(j)<<",";
}
cout<<"."<<endl; return EtaArr;
}
vector<double> biny(){
vector<double> EtaArr;
const int eta=4;
EtaArr.push_back(1.5);
for(int j(1); j<(eta+1); ++j)
{
EtaArr.push_back(EtaArr[j-1] + 0.875);
}
cout<<"ETA binning: ";
for(int j(0); j<(eta+1); ++j)
{
cout<<" "<<EtaArr.at(j)<<",";
}
cout<<"."<<endl; return EtaArr;
}
vector<double> binz(){
vector<double> nTracksArr;
const int ntracks=4;
nTracksArr.push_back(0.0);
nTracksArr.push_back(50.0);
nTracksArr.push_back(200.0);
nTracksArr.push_back(300.0);
nTracksArr.push_back(500.0);
cout<<"ntracks binning: ";
for(int j(0); j<(ntracks+1); ++j)
{
cout<<" "<<nTracksArr.at(j)<<",";
}
cout<<"."<<endl; return nTracksArr;
}
string cleanNameString(string str)
{
size_t st(0);
string toreplace(" */#.,[]{}()+-=:");
for(int i(0); i<toreplace.size(); ++i)
{
while(st != string::npos)
{
st = str.find(toreplace[i]);
if(st!=string::npos) str = str.replace(st, 1, "_");
}
st = 0;
}
return str;
}
double normalerror(double val1, double err1, double val2, double err2)
{
double errorratio(0);
errorratio=double(val1/val2)*sqrt(((err1/val1)*(err1/val1))+((err2/val2)*(err2/val2)));
return(errorratio);
}
string cleanForTables(string str)
{
size_t st(0);
string toreplace("_.*/#.,[]{}()+-=:&<>");
for(int i(0); i<toreplace.size(); ++i)
{
while(st != string::npos)
{
st = str.find(toreplace[i]);
if(st!=string::npos) str = str.replace(st, 1, "");
}
st = 0;
}
return str;
}
string roundToError(RooRealVar const& var, bool wantLatex)
{
valError ve;
ve.val=var.getVal();
ve.err= var.getError();
return roundToError(ve, wantLatex);
}
string roundToError(valError& ve, bool wantLatex)
{
int power(floor(TMath::Log10(ve.err)));
double todivide(TMath::Power(10, power-2));
int err3dig(TMath::Nint(ve.err/todivide));
int nfixed;
if(err3dig<=354 || err3dig>=950)
{
todivide = TMath::Power(10, power-1);
nfixed = 1-power;
}
if(err3dig>=355 && err3dig<=949)
{
todivide = TMath::Power(10, power);
nfixed = 0-power;
}
ve.err = todivide*TMath::Nint(ve.err/todivide);
ve.val = todivide*TMath::Nint(ve.val/todivide);
string ret(d2s(ve.val, nfixed)+"+-"+d2s(ve.err, nfixed));
if(wantLatex) ret= "$"+d2s(ve.val, nfixed)+"\\pm"+d2s(ve.err, nfixed)+"$";
return ret;
}
void copyTreeWithNewVar(TTree*& tNew, TTree* tOld, string cut, string formula, string newVarName)
{
setBranchStatusTTF(tOld, cut);
setBranchStatusTTF(tOld, formula);
TTreeFormula newVarTTF("newVarTTF", formula.c_str(), tOld);
if(cut == "") cut = "1";
TTreeFormula cutTTF("cutTTF", cut.c_str(), tOld);
TTreeFormula varTTF("varTTF", formula.c_str(), tOld);
tNew = tOld->CloneTree(0);
double newVarVal(0);
if(formula != "") tNew->Branch(newVarName.c_str(), &newVarVal, (newVarName+"/D").c_str() );
cout<<"Filling tree with new var... ";
for(int i(0); i<tOld->GetEntries(); ++i)
{
tOld->GetEntry(i);
if(cutTTF.EvalInstance() )
{
if(formula != "") newVarVal = newVarTTF.EvalInstance();
tNew->Fill();
}
}
cout<<"done! New tree has: "<<tNew->GetEntries()<<" entries."<<endl;
}
bool setBranchStatusTTF(TTree* t, string cuts)
{
TObjArray* array = t->GetListOfBranches();
int n(array->GetEntries());
string name;
bool ret(false);
for(int i(0); i<n; ++i)
{
name = ((*array)[i])->GetName();
if(cuts.find(name) != string::npos)
{
t->SetBranchStatus(name.c_str(), 1);
ret = true;
}
}
return ret;
}
double cutTree(string nametree, string decaytreename, string namecuttree, string cuts)
{
TFile f(nametree.c_str());
TTree* t = (TTree*)f.Get(decaytreename.c_str());
TFile f2(namecuttree.c_str(), "RECREATE");
TTree* t2 = t->CloneTree(0);
TTreeFormula ttf("ttf", cuts.c_str(), t);
cout<<"Cutting tree "<<nametree<<endl;
cout<<"Cut applied: "<<cuts<<endl;
for(int i(0); i<t->GetEntries(); ++i)
{
if(i % (t->GetEntries()/10) == 0) cout<<100*i/(t->GetEntries())<<" \% processed"<<endl;
t->GetEntry(i);
if(ttf.EvalInstance()) t2->Fill();
}
double effofcut;
effofcut = double(t2->GetEntries())/double(t->GetEntries());
cout<<"Efficiency of cut"<< cuts << " wrt " << nametree << " is: " << effofcut << endl;
t2->Write("",TObject::kOverwrite);
f2.Close();
f.Close();
return(effofcut);
}
string cleanAbsolutelyNameString(string str)
{
size_t st(0);
string toreplace("_.");
for(int i(0); i<toreplace.size(); ++i)
{
while(st != string::npos)
{
st = str.find(toreplace[i]);
if(st!=string::npos) str = str.replace(st, 1, " ");
}
st = 0;
}
return str;
}
void plotMergedFitsPrettyLogy(vector<double> binningx, vector<double> binningy, string pidcut, string state, string path)
{
int numberofbins = (binningx.size()-1)*(binningy.size()-1);
const int numberofpdfs = numberofbins/9;
cout<<" Number of pdf will be "<<numberofpdfs<<endl;
int counterm(0);
int counterk(0);
for(int s(0); s<numberofpdfs ;s++)
{
TCanvas* canvshifttotal = new TCanvas("PID","PID",800,800) ;
canvshifttotal->Divide(3,3);
int z(0);
for(int k(0); k<(binningx.size()-1) ;k++){
for(int m(0); m<(binningy.size()-1) ;m++){
if(z==0){
k=counterk;
m=counterm;
}
// string pidcut = "K_PIDK<0";
string kinbinstring = "K_P_"+d2s(binningx.at(k))+"_K_P_"+d2s(binningx.at(k+1))+"_K_ETA_"+d2s(binningy.at(m))+"_K_ETA_"+d2s(binningy.at(m+1));
cout<<"Here P bin "<< k<<" ETA bin "<<m<<endl;
cout<<"This is the string "<<kinbinstring<<endl;
TFile f((path+"/plotJpsiKstFitLogyPretty"+cleanNameString(kinbinstring)+"_"+cleanNameString(pidcut)+".root").c_str(),"READ");
TCanvas* canvTot = (TCanvas*)f.Get("canvTot");
canvshifttotal->cd(z+1) ; gPad->SetLeftMargin(0.15) ; canvTot->DrawClonePad();// canvTot->GetYaxis()->SetTitleOffset(1.4) ; canvTot->GetXaxis()->SetTitle("Corrected Mass") ; canvTot->Draw() ;
z++;
cout<<" z is"<<z<<endl;
if(z==9)
{
counterm=m;
cout<<"I am breaking from m"<<endl;
cout<<"Value of m "<< counterm<<endl;
break;
}
}
if(z==9)
{
counterk=k;
cout<<"I am breaking from K"<<endl;
cout<<"Value of k "<< counterk<<endl;
break;
}
}
canvshifttotal->SaveAs(("../MergedFits/ResultofFits_Pretty_Log_"+state+"_ALL"+i2s(s)+".pdf").c_str());
delete canvshifttotal;
}
}
void plotMergedFitsPretty(vector<double> binningx, vector<double> binningy, string pidcut, string state, string path)
{
int numberofbins = (binningx.size()-1)*(binningy.size()-1);
const int numberofpdfs = numberofbins/9;
cout<<" Number of pdf will be "<<numberofpdfs<<endl;
int counterm(0);
int counterk(0);
for(int s(0); s<numberofpdfs ;s++)
{
TCanvas* canvshifttotal = new TCanvas("PID","PID",800,800) ;
canvshifttotal->Divide(3,3);
int z(0);
for(int k(0); k<(binningx.size()-1) ;k++){
for(int m(0); m<(binningy.size()-1) ;m++){
if(z==0){
k=counterk;
m=counterm;
}
// string pidcut = "K_PIDK<0";
string kinbinstring = "K_P_"+d2s(binningx.at(k))+"_K_P_"+d2s(binningx.at(k+1))+"_K_ETA_"+d2s(binningy.at(m))+"_K_ETA_"+d2s(binningy.at(m+1));
cout<<"Here P bin "<< k<<" ETA bin "<<m<<endl;
cout<<"This is the string "<<kinbinstring<<endl;
TFile f((path+"/plotJpsiKstFitPretty"+cleanNameString(kinbinstring)+"_"+cleanNameString(pidcut)+".root").c_str(),"READ");
TCanvas* canvTot = (TCanvas*)f.Get("canvTot");
canvshifttotal->cd(z+1) ; gPad->SetLeftMargin(0.15) ; canvTot->DrawClonePad();// canvTot->GetYaxis()->SetTitleOffset(1.4) ; canvTot->GetXaxis()->SetTitle("Corrected Mass") ; canvTot->Draw() ;
z++;
cout<<" z is"<<z<<endl;
if(z==9)
{
counterm=m;
cout<<"I am breaking from m"<<endl;
cout<<"Value of m "<< counterm<<endl;
break;
}
}
if(z==9)
{
counterk=k;
cout<<"I am breaking from K"<<endl;
cout<<"Value of k "<< counterk<<endl;
break;
}
}
canvshifttotal->SaveAs(("../MergedFits/ResultofFits_Pretty_"+state+"_ALL"+i2s(s)+".pdf").c_str());
delete canvshifttotal;
}
}
void plotMergedFits(vector<double> binningx, vector<double> binningy, string pidcut, string state, string path)
{
int numberofbins = (binningx.size()-1)*(binningy.size()-1);
const int numberofpdfs = numberofbins/9;
cout<<" Number of pdf will be "<<numberofpdfs<<endl;
int counterm(0);
int counterk(0);
for(int s(0); s<numberofpdfs ;s++)
{
TCanvas* canvshifttotal = new TCanvas("PID","PID",800,800) ;
canvshifttotal->Divide(3,3);
int z(0);
for(int k(0); k<(binningx.size()-1) ;k++){
for(int m(0); m<(binningy.size()-1) ;m++){
if(z==0){
k=counterk;
m=counterm;
}
// string pidcut = "K_PIDK<0";
string kinbinstring = "K_P_"+d2s(binningx.at(k))+"_K_P_"+d2s(binningx.at(k+1))+"_K_ETA_"+d2s(binningy.at(m))+"_K_ETA_"+d2s(binningy.at(m+1));
cout<<"Here P bin "<< k<<" ETA bin "<<m<<endl;
cout<<"This is the string "<<kinbinstring<<endl;
TFile f((path+"/plotJpsiKst_"+cleanNameString(kinbinstring)+"_"+cleanNameString(pidcut)+".root").c_str(),"READ");
TCanvas* canvTot = (TCanvas*)f.Get("canv");
canvshifttotal->cd(z+1) ; gPad->SetLeftMargin(0.15) ; canvTot->DrawClonePad();// canvTot->GetYaxis()->SetTitleOffset(1.4) ; canvTot->GetXaxis()->SetTitle("Corrected Mass") ; canvTot->Draw() ;
z++;
cout<<" z is"<<z<<endl;
if(z==9)
{
counterm=m;
cout<<"I am breaking from m"<<endl;
cout<<"Value of m "<< counterm<<endl;
break;
}
}
if(z==9)
{
counterk=k;
cout<<"I am breaking from K"<<endl;
cout<<"Value of k "<< counterk<<endl;
break;
}
}
canvshifttotal->SaveAs(("../MergedFits/ResultofFits"+state+"_ALL"+i2s(s)+".pdf").c_str());
delete canvshifttotal;
}
}
//void prepare2Dhist(string piddir, string name, vector<double> xbin, vector<double> ybin)
//{
// double* PArr=&xbin[0];
// double* EtaArr=&ybin[0];
//
// const Int_t XBINS = (xbin.size()-1);
// const Int_t YBINS = (ybin.size()-1);
//
// cout<<"Number of Xbins: "<<XBINS<<endl;
// cout<<"Number of Ybins: "<<YBINS<<endl;
//
// TCanvas *canv=new TCanvas("plotmy3d","plotmy3d",600,600);
//
// TH2* h2 = new TH2D("PIDHist_sally", "PIDHist_sally", XBINS, PArr, YBINS, EtaArr);
//
// float myfav;
// int z(0);
// vector<float> kindistribution;
//
// for (int i=0; i<XBINS+0; i++) {
// for (int j=0; j<YBINS+0; j++) {
// myfav=3.8/2*double(j);
// kindistribution.push_back(myfav);
// h2->SetBinContent(i,j,myfav);
// z++;
// }
// }
//
// float check;
// for (int i=0; i<XBINS+0; i++) {
// for (int j=0; j<YBINS+0; j++) {
// check = h2->GetBinContent(i,j);
// }
// }
//
// TFile *F1 = new TFile((piddir+"PID_2D.root").c_str(),"UPDATE");
// h2->Write("", TObject::kOverwrite);
// F1->Close();
// delete F1;
// delete h2;
// delete canv;
//
//
//return;
//}
//void prepare3Dhist(string piddir, string name, vector<double> xbin, vector<double> ybin, vector<double> zbin)
//{
// double* PArr=&xbin[0];
// double* EtaArr=&ybin[0];
// double* nTracksArr=&zbin[0];
//
// const Int_t XBINS = (xbin.size()-1);
// const Int_t YBINS = (ybin.size()-1);
// const Int_t ZBINS = (zbin.size()-1);
//
// cout<<"Number of Xbins: "<<XBINS<<endl;
// cout<<"Number of Ybins: "<<YBINS<<endl;
// cout<<"Number of Zbins: "<<ZBINS<<endl;
//
// TCanvas *canv=new TCanvas("plotmy3d","plotmy3d",600,600);
//
// TH3* h3 = new TH3D("PIDHist_sally", "PIDHist_sally", XBINS, PArr, YBINS, EtaArr, ZBINS, nTracksArr);
//
// float myfav;
// int z(0);
// vector<float> kindistribution;
//
// for (int i=0; i<XBINS+0; i++) {
// for (int j=0; j<YBINS+0; j++) {
// for (int k=0; k<ZBINS+0; k++) {
// myfav=3.8/2*double(j);
// kindistribution.push_back(myfav);
// h3->SetBinContent(i,j,k, myfav);
// z++;
// }
// }
// }
//
// float check;
// for (int i=0; i<XBINS+0; i++) {
// for (int j=0; j<YBINS+0; j++) {
// for (int k=0; k<ZBINS+0; k++) {
// check = h3->GetBinContent(i,j,k);
// }
// }
// }
//
// TFile *F1 = new TFile((piddir+"PID_3D.root").c_str(),"UPDATE");
// h3->Write("", TObject::kOverwrite);
// F1->Close();
// delete F1;
// delete h3;
// delete canv;
//
//
//return;
//}
void savePullPlot(RooPlot& graph, string fileName)
{
RooHist* hist = graph.pullHist(0,0,true);
TGraphAsymmErrors tgae(hist->GetN());
tgae.SetTitle("");
double x(0);
double y(0);
for(int i(0); i<hist->GetN(); ++i)
{
hist->GetPoint(i,x,y);
tgae.SetPoint(i,x,y);
tgae.SetPointError(i, hist->GetErrorXlow(i), hist->GetErrorXhigh(i),
hist->GetErrorYlow(i), hist->GetErrorYhigh(i));
}
TCanvas c_pullplot("pullplot", "pullplot", 600, 150);
tgae.SetMarkerStyle(20);
tgae.SetMarkerSize(1);
tgae.SetMarkerColor(1);
tgae.GetXaxis()->SetLimits(graph.GetXaxis()->GetXmin(), graph.GetXaxis()->GetXmax());
tgae.GetYaxis()->SetRangeUser(-5,5);
tgae.GetYaxis()->SetLabelSize(0.1);
tgae.GetXaxis()->SetNdivisions(0);
tgae.GetYaxis()->SetNdivisions(503);
tgae.GetYaxis()->SetLabelSize(0.133);
TLine line1(graph.GetXaxis()->GetXmin(), -3, graph.GetXaxis()->GetXmax(), -3);
line1.SetLineColor(2);
TLine line2(graph.GetXaxis()->GetXmin(), 3, graph.GetXaxis()->GetXmax(), 3);
line2.SetLineColor(2);
tgae.Draw("AP");
line1.Draw();
line2.Draw();
TFile f(fileName.c_str(), "RECREATE");
c_pullplot.Write();
f.Close();
}
void saveFitInfo(ofstream& out, RooPlot* frame, int floatingParams, RooAbsPdf* pdf)
{
string separation("====================================");
if(frame)
{
double chi2;
int ndof;
out<<separation<<endl;
// ComputeChi2 computeChi2;
// computeChi2.getChi2(frame, floatingParams, chi2, ndof);
out<<"Chi2 = "<<chi2<<" / "<<ndof-floatingParams<<endl;
out<<"Prob = "<<TMath::Prob(chi2, ndof-floatingParams)<<endl;
}
if(pdf)
{
out<<separation<<endl;
RooArgSet* vars = pdf->getVariables();
vars->writeToStream(out, false);
}
}
void make2DPullPlot(TH1* data, TH1* model, TH1* pull)
{
int nX(data->GetXaxis()->GetNbins());
int nY(data->GetYaxis()->GetNbins());
double currentData;
double currentModel;
double currentError;
for(int iX(1); iX<=nX; ++iX)
{
for(int iY(1); iY<=nY; ++iY)
{
currentData = data->GetBinContent(iX, iY);
currentModel = model->GetBinContent(iX, iY);
currentError = data->GetBinError(iX, iY);
//currentError = sqrt(data->GetBinContent(iX, iY));
if(currentError == 0) currentError=1.;
pull->SetBinContent(iX, iY, (currentData-currentModel) / currentError);
if( abs( (currentData-currentModel) / currentError )>2.5)
{
cout<<"BIG PULL: data: "<<currentData<<", model: "<<currentModel<<", error: "<<currentError<<endl;
}
}
}
}
void lhcbStyle(double fontsize)
{
// define names for colours
Int_t black = 1;
Int_t red = 2;
Int_t green = 3;
Int_t blue = 4;
Int_t yellow = 5;
Int_t magenta= 6;
Int_t cyan = 7;
Int_t purple = 9;
////////////////////////////////////////////////////////////////////
// PURPOSE:
//
// This macro defines a standard style for (black-and-white)
// "publication quality" LHCb ROOT plots.
//
// USAGE:
//
// Include the lines
// gROOT->ProcessLine(".L lhcbstyle.C");
// lhcbStyle();
// at the beginning of your root macro.
//
// Example usage is given in myPlot.C
//
// COMMENTS:
//
// Font:
//
// The font is chosen to be 132, this is Times New Roman (like the text of
// your document) with precision 2.
//
// "Landscape histograms":
//
// The style here is designed for more or less square plots.
// For longer histograms, or canvas with many pads, adjustements are needed.
// For instance, for a canvas with 1x5 histograms:
// TCanvas* c1 = new TCanvas("c1", "L0 muons", 600, 800);
// c1->Divide(1,5);
// Adaptions like the following will be needed:
// gStyle->SetTickLength(0.05,"x");
// gStyle->SetTickLength(0.01,"y");
// gStyle->SetLabelSize(0.15,"x");
// gStyle->SetLabelSize(0.1,"y");
// gStyle->SetStatW(0.15);
// gStyle->SetStatH(0.5);
//
// Authors: Thomas Schietinger, Andrew Powell, Chris Parkes, Niels Tuning
// Maintained by Editorial board member (currently Niels)
///////////////////////////////////////////////////////////////////
// Use times new roman, precision 2
Int_t lhcbFont = 132; // Old LHCb style: 62;
// Line thickness
Double_t lhcbWidth = 2.00; // Old LHCb style: 3.00;
// Text size
Double_t lhcbTSize = fontsize;//0.06;
// use plain black on white colors
gROOT->SetStyle("Plain");
TStyle *lhcbStyle= new TStyle("lhcbStyle","LHCb plots style");
//lhcbStyle->SetErrorX(0); // don't suppress the error bar along X
lhcbStyle->SetFillColor(1);
lhcbStyle->SetFillStyle(1001); // solid
lhcbStyle->SetFrameFillColor(0);
lhcbStyle->SetFrameBorderMode(0);
lhcbStyle->SetPadBorderMode(0);
lhcbStyle->SetPadColor(0);
lhcbStyle->SetCanvasBorderMode(0);
lhcbStyle->SetCanvasColor(0);
lhcbStyle->SetStatColor(0);
lhcbStyle->SetLegendBorderSize(0);
lhcbStyle->SetLegendFont(132);
// If you want the usual gradient palette (blue -> red)
lhcbStyle->SetPalette(1);
// If you want colors that correspond to gray scale in black and white:
// int colors[8] = {0,5,7,3,6,2,4,1};
// lhcbStyle->SetPalette(8,colors);
// set the paper & margin sizes
lhcbStyle->SetPaperSize(20,26);
lhcbStyle->SetPadTopMargin(0.05);
lhcbStyle->SetPadRightMargin(0.05); // increase for colz plots
lhcbStyle->SetPadBottomMargin(0.16);
lhcbStyle->SetPadLeftMargin(0.14);
// use large fonts
lhcbStyle->SetTextFont(lhcbFont);
lhcbStyle->SetTextSize(lhcbTSize);
lhcbStyle->SetLabelFont(lhcbFont,"x");
lhcbStyle->SetLabelFont(lhcbFont,"y");
lhcbStyle->SetLabelFont(lhcbFont,"z");
lhcbStyle->SetLabelSize(lhcbTSize,"x");
lhcbStyle->SetLabelSize(lhcbTSize,"y");
lhcbStyle->SetLabelSize(lhcbTSize,"z");
lhcbStyle->SetTitleFont(lhcbFont);
lhcbStyle->SetTitleFont(lhcbFont,"x");
lhcbStyle->SetTitleFont(lhcbFont,"y");
lhcbStyle->SetTitleFont(lhcbFont,"z");
lhcbStyle->SetTitleSize(1.2*lhcbTSize,"x");
lhcbStyle->SetTitleSize(1.2*lhcbTSize,"y");
lhcbStyle->SetTitleSize(1.2*lhcbTSize,"z");
// use medium bold lines and thick markers
lhcbStyle->SetLineWidth(lhcbWidth);
lhcbStyle->SetFrameLineWidth(lhcbWidth);
lhcbStyle->SetHistLineWidth(lhcbWidth);
lhcbStyle->SetFuncWidth(lhcbWidth);
lhcbStyle->SetGridWidth(lhcbWidth);
lhcbStyle->SetLineStyleString(2,"[12 12]"); // postscript dashes
lhcbStyle->SetMarkerStyle(20);
lhcbStyle->SetMarkerSize(1.0);
// label offsets
lhcbStyle->SetLabelOffset(0.010,"X");
lhcbStyle->SetLabelOffset(0.010,"Y");
// by default, do not display histogram decorations:
lhcbStyle->SetOptStat(0);
//lhcbStyle->SetOptStat("emr"); // show only nent -e , mean - m , rms -r
// full opts at http://root.cern.ch/root/html/TStyle.html#TStyle:SetOptStat
lhcbStyle->SetStatFormat("6.3g"); // specified as c printf options
lhcbStyle->SetOptTitle(0);
lhcbStyle->SetOptFit(0);
//lhcbStyle->SetOptFit(1011); // order is probability, Chi2, errors, parameters
//titles
lhcbStyle->SetTitleOffset(0.95,"X");
lhcbStyle->SetTitleOffset(0.95,"Y");
lhcbStyle->SetTitleOffset(1.2,"Z");
lhcbStyle->SetTitleFillColor(0);
lhcbStyle->SetTitleStyle(0);
lhcbStyle->SetTitleBorderSize(0);
lhcbStyle->SetTitleFont(lhcbFont,"title");
lhcbStyle->SetTitleX(0.0);
lhcbStyle->SetTitleY(1.0);
lhcbStyle->SetTitleW(1.0);
lhcbStyle->SetTitleH(0.05);
// look of the statistics box:
lhcbStyle->SetStatBorderSize(0);
lhcbStyle->SetStatFont(lhcbFont);
lhcbStyle->SetStatFontSize(0.05);
lhcbStyle->SetStatX(0.9);
lhcbStyle->SetStatY(0.9);
lhcbStyle->SetStatW(0.25);
lhcbStyle->SetStatH(0.15);
// put tick marks on top and RHS of plots
// lhcbStyle->SetPadTickX(1);
// lhcbStyle->SetPadTickY(1);
// histogram divisions: only 5 in x to avoid label overlaps
lhcbStyle->SetNdivisions(505,"x");
lhcbStyle->SetNdivisions(510,"y");
gROOT->SetStyle("lhcbStyle");
gROOT->ForceStyle();
// add LHCb label
TPaveText* lhcbName = new TPaveText(gStyle->GetPadLeftMargin() + 0.05,
0.87 - gStyle->GetPadTopMargin(),
gStyle->GetPadLeftMargin() + 0.20,
0.95 - gStyle->GetPadTopMargin(),
"BRNDC");
lhcbName->AddText("LHCb");
lhcbName->SetFillColor(0);
lhcbName->SetTextAlign(12);
lhcbName->SetBorderSize(0);
TText *lhcbLabel = new TText();
lhcbLabel->SetTextFont(lhcbFont);
lhcbLabel->SetTextColor(1);
lhcbLabel->SetTextSize(lhcbTSize);
lhcbLabel->SetTextAlign(12);
TLatex *lhcbLatex = new TLatex();
lhcbLatex->SetTextFont(lhcbFont);
lhcbLatex->SetTextColor(1);
lhcbLatex->SetTextSize(lhcbTSize);
lhcbLatex->SetTextAlign(12);
cout << "-------------------------" << endl;
cout << "Set LHCb Style - Feb 2012" << endl;
cout << "-------------------------" << endl;
}
| [
"ss4314@ss4314-laptop.hep.ph.ic.ac.uk"
] | ss4314@ss4314-laptop.hep.ph.ic.ac.uk |
8deb281dd38705ff9dc7d2f332ca36e3e05d84ee | 935c8b1069ddfe89999c1006df965c553ebb34ea | /Source/UE4TPS/Private/Weapons/ModularWeapon.cpp | 89f17a21b2c2d950f045307c63caf565b23cdae0 | [] | no_license | haddriax/UE4_TPS | 15ef4046a2f7adf89210b8db8fd206729d805005 | 3095fb1217248bcdda97738fafda52ee7384614d | refs/heads/main | 2023-05-01T18:00:53.264549 | 2021-05-20T10:06:07 | 2021-05-20T10:06:07 | 310,012,257 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,401 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "Weapons/ModularWeapon.h"
#include "Components/SkeletalMeshComponent.h"
#include "Camera/CameraComponent.h"
#include "Characters/TpsCharacterBase.h"
#include "Weapons/FireMode/WeaponFireModeComponent.h"
AModularWeapon::AModularWeapon()
{
WeaponMesh = CreateDefaultSubobject<USkeletalMeshComponent>("Mesh1P");
WeaponMesh->CastShadow = true;
WeaponMesh->bReceivesDecals = false;
WeaponMesh->SetCollisionObjectType(ECC_WorldDynamic);
WeaponMesh->SetCollisionEnabled(ECollisionEnabled::NoCollision);
WeaponMesh->SetCollisionResponseToAllChannels(ECR_Ignore);
SetRootComponent(WeaponMesh);
WeaponRightHandSocketName = "socket_hand_right";
WeaponLeftHandSocketName = "socket_hand_left";
MuzzleFX_SocketName = "MuzzleSocket";
MuzzleTrace_SocketName = "MuzzleSocket";
MuzzleDirection_SocketName = "MuzzleDirectionSocket";
// WeaponFeedbacksComponent = CreateDefaultSubobject<UWeaponFeedbacksComponent>("WeaponFeedbacks");
}
void AModularWeapon::PostInitializeComponents()
{
Super::PostInitializeComponents();
for (UActorComponent* nonCasted_fireMode : GetComponents())
{
UWeaponFireModeComponent* fireMode = Cast<UWeaponFireModeComponent>(nonCasted_fireMode);
if (fireMode)
{
FireModes.Push(fireMode);
}
}
}
void AModularWeapon::OnConstruction(const FTransform& Transform)
{
Super::OnConstruction(Transform);
}
void AModularWeapon::BeginPlay()
{
Super::BeginPlay();
if (ParentCharacter)
{
AttachToPawnHoslterSlot(ParentCharacter);
}
}
void AModularWeapon::AttachToPawnHand(ATpsCharacterBase* Character)
{
// Attach the weapon to the player socket.
if (Character)
{
FAttachmentTransformRules attachmentTransformRules(
EAttachmentRule::SnapToTarget,
EAttachmentRule::SnapToTarget,
EAttachmentRule::SnapToTarget,
false
);
AttachToSocket(Character->GetMesh(), Character->GetWeaponInHandAttachPointOnCharacter());
WeaponMesh->SetRelativeLocation(FVector::ZeroVector);
}
}
void AModularWeapon::AttachToPawnHoslterSlot(ATpsCharacterBase* Character)
{
bool AttachSucceed = false;
switch (WeaponSlot)
{
case EWeaponSlot::Rifle:
AttachSucceed = AttachToSocket(Character->GetMesh(), Character->GetHolsterWeaponAttachPointOnCharacter());
// AttachSucceed = WeaponMesh->AttachToComponent(Character->GetMesh(), FAttachmentTransformRules::SnapToTargetNotIncludingScale, Character->GetHolsterWeaponAttachPointOnCharacter());
break;
case EWeaponSlot::Handgun:
unimplemented();
break;
default:
WeaponMesh->SetHiddenInGame(true);
UE_LOG(LogTemp, Error, TEXT("X %s - No matching WeaponSlot for holstering. Check if %s have it's WeaponSlot defined."), TEXT(__FUNCTION__), *GetName());
}
if (!AttachSucceed)
{
UE_LOG(LogTemp, Error, TEXT("X %s - Attaching weapon to it's holster socket failed."), TEXT(__FUNCTION__));
}
WeaponMesh->SetRelativeLocation(FVector::ZeroVector);
WeaponMesh->SetHiddenInGame(false);
}
bool AModularWeapon::AttachToSocket(USkeletalMeshComponent* MeshToAttachOn, FName SocketName)
{
bool bIsSuccess = WeaponMesh->AttachToComponent(MeshToAttachOn, FAttachmentTransformRules::SnapToTargetIncludingScale, SocketName);
SetActorRelativeLocation(FVector::ZeroVector);
return bIsSuccess;
}
void AModularWeapon::DetachFromPawn()
{
// Detach from the hand socket.
WeaponMesh->DetachFromComponent(FDetachmentTransformRules::KeepRelativeTransform);
AttachToPawnHoslterSlot(ParentCharacter);
}
const FName AModularWeapon::GetMuzzleAttachPoint() const
{
return MuzzleFX_SocketName;
}
void AModularWeapon::SetPlayer(ATpsCharacterBase* _Player)
{
ParentCharacter = _Player;
}
void AModularWeapon::SetWeaponState(EWeaponState NewState)
{
const EWeaponState PreviousState = CurrentState;
CurrentState = NewState;
// If we finished firing ...
if (PreviousState == EWeaponState::Firing && NewState != EWeaponState::Firing)
{
if (FireModes.IsValidIndex(ActiveFireMode))
{
FireModes[ActiveFireMode]->EndFire();
}
}
// If we should start firing ...
if (PreviousState != EWeaponState::Firing && NewState == EWeaponState::Firing)
{
if (FireModes.IsValidIndex(ActiveFireMode))
{
FireModes[ActiveFireMode]->BeginFire();
}
}
}
FVector AModularWeapon::GetMuzzleWorldLocation() const
{
return GetMesh()->GetSocketLocation(GetMuzzleAttachPoint());
}
FVector AModularWeapon::GetShotWorldDirection() const
{
return (GetMesh()->GetSocketLocation(GetShotDirectionSocketName()) - (GetMesh()->GetSocketLocation(GetMuzzleAttachPoint())));
}
void AModularWeapon::TryShooting()
{
if (!IsFiring() && CanFire())
{
SetWeaponState(EWeaponState::Firing);
}
}
void AModularWeapon::StopShooting()
{
if (IsFiring())
{
SetWeaponState(EWeaponState::Idle);
}
}
bool AModularWeapon::CanFire() const
{
// Can fire if is doing nothing or if is already firing.
bool bStateAllowFire = (IsIdling() || IsFiring());
// Ensure Player is referenced and not reloading.
return ((bStateAllowFire) && (!IsPendingReload()));
}
bool AModularWeapon::CanReload() const
{
bool bStateAllowReload = (!IsPendingEquip())
&& (!IsPendingUnequip())
&& (!IsPendingReload());
return bStateAllowReload;
}
bool AModularWeapon::CanSwitchWeapon() const
{
return IsIdling()
|| IsFiring();
}
bool AModularWeapon::EquipOn(ATpsCharacterBase* _Character)
{
if (CanSwitchWeapon())
{
SetPlayer(_Character);
SetWeaponState(EWeaponState::Equipping);
return true;
}
return false;
}
void AModularWeapon::EquipFinished()
{
SetWeaponState(EWeaponState::Idle);
bIsEquipped = true;
}
bool AModularWeapon::Unequip()
{
if (CanSwitchWeapon())
{
SetWeaponState(EWeaponState::Unequipping);
return true;
}
return false;
}
void AModularWeapon::UnequipFinished()
{
SetWeaponState(EWeaponState::Idle);
bIsEquipped = false;
SetPlayer(nullptr);
}
void AModularWeapon::Reload(float ReloadDuration)
{
if (CanReload())
{
// Reloading can cancel shooting.
StopShooting();
SetWeaponState(EWeaponState::Reloading);
// Prepare the ReloadFinished call.
GetWorldTimerManager().SetTimer(
TimerHandle_WeaponAction,
this,
&AModularWeapon::OnReloadFinished,
ReloadDuration,
false);
}
}
void AModularWeapon::OnReloadFinished()
{
// const int32 addToClip = GetAmmuntionsFromReserve(GetMissingAmmoInClip());
// AddAmmuntionsInClip(addToClip);
SetWeaponState(EWeaponState::Idle);
}
| [
"gael-garnier@outlook.fr"
] | gael-garnier@outlook.fr |
2f84a7a62f9d6f973b92598d40d17daf5240b23c | ca832b0d39d5e23611e49b1dd5dd2055cbbeed04 | /PhysiCell_Folder/main.cpp | a5fcfb09b7ca348ea159073d1b60a6c8c573f1b7 | [] | no_license | furkankurtoglu/Biofilm-Project | af41988fae0eb7ed1e6a3f97812af410a5f12779 | c106aaf3e08122e8802919ccd7d91f8329eb2a90 | refs/heads/master | 2022-05-02T13:07:32.709564 | 2022-03-05T16:28:14 | 2022-03-05T16:28:14 | 178,448,775 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,711 | cpp | /*
###############################################################################
# If you use PhysiCell in your project, please cite PhysiCell and the version #
# number, such as below: #
# #
# We implemented and solved the model using PhysiCell (Version x.y.z) [1]. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018 #
# DOI: 10.1371/journal.pcbi.1005991 #
# #
# See VERSION.txt or call get_PhysiCell_version() to get the current version #
# x.y.z. Call display_citations() to get detailed information on all cite-#
# able software used in your PhysiCell application. #
# #
# Because PhysiCell extensively uses BioFVM, we suggest you also cite BioFVM #
# as below: #
# #
# We implemented and solved the model using PhysiCell (Version x.y.z) [1], #
# with BioFVM [2] to solve the transport equations. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018 #
# DOI: 10.1371/journal.pcbi.1005991 #
# #
# [2] A Ghaffarizadeh, SH Friedman, and P Macklin, BioFVM: an efficient para- #
# llelized diffusive transport solver for 3-D biological simulations, #
# Bioinformatics 32(8): 1256-8, 2016. DOI: 10.1093/bioinformatics/btv730 #
# #
###############################################################################
# #
# BSD 3-Clause License (see https://opensource.org/licenses/BSD-3-Clause) #
# #
# Copyright (c) 2015-2018, Paul Macklin and the PhysiCell Project #
# All rights reserved. #
# #
# Redistribution and use in source and binary forms, with or without #
# modification, are permitted provided that the following conditions are met: #
# #
# 1. Redistributions of source code must retain the above copyright notice, #
# this list of conditions and the following disclaimer. #
# #
# 2. Redistributions in binary form must reproduce the above copyright #
# notice, this list of conditions and the following disclaimer in the #
# documentation and/or other materials provided with the distribution. #
# #
# 3. Neither the name of the copyright holder 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 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 <cstdio>
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <cmath>
#include <omp.h>
#include <fstream>
#include "./core/PhysiCell.h"
#include "./modules/PhysiCell_standard_modules.h"
// put custom code modules here!
#include "./custom_modules/custom.h"
using namespace BioFVM;
using namespace PhysiCell;
int main( int argc, char* argv[] )
{
// load and parse settings file(s)
bool XML_status = false;
if( argc > 1 )
{ XML_status = load_PhysiCell_config_file( argv[1] ); }
else
{ XML_status = load_PhysiCell_config_file( "./config/PhysiCell_settings.xml" ); }
if( !XML_status )
{ exit(-1); }
// OpenMP setup
omp_set_num_threads(PhysiCell_settings.omp_num_threads);
// time setup
std::string time_units = "min";
/* Microenvironment setup */
setup_microenvironment(); // modify this in the custom code
/* PhysiCell setup */
// set mechanics voxel size, and match the data structure to BioFVM
double mechanics_voxel_size = 30;
Cell_Container* cell_container = create_cell_container_for_microenvironment( microenvironment, mechanics_voxel_size );
/* Users typically start modifying here. START USERMODS */
create_cell_types();
setup_tissue();
/* Users typically stop modifying here. END USERMODS */
// set MultiCellDS save options
set_save_biofvm_mesh_as_matlab( true );
set_save_biofvm_data_as_matlab( true );
set_save_biofvm_cell_data( true );
set_save_biofvm_cell_data_as_custom_matlab( true );
// save a simulation snapshot
char filename[1024];
sprintf( filename , "%s/initial" , PhysiCell_settings.folder.c_str() );
save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time );
// save a quick SVG cross section through z = 0, after setting its
// length bar to 200 microns
PhysiCell_SVG_options.length_bar = 200;
// for simplicity, set a pathology coloring function
std::vector<std::string> (*cell_coloring_function)(Cell*) = my_coloring_function;
sprintf( filename , "%s/initial.svg" , PhysiCell_settings.folder.c_str() );
SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function );
display_citations();
// set the performance timers
BioFVM::RUNTIME_TIC();
BioFVM::TIC();
std::ofstream report_file;
if( PhysiCell_settings.enable_legacy_saves == true )
{
sprintf( filename , "%s/simulation_report.txt" , PhysiCell_settings.folder.c_str() );
report_file.open(filename); // create the data log file
report_file<<"simulated time\tnum cells\tnum division\tnum death\twall time"<<std::endl;
}
// main loop
try
{
while( PhysiCell_globals.current_time < PhysiCell_settings.max_time + 0.1*diffusion_dt )
{
//std::cout<<diffusion_dt ;
// save data if it's time.
if( fabs( PhysiCell_globals.current_time - PhysiCell_globals.next_full_save_time ) < 0.01 * diffusion_dt )
{
display_simulation_status( std::cout );
if( PhysiCell_settings.enable_legacy_saves == true )
{
log_output( PhysiCell_globals.current_time , PhysiCell_globals.full_output_index, microenvironment, report_file);
}
if( PhysiCell_settings.enable_full_saves == true )
{
sprintf( filename , "%s/output%08u" , PhysiCell_settings.folder.c_str(), PhysiCell_globals.full_output_index );
save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time );
}
PhysiCell_globals.full_output_index++;
PhysiCell_globals.next_full_save_time += PhysiCell_settings.full_save_interval;
}
// save SVG plot if it's time
if( fabs( PhysiCell_globals.current_time - PhysiCell_globals.next_SVG_save_time ) < 0.01 * diffusion_dt )
{
if( PhysiCell_settings.enable_SVG_saves == true )
{
sprintf( filename , "%s/snapshot%08u.svg" , PhysiCell_settings.folder.c_str() , PhysiCell_globals.SVG_output_index );
SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function );
PhysiCell_globals.SVG_output_index++;
PhysiCell_globals.next_SVG_save_time += PhysiCell_settings.SVG_save_interval;
}
}
// update the microenvironment
microenvironment.simulate_diffusion_decay( diffusion_dt );
// run PhysiCell
((Cell_Container *)microenvironment.agent_container)->update_all_cells( PhysiCell_globals.current_time );
/*
Custom add-ons could potentially go here.
*/
update_Dirichlet_Nodes();
make_adjustments();
PhysiCell_globals.current_time += diffusion_dt;
}
if( PhysiCell_settings.enable_legacy_saves == true )
{
log_output(PhysiCell_globals.current_time, PhysiCell_globals.full_output_index, microenvironment, report_file);
report_file.close();
}
}
catch( const std::exception& e )
{ // reference to the base of a polymorphic object
std::cout << e.what(); // information from length_error printed
}
// save a final simulation snapshot
sprintf( filename , "%s/final" , PhysiCell_settings.folder.c_str() );
save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time );
sprintf( filename , "%s/final.svg" , PhysiCell_settings.folder.c_str() );
SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function );
// timer
std::cout << std::endl << "Total simulation runtime: " << std::endl;
BioFVM::display_stopwatch_value( std::cout , BioFVM::runtime_stopwatch_value() );
return 0;
}
| [
"fkurtog@iu.edu"
] | fkurtog@iu.edu |
f62cf9bf7c6b65435ae6ac4cf06cff77bcbf6e18 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function13707/function13707_schedule_12/function13707_schedule_12_wrapper.cpp | 57127a4e334b3242f3ab636224ee3a693f72a2c5 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 935 | cpp | #include "Halide.h"
#include "function13707_schedule_12_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(128, 1024, 512);
Halide::Buffer<int32_t> buf0(128, 1024, 512);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function13707_schedule_12(buf00.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function13707/function13707_schedule_12/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
5505eba72503f9b90fe43ca5f2422611e1d3bd1f | 6d68bb97c0203f1f66a8d923a44615db491f4901 | /cf/547/547A.cpp | 90163f7ac1615968fdda6908b1322ff35e4edd6b | [] | no_license | czqsole/codeforces | f886a5aa79472b3f7a62f59394487b78f0d5d73e | 89580967e9429c98602837626c835b4981a954e3 | refs/heads/master | 2021-06-16T04:44:34.194290 | 2021-03-02T19:22:04 | 2021-03-02T19:22:04 | 150,667,045 | 0 | 0 | null | 2021-03-02T19:22:04 | 2018-09-28T01:15:12 | C++ | UTF-8 | C++ | false | false | 699 | cpp | /*
* @Author: czqsole
* @Date: 2019-03-20 20:15
*/
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
int ans = 0;
if(m % n == 0) {
int time = m / n;
while (time > 0) {
// cout << "time:" << time << endl;
if(time % 2 == 0) {
time /= 2;
ans++;
}
if(time % 3 == 0) {
time /= 3;
ans++;
}
if((time % 2 != 0) && (time % 3 != 0)) {
break;
}
}
if(time > 1) {
ans = -1;
}
} else {
ans = -1;
}
cout << ans << endl;
} | [
"czqsole@gmail.com"
] | czqsole@gmail.com |
b8bb5f381845465a6f6643805f1fae54038f510f | ffdc77394c5b5532b243cf3c33bd584cbdc65cb7 | /mindspore/lite/src/litert/kernel/cpu/bolt/bolt_kernel_manager.cc | 2f012718e409542eb7a7cd4ab4ced84c7b5fee4a | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"MPL-1.0",
"OpenSSL",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause-Open-MPI",
"MIT",
"MPL-2.0-no-copyleft-exception",
"NTP",
"BSD-3-Clause",
"GPL-1.0-or-later",
"0BSD",
"MPL-2.0",
"LicenseRef-scancode-f... | permissive | mindspore-ai/mindspore | ca7d5bb51a3451c2705ff2e583a740589d80393b | 54acb15d435533c815ee1bd9f6dc0b56b4d4cf83 | refs/heads/master | 2023-07-29T09:17:11.051569 | 2023-07-17T13:14:15 | 2023-07-17T13:14:15 | 239,714,835 | 4,178 | 768 | Apache-2.0 | 2023-07-26T22:31:11 | 2020-02-11T08:43:48 | C++ | UTF-8 | C++ | false | false | 2,249 | cc | /**
* Copyright 2023 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bolt/bolt_kernel_manager.h"
#include "bolt/bolt_parameter_manager.h"
namespace mindspore::kernel::bolt {
bool BoltSupportKernel(int op_type, TypeId data_type) {
auto creator = BoltKernelRegistry::GetInstance()->Creator({op_type, data_type});
if (creator != nullptr) {
return true;
}
return false;
}
LiteKernel *BoltKernelRegistry(const ParameterSpec ¶m_spec, const std::vector<lite::Tensor *> &inputs,
const std::vector<lite::Tensor *> &outputs, const lite::InnerContext *ctx,
kernel::KernelKey *key) {
auto creator = BoltKernelRegistry::GetInstance()->Creator({key->type, key->data_type});
LiteKernel *kernel = nullptr;
if (creator != nullptr) {
kernel = creator(param_spec, inputs, outputs, ctx);
}
if (kernel == nullptr) {
MS_LOG(DEBUG) << "Create bolt kernel failed!";
return nullptr;
}
key->format = BoltKernelRegistry::GetInstance()->GetKernelFormat({key->type, key->data_type});
return kernel;
}
LiteKernel *BoltKernelRegistry(OpParameter *parameter, const std::vector<lite::Tensor *> &inputs,
const std::vector<lite::Tensor *> &outputs, const lite::InnerContext *ctx,
kernel::KernelKey *key) {
// convert OpParameter to ParameterSpec
auto param_spec = BoltParameterRegistry::GetInstance()->CreateBoltParameter(parameter);
if (param_spec == nullptr) {
MS_LOG(DEBUG) << "Create bolt ParameterSpec failed!";
return nullptr;
}
return BoltKernelRegistry(*param_spec, inputs, outputs, ctx, key);
}
} // namespace mindspore::kernel::bolt
| [
"yangruoqi@huawei.com"
] | yangruoqi@huawei.com |
98ea3715baf5d1714360eb57c9b1ab760d7b087c | 966e2a8cf8bdd3af506dcd3f0714a48078af9311 | /test_file.cpp | bab56019701123d10a348b967286f5e81b39a715 | [] | no_license | xtsxisaxns/calib_fisheye | 65a708581da8ca40c42a6b34a59ca616162f7f08 | 8c0fdf7c0a64a612f5026604498e902e6aabe39f | refs/heads/master | 2021-10-27T15:52:26.883091 | 2019-04-18T06:57:00 | 2019-04-18T06:57:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,944 | cpp | /*------------------------------------------------------------------------------
Example code that shows the use of the 'cam2world" and 'world2cam" functions
Shows also how to undistort images into perspective or panoramic images
NOTE, IF YOU WANT TO SPEED UP THE REMAP FUNCTION I STRONGLY RECOMMEND TO INSTALL
INTELL IPP LIBRARIES ( http://software.intel.com/en-us/intel-ipp/ )
YOU JUST NEED TO INSTALL IT AND INCLUDE ipp.h IN YOUR PROGRAM
Copyright (C) 2009 DAVIDE SCARAMUZZA, ETH Zurich
Author: Davide Scaramuzza - email: davide.scaramuzza@ieee.org
------------------------------------------------------------------------------*/
#include "fisheye_param.h"
#include <iostream>
#include <string>
const int slider_max = 5000;
cv::Mat src1, dst1, src2, dst2;
cv::Mat mapx1, mapy1;
cv::Mat mapx2, mapy2;
cv::Mat K1, K2;
int fx, fy;
int xc, yc;
FisheyeParam ocam_model1, ocam_model2;
float theta1 = 20*CV_PI/180, theta2 = -60*CV_PI/180;
cv::Matx33d R11, R12, R21, R22;
void readTransformation(std::string filename, cv::Matx33d R, cv::Vec3d t)
{
std::ifstream result_in(filename.data());
assert(result_in.is_open());
cv::Matx44d T;
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
result_in >> T(i,j);
}
}
R = T.get_minor<3,3>(0,0);
t = cv::Vec3d(T(0,3), T(1,3), T(2,3));
result_in.close();
}
void calculateTwoRotation(cv::Matx33d R, cv::Vec3d tvec, cv::Matx33d R1, cv::Matx33d R2)
{
cv::Vec3d rvec = cv::Affine3d(R).rvec();
// rectification algorithm
rvec *= -0.5; // get average rotation
cv::Matx33d r_r;
Rodrigues(rvec, r_r); // rotate cameras to same orientation by averaging
cv::Vec3d t = r_r * tvec;
cv::Vec3d uu(t[0] > 0 ? 1 : -1, 0, 0);
// calculate global Z rotation
cv::Vec3d ww = t.cross(uu);
double nw = norm(ww);
if (nw > 0.0)
ww *= acos(fabs(t[0])/cv::norm(t))/nw;
cv::Matx33d wr;
Rodrigues(ww, wr);
// apply to both views
cv::Matx33d ri1 = wr * r_r.t();
cv::Mat(ri1, false).convertTo(R1, CV_64F);
cv::Matx33d ri2 = wr * r_r;
cv::Mat(ri2, false).convertTo(R2, CV_64F);
}
void Fisheye2twoPerspective(cv::Mat src, cv::Mat dst, float fx1, float fy1, float fx2, float fy2, cv::Matx33d R1, cv::Matx33d R2, FisheyeParam& ocam_model)
{
if(src.empty() || dst.empty())
{
std::cout << __FILE__ << ": "<< __LINE__ << " error!" << std::endl;
return;
}
cv::Size image_size = dst.size();
float xc1 = xc - fx1 * tan((theta1-theta2)/2), yc1 = yc;
float xc2 = xc - fx2 * tan(-(theta1-theta2)/2), yc2 = yc;
for(int i = 0; i < image_size.height; i++)
for(int j = 0; j < image_size.width; j++)
{
cv::Point3f point3d;
float x, y, z;
if(j <= xc )
{
x = (j-xc1) / fx1;
y = (i-yc1) / fy1;
z = 1;
float theta = -theta1;
point3d.x = z*sin(theta) + x*cos(theta);
point3d.y = y;
point3d.z = z*cos(theta) - x*sin(theta);
}
else
{
x = (j-xc2) / fx2;
y = (i-yc2) / fy2;
z = 1;
float theta = -theta2;
point3d.x = z*sin(theta) + x*cos(theta);
point3d.y = y;
point3d.z = z*cos(theta) - x*sin(theta);
}
cv::Point2f point2d = ocam_model.World2Camera(point3d);
int u = point2d.x, v = point2d.y;
if(u >= 0 && u < src.cols && v >= 0 && v < src.rows)
dst.at<cv::Vec3b>(i,j) = src.at<cv::Vec3b>(v,u);
}
}
void Fisheye2Perspective(cv::Mat src, cv::Mat dst, float fx, float fy, cv::Matx33d R, FisheyeParam& ocam_model)
{
if(src.empty() || dst.empty())
{
std::cout << __FILE__ << ": "<< __LINE__ << " error!" << std::endl;
return;
}
cv::Size image_size = dst.size();
//float xc1 = xc - fx1 * tan((theta1-theta2)/2), yc1 = yc;
//float xc2 = xc - fx2 * tan(-(theta1-theta2)/2), yc2 = yc;
for(int i = 0; i < image_size.height; i++)
for(int j = 0; j < image_size.width; j++)
{
cv::Point3f point3d;
float x, y, z;
x = (j - xc) / fx;
y = (i - yc) / fy;
z = 1;
cv::Vec3d p(x,y,z);
p = R.inv() * p;
point3d.x = p[0];
point3d.y = p[1];
point3d.z = p[2];
cv::Point2f point2d = ocam_model.World2Camera(point3d);
int u = point2d.x, v = point2d.y;
if(u >= 0 && u < src.cols && v >= 0 && v < src.rows)
dst.at<cv::Vec3b>(i,j) = src.at<cv::Vec3b>(v,u);
}
}
void Onchange(int, void*)
{
K1 = (cv::Mat_<float>(3, 3) << fx, 0, xc,
0, fy, yc,
0, 0, 1);
dst1 = cv::Mat(src1.rows, src1.cols, src1.type(), cv::Scalar::all(0));
dst2 = cv::Mat(src2.rows, src2.cols, src2.type(), cv::Scalar::all(0));
Fisheye2Perspective(src1, dst1, fx, fy, R12, ocam_model1);
Fisheye2Perspective(src2, dst2, fx, fy, R21, ocam_model2);
cv::imshow( "Undistorted Perspective Image1", dst1 );
cv::imshow( "Undistorted Perspective Image2", dst2 );
}
int main(int argc, char *argv[])
{
/* --------------------------------------------------------------------*/
/* Read the parameters of the omnidirectional camera from the TXT file */
/* --------------------------------------------------------------------*/
ocam_model1.Load("../intrinsic_parameters/left/calib.txt");
ocam_model2.Load("../intrinsic_parameters/front/calib.txt");
/* --------------------------------------------------------------------*/
/* Allocate space for the unistorted images */
/* --------------------------------------------------------------------*/
src1 = cv::imread("../bmp/frame_vc9_1814.bmp"); // source image 1
assert(!src1.empty());
src2 = cv::imread("../bmp/frame_vc10_1814.bmp"); // source image 1
assert(!src2.empty());
cv::Matx44d T1, T2;
readTransformation("../result/left.txt", T1);
readTransformation("../result/front.txt", T2);
//mapx1 = cv::Mat(src1.rows, src1.cols, CV_32FC1);
//mapy1 = cv::Mat(src1.rows, src1.cols, CV_32FC1);
dst1 = cv::Mat(src1.rows, src1.cols, src1.type(), cv::Scalar::all(0)); // undistorted panoramic image
dst2 = cv::Mat(src2.rows, src2.cols, src2.type(), cv::Scalar::all(0)); // undistorted panoramic image
/* -------------------------------------------------------------------- */
/* Create LooK1-Up-Table for perspective undistortion */
/* SF is K1ind of distance from the undistorted image to the camera */
/* (it is not meters, it is justa zoom fator) */
/* Try to change SF to see how it affects the result */
/* The undistortion is done on a plane perpendicular to the camera axis */
/* -------------------------------------------------------------------- */
fx = 480, fy = 360, xc = dst1.cols/2.0, yc = dst1.rows/2.0;
//K1 = (cv::Mat_<float>(3, 3) << fx, 0, xc,
// 0, fy, yc,
// 0, 0, 1);
calculateTwoRotation(T1, R11, R12);
calculateTwoRotation(T1, R21, R22);
Fisheye2Perspective(src1, dst1, fx, fy, R12, ocam_model1);
Fisheye2Perspective(src2, dst2, fx, fy, R21, ocam_model2);
cv::namedWindow( "Original fisheye camera image1", 0 );
cv::namedWindow( "Undistorted Perspective Image1", 0 );
cv::namedWindow( "Original fisheye camera image2", 0 );
cv::namedWindow( "Undistorted Perspective Image2", 0 );
cv::namedWindow( "toolbox", 0 );
cv::imshow( "Original fisheye camera image1", src1 );
cv::imshow( "Undistorted Perspective Image1", dst1 );
cv::imshow( "Original fisheye camera image2", src2 );
cv::imshow( "Undistorted Perspective Image2", dst2 );
cv::createTrackbar("fx", "toolbox", &fx, slider_max, Onchange);
cv::createTrackbar("fy", "toolbox", &fy, slider_max, Onchange);
cv::createTrackbar("xc", "toolbox", &xc, slider_max, Onchange);
cv::createTrackbar("yc", "toolbox", &yc, slider_max, Onchange);
/* --------------------------------------------------------------------*/
/* Wait until K1ey 'q' pressed */
/* --------------------------------------------------------------------*/
while((char)cv::waitKey(10) != 'q');
/* --------------------------------------------------------------------*/
/* Save image */
/* --------------------------------------------------------------------*/
cv::imwrite("undistorted_perspective.jpg", dst1);
printf("\nImage %s saved\n","undistorted_perspective1.jpg");
cv::imwrite("undistorted_perspective.jpg", dst2);
printf("\nImage %s saved\n","undistorted_perspective2.jpg");
cv::destroyAllWindows();
return 0;
}
| [
"280947007@qq.com"
] | 280947007@qq.com |
bf04abf291a3a89e42e80f386074718ab8df98f1 | 327e3b9a234487e12be5758bc9ac197a1969a294 | /include/myslam/frame.h | 08d393c2e55cfe9a21d8b0b30ddd597548e523fe | [] | no_license | deeplxx/myslam | d5daee55eb17d87ddc4ea77fa79b4d902b723875 | 36ce950af84be03dd100a23642330910a7afdfb7 | refs/heads/master | 2021-07-21T13:38:42.263696 | 2017-10-30T15:45:48 | 2017-10-30T15:45:48 | 108,426,577 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 992 | h | /*
基本数据单元
*/
#ifndef FRAME_H
#define FRAME_H
#include "myslam/camera.h"
#include "myslam/common_include.h"
namespace myslam {
class Frame {
public:
typedef shared_ptr<Frame> Ptr;
unsigned long id_; // frame id
double time_stamp_; // frame创建时间
Sophus::SE3 T_c_w_; // 相机位姿
Camera::Ptr camera_; // shared_ptr
cv::Mat color_, depth_; // 彩色图与深度图
public:
Frame();
Frame(unsigned long id, double time_stamp,
Sophus::SE3 T_c_w = Sophus::SE3(), Camera::Ptr camera = nullptr,
cv::Mat color = cv::Mat(), cv::Mat depth = cv::Mat());
~Frame();
// factory function
static Frame::Ptr createFrame();
// 查找给定点对应的深度
double findDepth(const cv::KeyPoint& kp);
// 获取相机光心
Eigen::Vector3d getCamCenter() const;
// 判断给定点是否在视野内,传入参数是世界坐标
bool isInFrame(const Eigen::Vector3d& pt_w);
};
}
#endif
| [
"xuyff08@gmail.com"
] | xuyff08@gmail.com |
0119e6b08f3c7c2005c493d595a2b0eefb1d6eab | 59dcbe703e0f4f7edb65d29da6163baf6c46a75d | /STM32F7-MISS-TouchGFX_WRK/Application/Gui/generated/fonts/src/Table_verdanab_26_4bpp.cpp | 8e53fe0a4589256fa470fb59592a3117d6d9998e | [] | no_license | sphinxyun/STM32F7-MISS-TouchGFX | 65fb99d877696fd80ef018aee4dfa70a29c99228 | 9cc1fd80d2086fa6a76cea5cc323672e62cc6fb6 | refs/heads/master | 2020-04-18T13:33:18.202134 | 2019-01-18T23:49:38 | 2019-01-18T23:49:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,099 | cpp |
#include <touchgfx/Font.hpp>
#ifndef NO_USING_NAMESPACE_TOUCHGFX
using namespace touchgfx;
#endif
FONT_LOCATION_FLASH_PRAGMA
KEEP extern const touchgfx::GlyphNode glyphs_verdanab_26_4bpp[] FONT_LOCATION_FLASH_ATTRIBUTE =
{
{ 0, 32, 0, 0, 0, 0, 9, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 0, 33, 6, 19, 19, 2, 10, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 57, 37, 31, 19, 19, 1, 33, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 361, 44, 8, 10, 5, 0, 9, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 401, 45, 11, 4, 11, 1, 12, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 425, 46, 6, 6, 6, 2, 9, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 443, 48, 17, 19, 19, 1, 18, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 614, 49, 13, 19, 19, 3, 18, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 747, 50, 16, 19, 19, 2, 18, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 899, 51, 16, 19, 19, 1, 18, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 1051, 52, 17, 19, 19, 1, 18, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 1222, 53, 15, 19, 19, 2, 18, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 1374, 54, 17, 19, 19, 1, 18, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 1545, 55, 16, 19, 19, 1, 18, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 1697, 56, 17, 19, 19, 1, 18, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 1868, 57, 16, 19, 19, 1, 18, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 2020, 58, 6, 15, 15, 2, 10, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 2065, 60, 18, 19, 18, 2, 23, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 2236, 62, 17, 19, 18, 3, 23, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 2407, 63, 14, 19, 19, 1, 16, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 2540, 65, 20, 19, 19, 0, 20, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 2730, 66, 17, 19, 19, 2, 20, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 2901, 69, 15, 19, 19, 2, 18, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 3053, 71, 19, 19, 19, 1, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 3243, 73, 12, 19, 19, 1, 14, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 3357, 76, 15, 19, 19, 2, 17, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 3509, 77, 21, 19, 19, 2, 25, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 3718, 78, 18, 19, 19, 2, 22, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 3889, 79, 20, 19, 19, 1, 22, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 4079, 80, 17, 19, 19, 2, 19, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 4250, 82, 19, 19, 19, 2, 20, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 4440, 83, 17, 19, 19, 1, 18, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 4611, 84, 18, 19, 19, 0, 18, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 4782, 85, 17, 19, 19, 2, 21, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 4953, 86, 20, 19, 19, 0, 20, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 5143, 101, 16, 15, 15, 1, 17, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 5263, 103, 16, 20, 15, 1, 18, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 5423, 104, 15, 20, 20, 2, 19, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 5583, 105, 5, 20, 20, 2, 9, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 5643, 110, 15, 15, 15, 2, 19, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 5763, 114, 11, 15, 15, 2, 13, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 5853, 115, 14, 15, 15, 1, 15, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0},
{ 5958, 116, 12, 19, 19, 0, 12, 255, 0, touchgfx::GLYPH_DATA_FORMAT_A4 | 0}
};
| [
"poryzala@gmail.com"
] | poryzala@gmail.com |
b412f6427a51df00d314cdff8a845874a749061b | 826c5c99332b1792f2f560edda7abddc41561e85 | /core/lib/aztec/src/base/matrix_def.h | df5680cd2702ee20829f65fb73f432a81ebe481e | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | mcyril/barcodes | 7064156751dc40afbc73d9aa6d7f48cdfe8d125e | 523570475149fcc9f2153ed5b11812de2a622224 | refs/heads/master | 2021-01-17T00:01:06.938986 | 2018-11-07T12:44:13 | 2018-11-07T12:44:13 | 38,630,569 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,626 | h | #pragma once
#include <cassert>
#include <algorithm>
template <typename Type, typename Allocator>
inline matrix<Type, Allocator>::matrix(const allocator_type &allocator)
: _data(allocator), _width(0), _height(0)
{
}
template <typename Type, typename Allocator>
inline matrix<Type, Allocator>::matrix(
size_type current_width, size_type current_height,
const value_type &value, const allocator_type &allocator)
: _data(current_width * current_height, value, allocator),
_width(current_width), _height(current_height)
{
}
template <typename Type, typename Allocator>
inline void matrix<Type, Allocator>::clear()
{
resize(0, 0);
}
template <typename Type, typename Allocator>
inline void matrix<Type, Allocator>::resize(
size_type new_width, size_type new_height,
const value_type &value)
{
if (new_width == width() && new_height == height())
return;
matrix t(new_width, new_height, value);
for (size_type y = 0, y_max = std::min(height(), new_height);
y < y_max; ++y)
{
for (size_type x = 0, x_max = std::min(width(), new_width);
x < x_max; ++x)
{
using std::swap;
swap((*this)(x, y), t(x, y));
}
}
swap(t);
}
template <typename Type, typename Allocator>
inline void matrix<Type, Allocator>::swap(matrix &right)
{
using std::swap;
swap(_data, right._data);
swap(_width, right._width);
swap(_height, right._height);
}
template <typename Type, typename Allocator>
inline typename matrix<Type, Allocator>::size_type
matrix<Type, Allocator>::width() const
{
return _width;
}
template <typename Type, typename Allocator>
inline typename matrix<Type, Allocator>::size_type
matrix<Type, Allocator>::height() const
{
return _height;
}
template <typename Type, typename Allocator>
inline typename matrix<Type, Allocator>::const_reference
matrix<Type, Allocator>::operator () (size_type x, size_type y) const
{
return _data[index(x, y)];
}
template <typename Type, typename Allocator>
inline typename matrix<Type, Allocator>::reference
matrix<Type, Allocator>::operator () (size_type x, size_type y)
{
return _data[index(x, y)];
}
template <typename Type, typename Allocator>
inline typename matrix<Type, Allocator>::size_type
matrix<Type, Allocator>::index(size_type x, size_type y) const
{
assert(x < width());
assert(y < height());
return y * width() + x;
}
template <typename Type, typename Allocator>
inline void swap(
matrix<Type, Allocator> &left, matrix<Type, Allocator> &right)
{
left.swap(right);
}
| [
"none@none"
] | none@none |
170cb3b6f345e8e2e6daaaa990aae54e3f90a0ea | 1fdc80e0636c1fa9f7ecd6ce418cd9232d9b527d | /Fibonacci_loop.cpp | f6056dbe65a9949736a69310c97ba0f01e57878c | [] | no_license | juanpsantana/WSQs | 88b70c5447382fc79919df166794f560bc61c8fb | 63caffddfd6339dc89b9dbbc057ebb11003d1d8a | refs/heads/master | 2021-01-02T09:09:07.053324 | 2015-05-05T21:51:55 | 2015-05-05T21:51:55 | 31,440,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 350 | cpp | #include <iostream>
#include <cstdlib>
using namespace std;
int Fibonacci_loop (int position){
if (position <3){
return 1;
}
if (position >=3){
int c;
int a = 1, b =1;
for(int i=2; i<position;i++){
c=a+b;
a=b;
b=c;
}
return c;
}
}
int main(){
int position;
cin>> position;
cout << Fibonacci_loop(position);
return 0;
} | [
"sagj960928"
] | sagj960928 |
c8609fbe7438fa7759a813893e20ccb073c4b5c2 | b095aab60cf06f6c37affe2b26bf6468f8d9e7bf | /tools/format_convert.h | d0938a709de5ebc494cdfb9c88afe8a73dffeb8c | [] | no_license | hustallenlee/dx-graph | f0b2191407f12f19069915ddeb7032e0b3a6055e | 265a8ad89cc5d91c9617200488e32298aa39d603 | refs/heads/master | 2021-01-13T08:36:57.852662 | 2015-11-07T13:25:39 | 2015-11-07T13:25:39 | 72,414,953 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,516 | h | /*
* dist-xs
*
* Copyright 2015 Key Laboratory of Data Storage System, Ministry of Education WNLO HUST
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _FORMAT_CONVERT_
#define _FORMAT_CONVERT_
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <map>
#include <utility>
#include "../utils/types.h"
#include "../utils/log_wrapper.h"
#include "../utils/type_utils.h"
namespace format {
class format_convert {
private:
std::string filename;
std::ifstream snap_file;
std::ofstream type_file;
std::ofstream map_file;
std::ofstream config_file;
int vertex_num;
long edge_num;
public:
format_convert(std::string fn):filename(fn){
snap_file.open(filename, std::ios::in);
#ifdef COMPACT_GRAPH
type_file.open(filename + ".bin",
std::ios::out | std::ios::binary);
config_file.open(filename + ".bin.ini", std::ios::out);
#else
type_file.open(filename + "_noncompact.bin",
std::ios::out | std::ios::binary);
config_file.open(filename + "_noncompact.bin.ini", std::ios::out);
#endif
map_file.open(filename + ".map",std::ios::out );
map_file << "#after before" << std::endl;
vertex_num = 0;
edge_num = 0;
}
~format_convert(){
snap_file.close();
type_file.close();
map_file.close();
config_file.close();
}
void write_config(){
config_file << "#type\tname\tvertices\tedges\n";
#ifdef COMPACT_GRAPH
config_file << "1" <<" "
<<filename+".bin"<<" "
<<vertex_num<<" "
<<edge_num<<std::endl;
#else
config_file << "2" <<" "
<<filename+"_noncompact.bin"<<" "
<<vertex_num<<" "
<<edge_num<<std::endl;
#endif
}
void to_type() {
char line[1024] = {0};
if (! snap_file){
LOG_TRIVIAL(error) << "no file is opened";
}
format::edge_t edge;
std::map<vertex_t, vertex_t> mapper;
vertex_t i=0;
std::cout << sizeof(edge) <<std::endl;
while(snap_file.getline(line,sizeof(line))){
std::istringstream record(line);
record >> edge.src;
record >> edge.dst;
#ifdef WEIGHT_EDGE
edge.value = generate_weight();
#endif
auto map_ins = mapper.insert( std::pair <vertex_t, vertex_t>(edge.src, i));
if (map_ins.second == true){
map_file << i <<" " << edge.src << std::endl;
edge.src = i;
i++;
}
else{
edge.src = map_ins.first->second;
}
map_ins = mapper.insert( std::pair <vertex_t, vertex_t>(edge.dst, i));
if (map_ins.second == true){
map_file << i <<" " << edge.dst << std::endl;
edge.dst = i;
i++;
}
else{
edge.dst = map_ins.first->second;
}
type_file.write( (char *) (&edge), sizeof(format::edge_t));
edge_num ++;
}
vertex_num = i;
#ifdef COMPACT_GRAPH
LOG_TRIVIAL(info) << "snap to compact type successfull";
#else
LOG_TRIVIAL(info) << "snap to non-compact type successfull";
#endif
write_config();
}
weight_t generate_weight(){
return 1.0;
}
};
}
#endif
| [
"allen_lee922@foxmail.com"
] | allen_lee922@foxmail.com |
31c8b111ef6b3a0f2e8bc1b249750f7deb7b40df | 612b72db8d4f04c6ebd23dae10983065f88590b5 | /MFC_Laser/MFC_Laser/MarkEzdDll.h | c3bd595e897949ac6c35e20a70d69c8aa954eb32 | [] | no_license | zlmone/laser | 3220e1a88ca6df2e6856bdcbfa5c72b61a4fc808 | 581c4e91d6a8f0e70ef643a0cc6612f017c37da6 | refs/heads/master | 2022-03-12T14:30:14.894754 | 2019-11-04T09:00:18 | 2019-11-04T09:01:09 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,475 | h | #pragma once
class MarkEzdDll
{
public:
MarkEzdDll();
~MarkEzdDll();
//HINSTANCE hEzdDLL = ::LoadLibraryEx(L"MarkEzd.dll", NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
HINSTANCE hEzdDLL = ::LoadLibrary(L"MarkEzd.dll");
/*
if (hEzdDLL == NULL)
{
MessageBox(_T("无法载入dll"), NULL);
}
*/
//初始化lmc1控制卡
//输入参数: strEzCadPath EzCad软件的执行路径
// bTestMode = TRUE 表示测试模式 bTestMode = FALSE 表示正常模式
// pOwenWnd 表示父窗口对象,如果需要实现停止打标,则系统会从此窗口截取消息
typedef int(*LMC1_INITIAL)(TCHAR * strEzCadPath, BOOL bTestMode, HWND hOwenWnd); //定义函数指针
LMC1_INITIAL lmc1_Initial = (LMC1_INITIAL)GetProcAddress(hEzdDLL, "lmc1_Initial");
//关闭lmc1控制卡
typedef int(*LMC1_CLOSE)();
LMC1_CLOSE lmc1_Close = (LMC1_CLOSE)GetProcAddress(hEzdDLL, "lmc1_Close");
//载入ezd文件,并清除数据库所有对象
//输入参数: strFileName EzCad文件名称
typedef int(*LMC1_LOADEZDFILE)(TCHAR* strFileName);
LMC1_LOADEZDFILE lmc1_LoadEzdFile = (LMC1_LOADEZDFILE)GetProcAddress(hEzdDLL, "lmc1_LoadEzdFile");
//标刻当前数据库里的所有数据
//输入参数: bFlyMark = TRUE 使能飞动打标 bFlyMark = FALSE 使能飞动打标
typedef int(*LMC1_MARK)(BOOL bFlyMark);
LMC1_MARK lmc1_Mark = (LMC1_MARK)GetProcAddress(hEzdDLL, "lmc1_Mark");
//更改当前数据库里的指定文本对象的文本
//输入参数: strTextName 要更改内容的文本对象的名称
// strTextNew 新的文本内容
typedef int(*LMC1_CHANGETEXTBYNAME)(TCHAR* strTextName, TCHAR*strTextNew);
LMC1_CHANGETEXTBYNAME lmc1_ChangeTextByName = (LMC1_CHANGETEXTBYNAME)GetProcAddress(hEzdDLL, "lmc1_ChangeTextByName");
// 读lmc1的输入端口
//输入参数: 读入的输入端口的数据
typedef int(*LMC1_READPORT)(WORD& data);
LMC1_READPORT lmc1_ReadPort = (LMC1_READPORT)GetProcAddress(hEzdDLL, "lmc1_ReadPort");
typedef int(*LMC1_WRITEPORT)(WORD data);
LMC1_WRITEPORT lmc1_WritePort = (LMC1_WRITEPORT)GetProcAddress(hEzdDLL, "lmc1_WritePort");
//得到指定对象的最大最小坐标,如果pEntName==NULL表示读取数据库所有对象的最大最小坐标
typedef int(*LMC1_GETENTSIZE)(TCHAR* pEntName, double& dMinx, double& dMiny, double& dMaxx, double& dMaxy, double& dZ);
LMC1_GETENTSIZE lmc1_GetEntSize = (LMC1_GETENTSIZE)GetProcAddress(hEzdDLL, "lmc1_GetEntSize");
};
| [
"1015718001@qq.com"
] | 1015718001@qq.com |
46da55df2807b0a9ec8f9b6bb3c318b26a42bf01 | d20252afc53722c7a1dd2c95d03e2a58537fbbbd | /week02/D)Gravity/src/testApp.cpp | 369b8952e30271e21c41a93d4a0a24bd3d82a1c5 | [] | no_license | gusfaria/gus_algo2013 | d3a00ecf5daffcbb42fdc2f77e474401a5475d60 | 1ec470b019887251125b70a4179c9fbee3c27cde | refs/heads/master | 2021-01-10T19:41:24.331695 | 2014-04-09T18:37:33 | 2014-04-09T18:37:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,826 | cpp | #include "testApp.h"
//--------------------------------------------------------------
void testApp::setup(){
ofSetCircleResolution(60);
ofSetVerticalSync(true);
// gravity = 0.98f;
earthGravity = 9.8;
ofSeedRandom();
}
//--------------------------------------------------------------
void testApp::update(){
for (int i = 0; i < myElements.size(); i++) {
myElements[i].update();
}
}
//--------------------------------------------------------------
void testApp::draw(){
mousePos.set(mouseX,mouseY);
for (int i = 0; i < myElements.size(); i++) {
myElements[i].draw();
}
ofDrawBitmapString("ACTUAL GRAVITY : " + ofToString(gravity), ofPoint(10,15));
ofDrawBitmapString("PRESS E FOR EARTH'S GRAVITY", ofPoint(10,30));
ofDrawBitmapString("PRESS M FOR MOON'S GRAVITY", ofPoint(10,45));
ofDrawBitmapString("PRESS J FOR JUPITER'S GRAVITY", ofPoint(10,60));
}
//--------------------------------------------------------------
void testApp::keyPressed(int key){
// change color of each one based on their gravity ???
// if (key == 'e') {
// gravity = earthGravity;
// color = (0,0,255);
// } else if (key == 'j'){
// color = (255,0,0);
// gravity = 2.48*earthGravity;
// } else if (key == 'm'){
// color = (255);
// gravity = earthGravity/6;
// } else {
// gravity = earthGravity/6;
// }
switch (key) {
case 'e':
gravity = earthGravity;
ofSetColor(255, 0, 0);
break;
case 'j':
gravity = 2.48*earthGravity;
break;
case 'm':
gravity = earthGravity/6;
break;
default:
break;
}
}
//--------------------------------------------------------------
void testApp::keyReleased(int key){
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
Element newElement;
newElement.setup(mousePos, gravity, color);
myElements.push_back(newElement);
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void testApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void testApp::dragEvent(ofDragInfo dragInfo){
}
| [
"gusfaria11@gmail.com"
] | gusfaria11@gmail.com |
67ed925491a0dda3dea4aefe898f16c25e9fa448 | 360e04537b3a0215fad4bfc2e521d20877c9fa60 | /Graph Theory/Til the Cows Come Home(Dijkstra).cpp | 5b264f0687896b9959fc3848752e7fdc3d770ac2 | [] | no_license | Randool/Algorithm | 95a95b3b75b1ff2dc1edfa06bb7f4c286ee3d514 | a6c4fc3551efedebe3bfe5955c4744d7ff5ec032 | refs/heads/master | 2020-03-16T19:40:49.033078 | 2019-07-08T15:05:50 | 2019-07-08T15:05:50 | 132,927,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,283 | cpp | #include <cstdio>
#include <iostream>
#define MAXN 2005
#define INF 0x3f3f3f3f
using namespace std;
int t, n; //(2 <= N <= 1000) (1 <= T <= 2000)
int edge[MAXN][MAXN];
int dis[MAXN];
int book[MAXN];
int u, v;
void Init() {
for (int i=1; i<=n; i++) {
for (int j=1; j<=n; j++) {
if(i==j)
edge[i][j] = 0;
else
edge[i][j] = INF;
}
}
}
void Input() {
int x, y, v;
for (int i=0; i<t; i++) {
scanf("%d%d%d", &x, &y, &v);
if (v < edge[x][y])
edge[x][y] = edge[y][x] = v;
}
}
void dijkstra()
{
for (int i=1; i<=n; i++)
{
book[i] = 0;
dis[i] = edge[n][i];
}
int _min, tmp;
for (int i=1; i<=n; i++)
{
_min = INF;
for (int j=1; j<=n; j++)
{
if (!book[j] && dis[j] < _min)
{
_min = dis[j];
tmp = j;
}
}
book[tmp] = 1;
for (int j=1; j<=n; j++) {
if (!book[j])
dis[j] = min(dis[j], dis[tmp] + edge[tmp][j]);
}
}
}
int main() {
//freopen("in.txt", "r", stdin);
scanf("%d%d", &t, &n);
Init();
Input();
dijkstra();
printf("%d\n", dis[1]);
return 0;
}
| [
"dlf43@qq.com"
] | dlf43@qq.com |
357ec97933c120814884b9cf9935199e8959eeb2 | 49912f208ac9af1866366cd0156ab86703f55f97 | /Aplikacja/Solver/include/ISolver.hpp | 1c8c391bd6bc070ca73fb28c6d3e2c170fe3a18f | [] | no_license | MacAndKaj/Theory_and_Methods_of_Optimization | 4d2ce3b1751f94a67d0fd12a7df97231ca2e518d | 383ebc445f8865293869eea5f1e292aa870299f2 | refs/heads/master | 2022-01-06T14:15:32.501882 | 2019-05-27T20:36:10 | 2019-05-27T20:36:10 | 172,745,366 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 846 | hpp | //
// Created by maciek on 06.03.19.
//
#ifndef SOLVER_ISOLVER_HPP
#define SOLVER_ISOLVER_HPP
#include <string>
#include <functional>
#include <Definitions_and_Helpers/Definitions.hpp>
#include <Methods/IterationMethodsParameters.hpp>
class SSolution;
class SVector;
class FunctionInPointParameters;
class FunctionWrapper;
class ISolver
{
public:
virtual void setMethod(MethodType) = 0;
virtual void setStartingPoint(const SVector&) = 0;
virtual void setAlgorithmParameters(const IterationMethodsParameters&) = 0;
virtual void setFunction(const unsigned int&,const std::string&) = 0;
virtual bool computeSolution(const std::function<void(FunctionInPointParameters)>&) = 0;
virtual SSolution getSolution() const = 0;
virtual std::shared_ptr<FunctionWrapper> getFunction() const = 0;
};
#endif //SOLVER_ISOLVER_HPP
| [
"mkajdak@gmail.com"
] | mkajdak@gmail.com |
f6688b56c4d1bb06f432e7845efe4d82e07a9bf0 | f19d4a122b94a87d576d9dce484b09b1ecf7a482 | /Lab-0206/Lab-0206/linkedList.h | 48587a8467377d29edf6cc7d73e937db3c19f6df | [] | no_license | dusandjovanovic/Linked-lists-and-Doubly-linked-lists-implementation | 9758f0a17c5c3aab500374c816b3fdbab8ea85bd | 18453b4ad3fd9880ea7319ea357e21e5b63f5ca6 | refs/heads/master | 2021-03-24T11:08:27.125758 | 2017-09-19T19:09:16 | 2017-09-19T19:09:16 | 103,829,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,933 | h | #pragma once
#include <iostream>
using namespace std;
class Node {
public:
double info;
int next;
bool swapped = false;
public:
Node() {
next = 0;
}
Node(double newData) {
info = newData;
next = 0;
}
Node(double newData, int succesor) {
info = newData;
next = succesor;
}
~Node() {
next = 0;
}
double returnInfo() {
return info;
}
void changeNode(double newData) {
info = newData;
}
int getNext() {
return next;
}
void show() {
cout << info << " | ";
}
};
class linkedList {
protected:
int size = 0;
int head;
int tail;
int lrmp = 0;
Node* data = nullptr;
public:
linkedList() {
head = tail = 0;
}
linkedList(int length) {
size = length;
head = tail = 0;
lrmp = 1;
data = new Node[size + 1];
for (int i = 1; i < size; i++)
data[i].next = i + 1;
data[size].next = 0;
}
~linkedList() {
if (data != nullptr)
delete[] data;
}
bool isEmpty() {
return head == 0;
}
double deleteFromHead() {
if (head == 0)
throw new std::exception();
int tmp = head;
if (head == tail)
head = tail = 0;
else
head = data[head].next;
double toReturn = data[tmp].info;
data[tmp].next = lrmp;
lrmp = tmp;
return toReturn;
}
double deleteFromTail() {
if (head == 0)
throw new std::exception();
int tmp = tail;
if (head == tail)
head = tail = 0;
else {
}
double toReturn = data[tmp].info;
data[tmp].next = lrmp;
lrmp = tmp;
return toReturn;
}
void addToHead(double element) {
if (lrmp == 0)
return;
int tmp = lrmp;
lrmp = data[lrmp].next;
data[tmp].info = element;
data[tmp].next = head;
if (head == 0)
tail = head = tmp;
else {
head = tmp;
}
}
void addToTail(double element) {
if (lrmp == 0)
return;
int tmp = lrmp;
lrmp = data[lrmp].next;
data[tmp].info = element;
data[tmp].next = 0;
if (tail == 0)
tail = head = tmp;
else {
data[tail].next = tmp;
tail = tmp;
}
}
void showAll() {
int tmp = head;
while (tmp != 0) {
data[tmp].show();
tmp = data[tmp].next;
}
cout << endl;
}
void bubbleSort() {
int predecessor = NULL;
int tmp = head;
int succesor = data[head].next;
while (data[succesor].swapped != true) {
while (succesor != NULL) {
if (data[tmp].info > data[succesor].info) {
double backup = data[tmp].info;
data[tmp].info = data[succesor].info;
data[succesor].info = backup;
}
tmp = data[tmp].next;
succesor = data[succesor].next;
if (predecessor == NULL)
predecessor = head;
else
predecessor = data[predecessor].next;
if (succesor == NULL || data[succesor].swapped == true) {
data[tmp].swapped = true;
break;
}
}
showAll(); // debug after bubble-pass
cout << "head: " << data[head].info << " " << "tail: " << data[tail].info << endl;
predecessor = NULL;
tmp = head;
succesor = data[head].next;
}
}
}; | [
"dusandjovanovic@outlook.com"
] | dusandjovanovic@outlook.com |
0c8caa4614b99e00629f879a029efbc5eb5068ff | 82db5e6ad45ea6702e352070686145013469fd33 | /ventanaprincipal.h | 834bb080db1e0f936c7d8bd2a30c30baa5188e31 | [] | no_license | pacheevb/ED2016_Dracula | 734a9bc94b1f6ff36ac06c5774eaa65956467233 | 61ed2fe498fff5c86dfefeae87a5475a7c0d99ed | refs/heads/master | 2021-01-10T05:20:12.552973 | 2016-04-17T23:01:34 | 2016-04-17T23:01:34 | 55,922,145 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 387 | h | #ifndef VENTANAPRINCIPAL_H
#define VENTANAPRINCIPAL_H
#include <QMainWindow>
namespace Ui {
class VentanaPrincipal;
}
class VentanaPrincipal : public QMainWindow
{
Q_OBJECT
public:
explicit VentanaPrincipal(QWidget *parent = 0);
~VentanaPrincipal();
private:
Ui::VentanaPrincipal *ui;
private slots:
void on_bIniciar_clicked();
};
#endif // VENTANAPRINCIPAL_H
| [
"pacheevb@gmail.com"
] | pacheevb@gmail.com |
ba997c109d79a1fb35881344d57375ff699ba2d9 | 8d7e8f09b831c5888aab49c2fd5e15b9eaf6c4d1 | /KittyGames/M4.h | 0c9a9909e6233da114cad76b739f03c32c20d4d9 | [] | no_license | mta19/FV2018 | 235b36a7f815a30361bc1809c953da074d5e9bb0 | e572318be458ec2ed0cf7f1829bf047754d8bb56 | refs/heads/master | 2021-04-29T16:35:52.214996 | 2018-05-21T19:35:05 | 2018-05-21T19:35:05 | 121,651,949 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 549 | h | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: M4.h
* Author: pedro
*
* Created on 26 de abril de 2018, 18:24
*/
#ifndef M4_H
#define M4_H
#include "Weapon.h"
class M4 : public Weapon {
public:
M4(String nombre);
M4(const M4& orig);
virtual ~M4();
void setFixture(b2PolygonShape * forma, float density, float restitution, float friction);
private:
};
#endif /* M4_H */
| [
"excarline@gmail.com"
] | excarline@gmail.com |
2ce07e85a32f9e09a273fec281a98cbb97965554 | eb5d98c43e558fc559285c055fc1ac1f50e01538 | /QtXlsx_VS_example_wxb/QtXlsx_hello/ssw/main.cpp | 8f6774350666b9869c94a0aba831bb4bdca55e95 | [] | no_license | lanbing0107/since201807_code_wxb_FeiXingBao | 39ceec8cc0fad5a284383c5de1e936a199dd2383 | dbffa6035be62193353bda83ceb813c035a5d366 | refs/heads/master | 2020-03-25T15:21:33.538223 | 2018-08-09T13:25:27 | 2018-08-09T13:25:27 | 143,878,950 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 534 | cpp | #include "ssw.h"
#include <QtWidgets/QApplication>
#include <QtXlsx\xlsxdocument.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ssw w;
w.show();
////------------------------hello--------------------------------////
//![0]
QXlsx::Document xlsx("d:/wxb/ssw/test.xlsx");
//![0]
//![1]
xlsx.write("A1", "Hello Qt!");
xlsx.write("A2", 12345);
xlsx.write("A3", "=44+33");
xlsx.write("A4", true);
//![2]
xlsx.save();
//------------------------hello--------------------------------//
return a.exec();
}
| [
"lanbing0107@users.noreply.github.com"
] | lanbing0107@users.noreply.github.com |
18e6cc27a12df21dc0ef926410e281dd3d5fd300 | 2faf62f2e4cba079aa5b9e0903983b2c632fe72c | /earthquake.h | c7083b168d598db03185fcc700db76bff85f0f93 | [] | no_license | 15plus15Na/SIPO | 533d8e25c037c72070085cb588fd6df3fdc3bc67 | 4d765e260c8ece1a3a9af9a569deffdace118aa7 | refs/heads/master | 2020-03-10T21:07:48.321714 | 2018-10-12T13:48:16 | 2018-10-12T13:48:16 | 129,586,055 | 0 | 0 | null | 2018-10-12T13:02:03 | 2018-04-15T07:11:08 | null | UTF-8 | C++ | false | false | 1,189 | h | #ifndef EARTHQUAKE_H_INCLUDED
#define EARTHQUAKE_H_INCLUDED
#include<vector>
using namespace std;
class Earthquake
{
protected:
int earthquakeQuantity;
vector<unsigned> numberOfDefinitionPoints;
vector<float> magnitude;
vector<float> depth;
vector<float> probability;
vector<vector<float> > coordination;
vector<vector<float> > coordination_line_X;
vector<vector<float> > coordination_line_Y;
vector<vector<float> > distanceFromOrigin;
vector<vector<unsigned> > additionalDefinitionData;
bool isPointSource(unsigned);
bool isLineSource(unsigned);
void calculateLineEquationParameters(unsigned);
public:
vector<vector<float> > lineSlope;
bool isInAdditionalPointGap(unsigned, unsigned);
unsigned getNumberOfEarthquakes();
float getProbability(unsigned);
float getMaginitude(unsigned);
void getCoordination(unsigned, vector<float> &);
friend class WorldModel;
friend class Property;
};
inline unsigned Earthquake::getNumberOfEarthquakes()
{
return magnitude.size();
}
#endif // EARTHQUAKE_H_INCLUDED
| [
"sinanaeimi@YAHOO.COM"
] | sinanaeimi@YAHOO.COM |
03101ccf1a38161bb882c48e66581e229d1b0890 | 2b8b8034e0e902341a2191f8d14ad1173ad9b0ae | /lib/windows/KMenuWindow.h | e94321cc55fc07825b2460e515d23ca4398967b2 | [] | no_license | Frizlab/kodisein | 3a4e48d4448ba6290a95394c33adcdf0c3013f04 | 1aece4de5946930936745330ba68d1d7339715bc | refs/heads/master | 2022-06-03T19:52:37.473697 | 2021-03-25T19:43:54 | 2021-03-25T19:43:54 | 92,667,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,212 | h | /*
* KMenuWindow.h
* kodisein
*/
#ifndef __KMenuWindow
#define __KMenuWindow
#pragma warning(disable:4786)
#include "KWindow.h"
#include "KMenu.h"
#include "KNotificationObject.h"
enum { KDL_MENUWINDOW_FLAG_STATUS_RELEASING = KDL_WINDOW_FLAG_END,
KDL_MENUWINDOW_FLAG_STATUS_MOVING,
KDL_MENUWINDOW_FLAG_END };
class KMenuItem;
class KMenuWindow : public KWindow
{
INTROSPECTION
public:
KMenuWindow ();
virtual void addMenuItem ( KMenuItem * );
virtual void release ( const KMouseEvent & );
virtual bool mouseMotion ( const KMouseEvent & );
virtual void layout () { widget->layout(); }
KMenuItem * getItemWithCallback ( KCallbackPtr );
GLfloat getMenuHeight ()
{ return widget->getSpacing()+KDL_MENU_DEFAULT_ITEM_HEIGHT; }
virtual bool pick ( const KMouseEvent & );
// pickhandler notifications
virtual void unpicked ();
virtual bool shouldPick ( const KPickable * );
virtual void picked ();
virtual string getXML ( int = 0 ) const;
virtual void setXML ( string & );
};
#endif
| [
"monsterkodi@users.sourceforge.net"
] | monsterkodi@users.sourceforge.net |
93bc7cb6fc055b4f01a235a3f4856d7ebf1ae2d6 | a2b28ba3349304ccb01b10edd9378a446d13abe6 | /WorldSpawnerTool/external/pterrain/ptat/layer/affectors/AffectorHeightTerrace.h | 9177b6d1e66b84da01d01a1457f308092b3d0cd5 | [] | no_license | TheAnswer/Tools | 9bec3570be8023c262eb7b6b4271bccad2008c48 | 880a68f618290445dd770e1b52176083244768f3 | refs/heads/master | 2023-08-17T07:44:54.870503 | 2020-05-10T20:32:32 | 2020-05-23T17:55:51 | 9,735,112 | 5 | 18 | null | null | null | null | UTF-8 | C++ | false | false | 1,885 | h | /*
* AffectorHeightTerrace.h
*
* Created on: 31/01/2010
* Author: victor
*/
#ifndef AFFECTORHEIGHTTERRACE_H_
#define AFFECTORHEIGHTTERRACE_H_
#include "../ProceduralRule.h"
class AffectorHeightTerrace : public ProceduralRule<'AHTR'>, public AffectorProceduralRule {
float flatRatio;
float height;
public:
AffectorHeightTerrace() {
affectorType = HEIGHTTERRACE;
}
void parseFromIffStream(engine::util::IffStream* iffStream) {
uint32 version = iffStream->getNextFormType();
iffStream->openForm(version);
switch (version) {
case '0004':
parseFromIffStream(iffStream, Version<'0004'>());
break;
default:
System::out << "unknown AffectorHeightTerrace version 0x" << hex << version << endl;
break;
}
iffStream->closeForm(version);
}
void parseFromIffStream(engine::util::IffStream* iffStream, Version<'0004'>) {
informationHeader.readObject(iffStream);
iffStream->openChunk('DATA');
flatRatio = iffStream->getFloat();
height = iffStream->getFloat();
iffStream->closeChunk('DATA');
}
void process(float x, float y, float transformValue, float& baseValue, TerrainGenerator* terrainGenerator, TerrainChunk* chunk, int i, int j) {
if (transformValue == 0)
return;
if (chunk != NULL)
baseValue = chunk->getHeight(i, j);
if (height <= 0)
return;
//float var1 = height + height;
float var1 = fmod(baseValue, height);
if (baseValue == 0) {
var1 += height;
}
float var2 = baseValue - var1;
float var3 = height * flatRatio + var2;
float var4 = height + var2;
if (baseValue > var3) {
var2 = (baseValue - var3) / (var4 - var3) * (var4 - var2) + var2;
}
baseValue = (var2 - baseValue) * transformValue + baseValue;
if (chunk != NULL)
chunk->setHeight(i, j, baseValue);
}
bool isEnabled() {
return informationHeader.isEnabled();
}
};
#endif /* AFFECTORHEIGHTTERRACE_H_ */
| [
"TheAnswer@c3d1530f-68f5-4bd0-87dc-8ef779617e40"
] | TheAnswer@c3d1530f-68f5-4bd0-87dc-8ef779617e40 |
966ae547da1bf7103ccbee9ccf62dda2ff5f4b18 | ba844435c391549715aac012abe8a1c8a6723b40 | /Week_2/problem_2.cpp | af2b601e4c3f728a17c3cb4c7dc256a1f88bbe08 | [] | no_license | aviral10/DAA_Lab | 54a67fb7c6ea5c8b0ed0ae0a93427fd83d85ca6b | d5df242caeb29ed9a22596193363f495207a5128 | refs/heads/master | 2023-08-29T22:42:38.400349 | 2021-11-15T18:35:55 | 2021-11-15T18:35:55 | 385,945,448 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,375 | cpp | #include <bits/stdc++.h>
using namespace std;
// Find a squence of indices i < j < k in the sorted array such that arr[i]+arr[j]=arr[k].
// Time Complexity: O((n^2)logn), Space Complexity: O(1)
int binarySearch(vector<int> &arr, int low, int high, int key){
while(low<=high){
int mid = ((long long)low+high)/2;
if(arr[mid] == key) return mid;
else if(arr[mid] < key) low = mid+1;
else high = mid-1;
}
return -1;
}
int main(){
//
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
freopen("inp2.txt", "r", stdin);
freopen("out2.txt", "w", stdout);
//
int t;
cin >> t;
while(t--){
int n, key;
cin >> n;
vector<int> arr(n);
for(int i=0;i<n;i++){
cin >> arr[i];
}
bool bro = 0;
for(int i=0;i<n-2;i++){
for(int j=i+1;j<n-1;j++){
int key = arr[i]+arr[j];
int k = binarySearch(arr, j+1, n-1, key);
if(k != -1){
cout << i << ' ' << j << ' ' << k << ' ';
cout << " Elements: [" << arr[i] << ' ' << arr[j] << ' ' << arr[k] << "]\n";
bro = true;
break;
}
}if(bro) break;
}
if(!bro) cout << "No Sequence Found\n";
}
return 0;
}
| [
"aviral19rana@gmail.com"
] | aviral19rana@gmail.com |
c725c055c8a7dbc402996174c1aed0238b033e87 | 12327bc25f9b85d152efcbe0264976789a1891a5 | /SR300Camera.h | f49f5b4617ec3c83fce15ad74a76b0c5596fd676 | [
"Apache-2.0"
] | permissive | monajalal/OpenARK | 50898103523f2a5709e933e9f79fc9a37f56308e | 3550afe70d5026aab07b964b93cb9fd2f0d9a78a | refs/heads/master | 2021-01-25T09:14:23.911398 | 2017-06-12T20:22:44 | 2017-06-12T20:22:44 | 93,799,949 | 0 | 0 | null | 2017-06-08T23:28:52 | 2017-06-08T23:28:52 | null | UTF-8 | C++ | false | false | 2,253 | h | #pragma once
// C++ Libraries
#include<string.h>
// OpenCV Libraries
#include <opencv2/opencv.hpp>
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/video/tracking.hpp>
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/features2d/features2d.hpp>
// OpenARK Libraries
#include "DepthCamera.h"
#include "Converter.h"
//using namespace Intel::RealSense;
/**
* Class defining the behavior of an SR300 Camera.
* Example on how to read from sensor and visualize its output
* @include SensorIO.cpp
*/
class SR300Camera : public DepthCamera
{
public:
/**
* Public constructor initializing the SR300 Camera.
* @param use_live_sensor uses input from real sensor if TRUE. Otherwise reads from input file. Default is set to TRUE.
*/
SR300Camera(bool use_live_sensor = true);
/**
* Deconstructor for the SR300 Camera.
*/
~SR300Camera();
/**
* Gets new frame from sensor.
* Updates xyzMap, ampMap, and flagMap. Resets clusters.
*/
void update();
/**
* Gracefully closes the SR300 camera.
*/
void destroyInstance();
private:
/**
* Getter method for the x-coordinate at (i,j).
* @param i ith row
* @param j jth column
* @return x-coodinate at (i,j)
*/
float getX(int i, int j) const;
/**
* Getter method for the x-coordinate at (i,j).
* @param i ith row
* @param j jth column
* @return x-coodinate at (i,j)
*/
float getY(int i, int j) const;
/**
* Getter method for the x-coordinate at (i,j).
* @param i ith row
* @param j jth column
* @return x-coodinate at (i,j)
*/
float getZ(int i, int j) const;
/**
* Update the z-coordinates of the xyzMap.
*/
void fillInZCoords();
/**
* Update the values in the ampMap.
*/
void fillInAmps();
//Private Variables
float* dists;
float* amps;
cv::Mat frame;
const int depth_fps = 30;
int depth_width;
int depth_height;
cv::Size bufferSize;
const Intel::RealSense::Sample *sample;
Intel::RealSense::SenseManager *sm = Intel::RealSense::SenseManager::CreateInstance();
Intel::RealSense::Session *session = sm->QuerySession();
Intel::RealSense::Device *device;
Intel::RealSense::CaptureManager *cm;
}; | [
"jalal@cs.wisc.edu"
] | jalal@cs.wisc.edu |
c8a91e38349ab1017d2b65d8dc6281439dcb0a6b | e4c5fc6441d9419f8391acc753718c1f37c81989 | /Snake/SnakeGame.cpp | 30b0d299948aeff3ff03f3013d913d30acfa010f | [] | no_license | Madsy/GameAutomata | 056d9a0b760150537defb4707727050d70728658 | e32f0442f3238c6110a39dff509244dbec2d60be | refs/heads/master | 2016-08-06T03:03:46.396841 | 2012-11-25T14:31:24 | 2012-11-25T14:31:24 | 6,806,076 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,741 | cpp | #include <fstream>
#include <iostream>
#include "shared/SnakeGame.hpp"
bool snakeInitLevel(const std::string& levelFile, SnakeGameInfo& state)
{
std::ifstream strm(levelFile.c_str());
if(!strm.is_open()) return false;
std::string line;
while(std::getline(strm, line)){
state.level.push_back(line);
}
state.levelWidth = state.level[0].length();
state.levelHeight = state.level.size();
return true;
}
void snakeInitSnakes(SnakeGameInfo& state, int playerCount)
{
/* IsCellClear checks whether the rpart position collides with
other snakes, so init state.snakes[i].parts[j] to be outside the map bounds to avoid this. */
Point point_outside_map(-1, -1);
SnakeInfo tmpSnake;
std::vector<Point> tmpParts;
state.playerCount = playerCount;
state.currentPlayer = 0;
/* TODO: Fix so that we can have longer snakes at the beginning of the level.
Currently we start with snakes of 1 in length. We rather want three-celled snakes. */
tmpParts.push_back(point_outside_map);
//tmpParts.push(point_outside_map);
//tmpParts.push(point_outside_map);
tmpSnake.bodyParts = tmpParts;
tmpSnake.alive = true;
/* Whenever growCount > 0, we move the snake body without updating the tail,
and decrement growCount accordingly. */
tmpSnake.growCount = 0;
state.snakes.resize(playerCount);
/* Initialize all snakes to be outside the map */
for(int eachSnake = 0; eachSnake < playerCount; ++eachSnake)
state.snakes[eachSnake] = tmpSnake;
for(int eachSnake = 0; eachSnake < playerCount; ++eachSnake){
Point rpart;
do {
rpart = randPoint(0, state.levelWidth - 1, 0, state.levelHeight - 1);
} while(!snakeIsCellClear(rpart.x, rpart.y, -1, state));
state.snakes[eachSnake].bodyParts[0] = rpart;
}
}
void snakeInitFood(SnakeGameInfo& state)
{
Point point_outside_map(-1, -1);
Point rfood;
/* SnakeIsCellClear checks if the rfood position collides with
state.foodPosition, so init state.foodPosition outside the map bounds to avoid that. */
state.foodPosition = point_outside_map;
do {
rfood = randPoint(0, state.levelWidth, 0, state.levelHeight);
} while(!snakeIsCellClear(rfood.x, rfood.y, -1, state));
state.foodPosition = rfood;
}
/* Called only if the snake doesn't collide with anything */
void snakeUpdateSnake(SnakeInfo& snake, Direction direction)
{
Point head = snake.bodyParts[0];
if(snakeIsSnakeGrowing(snake)){
snake.bodyParts.push_back(Point());
--snake.growCount;
}
/* body[i] = body[i-1], i.e the previous head becomes a part of the body */
for(int eachBody = snake.bodyParts.size() - 1; eachBody > 0; --eachBody){
/* <1>23456 => <1>12345 => <0>12345*/
snake.bodyParts[eachBody] = snake.bodyParts[eachBody - 1];
}
snake.bodyParts[0] = snakeComputeNewHead(head, direction);
}
void snakeUpdateFood(SnakeGameInfo& state)
{
Point point_outside_map(-1, -1);
Point rfood;
state.foodPosition = point_outside_map;
do {
rfood = randPoint(0, state.levelWidth, 0, state.levelHeight);
} while(!snakeIsCellClear(rfood.x, rfood.y, -1, state));
state.foodPosition = rfood;
}
/* Returns the winning player id */
int snakeGameTick(SnakeGameInfo& state, const std::vector<Direction>& input)
{
int aliveCount = 0;
int winnerSnake = 0;
/* Kill snakes with illegal input */
for(int eachSnake = 0; eachSnake < (int)state.snakes.size(); ++eachSnake){
if(input[eachSnake] == IllegalDirection)
state.snakes[eachSnake].alive = false;
}
/* Update to new positions */
for(int eachSnake = 0; eachSnake < (int)state.snakes.size(); ++eachSnake){
if(state.snakes[eachSnake].alive){
snakeUpdateSnake(state.snakes[eachSnake], input[eachSnake]);
}
}
/* With the new positions, cull out any dead snakes that collided */
for(int eachSnake = 0; eachSnake < (int)state.snakes.size(); ++eachSnake){
if(state.snakes[eachSnake].alive){
Point head = state.snakes[eachSnake].bodyParts[0];
state.snakes[eachSnake].alive = snakeIsCellClear(head.x, head.y, eachSnake, state);
++aliveCount;
winnerSnake = eachSnake;
}
}
/* Now only the alive updated snakes are left. Check for winners, and if someone grabbed the food. */
if(aliveCount == 1) return winnerSnake + 1;
else if(aliveCount == 0) return 0; /* 0 == draw */
for(int eachSnake = 0; eachSnake < (int)state.snakes.size(); ++eachSnake){
if(state.snakes[eachSnake].alive){
Point head = state.snakes[eachSnake].bodyParts[0];
/* Food makes the snake tail grow for 'growCount' turns */
if(snakeIsCellFood(head.x, head.y, state.foodPosition)){
state.snakes[eachSnake].growCount += 3;
snakeUpdateFood(state);
}
}
}
return -1; /* -1 = continue */
}
| [
"mads@mechcore.net"
] | mads@mechcore.net |
dc5614ca779ad404aecc5e35451c837ae4818e24 | 0964ea272332be97654aa5f5eaa57ce021c7d24d | /glfw-application/src/vertexarray.cpp | e6ee240163251e380ede809693994a5eaf8ea977 | [] | no_license | tdgroot/glfw-application | 4cf6809f1625dd0d8dabba3a55506b5dc96df2ec | 9e87f5f2095883aa9d84fd6d14d1542a28ab1f8d | refs/heads/master | 2020-05-07T09:18:05.066167 | 2019-04-11T18:15:59 | 2019-04-11T18:15:59 | 180,371,554 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 861 | cpp | #include "vertexarray.h"
VertexArray::VertexArray()
{
glGenVertexArrays(1, &renderer_id);
glBindVertexArray(renderer_id);
}
VertexArray::~VertexArray()
{
glDeleteVertexArrays(1, &renderer_id);
}
void VertexArray::add_buffer(const VertexBuffer& vb, const VertexBufferLayout& layout)
{
bind();
vb.bind();
const auto& elements = layout.get_elements();
unsigned int offset = 0;
for (unsigned int i = 0; i < elements.size(); i++)
{
const auto& element = elements[i];
glEnableVertexAttribArray(i);
glVertexAttribPointer(i, element.count, element.type,
element.normalized, layout.get_stride(), (const void*)offset);
offset += element.count * VertexBufferElement::get_size_of_type(element.type);
}
vb.unbind();
}
void VertexArray::bind() const
{
glBindVertexArray(renderer_id);
}
void VertexArray::unbind() const
{
glBindVertexArray(0);
} | [
"tdegroot96@gmail.com"
] | tdegroot96@gmail.com |
a559600e08a0bc7e12fba84c5bf82804333d8f0f | b7e0b20cb72fef568d2d114c806e150953a5866c | /C/groupe_aleatoire/groupe_aléatoire/groupe_aléatoire/groupe_aléatoire.cpp | b6838a3bc41b16175d9789a5d102e3baefa89387 | [] | no_license | PierroootEL/dev_irup | 4eb43420de4a1b4c56b2926d67f86b1edd5e04fb | 774e8f506bc4d11e6ad8a47d52e9092e09726575 | refs/heads/main | 2023-08-05T09:42:46.675957 | 2021-09-21T17:09:05 | 2021-09-21T17:09:05 | 408,889,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,828 | cpp | // groupe_aléatoire.cpp : Ce fichier contient la fonction 'main'. L'exécution du programme commence et se termine à cet endroit.
//
#include <iostream>
#include <time.h>
int main()
{
int are_ok[12] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
const char *eleves[12];
eleves[0] = "Pierre";
eleves[1] = "Louis";
eleves[2] = "Evan";
eleves[3] = "Thibault";
eleves[4] = "Esteban";
eleves[5] = "Julien";
eleves[6] = "Enzo";
eleves[7] = "Jerem";
eleves[8] = "Théo";
eleves[9] = "Fredo";
eleves[10] = "Jeremy";
eleves[11] = "Rayanne";
while (true) {
int eleve1 = 0;
int eleve2 = 0;
while (are_ok[eleve1] != 1) {
srand(time(NULL));
eleve1 = rand() % 12;
}
while (eleve1 == eleve2 && are_ok[eleve2] != 1) {
srand(time(NULL));
eleve2 = rand() % 12;
}
printf("%d \n %d", eleve1, eleve2);
printf("%s est en groupe avec %s \n", eleves[eleve1], eleves[eleve2]);
are_ok[eleve1] = 0;
are_ok[eleve2] = 0;
}
return 0;
}
// Exécuter le programme : Ctrl+F5 ou menu Déboguer > Exécuter sans débogage
// Déboguer le programme : F5 ou menu Déboguer > Démarrer le débogage
// Astuces pour bien démarrer :
// 1. Utilisez la fenêtre Explorateur de solutions pour ajouter des fichiers et les gérer.
// 2. Utilisez la fenêtre Team Explorer pour vous connecter au contrôle de code source.
// 3. Utilisez la fenêtre Sortie pour voir la sortie de la génération et d'autres messages.
// 4. Utilisez la fenêtre Liste d'erreurs pour voir les erreurs.
// 5. Accédez à Projet > Ajouter un nouvel élément pour créer des fichiers de code, ou à Projet > Ajouter un élément existant pour ajouter des fichiers de code existants au projet.
// 6. Pour rouvrir ce projet plus tard, accédez à Fichier > Ouvrir > Projet et sélectionnez le fichier .sln.
| [
"blanchardpierre03@gmail.com"
] | blanchardpierre03@gmail.com |
af8b00d0dc63a76c2785a18348c13335a8f05350 | 4f50e1cbf68d906156421f1e2efdf1999020aa51 | /evennumberedexercise/Exercise12_08.cpp | 74dee3cb60a5c62c05b41fd891834224d80f03c4 | [] | no_license | Mohammad-Abudaf/intro-to-cpp-solu | c186d90f72ed851a9f50e8d969c9857a9f430286 | a092aa6ed269cb8988f4fc2ccc699730982d9456 | refs/heads/master | 2023-03-09T23:02:48.764102 | 2021-02-26T16:26:30 | 2021-02-26T16:26:30 | 308,122,623 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,453 | cpp | #include <iostream>
using namespace std;
template<typename T>
class MyVector
{
public:
MyVector();
void push_back(T element);
void pop_back();
unsigned int size();
bool empty();
T at(int index);
void clear();
void swap(MyVector v2);
private:
T elements[100];
int vectorSize;
};
template<typename T>
MyVector<T>::MyVector()
{
vectorSize = 0;
}
template<typename T>
bool MyVector<T>::empty()
{
return (vectorSize == 0);
}
template<typename T>
T MyVector<T>::at(int index)
{
return elements[index];
}
template<typename T>
void MyVector<T>::push_back(T value)
{
elements[vectorSize++] = value;
}
template<typename T>
void MyVector<T>::pop_back()
{
return elements[--vectorSize];
}
template<typename T>
unsigned int MyVector<T>::size()
{
return vectorSize;
}
template<typename T>
void MyVector<T>::clear()
{
vectorSize = 0;
}
template<typename T>
void MyVector<T>::swap(MyVector v2)
{
T temp[100];
int tempSize = v2.size();
for (int i = 0; i < v2.size(); i++)
temp[i] = v2.at(i);
v2.clear();
for (int i = 0; i < size(); i++)
v2.push_back(at(i));
clear();
for (int i = 0; i < tempSize; i++)
push_back(temp[i]);
}
int main()
{
MyVector<int> v1;
v1.push_back(1);
v1.push_back(2);
MyVector<int> v2;
v2.push_back(3);
v2.push_back(4);
v2.push_back(5);
v2.push_back(6);
v2.push_back(7);
v1.swap(v2);
for (int i = 0; i < v1.size(); i++)
cout << v1.at(i) << " ";
}
| [
"mohammad_abudaf@hotmail.com"
] | mohammad_abudaf@hotmail.com |
509ac0a9d070a6a231a20a8049e4eddbf28e0b94 | 6fe8ea820bbaba79ad55a4d2c680ddea7f9b9a46 | /src/masternodeconfig.h | 912c4e8ded9ce00cabcbb6518b4862941ab1c65f | [
"MIT"
] | permissive | Evydder/zeroonecoin | 748ccfb0b29c79d559ee9e43c173fdeb7192fb29 | ce0d7ff3c581ffd0f471001be768eb9bed2ee22e | refs/heads/master | 2020-03-11T04:03:49.145681 | 2018-02-10T09:54:06 | 2018-02-10T09:54:06 | 127,297,104 | 0 | 0 | MIT | 2018-03-29T13:40:27 | 2018-03-29T13:40:27 | null | UTF-8 | C++ | false | false | 2,357 | h | // Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017-2018 The ZeroOne Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef SRC_MASTERNODECONFIG_H_
#define SRC_MASTERNODECONFIG_H_
class CMasternodeConfig;
extern CMasternodeConfig masternodeConfig;
class CMasternodeConfig
{
public:
class CMasternodeEntry {
private:
std::string alias;
std::string ip;
std::string privKey;
std::string txHash;
std::string outputIndex;
public:
CMasternodeEntry(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex) {
this->alias = alias;
this->ip = ip;
this->privKey = privKey;
this->txHash = txHash;
this->outputIndex = outputIndex;
}
const std::string& getAlias() const {
return alias;
}
void setAlias(const std::string& alias) {
this->alias = alias;
}
const std::string& getOutputIndex() const {
return outputIndex;
}
void setOutputIndex(const std::string& outputIndex) {
this->outputIndex = outputIndex;
}
const std::string& getPrivKey() const {
return privKey;
}
void setPrivKey(const std::string& privKey) {
this->privKey = privKey;
}
const std::string& getTxHash() const {
return txHash;
}
void setTxHash(const std::string& txHash) {
this->txHash = txHash;
}
const std::string& getIp() const {
return ip;
}
void setIp(const std::string& ip) {
this->ip = ip;
}
};
CMasternodeConfig() {
entries = std::vector<CMasternodeEntry>();
}
void clear();
bool read(std::string& strErr);
void add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex);
std::vector<CMasternodeEntry>& getEntries() {
return entries;
}
int getCount() {
return (int)entries.size();
}
private:
std::vector<CMasternodeEntry> entries;
};
#endif /* SRC_MASTERNODECONFIG_H_ */
| [
"zeroonecoin@yandex.ru"
] | zeroonecoin@yandex.ru |
b40eab2b74dcb79387fced8f69412be48173e287 | 2b9531d5794de05d3762958befd06d25ef6c5332 | /Assignment12/Common/shaderProgram.cpp | f28e44892b03851f2e0e44ae750a281b27585627 | [] | no_license | nestharusEDU/cs480Solomon | 0f9588483bc1d5b2dd0350c4620a2edae2c12f4a | e1090142490b34fb5c5e9f69088fc805149c5ac2 | refs/heads/master | 2016-09-05T13:24:32.514673 | 2014-12-17T14:24:17 | 2014-12-17T14:24:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,578 | cpp | #include <iostream>
#include "shaderProgram.h"
using std::string;
using std::cout;
using std::cerr;
using std::endl;
// Constructor
ShaderProgram::ShaderProgram()
{
// Generate a unique Id / handle for the shader program
// Note: We MUST have a valid rendering context before generating
// the programId or it causes a segfault!
programId = glCreateProgram();
// Initially, we have zero shaders attached to the program
shaderCount = 0;
linked = false;
} //ShaderProgram
// Destructor
ShaderProgram::~ShaderProgram()
{
// Delete the shader program from the graphics card memory to
// free all the resources it's been using
glDeleteProgram(programId);
} //~ShaderProgram
bool ShaderProgram::getBoolParameter(GLenum pname)
{
GLint ret;
glGetProgramiv(programId, pname, &ret);
return ret == GL_TRUE;
} //getBoolParameter
GLint ShaderProgram::getIntParameter(GLenum pname)
{
GLint ret;
glGetProgramiv(programId, pname, &ret);
return ret;
} //getIntParameter
// Method to attach a shader to the shader program
void ShaderProgram::attachShader(Shader& shader)
{
if (linked)
{
return;
} //if
// Attach the shader to the program
// Note: We identify the shader by its unique Id value
glAttachShader(programId, shader.getId());
// Increment the number of shaders we have associated with the program
++shaderCount;
} //attachShader
bool ShaderProgram::validate()
{
if (!linked)
{
return false;
} //if
bool validated = isValidated();
if (!validated)
{
GLint infoLogLength = getInfoLogLength();
GLchar* strInfoLog = new GLchar[infoLogLength + 1];
glGetShaderInfoLog(programId, infoLogLength, NULL, strInfoLog);
cerr << "Invalid shader program: " << strInfoLog << endl;
delete[] strInfoLog;
} //if
return validated;
} //validate
// Method to link the shader program and display the link status
bool ShaderProgram::link()
{
if (linked)
{
return false;
} //if
// If we have at least two shaders (like a vertex shader and a fragment shader)...
if (shaderCount > 1)
{
// Perform the linking process
glLinkProgram(programId);
// Check the status
GLint linkStatus;
glGetProgramiv(programId, GL_LINK_STATUS, &linkStatus);
if (GL_LINK_STATUS == GL_FALSE)
{
cerr << "Shader program linking failed." << endl;
linked = false;
} //if
else
{
cout << "Shader program linking OK." << endl;
linked = true;
} //else
} //if
else
{
cerr << "Can't link shaders - you need at least 2, but attached shader count is only: " << shaderCount << endl;
linked = false;
} //else
return linked;
} //link | [
"mrasolomon@gmail.com"
] | mrasolomon@gmail.com |
18f6599667d20157452d8cae8525625969fb81c5 | e05ee73f59fa33c462743b30cbc5d35263383e89 | /sparse/src/cpqmr.cpp | 459ee917211040176eaba8d134a944e0fed7477d | [] | no_license | bhrnjica/magma | 33c9e8a89f9bc2352f70867a48ec2dab7f94a984 | 88c8ca1a668055859a1cb9a31a204b702b688df5 | refs/heads/master | 2021-10-09T18:49:50.396412 | 2019-01-02T13:51:33 | 2019-01-02T13:51:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,108 | cpp | /*
-- MAGMA (version 2.4.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date June 2018
@author Hartwig Anzt
@generated from sparse/src/zpqmr.cpp, normal z -> c, Mon Jun 25 18:24:30 2018
*/
#include "magmasparse_internal.h"
#define RTOLERANCE lapackf77_slamch( "E" )
#define ATOLERANCE lapackf77_slamch( "E" )
/**
Purpose
-------
Solves a system of linear equations
A * X = B
where A is a general complex matrix A.
This is a GPU implementation of the preconditioned
Quasi-Minimal Residual method (QMR).
Arguments
---------
@param[in]
A magma_c_matrix
input matrix A
@param[in]
b magma_c_matrix
RHS b
@param[in,out]
x magma_c_matrix*
solution approximation
@param[in,out]
solver_par magma_c_solver_par*
solver parameters
@param[in]
precond_par magma_c_preconditioner*
preconditioner
@param[in]
queue magma_queue_t
Queue to execute in.
@ingroup magmasparse_cgesv
********************************************************************/
extern "C" magma_int_t
magma_cpqmr(
magma_c_matrix A, magma_c_matrix b, magma_c_matrix *x,
magma_c_solver_par *solver_par,
magma_c_preconditioner *precond_par,
magma_queue_t queue )
{
magma_int_t info = MAGMA_NOTCONVERGED;
// prepare solver feedback
solver_par->solver = Magma_QMR;
solver_par->numiter = 0;
solver_par->spmv_count = 0;
// local variables
magmaFloatComplex c_zero = MAGMA_C_ZERO, c_one = MAGMA_C_ONE;
// solver variables
float nom0, r0, res=0.0, nomb;
magmaFloatComplex rho = c_one, rho1 = c_one, eta = -c_one , pds = c_one,
thet = c_one, thet1 = c_one, epsilon = c_one,
beta = c_one, delta = c_one, pde = c_one, rde = c_one,
gamm = c_one, gamm1 = c_one, psi = c_one;
magma_int_t dofs = A.num_rows* b.num_cols;
// need to transpose the matrix
magma_c_matrix AT={Magma_CSR}, Ah1={Magma_CSR}, Ah2={Magma_CSR};
// GPU workspace
magma_c_matrix r={Magma_CSR}, r_tld={Magma_CSR},
v={Magma_CSR}, w={Magma_CSR}, wt={Magma_CSR},
d={Magma_CSR}, s={Magma_CSR}, z={Magma_CSR}, q={Magma_CSR},
p={Magma_CSR}, pt={Magma_CSR}, y={Magma_CSR},
vt={Magma_CSR}, yt={Magma_CSR}, zt={Magma_CSR};
CHECK( magma_cvinit( &r, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_cvinit( &r_tld, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_cvinit( &v, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_cvinit( &w, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_cvinit( &wt,Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_cvinit( &d, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_cvinit( &s, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_cvinit( &z, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_cvinit( &q, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_cvinit( &p, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_cvinit( &pt,Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_cvinit( &y, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_cvinit( &yt, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_cvinit( &vt, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
CHECK( magma_cvinit( &zt, Magma_DEV, A.num_rows, b.num_cols, c_zero, queue ));
// solver setup
CHECK( magma_cresidualvec( A, b, *x, &r, &nom0, queue));
solver_par->init_res = nom0;
magma_ccopy( dofs, r.dval, 1, r_tld.dval, 1, queue );
magma_ccopy( dofs, r.dval, 1, vt.dval, 1, queue );
magma_ccopy( dofs, r.dval, 1, wt.dval, 1, queue );
// transpose the matrix
magma_cmtransfer( A, &Ah1, Magma_DEV, Magma_CPU, queue );
magma_cmconvert( Ah1, &Ah2, A.storage_type, Magma_CSR, queue );
magma_cmfree(&Ah1, queue );
magma_cmtransposeconjugate( Ah2, &Ah1, queue );
magma_cmfree(&Ah2, queue );
Ah2.blocksize = A.blocksize;
Ah2.alignment = A.alignment;
magma_cmconvert( Ah1, &Ah2, Magma_CSR, A.storage_type, queue );
magma_cmfree(&Ah1, queue );
magma_cmtransfer( Ah2, &AT, Magma_CPU, Magma_DEV, queue );
magma_cmfree(&Ah2, queue );
nomb = magma_scnrm2( dofs, b.dval, 1, queue );
if ( nomb == 0.0 ){
nomb=1.0;
}
if ( (r0 = nomb * solver_par->rtol) < ATOLERANCE ){
r0 = ATOLERANCE;
}
solver_par->final_res = solver_par->init_res;
solver_par->iter_res = solver_par->init_res;
if ( solver_par->verbose > 0 ) {
solver_par->res_vec[0] = (real_Double_t)nom0;
solver_par->timing[0] = 0.0;
}
if ( nom0 < r0 ) {
info = MAGMA_SUCCESS;
goto cleanup;
}
// no precond: y = vt, z = wt
// magma_ccopy( dofs, vt.dval, 1, y.dval, 1, queue );
// magma_ccopy( dofs, wt.dval, 1, z.dval, 1, queue );
CHECK( magma_c_applyprecond_left( MagmaNoTrans, A, vt, &y, precond_par, queue ));
CHECK( magma_c_applyprecond_right( MagmaTrans, A, wt, &z, precond_par, queue ));
psi = magma_csqrt( magma_cdotc( dofs, z.dval, 1, z.dval, 1, queue ));
rho = magma_csqrt( magma_cdotc( dofs, y.dval, 1, y.dval, 1, queue ));
// v = vt / rho
// y = y / rho
// w = wt / psi
// z = z / psi
magma_ccopy( dofs, vt.dval, 1, v.dval, 1, queue );
magma_ccopy( dofs, wt.dval, 1, w.dval, 1, queue );
magma_cscal( dofs, c_one / rho, v.dval, 1, queue );
magma_cscal( dofs, c_one / rho, y.dval, 1, queue );
magma_cscal( dofs, c_one / psi, w.dval, 1, queue );
magma_cscal( dofs, c_one / psi, z.dval, 1, queue );
//Chronometry
real_Double_t tempo1, tempo2;
tempo1 = magma_sync_wtime( queue );
solver_par->numiter = 0;
// start iteration
do
{
solver_par->numiter++;
if( magma_c_isnan_inf( rho ) || magma_c_isnan_inf( psi ) ){
info = MAGMA_DIVERGENCE;
break;
}
// delta = z' * y;
delta = magma_cdotc( dofs, z.dval, 1, y.dval, 1, queue );
if( magma_c_isnan_inf( delta ) ){
info = MAGMA_DIVERGENCE;
break;
}
// no precond: yt = y, zt = z
// magma_ccopy( dofs, y.dval, 1, yt.dval, 1, queue );
// magma_ccopy( dofs, z.dval, 1, zt.dval, 1, queue );
CHECK( magma_c_applyprecond_right( MagmaNoTrans, A, y, &yt, precond_par, queue ));
CHECK( magma_c_applyprecond_left( MagmaTrans, A, z, &zt, precond_par, queue ));
if( solver_par->numiter == 1 ){
// p = y;
// q = z;
magma_ccopy( dofs, yt.dval, 1, p.dval, 1, queue );
magma_ccopy( dofs, zt.dval, 1, q.dval, 1, queue );
}
else{
pde = psi * delta / epsilon;
rde = rho * MAGMA_C_CONJ(delta/epsilon);
// p = yt - pde * p;
magma_cscal( dofs, -pde, p.dval, 1, queue );
magma_caxpy( dofs, c_one, yt.dval, 1, p.dval, 1, queue );
// q = zt - rde * q;
magma_cscal( dofs, -rde, q.dval, 1, queue );
magma_caxpy( dofs, c_one, zt.dval, 1, q.dval, 1, queue );
}
if( magma_c_isnan_inf( rho ) || magma_c_isnan_inf( psi ) ){
info = MAGMA_DIVERGENCE;
break;
}
CHECK( magma_c_spmv( c_one, A, p, c_zero, pt, queue ));
solver_par->spmv_count++;
// epsilon = q' * pt;
epsilon = magma_cdotc( dofs, q.dval, 1, pt.dval, 1, queue );
beta = epsilon / delta;
if( magma_c_isnan_inf( epsilon ) || magma_c_isnan_inf( beta ) ){
info = MAGMA_DIVERGENCE;
break;
}
// vt = pt - beta * v;
magma_ccopy( dofs, v.dval, 1, vt.dval, 1, queue );
magma_cscal( dofs, -beta, vt.dval, 1, queue );
magma_caxpy( dofs, c_one, pt.dval, 1, vt.dval, 1, queue );
// no precond: y = v
//magma_ccopy( dofs, v.dval, 1, y.dval, 1, queue );
// wt = A' * q - beta' * w;
CHECK( magma_c_spmv( c_one, AT, q, c_zero, wt, queue ));
solver_par->spmv_count++;
magma_caxpy( dofs, - MAGMA_C_CONJ( beta ), w.dval, 1, wt.dval, 1, queue );
// no precond: z = wt
// magma_ccopy( dofs, wt.dval, 1, z.dval, 1, queue );
CHECK( magma_c_applyprecond_right( MagmaTrans, A, wt, &z, precond_par, queue ));
CHECK( magma_c_applyprecond_left( MagmaNoTrans, A, vt, &y, precond_par, queue ));
rho1 = rho;
// rho = norm(y);
rho = magma_csqrt( magma_cdotc( dofs, y.dval, 1, y.dval, 1, queue ));
thet1 = thet;
thet = rho / (gamm * MAGMA_C_MAKE( MAGMA_C_ABS(beta), 0.0 ));
gamm1 = gamm;
gamm = c_one / magma_csqrt(c_one + thet*thet);
eta = - eta * rho1 * gamm * gamm / (beta * gamm1 * gamm1);
if( magma_c_isnan_inf( thet ) || magma_c_isnan_inf( gamm ) || magma_c_isnan_inf( eta ) ){
info = MAGMA_DIVERGENCE;
break;
}
if( solver_par->numiter == 1 ){
// d = eta * p;
// s = eta * pt;
magma_ccopy( dofs, p.dval, 1, d.dval, 1, queue );
magma_cscal( dofs, eta, d.dval, 1, queue );
magma_ccopy( dofs, pt.dval, 1, s.dval, 1, queue );
magma_cscal( dofs, eta, s.dval, 1, queue );
// x = x + d;
magma_caxpy( dofs, c_one, d.dval, 1, x->dval, 1, queue );
// r = r - s;
magma_caxpy( dofs, -c_one, s.dval, 1, r.dval, 1, queue );
}
else{
// d = eta * p + (thet1 * gamm)^2 * d;
// s = eta * pt + (thet1 * gamm)^2 * s;
pds = (thet1 * gamm) * (thet1 * gamm);
magma_cscal( dofs, pds, d.dval, 1, queue );
magma_caxpy( dofs, eta, p.dval, 1, d.dval, 1, queue );
magma_cscal( dofs, pds, s.dval, 1, queue );
magma_caxpy( dofs, eta, pt.dval, 1, s.dval, 1, queue );
// x = x + d;
magma_caxpy( dofs, c_one, d.dval, 1, x->dval, 1, queue );
// r = r - s;
magma_caxpy( dofs, -c_one, s.dval, 1, r.dval, 1, queue );
}
// psi = norm(z);
psi = magma_csqrt( magma_cdotc( dofs, z.dval, 1, z.dval, 1, queue ) );
res = magma_scnrm2( dofs, r.dval, 1, queue );
if ( solver_par->verbose > 0 ) {
tempo2 = magma_sync_wtime( queue );
if ( (solver_par->numiter)%solver_par->verbose == c_zero ) {
solver_par->res_vec[(solver_par->numiter)/solver_par->verbose]
= (real_Double_t) res;
solver_par->timing[(solver_par->numiter)/solver_par->verbose]
= (real_Double_t) tempo2-tempo1;
}
}
// v = y / rho
// y = y / rho
// w = wt / psi
// z = z / psi
magma_cqmr_8(
r.num_rows,
r.num_cols,
rho,
psi,
vt.dval,
wt.dval,
y.dval,
z.dval,
v.dval,
w.dval,
queue );
if ( res/nomb <= solver_par->rtol || res <= solver_par->atol ){
break;
}
}
while ( solver_par->numiter+1 <= solver_par->maxiter );
tempo2 = magma_sync_wtime( queue );
solver_par->runtime = (real_Double_t) tempo2-tempo1;
float residual;
CHECK( magma_cresidualvec( A, b, *x, &r, &residual, queue));
solver_par->iter_res = res;
solver_par->final_res = residual;
if ( solver_par->numiter < solver_par->maxiter && info == MAGMA_SUCCESS ) {
info = MAGMA_SUCCESS;
} else if ( solver_par->init_res > solver_par->final_res ) {
if ( solver_par->verbose > 0 ) {
if ( (solver_par->numiter)%solver_par->verbose == c_zero ) {
solver_par->res_vec[(solver_par->numiter)/solver_par->verbose]
= (real_Double_t) res;
solver_par->timing[(solver_par->numiter)/solver_par->verbose]
= (real_Double_t) tempo2-tempo1;
}
}
info = MAGMA_SLOW_CONVERGENCE;
if( solver_par->iter_res < solver_par->rtol*nomb ||
solver_par->iter_res < solver_par->atol ) {
info = MAGMA_SUCCESS;
}
}
else {
if ( solver_par->verbose > 0 ) {
if ( (solver_par->numiter)%solver_par->verbose == c_zero ) {
solver_par->res_vec[(solver_par->numiter)/solver_par->verbose]
= (real_Double_t) res;
solver_par->timing[(solver_par->numiter)/solver_par->verbose]
= (real_Double_t) tempo2-tempo1;
}
}
info = MAGMA_DIVERGENCE;
}
cleanup:
magma_cmfree(&r, queue );
magma_cmfree(&r_tld, queue );
magma_cmfree(&v, queue );
magma_cmfree(&w, queue );
magma_cmfree(&wt, queue );
magma_cmfree(&d, queue );
magma_cmfree(&s, queue );
magma_cmfree(&z, queue );
magma_cmfree(&q, queue );
magma_cmfree(&p, queue );
magma_cmfree(&zt, queue );
magma_cmfree(&vt, queue );
magma_cmfree(&yt, queue );
magma_cmfree(&pt, queue );
magma_cmfree(&y, queue );
magma_cmfree(&AT, queue );
magma_cmfree(&Ah1, queue );
magma_cmfree(&Ah2, queue );
solver_par->info = info;
return info;
} /* magma_cqmr */
| [
"sinkingsugar@gmail.com"
] | sinkingsugar@gmail.com |
fd47be35175000dc4fdcf0124afe194d9ada86fc | a68707e03246986cec128271bb0fbf90f91b31fc | /node_modules/react-native/ReactCommon/fabric/components/activityindicator/ActivityIndicatorViewComponentDescriptor.h | 7dbe425337f335c415b9ff7698589127db6a2a9c | [
"CC-BY-SA-4.0",
"MIT",
"CC-BY-4.0",
"CC-BY-NC-SA-4.0"
] | permissive | albseb511/react-native-kite-zerodha-mockup | fe1163275ec5c5ac27d8852e0737445c0928a7d4 | 70237dacabf889cf22b99f65522010416ed0177e | refs/heads/master | 2023-01-08T21:11:03.958157 | 2019-05-21T19:48:45 | 2019-05-21T19:48:45 | 187,160,542 | 9 | 7 | MIT | 2023-01-03T21:58:52 | 2019-05-17T06:37:00 | Java | UTF-8 | C++ | false | false | 538 | h | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <react/components/activityindicator/ActivityIndicatorViewShadowNode.h>
#include <react/core/ConcreteComponentDescriptor.h>
namespace facebook {
namespace react {
using ActivityIndicatorViewComponentDescriptor =
ConcreteComponentDescriptor<ActivityIndicatorViewShadowNode>;
} // namespace react
} // namespace facebook
| [
"albert@wisense.in"
] | albert@wisense.in |
815c6aec534dfa50576e051c1de4ec0ddd6bfc48 | 95dcf1b68eb966fd540767f9315c0bf55261ef75 | /build/pc/Boost_1_50_0/boost/date_time/time_defs.hpp | 87959a83ed56d815764ae41bf17ed4a5242d57fc | [
"BSL-1.0"
] | permissive | quinsmpang/foundations.github.com | 9860f88d1227ae4efd0772b3adcf9d724075e4d1 | 7dcef9ae54b7e0026fd0b27b09626571c65e3435 | refs/heads/master | 2021-01-18T01:57:54.298696 | 2012-10-14T14:44:38 | 2012-10-14T14:44:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 994 | hpp | #ifndef DATE_TIME_TIME_PRECISION_LIMITS_HPP
#define DATE_TIME_TIME_PRECISION_LIMITS_HPP
/* Copyright (c) 2002,2003 CrystalClear Software, Inc.
* Use, modification and distribution is subject to the
* Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
* Author: Jeff Garland
* $Date: 2008-11-13 03:37:53 +0800 (星期四, 2008-11-13) $
*/
/*! \file time_defs.hpp
This file contains nice definitions for handling the resoluion of various time
reprsentations.
*/
namespace boost {
namespace date_time {
//!Defines some nice types for handling time level resolutions
enum time_resolutions {
sec,
tenth,
hundreth, // deprecated misspelled version of hundredth
hundredth = hundreth,
milli,
ten_thousandth,
micro,
nano,
NumResolutions
};
//! Flags for daylight savings or summer time
enum dst_flags {not_dst, is_dst, calculate};
} } //namespace date_time
#endif
| [
"wisbyme@yahoo.com"
] | wisbyme@yahoo.com |
53df4fef0f42de507d95c4555b5d38ea25b323d4 | b38859b17c0b703f43019bde98b3e5932457d4f0 | /basic/for/2739.cpp | 59ab0df09fa9741889e6aa7483d90fda88d11830 | [] | no_license | kimsumin-inf/Baekjun-problem | 2b60f8fa95232a04900ba59d46b92006dd7ebd8e | b6928469dce54917cae2e301d353f6f302308920 | refs/heads/master | 2023-08-18T15:03:48.875556 | 2021-09-18T15:07:26 | 2021-09-18T15:07:26 | 349,307,685 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 128 | cpp | #include "myheader.h"
using namespace std;
int main() {
int num;
cin >> num;
limit(num, 1, 9);
multiplication_table(num);
} | [
"ksm4465ksm@gmail.com"
] | ksm4465ksm@gmail.com |
b6f85f6c29a6de409c0e908cf5f4033b0423b867 | dbbcae6490abfb4ea937e3db575461623eb00d25 | /Tareas/Tarea_4/pueba_hld.cpp | f4023e2a01fc5e2bfd742426353c68a5375b4505 | [] | no_license | danielvallejo237/Advanced-Programming | 20ca78dfc1ee79f043efba315f766574939047b2 | 199bce1060622385d2b738e5c67e63e64d6a7eaa | refs/heads/main | 2023-05-21T12:09:56.130991 | 2021-06-10T17:01:27 | 2021-06-10T17:01:27 | 344,992,130 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,754 | cpp | // hld_euler_sum.cpp
// Eric K. Zhang; Nov. 22, 2017
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
#define MAXN 100005
#define MAXSEG 262144
int N;
vector<int> adj[MAXN];
namespace hld {
int parent[MAXN];
vector<int> ch[MAXN];
int depth[MAXN];
int sz[MAXN];
int in[MAXN];
int rin[MAXN];
int nxt[MAXN];
int out[MAXN];
int t = 0;
void dfs_sz(int n=0, int p=-1, int d=0) {
parent[n] = p, sz[n] = 1;
depth[n] = d;
for (auto v : adj[n]) if (v != p) {
dfs_sz(v, n, d + 1);
sz[n] += sz[v];
ch[n].push_back(v);
if (sz[v] > sz[ch[n][0]])
swap(ch[n][0], ch[n].back());
}
}
void dfs_hld(int n=0) {
in[n] = t++;
rin[in[n]] = n;
for (auto v : ch[n]) {
nxt[v] = (v == ch[n][0] ? nxt[n] : v);
dfs_hld(v);
}
out[n] = t;
}
void init() {
dfs_sz();
dfs_hld();
}
int lca(int u, int v) {
while (nxt[u] != nxt[v]) {
if (depth[nxt[u]] < depth[nxt[v]]) swap(u, v);
u = parent[nxt[u]];
}
return depth[u] < depth[v] ? u : v;
}
LL st[MAXSEG];
LL lazy[MAXSEG];
void push(int node, int lo, int hi) {
if (lazy[node] == 0) return;
st[node] += (hi - lo + 1) * lazy[node];
if (lo != hi) {
lazy[2 * node + 1] += lazy[node];
lazy[2 * node + 2] += lazy[node];
}
lazy[node] = 0;
}
void update_range(int s, int e, int x, int lo=0, int hi=-1, int node=0) {
if (hi == -1) hi = N - 1;
push(node, lo, hi);
if (hi < s || lo > e) return;
if (lo >= s && hi <= e) {
lazy[node] = x;
push(node, lo, hi);
return;
}
int mid = (lo + hi) / 2;
update_range(s, e, x, lo, mid, 2 * node + 1);
update_range(s, e, x, mid + 1, hi, 2 * node + 2);
st[node] = st[2 * node + 1] + st[2 * node + 2];
}
LL query(int s, int e, int lo=0, int hi=-1, int node=0) {
if (hi == -1) hi = N - 1;
push(node, lo, hi);
if (hi < s || lo > e) return 0;
if (lo >= s && hi <= e) return st[node];
int mid = (lo + hi) / 2;
return query(s, e, lo, mid, 2 * node + 1) +
query(s, e, mid + 1, hi, 2 * node + 2);
}
void update_subtree(int n, int x) {
update_range(in[n], out[n] - 1, x);
}
LL query_subtree(int n) {
return query(in[n], out[n] - 1);
}
void update_path(int u, int v, int x, bool ignore_lca=false) {
while (nxt[u] != nxt[v]) {
if (depth[nxt[u]] < depth[nxt[v]]) swap(u, v);
update_range(in[nxt[u]], in[u], x);
u = parent[nxt[u]];
}
if (depth[u] < depth[v]) swap(u, v);
update_range(in[v] + ignore_lca, in[u], x);
}
LL query_path(int u, int v, bool ignore_lca=false) {
LL ret = 0;
while (nxt[u] != nxt[v]) {
if (depth[nxt[u]] < depth[nxt[v]]) swap(u, v);
ret += query(in[nxt[u]], in[u]);
u = parent[nxt[u]];
}
if (depth[u] < depth[v]) swap(u, v);
ret += query(in[v] + ignore_lca, in[u]);
return ret;
}
}
| [
"daniel.vallejo@cimat.mx"
] | daniel.vallejo@cimat.mx |
5e1b7febdc73bd2e2c788c5ac5534d8e6874b55f | 8e3e32495d47285d7e656c25bc204b0ca2c3c23f | /Block/object_block.cpp | 7d4395643f6ad521cc04bdce1335739c67cd9fe7 | [] | no_license | MohamedAli25/XML-JSON-Converter | cdb9de708e5fc75a03e2e3dae2d61cece1eaabee | 7a4da28bacf39abbe692dbcbf011a4f6bed4083d | refs/heads/master | 2021-05-26T22:10:37.607701 | 2020-04-10T02:01:14 | 2020-04-10T02:01:14 | 254,174,697 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 231 | cpp | #include "object_block.h"
ObjectBlock::ObjectBlock(QString name) : Block{name} {}
QVector<Block *> *ObjectBlock::getValue()
{
return &blocks;
}
void ObjectBlock::addBlock(Block *blockPtr)
{
blocks.push_back(blockPtr);
}
| [
"m.ad.ali2165@gmail.com"
] | m.ad.ali2165@gmail.com |
14ed01161417961424b4be934310009bdc828a57 | 8b1e05154bdbe7aa595310c6cc5ab7ec84be88d5 | /src/consensus/validation.h | 2899bdd01cc36428327d50fd7c6ae74f7d6507f3 | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | permissive | AustraliaCash/AustraliaCash-Core | c2ab806db3c123c41882aacd1af23109cce6b4db | 5e31845eea27eecd06135ddd873d4f37fba9ee60 | refs/heads/master | 2023-07-09T20:26:35.387036 | 2023-06-26T20:27:24 | 2023-06-26T20:27:24 | 157,548,102 | 9 | 6 | MIT | 2023-06-26T20:27:25 | 2018-11-14T12:50:16 | C++ | UTF-8 | C++ | false | false | 8,147 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2021 The AustraliaCash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_CONSENSUS_VALIDATION_H
#define BITCOIN_CONSENSUS_VALIDATION_H
#include <string>
#include <version.h>
#include <consensus/consensus.h>
#include <primitives/transaction.h>
#include <primitives/block.h>
/** Index marker for when no witness commitment is present in a coinbase transaction. */
static constexpr int NO_WITNESS_COMMITMENT{-1};
/** Minimum size of a witness commitment structure. Defined in BIP 141. **/
static constexpr size_t MINIMUM_WITNESS_COMMITMENT{38};
/** A "reason" why a transaction was invalid, suitable for determining whether the
* provider of the transaction should be banned/ignored/disconnected/etc.
*/
enum class TxValidationResult {
TX_RESULT_UNSET = 0, //!< initial value. Tx has not yet been rejected
TX_CONSENSUS, //!< invalid by consensus rules
/**
* Invalid by a change to consensus rules more recent than SegWit.
* Currently unused as there are no such consensus rule changes, and any download
* sources realistically need to support SegWit in order to provide useful data,
* so differentiating between always-invalid and invalid-by-pre-SegWit-soft-fork
* is uninteresting.
*/
TX_RECENT_CONSENSUS_CHANGE,
TX_INPUTS_NOT_STANDARD, //!< inputs (covered by txid) failed policy rules
TX_NOT_STANDARD, //!< otherwise didn't meet our local policy rules
TX_MISSING_INPUTS, //!< transaction was missing some of its inputs
TX_PREMATURE_SPEND, //!< transaction spends a coinbase too early, or violates locktime/sequence locks
/**
* Transaction might have a witness prior to SegWit
* activation, or witness may have been malleated (which includes
* non-standard witnesses).
*/
TX_WITNESS_MUTATED,
/**
* Transaction is missing a witness.
*/
TX_WITNESS_STRIPPED,
/**
* Tx already in mempool or conflicts with a tx in the chain
* (if it conflicts with another tx in mempool, we use MEMPOOL_POLICY as it failed to reach the RBF threshold)
* Currently this is only used if the transaction already exists in the mempool or on chain.
*/
TX_CONFLICT,
TX_MEMPOOL_POLICY, //!< violated mempool's fee/size/descendant/RBF/etc limits
TX_NO_MEMPOOL, //!< this node does not have a mempool so can't validate the transaction
};
/** A "reason" why a block was invalid, suitable for determining whether the
* provider of the block should be banned/ignored/disconnected/etc.
* These are much more granular than the rejection codes, which may be more
* useful for some other use-cases.
*/
enum class BlockValidationResult {
BLOCK_RESULT_UNSET = 0, //!< initial value. Block has not yet been rejected
BLOCK_CONSENSUS, //!< invalid by consensus rules (excluding any below reasons)
/**
* Invalid by a change to consensus rules more recent than SegWit.
* Currently unused as there are no such consensus rule changes, and any download
* sources realistically need to support SegWit in order to provide useful data,
* so differentiating between always-invalid and invalid-by-pre-SegWit-soft-fork
* is uninteresting.
*/
BLOCK_RECENT_CONSENSUS_CHANGE,
BLOCK_CACHED_INVALID, //!< this block was cached as being invalid and we didn't store the reason why
BLOCK_INVALID_HEADER, //!< invalid proof of work or time too old
BLOCK_MUTATED, //!< the block's data didn't match the data committed to by the PoW
BLOCK_MISSING_PREV, //!< We don't have the previous block the checked one is built on
BLOCK_INVALID_PREV, //!< A block this one builds on is invalid
BLOCK_TIME_FUTURE, //!< block timestamp was > 2 hours in the future (or our clock is bad)
BLOCK_CHECKPOINT, //!< the block failed to meet one of our checkpoints
BLOCK_HEADER_LOW_WORK //!< the block header may be on a too-little-work chain
};
/** Template for capturing information about block/transaction validation. This is instantiated
* by TxValidationState and BlockValidationState for validation information on transactions
* and blocks respectively. */
template <typename Result>
class ValidationState
{
private:
enum class ModeState {
M_VALID, //!< everything ok
M_INVALID, //!< network rule violation (DoS value may be set)
M_ERROR, //!< run-time error
} m_mode{ModeState::M_VALID};
Result m_result{};
std::string m_reject_reason;
std::string m_debug_message;
public:
bool Invalid(Result result,
const std::string& reject_reason = "",
const std::string& debug_message = "")
{
m_result = result;
m_reject_reason = reject_reason;
m_debug_message = debug_message;
if (m_mode != ModeState::M_ERROR) m_mode = ModeState::M_INVALID;
return false;
}
bool Error(const std::string& reject_reason)
{
if (m_mode == ModeState::M_VALID)
m_reject_reason = reject_reason;
m_mode = ModeState::M_ERROR;
return false;
}
bool IsValid() const { return m_mode == ModeState::M_VALID; }
bool IsInvalid() const { return m_mode == ModeState::M_INVALID; }
bool IsError() const { return m_mode == ModeState::M_ERROR; }
Result GetResult() const { return m_result; }
std::string GetRejectReason() const { return m_reject_reason; }
std::string GetDebugMessage() const { return m_debug_message; }
std::string ToString() const
{
if (IsValid()) {
return "Valid";
}
if (!m_debug_message.empty()) {
return m_reject_reason + ", " + m_debug_message;
}
return m_reject_reason;
}
};
class TxValidationState : public ValidationState<TxValidationResult> {};
class BlockValidationState : public ValidationState<BlockValidationResult> {};
// These implement the weight = (stripped_size * 4) + witness_size formula,
// using only serialization with and without witness data. As witness_size
// is equal to total_size - stripped_size, this formula is identical to:
// weight = (stripped_size * 3) + total_size.
static inline int64_t GetTransactionWeight(const CTransaction& tx)
{
return ::GetSerializeSize(tx, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * (WITNESS_SCALE_FACTOR - 1) + ::GetSerializeSize(tx, PROTOCOL_VERSION);
}
static inline int64_t GetBlockWeight(const CBlock& block)
{
return ::GetSerializeSize(block, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * (WITNESS_SCALE_FACTOR - 1) + ::GetSerializeSize(block, PROTOCOL_VERSION);
}
static inline int64_t GetTransactionInputWeight(const CTxIn& txin)
{
// scriptWitness size is added here because witnesses and txins are split up in segwit serialization.
return ::GetSerializeSize(txin, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * (WITNESS_SCALE_FACTOR - 1) + ::GetSerializeSize(txin, PROTOCOL_VERSION) + ::GetSerializeSize(txin.scriptWitness.stack, PROTOCOL_VERSION);
}
/** Compute at which vout of the block's coinbase transaction the witness commitment occurs, or -1 if not found */
inline int GetWitnessCommitmentIndex(const CBlock& block)
{
int commitpos = NO_WITNESS_COMMITMENT;
if (!block.vtx.empty()) {
for (size_t o = 0; o < block.vtx[0]->vout.size(); o++) {
const CTxOut& vout = block.vtx[0]->vout[o];
if (vout.scriptPubKey.size() >= MINIMUM_WITNESS_COMMITMENT &&
vout.scriptPubKey[0] == OP_RETURN &&
vout.scriptPubKey[1] == 0x24 &&
vout.scriptPubKey[2] == 0xaa &&
vout.scriptPubKey[3] == 0x21 &&
vout.scriptPubKey[4] == 0xa9 &&
vout.scriptPubKey[5] == 0xed) {
commitpos = o;
}
}
}
return commitpos;
}
#endif // BITCOIN_CONSENSUS_VALIDATION_H
| [
"31876349+farsider350@users.noreply.github.com"
] | 31876349+farsider350@users.noreply.github.com |
a20c762b6e0b21464f1460cccc0f8e9098ec54ca | e4ec5b6cf3cfe2568ef0b5654c019e398b4ecc67 | /aws-sdk-cpp/1.2.10/include/aws/opsworkscm/model/DescribeNodeAssociationStatusResult.h | 6858c193635d42474bb7f53e7a0dac84976598e1 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | EnjoyLifeFund/macHighSierra-cellars | 59051e496ed0e68d14e0d5d91367a2c92c95e1fb | 49a477d42f081e52f4c5bdd39535156a2df52d09 | refs/heads/master | 2022-12-25T19:28:29.992466 | 2017-10-10T13:00:08 | 2017-10-10T13:00:08 | 96,081,471 | 3 | 1 | null | 2022-12-17T02:26:21 | 2017-07-03T07:17:34 | null | UTF-8 | C++ | false | false | 4,358 | h | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/opsworkscm/OpsWorksCM_EXPORTS.h>
#include <aws/opsworkscm/model/NodeAssociationStatus.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace OpsWorksCM
{
namespace Model
{
class AWS_OPSWORKSCM_API DescribeNodeAssociationStatusResult
{
public:
DescribeNodeAssociationStatusResult();
DescribeNodeAssociationStatusResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
DescribeNodeAssociationStatusResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The status of the association or disassociation request. </p> <p
* class="title"> <b>Possible values:</b> </p> <ul> <li> <p> <code>SUCCESS</code>:
* The association or disassociation succeeded. </p> </li> <li> <p>
* <code>FAILED</code>: The association or disassociation failed. </p> </li> <li>
* <p> <code>IN_PROGRESS</code>: The association or disassociation is still in
* progress. </p> </li> </ul>
*/
inline const NodeAssociationStatus& GetNodeAssociationStatus() const{ return m_nodeAssociationStatus; }
/**
* <p>The status of the association or disassociation request. </p> <p
* class="title"> <b>Possible values:</b> </p> <ul> <li> <p> <code>SUCCESS</code>:
* The association or disassociation succeeded. </p> </li> <li> <p>
* <code>FAILED</code>: The association or disassociation failed. </p> </li> <li>
* <p> <code>IN_PROGRESS</code>: The association or disassociation is still in
* progress. </p> </li> </ul>
*/
inline void SetNodeAssociationStatus(const NodeAssociationStatus& value) { m_nodeAssociationStatus = value; }
/**
* <p>The status of the association or disassociation request. </p> <p
* class="title"> <b>Possible values:</b> </p> <ul> <li> <p> <code>SUCCESS</code>:
* The association or disassociation succeeded. </p> </li> <li> <p>
* <code>FAILED</code>: The association or disassociation failed. </p> </li> <li>
* <p> <code>IN_PROGRESS</code>: The association or disassociation is still in
* progress. </p> </li> </ul>
*/
inline void SetNodeAssociationStatus(NodeAssociationStatus&& value) { m_nodeAssociationStatus = std::move(value); }
/**
* <p>The status of the association or disassociation request. </p> <p
* class="title"> <b>Possible values:</b> </p> <ul> <li> <p> <code>SUCCESS</code>:
* The association or disassociation succeeded. </p> </li> <li> <p>
* <code>FAILED</code>: The association or disassociation failed. </p> </li> <li>
* <p> <code>IN_PROGRESS</code>: The association or disassociation is still in
* progress. </p> </li> </ul>
*/
inline DescribeNodeAssociationStatusResult& WithNodeAssociationStatus(const NodeAssociationStatus& value) { SetNodeAssociationStatus(value); return *this;}
/**
* <p>The status of the association or disassociation request. </p> <p
* class="title"> <b>Possible values:</b> </p> <ul> <li> <p> <code>SUCCESS</code>:
* The association or disassociation succeeded. </p> </li> <li> <p>
* <code>FAILED</code>: The association or disassociation failed. </p> </li> <li>
* <p> <code>IN_PROGRESS</code>: The association or disassociation is still in
* progress. </p> </li> </ul>
*/
inline DescribeNodeAssociationStatusResult& WithNodeAssociationStatus(NodeAssociationStatus&& value) { SetNodeAssociationStatus(std::move(value)); return *this;}
private:
NodeAssociationStatus m_nodeAssociationStatus;
};
} // namespace Model
} // namespace OpsWorksCM
} // namespace Aws
| [
"Raliclo@gmail.com"
] | Raliclo@gmail.com |
35d289ca4b6c54d4367e703447e1fb610e9cb83f | 3b4b4d34fd50da8c1ca553941aac8a79d1f9afb6 | /ipod-nano/src/IPodFrameWidget.cc | 44028571b45b1375308a5a0405a02ca3ca2dcb55 | [] | no_license | pflemming/Layoutomator-Nano | ed28e926b5cba4ad10fe93b465601f667d85f927 | ee93bf235246029d47e9969630ed22a4136650fe | refs/heads/master | 2021-01-16T18:58:25.926631 | 2012-01-03T22:33:51 | 2012-01-03T22:33:51 | 3,099,490 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,091 | cc | #include "IPodFrameWidget.h"
#include "widgets/ImageWidget.h"
#include "widgets/ButtonWidget.h"
#include "helpers.h"
#include <QGridLayout>
#include <QMoveEvent>
#include <QSize>
#include <QTimer>
#include <math.h>
namespace ipn
{
IPodFrameWidget::IPodFrameWidget(QWidget *parent) : QWidget(parent),
m_currentlyDragging(false),
m_dragging(false)
{
m_paddingTop = 57;
QGridLayout *layout = new QGridLayout(this);
QString frameParts[3][3] = {{"tl.png", "t.png", "tr.png"},
{"l.png", "", "r.png"},
{"bl.png", "b.png", "br.png"}};
for (int i = FRAME_TOP; i <= FRAME_BOTTOM; i++)
for (int j = FRAME_LEFT; j <= FRAME_RIGHT; j++)
// Draw all parts of the frame and leave the middle empty
if (!(i == FRAME_CENTER && j == FRAME_CENTER))
{
m_frameImages[i][j] = new ImageWidget(this);
m_frameImages[i][j]->setImage(":/img/frame/" + frameParts[i][j]);
// Make sure the screen's resolution is always 240×240 pixels
if (i == FRAME_CENTER)
m_frameImages[i][j]->resize(m_frameImages[i][j]->width(), 240);
if (j == FRAME_CENTER)
m_frameImages[i][j]->resize(240, m_frameImages[i][j]->height());
layout->addWidget(m_frameImages[i][j], i, j);
}
m_appWidget = new QWidget(this);
layout->addWidget(m_appWidget, FRAME_CENTER, FRAME_CENTER);
layout->setSpacing(0);
layout->setContentsMargins(0, m_paddingTop, 0, 0);
m_hardwareButton = new ButtonWidget(this);
m_hardwareButton->setInactiveImages(":/img/frame/hardware_button.png",
":/img/frame/hardware_button_down.png");
m_hardwareButton->move(240, 0);
m_hardwareButton->setMouseTracking(true);
connect(m_hardwareButton, SIGNAL(clicked()), this, SLOT(popApp()));
setFixedSize(frameSize());
resize(frameSize());
m_animationOffset = 0;
m_animationType = ANIMATION_NONE;
m_animationTimer = new QTimer(this);
m_animationTimer->setInterval(30);
m_animationTimer->setSingleShot(false);
connect(m_animationTimer, SIGNAL(timeout()), this, SLOT(drawAnimation()));
setMouseTracking(true);
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
}
QSize IPodFrameWidget::frameSize()
{
int width = m_frameImages[FRAME_TOP][FRAME_LEFT]->width()
+ 240 + m_frameImages[FRAME_TOP][FRAME_RIGHT]->width();
int height = m_frameImages[FRAME_TOP][FRAME_LEFT]->height()
+ 240 + m_frameImages[FRAME_BOTTOM][FRAME_LEFT]->height()
+ m_paddingTop;
return QSize(width, height);
}
QRect IPodFrameWidget::contentRect()
{
int x = m_frameImages[FRAME_TOP][FRAME_LEFT]->width();
int y = m_frameImages[FRAME_TOP][FRAME_LEFT]->height() + m_paddingTop;
return QRect(x, y, 240, 240);
}
int IPodFrameWidget::paddingTop()
{
return m_paddingTop;
}
void IPodFrameWidget::mouseMoveEvent(QMouseEvent *event)
{
if (m_prevMousePosition.isNull())
m_prevMousePosition = event->globalPos();
if (m_dragging)
move(pos() + event->globalPos() - m_prevMousePosition);
m_prevMousePosition = event->globalPos();
event->ignore();
}
void IPodFrameWidget::mousePressEvent(QMouseEvent *event)
{
if (!contentRect().contains(event->pos()))
m_dragging = true;
m_prevMousePosition = event->globalPos();
}
void IPodFrameWidget::mouseReleaseEvent(QMouseEvent*)
{
m_dragging = false;
}
void IPodFrameWidget::moveEvent(QMoveEvent *event)
{
// Emit event for use without and with the position difference as parameter
emit frameMoved();
emit frameMoved(event->pos() - event->oldPos());
}
App *IPodFrameWidget::topApp()
{
return m_appStack.isEmpty() ? NULL : m_appStack.back();
}
App *IPodFrameWidget::preTopApp()
{
return m_appStack.size() < 2 ? NULL : m_appStack.at(m_appStack.size() - 2);
}
void IPodFrameWidget::instantPushApp(App *app)
{
// Make sure the app's parent is our app wrapper widget
app->setParent(m_appWidget);
app->resize(240, 240);
app->move(0, 0);
// Push the app on the stack an redraw everything
m_appStack.append(app);
refresh();
}
void IPodFrameWidget::pushApp(App *app)
{
instantPushApp(app);
if (topApp())
topApp()->move(240, 0);
if (preTopApp())
{
preTopApp()->move(0, 0);
preTopApp()->show();
}
m_animationOffset = 240;
m_animationType = ANIMATION_LEFT;
m_animationTimer->start();
}
void IPodFrameWidget::instantPopApp()
{
if (m_appStack.isEmpty())
return;
// Remove the app from the stack, but keep a pointer on it
App *lastApp = m_appStack.back();
m_appStack.pop_back();
// Redraw everything
refresh();
// After refreshing, hide the app to prevent flickering
lastApp->hide();
}
void IPodFrameWidget::popApp()
{
if (m_appStack.isEmpty())
return;
if (m_animationType != ANIMATION_NONE)
return;
m_popAppCount = 1;
m_opaquePopAppCount = 1;
popMultipleApps();
}
void IPodFrameWidget::instantSwitchBackTo(App *app)
{
// Delete the last app from the stack until we find the specified app
while (!m_appStack.isEmpty())
{
if (m_appStack.last() == app)
break;
m_appStack.last()->hide();
m_appStack.pop_back();
}
// Redraw everything
refresh();
}
void IPodFrameWidget::switchBackTo(App *app)
{
if (m_animationType != ANIMATION_NONE)
return;
m_opaquePopAppCount = -1;
for (int i = m_appStack.size() - 1; i >= 0; i--)
{
m_opaquePopAppCount += m_appStack.at(i)->isOpaque();
if (app == m_appStack.at(i))
{
m_popAppCount = m_appStack.size() - i - 1;
popMultipleApps();
return;
}
}
}
void IPodFrameWidget::instantReplaceAllAppsBy(App *app)
{
// Hide all apps on the stack
for (QVector<App*>::iterator a = m_appStack.begin(); a != m_appStack.end(); a++)
(*a)->hide();
// Make the specified app the only app on the stack
m_appStack.clear();
instantPushApp(app);
// Redraw everything
refresh();
}
void IPodFrameWidget::refresh()
{
// Iterate backwards to the last opaque app:
QVector<App*>::iterator w = m_appStack.end() - 1;
(*w)->show();
while (w != m_appStack.begin() && !(*w)->isOpaque())
{
w--;
(*w)->show();
}
// All other apps below are not visible and don't have to be drawn:
while (w != m_appStack.begin())
{
w--;
(*w)->hide();
}
}
void IPodFrameWidget::drawAnimation()
{
if (m_animationType == ANIMATION_LEFT)
m_animationOffset *= 0.6;
else if (m_animationType == ANIMATION_RIGHT)
m_animationOffset *= 1.0 - 0.4 * pow(0.5, (float)m_opaquePopAppCount - 1.0);
if (m_animationOffset > -1.0 && m_animationOffset < 1.0)
{
// Animation finished
m_animationOffset = 0;
m_animationTimer->stop();
if (m_animationType == ANIMATION_RIGHT)
// Remove apps
for (int i = 0; i < m_popAppCount; i++)
{
m_appStack.back()->hide();
m_appStack.pop_back();
}
if (m_animationType == ANIMATION_LEFT && topApp() && preTopApp()
&& topApp()->isOpaque())
{
preTopApp()->hide();
preTopApp()->move(0, 0);
}
if (topApp())
topApp()->move(0, 0);
m_animationType = ANIMATION_NONE;
return;
}
// Proceed animation:
if (m_animationType == ANIMATION_LEFT)
{
if (topApp())
topApp()->move(m_animationOffset, 0);
if (preTopApp() && topApp()->isOpaque())
preTopApp()->move(m_animationOffset - 240.0, 0);
}
if (m_animationType == ANIMATION_RIGHT)
{
int pos = m_opaquePopAppCount;
for (int i = m_appStack.size() - 1; i >= m_appStack.size() - 1 - m_popAppCount; i--)
{
if (i < m_appStack.size() - 1)
{
pos--;
if (!m_appStack.at(i+1)->isOpaque())
{
if (i == m_appStack.size() - 1 - m_popAppCount)
{
m_appStack.at(i)->move(0, 0);
continue;
}
else
pos++;
}
}
m_appStack.at(i)->move(m_animationOffset + 240.0 * (float)pos, 0);
}
}
}
void IPodFrameWidget::popMultipleApps()
{
if (m_appStack.size() < 2)
return;
for (int i = 0; i < m_popAppCount; i++)
m_appStack.at(m_appStack.size() - 2 - i)->show();
m_animationOffset = -240.0 * (float)m_opaquePopAppCount;
m_animationType = ANIMATION_RIGHT;
m_animationTimer->start();
}
} // namespace ipn
| [
"anita.dieckhoff@student.hpi.uni-potsdam.de"
] | anita.dieckhoff@student.hpi.uni-potsdam.de |
53e55db49a9c50098d572bdb49c709e674fb6287 | fc353ca6be2bc55cb69f6ce3e21800a1ede28270 | /common/util/src/RateManagerAsync.cpp | 7d1b030d65b7a504035db7278f705b1e86ba425f | [] | no_license | aggelis/HDTN | b4b43781a2e6490b9f7066377553e53f37fff742 | 85c1a060fb1f65fed0755fee8f0a45233c1d78d8 | refs/heads/master | 2023-09-05T09:36:47.019948 | 2021-09-29T15:00:47 | 2021-09-29T15:00:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,084 | cpp | #include "RateManagerAsync.h"
#include <iostream>
#include <boost/bind.hpp>
RateManagerAsync::RateManagerAsync(boost::asio::io_service & ioService, const uint64_t rateBitsPerSec, const uint64_t maxPacketsBeingSent) :
m_ioServiceRef(ioService),
m_rateTimer(ioService),
m_rateBitsPerSec(rateBitsPerSec),
m_maxPacketsBeingSent(maxPacketsBeingSent),
m_bytesToAckByRateCb(static_cast<uint32_t>(m_maxPacketsBeingSent + 10)),
m_bytesToAckByRateCbVec(m_maxPacketsBeingSent + 10),
m_bytesToAckBySentCallbackCb(static_cast<uint32_t>(m_maxPacketsBeingSent + 10)),
m_bytesToAckBySentCallbackCbVec(m_maxPacketsBeingSent + 10)
{
Reset();
}
RateManagerAsync::~RateManagerAsync() {
//Reset();
//print stats
std::cout << "m_totalPacketsSentBySentCallback " << m_totalPacketsSentBySentCallback << std::endl;
std::cout << "m_totalBytesSentBySentCallback " << m_totalBytesSentBySentCallback << std::endl;
std::cout << "m_totalPacketsSentByRate " << m_totalPacketsSentByRate << std::endl;
std::cout << "m_totalBytesSentByRate " << m_totalBytesSentByRate << std::endl;
std::cout << "m_totalPacketsDequeuedForSend " << m_totalPacketsDequeuedForSend << std::endl;
std::cout << "m_totalBytesDequeuedForSend " << m_totalBytesDequeuedForSend << std::endl;
}
void RateManagerAsync::Reset() {
m_totalPacketsSentBySentCallback = 0;
m_totalBytesSentBySentCallback = 0;
m_totalPacketsSentByRate = 0;
m_totalBytesSentByRate = 0;
m_totalPacketsDequeuedForSend = 0;
m_totalBytesDequeuedForSend = 0;
m_rateTimerIsRunning = false;
}
void RateManagerAsync::SetRate(uint64_t rateBitsPerSec) {
m_rateBitsPerSec = rateBitsPerSec;
}
void RateManagerAsync::SetPacketsSentCallback(const PacketsSentCallback_t & callback) {
m_packetsSentCallback = callback;
}
std::size_t RateManagerAsync::GetTotalPacketsCompletelySent() {
const std::size_t totalSentBySentCallback = m_totalPacketsSentBySentCallback;
const std::size_t totalSentByRate = m_totalPacketsSentByRate;
return std::min(totalSentBySentCallback, totalSentByRate);
}
std::size_t RateManagerAsync::GetTotalPacketsDequeuedForSend() {
return m_totalPacketsDequeuedForSend;
}
std::size_t RateManagerAsync::GetTotalPacketsBeingSent() {
return GetTotalPacketsDequeuedForSend() - GetTotalPacketsCompletelySent();
}
std::size_t RateManagerAsync::GetTotalBytesCompletelySent() {
const std::size_t totalSentBySentCallback = m_totalBytesSentBySentCallback;
const std::size_t totalSentByRate = m_totalBytesSentByRate;
return std::min(totalSentBySentCallback, totalSentByRate);
}
std::size_t RateManagerAsync::GetTotalBytesDequeuedForSend() {
return m_totalBytesDequeuedForSend;
}
std::size_t RateManagerAsync::GetTotalBytesBeingSent() {
return GetTotalBytesDequeuedForSend() - GetTotalBytesCompletelySent();
}
bool RateManagerAsync::SignalNewPacketDequeuedForSend(uint64_t packetSizeBytes) {
const unsigned int writeIndexRate = m_bytesToAckByRateCb.GetIndexForWrite(); //don't put this in tcp async write callback
if (writeIndexRate == UINT32_MAX) { //push check
std::cerr << "Error in RateManagerAsync::SignalNewPacketDequeuedForSend.. too many unacked packets by rate" << std::endl;
return false;
}
const unsigned int writeIndexSentCallback = m_bytesToAckBySentCallbackCb.GetIndexForWrite(); //don't put this in tcp async write callback
if (writeIndexSentCallback == UINT32_MAX) { //push check
std::cerr << "Error in RateManagerAsync::SignalNewPacketDequeuedForSend.. too many unacked packets by tcp send callback" << std::endl;
return false;
}
++m_totalPacketsDequeuedForSend;
m_bytesToAckByRateCbVec[writeIndexRate] = packetSizeBytes;
m_bytesToAckByRateCb.CommitWrite(); //pushed
m_bytesToAckBySentCallbackCbVec[writeIndexSentCallback] = packetSizeBytes;
m_bytesToAckBySentCallbackCb.CommitWrite(); //pushed
boost::asio::post(m_ioServiceRef, boost::bind(&RateManagerAsync::TryRestartRateTimer, this)); //keep TryRestartRateTimer within ioservice thread
return true;
}
//restarts the rate timer if there is a pending ack in the cb
void RateManagerAsync::TryRestartRateTimer() {
if (!m_rateTimerIsRunning && (m_groupingOfBytesToAckByRateVec.size() == 0)) {
uint64_t delayMicroSec = 0;
for (unsigned int readIndex = m_bytesToAckByRateCb.GetIndexForRead(); readIndex != UINT32_MAX; readIndex = m_bytesToAckByRateCb.GetIndexForRead()) { //notempty
const double numBitsDouble = static_cast<double>(m_bytesToAckByRateCbVec[readIndex]) * 8.0;
const double delayMicroSecDouble = (1e6 / m_rateBitsPerSec) * numBitsDouble;
delayMicroSec += static_cast<uint64_t>(delayMicroSecDouble);
m_groupingOfBytesToAckByRateVec.push_back(m_bytesToAckByRateCbVec[readIndex]);
m_bytesToAckByRateCb.CommitRead();
if (delayMicroSec >= 10000) { //try to avoid sleeping for any time smaller than 10 milliseconds
break;
}
}
if (m_groupingOfBytesToAckByRateVec.size()) {
//std::cout << "d " << delayMicroSec << " sz " << m_groupingOfBytesToAckByRateVec.size() << std::endl;
m_rateTimer.expires_from_now(boost::posix_time::microseconds(delayMicroSec));
m_rateTimer.async_wait(boost::bind(&RateManagerAsync::OnRate_TimerExpired, this, boost::asio::placeholders::error));
m_rateTimerIsRunning = true;
}
}
}
void RateManagerAsync::OnRate_TimerExpired(const boost::system::error_code& e) {
m_rateTimerIsRunning = false;
if (e != boost::asio::error::operation_aborted) {
// Timer was not cancelled, take necessary action.
if (m_groupingOfBytesToAckByRateVec.size() > 0) {
m_totalPacketsSentByRate += m_groupingOfBytesToAckByRateVec.size();
for (std::size_t i = 0; i < m_groupingOfBytesToAckByRateVec.size(); ++i) {
m_totalBytesSentByRate += m_groupingOfBytesToAckByRateVec[i];
}
m_groupingOfBytesToAckByRateVec.clear();
if (m_totalPacketsSentByRate <= m_totalPacketsSentBySentCallback) { //tcp send callback segments ahead
if (m_packetsSentCallback) {
m_packetsSentCallback();
}
m_conditionVariablePacketSent.notify_one();
}
TryRestartRateTimer(); //must be called after commit read
}
else {
std::cerr << "error in RateManagerAsync::OnRate_TimerExpired: m_groupingOfBytesToAckByRateVec is size 0" << std::endl;
}
}
else {
//std::cout << "timer cancelled\n";
}
}
void RateManagerAsync::NotifyPacketSentFromCallback_ThreadSafe(std::size_t bytes_transferred) {
boost::asio::post(m_ioServiceRef, boost::bind(&RateManagerAsync::IoServiceThreadNotifyPacketSentCallback, this, bytes_transferred));
}
bool RateManagerAsync::IoServiceThreadNotifyPacketSentCallback(std::size_t bytes_transferred) {
const unsigned int readIndex = m_bytesToAckBySentCallbackCb.GetIndexForRead();
if (readIndex == UINT32_MAX) { //empty
std::cerr << "error in RateManagerAsync::IoServiceThreadNotifyPacketSentCallback: AckCallback called with empty queue" << std::endl;
return false;
}
else if (m_bytesToAckBySentCallbackCbVec[readIndex] == bytes_transferred) {
++m_totalPacketsSentBySentCallback;
m_totalBytesSentBySentCallback += m_bytesToAckBySentCallbackCbVec[readIndex];
m_bytesToAckBySentCallbackCb.CommitRead();
if (m_totalPacketsSentBySentCallback <= m_totalPacketsSentByRate) { //rate segments ahead
if (m_packetsSentCallback) {
m_packetsSentCallback();
}
m_conditionVariablePacketSent.notify_one();
}
return true;
}
else {
std::cerr << "error in RateManagerAsync::IoServiceThreadNotifyPacketSentCallback: wrong bytes acked: expected " << m_bytesToAckBySentCallbackCbVec[readIndex] << " but got " << bytes_transferred << std::endl;
return false;
}
}
void RateManagerAsync::WaitForAllDequeuedPacketsToFullySend_Blocking(unsigned int timeoutSeconds, bool printStats) {
std::size_t previousUnacked = std::numeric_limits<std::size_t>::max();
const unsigned int maxAttempts = (timeoutSeconds * 2);
for (unsigned int attempt = 0; attempt < maxAttempts; ++attempt) {
const std::size_t numUnacked = GetTotalPacketsBeingSent();
if (numUnacked) {
if (printStats) {
std::cout << "notice: waiting on " << numUnacked << " unacked bundles" << std::endl;
}
if (previousUnacked > numUnacked) {
previousUnacked = numUnacked;
attempt = 0;
}
boost::mutex::scoped_lock lock(m_cvMutex);
m_conditionVariablePacketSent.timed_wait(lock, boost::posix_time::milliseconds(500)); // call lock.unlock() and blocks the current thread
//thread is now unblocked, and the lock is reacquired by invoking lock.lock()
continue;
}
break;
}
}
void RateManagerAsync::WaitForAvailabilityToSendPacket_Blocking(unsigned int timeoutSeconds) {
const unsigned int maxAttempts = (timeoutSeconds * 2);
for (unsigned int attempt = 0; attempt < maxAttempts; ++attempt) {
const std::size_t numPacketsBeingSent = GetTotalPacketsBeingSent();
if (!HasAvailabilityToSendPacket()) {
boost::mutex::scoped_lock lock(m_cvMutex);
m_conditionVariablePacketSent.timed_wait(lock, boost::posix_time::milliseconds(500)); // call lock.unlock() and blocks the current thread
//thread is now unblocked, and the lock is reacquired by invoking lock.lock()
continue;
}
break;
}
}
bool RateManagerAsync::HasAvailabilityToSendPacket() {
return (GetTotalPacketsBeingSent() <= m_maxPacketsBeingSent);
} | [
"btomko@ndc.nasa.gov"
] | btomko@ndc.nasa.gov |
bbdfbde846103c07e6a94319a4bfb60675769027 | aa19cd5bf70a359ddfacfa769a2a27ff1c7ea099 | /Data Structures and Algorithms Assignment 1/MyOrderedArray.h | 9bd4f700d0d781f62b5b344df67098e8d3ddf75c | [] | no_license | IronArrow2/Data-Structures-and-Algorithms-Assignment-1 | 0b33b16c4f5a1e5987013cf86dd91dcacdd00c61 | dcd17f56a3a3a0c51f9efea825d79ccfafef6ddf | refs/heads/master | 2023-08-16T10:13:54.887183 | 2021-10-08T00:38:45 | 2021-10-08T00:38:45 | 414,690,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,351 | h | #pragma once
#include "MyArray.h"
template<class T>
class MyOrderedArray : public MyArray<T>
{
public:
MyOrderedArray(int size, int growBy = 1) : MyArray<T>(size, growBy) {}
~MyOrderedArray() = default;
// Insertion -- Big-O = O(N)
void push(T val)
{
assert(MyArray<T>::m_array != nullptr);
if (MyArray<T>::m_numElements >= MyArray<T>::m_maxSize)
{
MyArray<T>::Expand();
}
int i, k; // i - Index to be inserted. k - Used for shifting purposes
// Step 1: Find the index to insert val
for (i = 0; i < MyArray<T>::m_numElements; i++)
{
if (MyArray<T>::m_array[i] == val)
{
//duplicate data, don't finish insertion operation
return;
}
if (MyArray<T>::m_array[i] > val)
{
break;
}
}
// Step 2: Shift everything to the right of the index(i) forward by one. Work backwards
for (k = MyArray<T>::m_numElements; k > i; k--)
{
MyArray<T>::m_array[k] = MyArray<T>::m_array[k - 1];
}
// Step 3: Insert val into the array at index
MyArray<T>::m_array[i] = val;
MyArray<T>::m_numElements++;
// return i;
}
// Searching
// Binary Search
int search(T searchKey)
{
// Call to binary search recursive function
// Binary Search: searchKey, initial lowerBound, initial upperBound
return binarySearch(searchKey, 0, MyArray<T>::m_numElements - 1);
}
private:
// Private functions
// Recursive Binary Search
int binarySearch(T searchKey, int lowerBound, int upperBound)
{
assert(MyArray<T>::m_array != nullptr);
assert(lowerBound >= 0);
assert(upperBound < MyArray<T>::m_numElements);
// Bitwise divide by 2
int current = (lowerBound + upperBound) >> 1;
// Check 1 "Base case": Did we find the searchKey at the current index?
if (MyArray<T>::m_array[current] == searchKey)
{
// We found it! Return the index
return current;
}
// Check 2 "Base base": Are we done searching?
else if (lowerBound > upperBound)
{
// Did not find searchKey within m_array
return -1;
}
// Check 3: Which half of the array is searchKey in?
else
{
if (MyArray<T>::m_array[current] < searchKey)
{
// Search the upper half of the array
return binarySearch(searchKey, current + 1, upperBound);
}
else
{
// Search the lower half of the array
return binarySearch(searchKey, lowerBound, current - 1);
}
}
return -1;
}
}; | [
"72821274+IronArrow2@users.noreply.github.com"
] | 72821274+IronArrow2@users.noreply.github.com |
4ceac473725e92241b7628da2312f1d9af8773a1 | a94a34cd7af1f45267e6eb0dfda627f1a9c7070c | /Practices/Training/Competition/SummerVacation/20190723/source/jn02-35_192.168.100.35_余家谦/folding.cpp | 29362e48397f6095975e2de60d5cbb6b6c82c8ee | [] | no_license | AI1379/OILearning | 91f266b942d644e8567cda20c94126ee63e6dd4b | 98a3bd303bc2be97e8ca86d955d85eb7c1920035 | refs/heads/master | 2021-10-16T16:37:39.161312 | 2021-10-09T11:50:32 | 2021-10-09T11:50:32 | 187,294,534 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 419 | cpp | #include<bits/stdc++.h>
using namespace std;
int temp,ans;
double w1,h1,w2,h2;
int main(){
freopen("folding.in","r",stdin);
freopen("folding.out","w",stdout);
cin>>w1>>h1>>w2>>h2;
if(w1<h1){
temp=w1;
w1=h1;
h1=temp;
}
if(w2<h2){
temp=w2;
w2=h2;
h2=temp;
}
if(w1<w2||h1<h2){
cout<<-1;
return 0;
}
while(w1>w2){
w1/=2;
ans++;
}
while(h1>h2){
h1/=2;
ans++;
}
cout<<ans;
return 0;
}
| [
"Kc20060529@163.com"
] | Kc20060529@163.com |
f58b039899b873577e0d516b11f8d141c34f75a3 | 2cb3e1435380226bc019f9c4970be871fd54288e | /opencv/build/modules/core/count_non_zero.simd_declarations.hpp | 441341b7d55c35c80999a868f48076667d998f9d | [
"Apache-2.0"
] | permissive | 35048542/opencv-contrib-ARM64 | 0db9f49721055f8597dd766ee8749be68054c526 | 25386df773f88a071532ec69ff541c31e62ec8f2 | refs/heads/main | 2023-07-20T10:43:13.265246 | 2021-08-24T13:55:38 | 2021-08-24T13:55:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 180 | hpp | #define CV_CPU_SIMD_FILENAME "/home/epasholl/opencv/opencv-master/modules/core/src/count_non_zero.simd.hpp"
#define CV_CPU_DISPATCH_MODES_ALL BASELINE
#undef CV_CPU_SIMD_FILENAME
| [
"epasholl@umich.edu"
] | epasholl@umich.edu |
c5d0ef8211a1df0903325e8bcbdacfb87047e9a7 | dd6147bf9433298a64bbceb7fdccaa4cc477fba6 | /8381/Maria_Lisok/lr4/code/Base/compositeUnit.cpp | 171a1e58154a05612c6fa3dde891c59a98e87236 | [] | no_license | moevm/oop | 64a89677879341a3e8e91ba6d719ab598dcabb49 | faffa7e14003b13c658ccf8853d6189b51ee30e6 | refs/heads/master | 2023-03-16T15:48:35.226647 | 2020-06-08T16:16:31 | 2020-06-08T16:16:31 | 85,785,460 | 42 | 304 | null | 2023-03-06T23:46:08 | 2017-03-22T04:37:01 | C++ | UTF-8 | C++ | false | false | 1,691 | cpp | #include "compositeUnit.h"
void CompositeUnit::addUnit(Unit *unit)
{
units.push_back(unit);
}
bool CompositeUnit::delUnit(Subject *unit)
{
for(std::vector<Unit*>::iterator iter = units.begin(); iter != units.end(); iter++){
if (*iter == unit){
units.erase(iter);
return true;
}
}
return false;
}
string CompositeUnit::getName()
{
string names{};
for(Unit* u : units){
if(u == units.back()){
names.append(u->getName());
}else{
names.append("\n");
}
}
return names;
}
Unit *CompositeUnit::copyItem()
{
return new CompositeUnit(*this);
}
string CompositeUnit::characteristic()
{
string characteristic{};
for(Unit* u : units){
if(u == units.back()){
characteristic.append(u->getName());
}else{
characteristic.append("\n");
}
}
return characteristic;
}
Attributes *CompositeUnit::getAttributes() const
{
size_t health = 0;
size_t armor = 0;
size_t attack = 0;
for(Unit* u : units){
health += static_cast<size_t>(u->getAttributes()->getHealth());
armor += static_cast<size_t>(u->getAttributes()->getArmor());
attack += static_cast<size_t>(u->getAttributes()->getAttack());
}
attributes->setAllAttributes(static_cast<int>(health), static_cast<int>(armor), static_cast<int>(attack));
return attributes;
}
void CompositeUnit::move(int x, int y)
{
for(Unit* u : units){
u->move(x, y);
}
}
Unit *CompositeUnit::getUnit(int x) const
{
return units.at(x);
}
UnitsType CompositeUnit::getTypeEnum() const
{
return COMPOSITEUNITS;
}
| [
"mari.lisok@mail.ru"
] | mari.lisok@mail.ru |
c7266cb9a800c1b7d7168d7c566641c4523633e2 | f72eebaf78ac6613c1bc6950487f4206075a680f | /Main.cpp | 473813cd1ee20d50505feaf770ec55d1a6a7220f | [] | no_license | unkleandy/GeneticAlgorithm | 556493073763f8e7394db0514a6f14887da6f652 | a987cff34e2770c4bd24deefbbd8168fcf334140 | refs/heads/master | 2023-04-24T01:27:40.469040 | 2021-05-28T16:41:12 | 2021-05-28T16:41:12 | 227,451,093 | 0 | 0 | null | 2021-05-28T16:41:13 | 2019-12-11T20:10:10 | C++ | UTF-8 | C++ | false | false | 796 | cpp | #include <console.h>
using namespace::std;
using namespace windows_console;
int main() {
csl << window::title("B52")
<< window::fit(300, 200, "Consolas", font::size_type{ 3 }, font::ratio_type{ 1 })
<< window::unclosable
<< window::unresizable
<< window::center
<< cursor::invisible;
image im;
im << pen(dot, text_color(bright, red), background_color(dark, red))
<< point(100, 100)
<< brush(dot, text_color(dark, blue), background_color(dark, blue))
<< rectangle(105, 105, 150, 150)
<< no_brush
<< circle(200, 155, 50)
<< line(0, 0, 250, 100);
csl << im;
console_events ce;
ce.read_events();
while (ce.key_events_count())
switch (ce.next_key_event().ascii_value())
{
case 27: return 0;
case ' ': return 0;
break;
default: break;
}
return 0;
} | [
"1174982@decinfo.cvm"
] | 1174982@decinfo.cvm |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.