blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
177ce34280310c74c7014e19f6475d695f62eda6 | C++ | scarensac/SPlisHSPlasH_for_cuda | /SPlisHSPlasH/MathLib/Point3d.h | UTF-8 | 3,846 | 2.9375 | 3 | [
"MIT"
] | permissive | /*
Simbicon 1.5 Controller Editor Framework,
Copyright 2009 Stelian Coros, Philippe Beaudoin and Michiel van de Panne.
All rights reserved. Web: www.cs.ubc.ca/~van/simbicon_cef
This file is part of the Simbicon 1.5 Controller Editor Framework.
Simbicon 1.5 Controller Editor Framework is free software: you can
redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Simbicon 1.5 Controller Editor Framework 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 Simbicon 1.5 Controller Editor Framework.
If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <MathLib\ThreeTuple.h>
#include <Utils/Utils.h>
class Vector3d;
/*=====================================================================================================================================================*
| This class implements a Point in 3d. It will be stored in homogenous coordinates (x, y, z, w). Every time a w-component is set, the x, y, z will be |
| rescaled so that w results in being 1 - in other words, the w component is always 1. The x, y and z components are inherited from the Three Tuple |
| class that this class extends. |
*=====================================================================================================================================================*/
class Point3d : public ThreeTuple{
public:
/**
some useful constructors.
*/
Point3d() : ThreeTuple(){
}
Point3d(double x, double y, double z) : ThreeTuple(x, y, z){
}
Point3d(double x, double y, double z, double w) : ThreeTuple(x, y, z){
setW(w);
}
Point3d(double x, double y) : ThreeTuple(x, y){
}
Point3d(std::string data) : ThreeTuple(data){
}
Point3d(char* data) : ThreeTuple(data){
}
Point3d(const char* data) : ThreeTuple(data){
}
Point3d(ThreeTuple &p) : ThreeTuple(p){
}
Point3d(const Point3d& other){
this->x = other.x;
this->y = other.y;
this->z = other.z;
}
Point3d& operator = (const Point3d& other){
this->x = other.x;
this->y = other.y;
this->z = other.z;
return *this;
}
/**
default destructor.
*/
virtual ~Point3d(){}
/**
this method is used to set the w component.
*/
inline void setW(double w){
if (w == 0)
throwError("Cannot set w-component of a point to 0.");
this->x/=w;
this->y/=w;
this->z/=w;
}
//*this = p + v * s
void setToOffsetFromPoint(const Point3d &p, const Vector3d& v, double s);
/**
addition of a point and a vector - results in a point
*/
Point3d operator + (const Vector3d &v) const;
/**
add this vector to the current point
*/
Point3d& operator += (const Vector3d &v);
inline Point3d& operator /= (double val){
double v = 1/val;
x *= v;
y *= v;
z *= v;
return *this;
}
inline Point3d operator / (double val){
double r = 1/val;
return Point3d(this->x*r , this->y*r,this->z*r);
}
/**
difference betewwn two points - results in a vector
*/
Vector3d operator - (const Point3d &p) const;
/**
difference betewwn two points - results in a vector
*/
Vector3d operator * (double val) const;
/**
Returns a vector that has all its components multiplied by -1.
*/
inline Point3d operator - (){
return Point3d(-this->x, -this->y, -this->z);
}
void drawObject();
// virtual Point3d* createCopy();
};
| true |
b431fb97e3b4d1baec3a9a56b6d075d21759e80e | C++ | dpeng/smallApps | /Calendar/Calendar/Lunar.cpp | GB18030 | 24,468 | 2.515625 | 3 | [] | no_license | #include "StdAfx.h"
#include "Lunar.h"
//1900굽2100ÿеϢ
//ÿֻ2930죬һ1213λʾӦλΪ130죬Ϊ29
const int CLunar::m_lunarInfo[]={ //ũϢ
0x4bd8,0x4ae0,0xa570,0x54d5,0xd260,0xd950,0x5554,0x56af,0x9ad0,0x55d2,//1900-1909
0x4ae0,0xa5b6,0xa4d0,0xd250,0xd255,0xb54f,0xd6a0,0xada2,0x95b0,0x4977,//1910-1919
0x497f,0xa4b0,0xb4b5,0x6a50,0x6d40,0xab54,0x2b6f,0x9570,0x52f2,0x4970,//1920-1929
0x6566,0xd4a0,0xea50,0x6a95,0x5adf,0x2b60,0x86e3,0x92ef,0xc8d7,0xc95f,//1930-1939
0xd4a0,0xd8a6,0xb55f,0x56a0,0xa5b4,0x25df,0x92d0,0xd2b2,0xa950,0xb557,//1940-1949
0x6ca0,0xb550,0x5355,0x4daf,0xa5b0,0x4573,0x52bf,0xa9a8,0xe950,0x6aa0,//1950-1959
0xaea6,0xab50,0x4b60,0xaae4,0xa570,0x5260,0xf263,0xd950,0x5b57,0x56a0,//1960-1969
0x96d0,0x4dd5,0x4ad0,0xa4d0,0xd4d4,0xd250,0xd558,0xb540,0xb6a0,0x95a6,//1970-1979
0x95bf,0x49b0,0xa974,0xa4b0,0xb27a,0x6a50,0x6d40,0xaf46,0xab60,0x9570,//1980-1989
0x4af5,0x4970,0x64b0,0x74a3,0xea50,0x6b58,0x5ac0,0xab60,0x96d5,0x92e0,//1990-1999
0xc960,0xd954,0xd4a0,0xda50,0x7552,0x56a0,0xabb7,0x25d0,0x92d0,0xcab5,//2000-2009
0xa950,0xb4a0,0xbaa4,0xad50,0x55d9,0x4ba0,0xa5b0,0x5176,0x52bf,0xa930,//2010-2019
0x7954,0x6aa0,0xad50,0x5b52,0x4b60,0xa6e6,0xa4e0,0xd260,0xea65,0xd530,//2020-2029
0x5aa0,0x76a3,0x96d0,0x4afb,0x4ad0,0xa4d0,0xd0b6,0xd25f,0xd520,0xdd45,//2030-2039
0xb5a0,0x56d0,0x55b2,0x49b0,0xa577,0xa4b0,0xaa50,0xb255,0x6d2f,0xada0,//2040-2049
0x4b63,0x937f,0x49f8,0x4970,0x64b0,0x68a6,0xea5f,0x6b20,0xa6c4,0xaaef,//2050-2059
0x92e0,0xd2e3,0xc960,0xd557,0xd4a0,0xda50,0x5d55,0x56a0,0xa6d0,0x55d4,//2060-2069
0x52d0,0xa9b8,0xa950,0xb4a0,0xb6a6,0xad50,0x55a0,0xaba4,0xa5b0,0x52b0,//2070-2079
0xb273,0x6930,0x7337,0x6aa0,0xad50,0x4b55,0x4b6f,0xa570,0x54e4,0xd260,//2080-2089
0xe968,0xd520,0xdaa0,0x6aa6,0x56df,0x4ae0,0xa9d4,0xa4d0,0xd150,0xf252,//2090-2099
0x0d520//2100
};
const CString CLunar::m_TIANGAN[]={ //
_T(""),_T(""),_T(""),_T(""),_T(""),_T(""),_T(""),_T(""),
_T(""),_T("")
};
const CString CLunar::m_DIZHI[]={ //֧
_T(""),_T(""),_T(""),_T("î"),_T(""),_T(""),_T(""),_T("δ"),
_T(""),_T(""),_T(""),_T("")
};
const CString CLunar::m_Animals[]={ //Ф
_T(""),_T("ţ"),_T(""),_T(""),_T(""),_T(""),_T(""),_T(""),
_T(""),_T(""),_T(""),_T("")
};
const CString CLunar::m_nStr1[]={ //ֵ
_T(""),_T("һ"),_T(""),_T(""),_T(""),_T(""),_T(""),_T(""),
_T(""),_T(""),_T("ʮ"),_T("ʮһ"),_T("ʮ")
};
//const CString CLunar::m_cMonName[] = {"*","","","","","","", "","","","ʮ","ʮһ",""};//ũµ
const CString CLunar::m_nStr2[]={ //ֵ
_T(""),_T("ʮ"),_T("إ"),_T("ئ"),_T("")
};
const int CLunar::m_solarMonth[]={ //µ
31,28,31,30,31,30,31,31,30,31,30,31
};
const CString CLunar::m_solarTerm[]={ //
_T("С"),_T(""),_T(""),_T("ˮ"),_T(""),_T(""),_T(""),
_T(""),_T(""),_T("С"),_T("â"),_T(""),_T("С"),_T(""),
_T(""),_T(""),_T("¶"),_T(""),_T("¶"),_T("˪"),_T(""),
_T("Сѩ"),_T("ѩ"),_T("")
};
/*
ÿС㵽ڵ㣨ʮȱ㣩ķ
תÿ궼һ
ڹתԲвȷĵȲ
*/
const int CLunar::m_sTermInfo[]={ //Ϣ
0,21208,42467,63836,85337,107014,128867,150921,173149,195551,218072,240693,
263343,285989,308563,331033,353350,375494,397447,419210,440795,462224,483532,
504758
};
const CString CLunar::m_monthName[]={ //µӢ
_T("JAN"),_T("FEB"),_T("MAR"),_T("APR"),_T("MAY"),_T("JUN"),_T("JUL"),_T("AUG"),
_T("SEP"),_T("OCT"),_T("NOV"),_T("DEC")
};
const CString CLunar::m_sFtv[]={ // *ʾż
_T("0101*Ԫ"),
_T("0106 й13˿[2005]"),
_T("0108 ܶ[1976]"),
_T("0121 [1924]"),
_T("0127 䵮[1893]"),
//-
_T("0202 ʪ[1996]"),
_T("0207 ԮϷ[1964]"),
_T("0210 [1960]"),
_T("0214 ˽"),
_T("0215 й12˿[1995]"),
_T("0219 Сƽ[1997]"),
_T("0221 ֳƶȶ[1949]"),
_T("0224 "),
_T("0228 ס"),
//-
_T("0301 ʺ[1983]"),
_T("0303 ȫ[2000]"),
_T("0305 й־Ը߷[2000] ëʡͬ־ѧϰ[1963] ܶ[1898] ˹[1953]"),
_T("0308 ʸŮ[1910]"),
_T("0312 ֲ[1979] ɽ"),
_T("0314 ʾ() ˼[1883]"),
_T("0315 Ȩ[1983]"),
_T("0316 ϵƶСȫͳһж"),
_T("0317 йҽ[1929] ʺ"),
_T("0317 йҽ[1929] ʺ"),
_T("0318 ȫƼ˲Ż 蹫[1871]"),
_T("0321 ˯[2001] ɭ(ҵ)[1972] ӹ[1976]"),
//_T("0321 "),
_T("0322 ˮ[1993] йˮ(322328)[1988/1994]"),
_T("0323 [1950]"),
_T("0324 ν˲[1996]"),
//_T("0325 ȫСѧȫ"),
_T("0330 ˹̹"),
//-
_T("0401 ˽ ȫ˶() ˰()"),
_T("0402 ʶͯͼ"),
_T("0407 [1950] 1994¬ᄈйʷ˼[2004]"),
_T("0421 ȫҵһ[1994]"),
_T("0422 [1970] [1870]"),
_T("0423 ͼͰȨ"),
_T("0424 귴ֳ[1957] ǷŹ"),
_T("0425 ȫԤ[1986]"),
_T("0426 ֪ʶȨ[2001]"),
_T("0427 "),
_T("0430 ȫͨȫ˼"),
//-
_T("0501 Ͷ[1889] ʾ"),
_T("0503 "),
_T("0504 й[1939] ˶[1919] Ƽ"),
_T("0505 ȱ[1994] ˼[1818]"),
_T("0508 ʮ[1948] Ц"),
_T("0512 ʻʿ[1912]"),
_T("0515 ʼͥ(ѯ)[1994]"),
_T("0517 [1969]"),
_T("0518 ʲ"),
_T("0520 ȫѧӪ[1990] ȫѧӪ[1990]"),
_T("0522 [1994/2001]"),
//_T("0523 ţ"),
_T("0526 ս[1993]"),
_T("0529 [1981]"),
_T("0530 ئԵ۹˶[1925]"),
_T("0531 [1988]"),
//-
_T("0601 ʶͯ[1949]"),
_T("0605 绷[1974]"),
_T("0606 ȫ[1996]"),
_T("0611 й˿"),
_T("0617 λĮɺ[1995]"),
_T("0620 [2001]"),
_T("0622 йͯƻ"),
_T("0623 ʰƥ[1894] "),
_T("0625 ȫ[1991]"),
_T("0626 ʷƷ[1987] (Ϲ)"),
_T("0630 "),
//-
_T("0701 й[1921] ۻع[1997] ʽ[1985] ޡʮ˿ա[1988]"),
_T("0702 "),
_T("0706 [1976]"),
_T("0707 йս[1937]"),
_T("0711 й[2005] (50)˿[1987]"),
_T("0720 ״γɹ[1969]"),
_T("0726 ()"),
_T("0728 һս[1914]"),
_T("0730 Ů"),
//-
_T("0801 йž[1927]"),
_T("0805 ˹[1895]"),
_T("0806 ʵӰ[1932]"),
_T("0808 йӽ(ְֽ)[1988]"),
_T("0809 [1994]"),
_T("0812 [1999]"),
_T("0813 Ʋ[1975/1976]"),
_T("0815 ձʽͶ[1945] 練˹սʤ[1945]"),
_T("0826 ȫʦѯ[1993]"),
//-
_T("0903 йսʤ[1945]"),
_T("0908 ɨä[1966] Ź(Ž)[1958]"),
_T("0909 ë[1976]"),
_T("0910 ʦ[1985]"),
_T("0914 "),
_T("0916 ʳ㱣[1987]"),
_T("0918 šһ±(й)[1931]"),
_T("0920 ȫ[2003] ȫ[1989]"),
_T("0921 ʺƽ(ȫͣͷDZ,2002Ժ)[2002]"),
_T("0925 ³Ѹ[1881]"),
_T("0926 ()Ļ[1989]"),
_T("0927 [1979]"),
//-
_T("1001*[1949] [1980] ʾ(˽)[1991]"),
//_T("1001 "),
_T("1002 ʺƽ()[1949]"),
_T("1004 綯[1949]"),
_T("1008 ȫѪѹ[1998] ʨӻӾ[1998]"),
_T("1009 ()[1969]"),
_T("1010 [1911] 羫[1992] "),
_T("1011 ԮϷη"),
_T("1012 (60)˿[1999]"),
_T("1013 йȷӽӼ[1949] 籣 ʽʦ øʱΪʱʱ[1884]"),
_T("1014 [1969]"),
_T("1015 ä˽(Ƚ)[1984]"),
_T("1016 ʳ[1979]"),
_T("1017 ƶ[1992]"),
_T("1019 ³Ѹ[1936]"),
_T("1022 紫ͳҽҩ[1992]"),
_T("1024 Ϲ[1945] 緢չϢ"),
_T("1028 硰Խա[2000]"),
_T("1031 ڼ"),
//-
_T("1107 ʮ(ֶгͽա)[1917]"),
_T("1108 й[2000]"),
_T("1109 ȫȫ[1992]"),
_T("1110 [1946]"),
_T("1111 ʿѧƽ(һ)"),
_T("1112 ɽ[1866, 1926] [1969]"),
_T("1114 [1991]"),
_T("1117 ʴѧ(ѧ)[1946]"),
_T("1120 ͯ[1986]"),
_T("1121 ʺ[1973] [1996]"),
_T("1124 浮[1893]"),
_T("1128 ˹[1820]"),
_T("1129 Ԯ˹̹[1977]"),
//-
_T("1201 簬̲[1988] µ[1886]"),
_T("1202 ϳһʽū[1986]"),
_T("1203 м[1992]"),
_T("1204 й[2001]"),
_T("1205 ʾúᷢչ־ԸԱ[1985] ʿ"),
_T("1207 [1994, 1996]"),
//_T("1208 ʶͯ"),
_T("1209 һ˶[1935] [1995]"),
_T("1210 Ȩ(ŵ)[1950]"),
_T("1211 [1998]"),
_T("1212 ±[1936]"),
_T("1213 Ͼɱա,Ѫʷ![1937]"),
_T("1215 ǿ"),
_T("1220 Żع[1999]"),
_T("1221 ˹ֵ[1879]"),
_T("1224 ƽҹ"),
_T("1225 ʥ"),
_T("1226 ë[1893]")
//_T("1229 ")
};
const CString CLunar::m_wFtv[]={//ijµĵڼڼ 6,7,8,9,10 ʾ 1,2,3,4,5 ڼ
/*_T("0120 "),
_T("0160 (粡)[1954]"), //һµһգµһգ
_T("0530 ĸ"),
_T("0540 ȫ"),
_T("0640 "),
_T("0921 Ͷ"),
_T("0942 ʺƽ"),
_T("0950 ˽ ͯ"),
_T("0960 纣"),
_T("1021 ס"),
_T("1023 ʼȻֺ()"),
_T("1154 ж")
*/
//ijµĵڼڼ 5,6,7,8 ʾ 1,2,3,4 ڼ
_T("0110 "),
_T("0150 (粡)[1954]"), //һµһգµһգ
_T("0351 ȫСѧȫ[1996]"),
_T("0430 ͯ[1986]"),
_T("0453 "),
_T("0520 ĸ[1914] ƶĸ[1997]"),
_T("0530 ȫ[1990]"),
_T("0532 ţ[1961]"),
_T("0630 "),
_T("0716 ʺ"),
_T("0911 Ͷ[1894]"),
_T("0932 ʺƽ(19812001)[1981]"),
_T("0936 ȫ[2001]"),
_T("0940 ˽[1958]"),
_T("0950 纣[1978] [2000]"),
_T("1011 ˾(ס)[1985]"),
_T("1013 ʼȻֺ()[1990]"),
_T("1144 ж"),
_T("1220 ʶͯӹ㲥")
};
const CString CLunar::m_lFtv[]={//ũ
_T("0101*"),
_T("0115 Ԫ(й˽) ׳ Ԫ ɽ ﺲ忨"),
_T("0116 «Ͻ(ʮʮ)"),
//_T("0202 ̧ͷ"),
_T("0125 ֽ"),
_T("0129 "),
_T("0201 "),
_T("0202 (̧ͷ) "),
_T("0208 嵶˽"),
_T("0315 ½(ʮإһ)"),
_T("0323 (ʥĸ)"),
_T("0408 ţ"),
_T("0418 Ǩ"),
_T("0505 峯 "),
_T("0513 ˮ"),
_T("0522 ¿³"),
_T("0529 Ŭ"),
_T("0606 ùý ܽ ׳ 峢½"),
_T("0624 塢塢塢塢塢ŵѽ"),
_T("0707 й˽(Ů, ɽ)"),
_T("0713 ½"),
_T("0715 Ԫ תɽ"),
_T("0815* 峢½"),
_T("0909 й(ϻ)[1989]"),
_T("1001 (ʮ³)"),
_T("1016 "),
_T("1208 ˽"),
_T("1223 [С(ɨ)]"),
_T("1224 Ϸ[ϷС()]"),
//_T("1224 С"),
_T("1200*Ϧ")
};
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CLunar::CLunar()
{
Init();
}
CLunar::~CLunar()
{
}
void CLunar::Init()
{
m_lYear=0; //Ԫ4λ
m_lMonth=0; //ũ
m_lDay=0; //ũ
m_isLeap=FALSE; //ǷΪũ?
//
m_cYear=_T(""); //, 2
m_cMonth=_T(""); //, 2
m_cDay=_T(""); //, 2
m_cAnimal=_T(""); //
//
m_lunarFestival=_T(""); //ũ
m_solarFestival=_T(""); //
m_solarTerms=_T(""); //
m_cYearName=_T(""); //żʾ
m_cWordDay=_T(""); //ֱʾ
m_cWordMonth=_T("");//ֱʾ
m_cMonthSB=_T(""); //´ С
}
//ũ y
int CLunar::getYearDays(int y)
{
int i=0, sum = 348;
for(i=0x8000; i>0x8; i>>=1)
sum += (m_lunarInfo[y-1900] & i)? 1: 0;
return(sum+getLeapDays(y));
}
//ũ yµ
int CLunar::getLeapDays(int y)
{
if(getLeapMonth(y))
return((m_lunarInfo[y-1899]&0xf)==0xf? 30: 29);
else
return(0);
}
//ũ yĸ 1-12 , û 0
int CLunar::getLeapMonth(int y)
{
int lm = m_lunarInfo[y-1900] & 0xf;
return(lm==0xf?0:lm);
}
//ũ ymµ
int CLunar::getMonthDays(int y,int m)
{
return((m_lunarInfo[y-1900] & (0x10000>>m))? 30: 29 );
}
// offset ظ֧, 0=
// 1900Ϊ(6036)
//cyclical(SY-1900+36) + ' '+Animals[(SY-4)%12]+'
CString CLunar::getGZ(LONGLONG num)
{
return m_TIANGAN[num%10] + m_DIZHI[num%12];
}
/*
//ڣڼ
int CLunar::getDayOfWeek(myDATETIME DayWk)
{
if(DayWk.month==1||DayWk.month==2)
{
DayWk.month+=12;
DayWk.year--;
}
int weekNum = (DayWk.day+1+2*DayWk.month+3*(DayWk.month+1)/5+DayWk.year+DayWk.year/4-DayWk.year/100+DayWk.year/400)%7;
return weekNum+1;
}
*/
/*
31556925974.7ΪתڣǺ롣
죬265.242199죬ÿİ97꣬
ͬҲԿĻһʮ
ǵĹ㷨һ
ijС (1900,0,6,2,5)
*/
int CLunar::getSTerm(int y,int n)//ijĵnΪ(0С)
{
LONGLONG lUtc1=-22085493000000000; //1900,1,6,2,5,0 unit:100ns
LONGLONG lUtc2=-116444736000000000; //1601,1,1,0,0,0 unit:100ns
ULONGLONG lDate=315569259747000;
lDate *= (y-1900);
lDate += UInt32x32To64(600000000,m_sTermInfo[n]);
lDate += lUtc1; //100ns--->ms
lDate -=lUtc2;
SYSTEMTIME st;
FileTimeToSystemTime((FILETIME*)&lDate,&st);
return st.wDay;
}
void CLunar::LunarCalendar(COleDateTime tmMeas)//ڣ
{
Init();
m_tmMeas = tmMeas;
int i, leap=0, temp=0;
//COleDateTime tmConst(1900,1,31,m_tmMeas.GetHour(),m_tmMeas.GetMinute(),m_tmMeas.GetSecond());
//COleDateTimeSpan tmSpan=m_tmMeas-tmConst;
//int offset2=static_cast<int>(floor(tmSpan.GetTotalDays()));
int y = m_tmMeas.GetYear();
int m = m_tmMeas.GetMonth();
int d = m_tmMeas.GetDay();
int w = m_tmMeas.GetDayOfWeek();
if (y == -1)
{
return;
}
ASSERT(y>1899 && y<2101);
m_cYearName = getYearName(y);
INT offset=static_cast<int>(getUTC(y,m,d)/864000000000 - getUTC(1900,1,31)/864000000000);
//int offset=lDaysFrom1900(date)-30;
for(i = 1900; i < 2100 && offset >0; i++)
{
temp = getYearDays(i);
offset -= temp;
}
if(offset < 0)
{
offset+=temp;
i--;
}
m_lYear = i;
leap = getLeapMonth(i); //ĸ
m_isLeap = FALSE;
for(i=1; i<13 && offset>0; i++)
{
//
if(leap>0 && i==(leap+1) && (!m_isLeap))
{
--i;
m_isLeap = TRUE;
temp = getLeapDays(m_lYear);
}
else
{
temp = getMonthDays(m_lYear, i);
}
//
if(m_isLeap==TRUE && i==(leap+1))
m_isLeap = FALSE;
offset -= temp;
}
if(offset==0 && leap>0 && i==leap+1)
{
if(m_isLeap)
{
m_isLeap = FALSE;
}
else
{
m_isLeap = TRUE;
--i;
}
}
if(offset < 0)
{
offset += temp;
--i;
}
m_lMonth = i;
m_cWordMonth = getWordMonth(i);
m_lDay = offset + 1;
m_cWordDay = getWordDay(m_lDay);
m_cMonthSB = ((m_isLeap?getLeapDays(m_lYear):getMonthDays(m_lYear,m_lMonth))>29)?_T(""):_T("С");
//////////////////////////////////////////////////////////////////////////
//ʼ
//36һѭ
//////// 1900Ϊ(6036)
m_cAnimal=m_Animals[(m_lYear-4)%12];
m_cYear=getGZ(m_lYear-1900+36);
/////// 19001СǰΪ (6012)
//m_cMonth= getGZ((y-1900)*12+m+12);
m_cMonth= getGZ((m_lYear-1900)*12+m_lMonth+1+12);
////////
//һ 1900/1/1
//1900/1/1 1970/1/1 25567, 1900/1/1 Ϊ(6010)
LONGLONG dayCyclical = getUTC(y,m,d)/864000000000+25567+10;
m_cDay= getGZ(dayCyclical);
//////////////////////////////////////////////////////////////////////////
//ʼ
//
int nMSterm = getSTerm(y, (m-1)*2);
if(d == getSTerm(y,(m-1)*2))
m_solarTerms = m_solarTerm[(m-1)*2];
else if(d==getSTerm(y,(m-1)*2+1))
m_solarTerms = m_solarTerm[(m-1)*2+1];
else
m_solarTerms =_T("");
//
m_solarFestival =_T("");
m_bStrong = FALSE;
int nFtvM =0, nFtvD =0;
CString strDesc;
BOOL bStrong;
int jtjt=sizeof(m_sFtv)/sizeof(m_sFtv[0]);
for(i=0; i<sizeof(m_sFtv)/sizeof(m_sFtv[0]); i++)
{
parseFtv(m_sFtv[i], nFtvM, nFtvD, strDesc, bStrong);
if(m == nFtvM && d == nFtvD)
{
if(!m_solarFestival.IsEmpty())
m_solarFestival += _T(" ");
m_solarFestival += strDesc;
m_bStrong = bStrong;
}
}
//ܽ
int nWeekNo =0, nWeekDay =0; //ڼܣڼ
for(i=0; i<sizeof(m_wFtv)/sizeof(m_wFtv[0]); i++)
{
parseFtv(m_wFtv[i],nFtvM,nFtvD,strDesc,bStrong);
nWeekNo = nFtvD/10;
nWeekDay = nFtvD%10; //0--
if((m == nFtvM) && (w-1) == nWeekDay )
{
if((nWeekNo<6 && (getWeekOfMonth(y,m,d)==nWeekNo)) || (nWeekNo>=6 && ((getWeeksOfMonth(y,m)-getWeekOfMonth(y,m,d)+6)==nWeekNo)))
{
if(!m_solarFestival.IsEmpty())
m_solarFestival += _T(" ");
m_solarFestival += strDesc;
m_bStrong = (m_bStrong? TRUE:bStrong);
}
}
}
//ɫ
//COleDateTime tmFirst(y,m,13,1,0,0); //13Dz
if(d==13 && w==6)
{
if(!m_solarFestival.IsEmpty())
m_solarFestival +=_T(" ");
m_solarFestival += _T("ɫ");;
}
//ֻ34 վдʢӣ321ջ֮ĵһ
//if(m==3 || m==4) {
// var estDay = new easter(y);
// if(m == estDay.m)
// ' Easter Sunday';
//}
//ũ
m_lunarFestival=_T("");
for(int j=0;j<sizeof(m_lFtv)/sizeof(m_lFtv[0]);j++)
{
parseFtv(m_lFtv[j],nFtvM,nFtvD,strDesc,bStrong);
if((m_lMonth==nFtvM && m_lDay==nFtvD) || (m_lMonth==nFtvM && nFtvD==0 && (m_isLeap?getLeapDays(m_lYear):getMonthDays(m_lYear,m_lMonth))==m_lDay)) //һ죬0ʾ
{
m_lunarFestival=strDesc;
m_bStrong=(m_bStrong?TRUE:bStrong);
}
}
}
// ָ UTCʱ 100ns
LONGLONG CLunar::getUTC(int nYear,int nMonth,int nDay,int nHour,int nMin,int nSec )
{
COleDateTime tmUtc(1970,1,1,0,0,0);
COleDateTime tmBase(nYear,nMonth,nDay,nHour,nMin,nSec);
SYSTEMTIME stUtc,stBase;
ULARGE_INTEGER lUtc,lBase;
tmUtc.GetAsSystemTime(stUtc);
tmBase.GetAsSystemTime(stBase);
SystemTimeToFileTime(&stUtc,(LPFILETIME)&lUtc);
SystemTimeToFileTime(&stBase,(LPFILETIME)&lBase);
LONGLONG lValue=static_cast<LONGLONG>(lBase.QuadPart-lUtc.QuadPart);
return lValue;
}
void CLunar::parseFtv(CString strInfo,int& nFirst,int& nLast,CString& strDesc,BOOL& bStrong)
{
CString sInfo(strInfo);
sInfo.TrimLeft();
sInfo.TrimRight();
if(sInfo.IsEmpty())
return;
CString sFirstNum,sLastNum;
sFirstNum=sInfo.Left(2);
sLastNum=sInfo.Mid(2,2);
nFirst=_ttoi(sFirstNum.GetBuffer(2));
nLast=_ttoi(sLastNum.GetBuffer(2));
sFirstNum.ReleaseBuffer();
sLastNum.ReleaseBuffer();
CString sStrong=sInfo.Mid(4,1);
if(sStrong==_T("*"))
bStrong=TRUE;
else
bStrong=FALSE;
strDesc=sInfo.Mid(5);
strDesc.TrimLeft();
}
int CLunar::getWeekOfMonth(int y, int m, int d)
{
COleDateTime tm(y,m,1,1,0,0);
COleDateTime tmCurr(y,m,d,1,0,0);
int nSpanDays=d-1;
int nWeekSpan=nSpanDays/7+1;
int nWeekDay=tm.GetDayOfWeek()+nSpanDays%7;
if(nWeekDay>7)
{
nWeekDay-=7;
nWeekSpan++;
}
return nWeekSpan;
}
int CLunar::getWeeksOfMonth(int y, int m)
{
return getWeekOfMonth(y, m, getSunMonthDays(y,m));
}
//õ
int CLunar::getSunMonthDays(int y, int m)
{
//㵱
int nMonths=0;
nMonths = m_solarMonth[m-1];
if(y % 100 != 0 && y % 4 == 0)
{
if(m == 2)
nMonths += 1;
}
return nMonths;
}
//
CString CLunar::getWordDay(int d)
{
CString s;
switch (d)
{
case 10:
s = _T("ʮ");
break;
case 20:
s = _T("ʮ");
break;
case 30:
s = _T("ʮ");
break;
default :
s = m_nStr2[d/10];
s += m_nStr1[d%10];
}
return s;
}
//
CString CLunar::getYearName(int y)
{
CString cYear,cTmp;
if(y>1874 && y<1909) //
{
(y-1874==1)?cTmp=_T("Ԫ"):cTmp.Format(_T("%d"),y-1874);
cYear.Format(_T("%s"),cTmp);
}
else if(y>1908 && y<1912) //ͳ
{
(y-1908==1)?cTmp=_T("Ԫ"):cTmp.Format(_T("%d"),y-1908);
cYear.Format(_T("ͳ%s"),cTmp);
}
else if(y>1911 && y<1950) //
{
(y-1911==1)?cTmp=_T("Ԫ"):cTmp.Format(_T("%d"),y-1911);
cYear.Format(_T("%s"),cTmp);
}
else if(y>1949) //
{
(y-1949==1)?cTmp=_T("Ԫ"):cTmp.Format(_T("%d"),y-1949);
cYear.Format(_T("%s"),cTmp);
}
else
cYear.Format(_T("Ԫ%d"),y);
return cYear;
}
| true |
2c25350910605212939f90789d63b4840c3942ae | C++ | Qazwar/ParabellumFramework | /ParabellumEngine/ParabellumFramework/InputDevice.cpp | UTF-8 | 7,287 | 2.578125 | 3 | [
"MIT"
] | permissive | #include "stdafx.h"
#include "InputDevice.h"
// ----------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------
ParabellumFramework::IO::InputDevice::InputDevice()
{
m_keyStateSwitch = false;
for (EUINT32 i = 0; i < 256; ++i)
{
m_currentKeyboardState[i] = 0;
m_previousKeyboardState[i] = 0;
}
m_historyPosition = 0;
m_mouseSpeed = 0.001f;
m_isLeftButtonHolded = false;
m_keyStateSwitch = false;
m_previousMouseX = 0;
m_previousMouseY = 0;
m_mouseX = 0;
m_mouseY = 0;
m_mouseDeltaX = 0;
m_mouseDeltaY = 0;
m_mousePreviousNormalized.Set(0.0f, 0.0f);
m_mouseCurrentNormalized.Set(0.0f, 0.0f);
m_mouseDeltaNormalized.Set(0.0f, 0.0f);
PFDLOG("PFII", "IODV", "InputDevice() : created");
}
ParabellumFramework::IO::InputDevice::InputDevice(InputDevice&)
{
}
ParabellumFramework::IO::InputDevice::~InputDevice()
{
}
// ----------------------------------------------------
// Methods
// ----------------------------------------------------
void
ParabellumFramework::IO::InputDevice::Update()
{
// save previous state before update
m_previousMouseState = m_currentMouseState;
// switch the state arrays
m_keyStateSwitch = !m_keyStateSwitch;
// update device
Device_Update();
// check the difference between mouse coordinates and generate an event
if ( (m_previousMouseX != m_mouseX) || (m_previousMouseY != m_mouseY) )
{
EventMouseMoved(m_mouseX, m_mouseY);
}
for (EUINT32 i = 0; i < 256; ++i)
{
if (WasKeyReleased(i)) EventKeyReleased((EBYTE)i);
if (IsKeyHolded(i)) EventKeyHolded((EBYTE)i);
}
// calculate selectin area for Left Button
if ( (IsLeftButtonDown() == true) && (m_isLeftButtonHolded == false) )
{
m_leftButtonPressed = m_mouseCurrentNormalized;
m_isLeftButtonHolded = true;
EventMouseLeftPressed(m_mouseCurrentNormalized.X, m_mouseCurrentNormalized.Y);
}
if ((IsLeftButtonDown() == false) && (m_isLeftButtonHolded == true))
{
m_leftButtonReleased = m_mouseCurrentNormalized;
m_isLeftButtonHolded = false;
EventMouseLeftReleased(m_mouseCurrentNormalized.X, m_mouseCurrentNormalized.Y);
}
// generate an event when a left button was pressed and dragged
if ((m_isLeftButtonHolded == true) && (WasMouseMoved() == true))
{
EventMouseLeftDragged(m_leftButtonPressed.X, m_leftButtonPressed.Y, m_mouseCurrentNormalized.X, m_mouseCurrentNormalized.Y, m_mouseDeltaNormalized.X, m_mouseDeltaNormalized.Y);
}
}
// ----------------------------------------------------
// Gets and Sets
// ----------------------------------------------------
unsigned char**
ParabellumFramework::IO::InputDevice::GetAddressOfKeyboardState()
{
if (m_keyStateSwitch == false)
return (unsigned char**)&m_currentKeyboardState;
else
return (unsigned char**)&m_previousKeyboardState;
}
unsigned char
ParabellumFramework::IO::InputDevice::GetCurrentKeyboardState(EUINT32 key)
{
if (m_keyStateSwitch == false)
return m_currentKeyboardState[key];
else
return m_previousKeyboardState[key];
}
unsigned char
ParabellumFramework::IO::InputDevice::GetPreviousKeyboardState(EUINT32 key)
{
if (m_keyStateSwitch == true)
return m_currentKeyboardState[key];
else
return m_previousKeyboardState[key];
}
ParabellumFramework::EBOOL
ParabellumFramework::IO::InputDevice::WasKeyReleased(EUINT32 key)
{
if ((GetPreviousKeyboardState(key) != 0) && (GetCurrentKeyboardState(key) == 0))
return true;
return false;
}
ParabellumFramework::EBOOL
ParabellumFramework::IO::InputDevice::IsKeyHolded(EUINT32 key)
{
if ((GetPreviousKeyboardState(key) != 0) && (GetCurrentKeyboardState(key) != 0))
return true;
return false;
}
ParabellumFramework::EBOOL
ParabellumFramework::IO::InputDevice::WasMouseMoved()
{
if ((m_previousMouseX - m_mouseX) != 0)
return true;
if ((m_previousMouseY - m_mouseY) != 0)
return true;
return false;
}
ParabellumFramework::EBOOL
ParabellumFramework::IO::InputDevice::WasLeftButtonDown()
{
if (PF_FLAG_ISSET(GetPreviousMouseState(), PFM_LEFT_DOWN))
return true;
return false;
}
ParabellumFramework::EBOOL
ParabellumFramework::IO::InputDevice::IsLeftButtonDown()
{
if (PF_FLAG_ISSET(GetCurrentMouseState(), PFM_LEFT_DOWN))
return true;
return false;
}
ParabellumFramework::EBOOL
ParabellumFramework::IO::InputDevice::WasLeftButtonReleased()
{
if (
(PF_FLAG_ISSET(GetCurrentMouseState(), PFM_LEFT_DOWN) == false) &&
(PF_FLAG_ISSET(GetPreviousMouseState(), PFM_LEFT_DOWN) == true)
)
return true;
return false;
}
ParabellumFramework::EUINT32
ParabellumFramework::IO::InputDevice::GetMouseX()
{
return m_mouseX;
}
ParabellumFramework::EUINT32
ParabellumFramework::IO::InputDevice::GetMouseY()
{
return m_mouseY;
}
ParabellumFramework::EINT32
ParabellumFramework::IO::InputDevice::GetMouseDeltaX()
{
return m_mouseDeltaX;
}
ParabellumFramework::EINT32
ParabellumFramework::IO::InputDevice::GetMouseDeltaY()
{
return m_mouseDeltaY;
}
void
ParabellumFramework::IO::InputDevice::GetMousePosition(EINT32& px, EINT32& py)
{
px = m_mouseX;
py = m_mouseY;
}
void
ParabellumFramework::IO::InputDevice::GetMousePositionNormalized(_OUT_ EFLOAT32& x, _OUT_ EFLOAT32& y)
{
x = m_mouseCurrentNormalized.X;
y = m_mouseCurrentNormalized.Y;
}
ParabellumFramework::EBOOL
ParabellumFramework::IO::InputDevice::GetMouseDragged(
_OUT_ EFLOAT32& pressedX, _OUT_ EFLOAT32& pressedY,
_OUT_ EFLOAT32& currentX, _OUT_ EFLOAT32& currentY,
_OUT_ EFLOAT32& deltaX, _OUT_ EFLOAT32& deltaY)
{
if ((m_isLeftButtonHolded == true) && (WasMouseMoved() == true))
{
pressedX = m_leftButtonPressed.X;
pressedY = m_leftButtonPressed.Y;
currentX = m_mouseCurrentNormalized.X;
currentY = m_mouseCurrentNormalized.Y;
deltaX = m_mouseDeltaNormalized.X;
deltaY = m_mouseDeltaNormalized.Y;
return true;
}
return false;
}
void
ParabellumFramework::IO::InputDevice::SetMousePosition(EUINT32 x, EUINT32 y)
{
// save previous values
m_previousMouseX = m_mouseX;
m_previousMouseY = m_mouseY;
m_mousePreviousNormalized = m_mouseCurrentNormalized;
m_mouseDeltaX = x - m_mouseX;
m_mouseDeltaY = y - m_mouseY;
if (m_isFicexDisplacement == false)
{
m_mouseX += m_mouseDeltaX;
m_mouseY += m_mouseDeltaY;
}
else
{
Vector2D fixVec;
fixVec = Math::Projection( Vector2D((EFLOAT32)m_mouseDeltaX, (EFLOAT32)m_mouseDeltaY), m_displacementVector);
m_mouseX += fixVec.X;
m_mouseY += fixVec.Y;
}
if (m_mouseX < 0) m_mouseX = 0;
if (m_mouseY < 0) m_mouseY = 0;
if (m_mouseX > 1650) m_mouseX = 1650;
if (m_mouseY > 1020) m_mouseY = 1020;
m_mouseCurrentNormalized.X = (EFLOAT32)m_mouseX / 1650.0f;
m_mouseCurrentNormalized.Y = (EFLOAT32)m_mouseY / 1020.0f;
m_mouseCurrentNormalized = Math::Clamp(m_mouseCurrentNormalized, 0.0f, 1.0f);
m_mouseDeltaNormalized = m_mouseCurrentNormalized - m_mousePreviousNormalized;
m_mouseDeltaNormalized = Math::Clamp(m_mouseDeltaNormalized, -1.0f, 1.0f);
}
void
ParabellumFramework::IO::InputDevice::MoveMousePosition(EUINT32 dx, EUINT32 dy)
{
SetMousePosition(m_mouseX + dx, m_mouseY + dy);
}
void
ParabellumFramework::IO::InputDevice::SetDisplacementVector(_IN_ Vector2D* displacementVector, EBOOL enabled)
{
m_isFicexDisplacement = enabled;
if(m_isFicexDisplacement)
m_displacementVector = *displacementVector;
} | true |
2938bf3d7ed949cf8326bfbea3503a923c374aeb | C++ | snega1003/cpp-tasks | /task9/src/test/trait_test.cc | UTF-8 | 510 | 2.734375 | 3 | [] | no_license | #include <gtest/gtest.h>
#include <vector>
#include <algorithm>
#include <iostream>
#include <random>
#include "project/trait.hh"
#include "project/group.hh"
#include "project/man.hh"
TEST(Traits, size)
{
using namespace my;
Man m("aaa", "bbb");
EXPECT_EQ(trait<Man>::size(m), 11);
Group g("NAME");
g.add(m);
EXPECT_EQ(trait<Group>::size(g), 79);
std::cout << trait<Group>::size(g) << std::endl;
g.add(Man("aaa", "bbb"));
EXPECT_EQ(trait<Group>::size(g), 90);
}
| true |
31a18b1b0c314073cfd8d7953a481898541bbb5e | C++ | luchunabf/Cplusplus | /test_6_30_static/test_6_30_static/static.cpp | GB18030 | 1,360 | 3.625 | 4 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
#if 0
//ʵһ࣬д˶ٸ
class A
{
public:
A()//캯һαʾһ
{
++_getCount;
}
A(const A& t)//캯һαʾһ
{
++_getCount;
}
static int GetCount()//̬Ա
{
return _getCount;
}
private:
static int _getCount;
};
int A::_getCount = 0;
int main()
{
cout << A::GetCount() << endl;
A a1, a2;
A a3(a2);
cout << A::GetCount() << endl;
return 0;
}
#endif
//1 + 2 + 3 + ... + nҪʹó˳forwhileifelseswitchcaseȹؼּж䣨A ? B : C
class Solution {
class Sum
{
public:
Sum()
{
++_count;
_total += _count;
}
static void Sumret()
{
_count = 0;
_total = 0;
}
static int GetCount()
{
return _total;
}
private:
static int _count;
static int _total;
};
public:
int Sum_Solution(int n) {
Sum::Sumret();
Sum* ps = new Sum[n];//ȶһ࣬ȻһnԪص飬ôĹ캯ᱻnΣǰۼӴŵ캯Ϳˡ
delete[] ps;
return Sum::GetCount();
}
};
int Solution::Sum::_count = 0;
int Solution::Sum::_total = 0;
| true |
ff84156a5384128bef8f9b571d6c7dec508e937c | C++ | OverFlame/bi | /JSOIT1-233.cpp | UTF-8 | 332 | 2.734375 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
using namespace std;
char s[233];
int sum, i = 0;
int main()
{
freopen("title.in","r",stdin);
freopen("title.out","w",stdout);
while (cin >> s[i] && s[i] != EOF)
{
++i;
if (s[i] != ' ')
++sum;
}
cout << sum << endl;
fclose(stdin);
fclose(stdout);
return 0;
}
| true |
74ccac9b51a21cb3c137beedb45d82ff56ee9663 | C++ | actor-framework/actor-framework | /libcaf_core/caf/detail/sync_ring_buffer.test.cpp | UTF-8 | 3,190 | 3.03125 | 3 | [] | permissive | // This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#include "caf/detail/sync_ring_buffer.hpp"
#include "caf/test/caf_test_main.hpp"
#include "caf/test/test.hpp"
#include <algorithm>
#include <vector>
using namespace caf;
namespace {
constexpr size_t int_buffer_size = 64;
using int_buffer = detail::sync_ring_buffer<int, int_buffer_size>;
std::vector<int> consumer(int_buffer& buf, size_t num) {
std::vector<int> result;
for (size_t i = 0; i < num; ++i) {
buf.wait_nonempty();
result.emplace_back(buf.front());
buf.pop_front();
}
return result;
}
void producer(int_buffer& buf, int first, int last) {
for (auto i = first; i != last; ++i)
buf.push_back(std::move(i));
}
} // namespace
TEST("a default-constructed ring buffer is empty") {
int_buffer buf;
check(buf.empty());
check(!buf.full());
check_eq(buf.size(), 0u);
}
TEST("push_back adds one element to the ring buffer") {
int_buffer buf;
print_debug("add one element");
buf.push_back(42);
check(!buf.empty());
check(!buf.full());
check_eq(buf.size(), 1u);
check_eq(buf.front(), 42);
print_debug("remove element");
buf.pop_front();
check(buf.empty());
check(!buf.full());
check_eq(buf.size(), 0u);
print_debug("fill buffer");
for (int i = 0; i < static_cast<int>(int_buffer_size - 1); ++i)
buf.push_back(std::move(i));
check(!buf.empty());
check(buf.full());
check_eq(buf.size(), int_buffer_size - 1);
check_eq(buf.front(), 0);
}
TEST("get_all returns all elements from the ring buffer") {
int_buffer buf;
using array_type = std::array<int, int_buffer_size>;
using vector_type = std::vector<int>;
array_type tmp;
auto fetch_all = [&] {
auto i = tmp.begin();
auto e = buf.get_all(i);
return vector_type(i, e);
};
print_debug("add five element");
for (int i = 0; i < 5; ++i)
buf.push_back(std::move(i));
check(!buf.empty());
check(!buf.full());
check_eq(buf.size(), 5u);
check_eq(buf.front(), 0);
print_debug("drain elements");
check_eq(fetch_all(), vector_type({0, 1, 2, 3, 4}));
check(buf.empty());
check(!buf.full());
check_eq(buf.size(), 0u);
print_debug("add 60 elements (wraps around)");
vector_type expected;
for (int i = 0; i < 60; ++i) {
expected.push_back(i);
buf.push_back(std::move(i));
}
check_eq(buf.size(), 60u);
check_eq(fetch_all(), expected);
check(buf.empty());
check(!buf.full());
check_eq(buf.size(), 0u);
}
TEST("sync_ring_buffer can be used with multiple producers") {
int_buffer buf;
std::vector<std::thread> producers;
producers.emplace_back(producer, std::ref(buf), 0, 100);
producers.emplace_back(producer, std::ref(buf), 100, 200);
producers.emplace_back(producer, std::ref(buf), 200, 300);
auto vec = consumer(buf, 300);
std::sort(vec.begin(), vec.end());
check(std::is_sorted(vec.begin(), vec.end()));
check_eq(vec.size(), 300u);
check_eq(vec.front(), 0);
check_eq(vec.back(), 299);
for (auto& t : producers)
t.join();
}
CAF_TEST_MAIN()
| true |
1825e1fc2d42c74dca6ab119fcf4f57dde6fa42c | C++ | francoisferland/hbba_base | /iw_tools/src/exploitation_matcher.cpp | UTF-8 | 3,523 | 2.625 | 3 | [] | no_license | #include <iw_tools/exploitation_matcher.hpp>
using namespace iw_tools;
ExploitationMatcher::ExploitationMatcher(
ros::NodeHandle& n, ros::NodeHandle& np)
{
sub_intention_ = n.subscribe("intention", 10,
&ExploitationMatcher::intentionCB, this);
sub_priority_ = np.subscribe("priority", 10,
&ExploitationMatcher::priorityCB, this);
pub_desire_ =
np.advertise<std_msgs::String>("exploited_desire", 10);
srv_register_ =
np.advertiseService("register_em", &ExploitationMatcher::registerCB, this);
topic_ns_ = np.getNamespace();
}
void ExploitationMatcher::intentionCB(const hbba_msgs::Intention::ConstPtr& msg)
{
// Flush the current desire map and rebuild it from scratch.
// Skip empty desires.
desire_map_.clear();
assert(msg->desires.size() == msg->desire_types.size());
for (size_t i = 0; i < msg->desires.size(); ++i)
{
const std::string& d_id = msg->desires[i];
const std::string& d_t = msg->desire_types[i];
if (d_id != "" && d_t != "")
{
DesireMapType::iterator dv = desire_map_.find(d_t);
if (dv == desire_map_.end())
dv = desire_map_.insert(
std::make_pair(d_t, StringVector())).first;
dv->second.push_back(d_id);
}
}
}
void ExploitationMatcher::priorityCB(const std_msgs::Int32::ConstPtr& msg)
{
// Find if any desire classes can be matched to the incoming
// priority value.
// Then, for each class found, find if any desires in the latest
// intention are currently associated with it.
// Publish an exploitation match for each of them, or warn the user.
int priority = msg->data;
if (priority_map_.find(priority) == priority_map_.end())
{
//ROS_DEBUG("Unknown priority value %i for topic %s",
// priority,
// topic_ns_.c_str());
return;
}
const StringVector& list = priority_map_[priority];
typedef StringVector::const_iterator ItType;
for (ItType i = list.begin(); i != list.end(); i++)
{
//ROS_DEBUG("Exploitation for desire type %s.", i->c_str());
DesireMapType::const_iterator d = desire_map_.find(*i);
if (d == desire_map_.end())
{
// This is totally normal for priorities than can fulfill
// two different desires:
//ROS_WARN("Desire type %s can't be matched to "
// "a current desire", i->c_str());
continue;
}
for (ItType j = d->second.begin(); j != d->second.end(); ++j)
{
std_msgs::String msg;
msg.data = *j;
pub_desire_.publish(msg);
if (cb_)
cb_(*j);
}
}
}
bool ExploitationMatcher::registerCB(
hbba_msgs::RegisterExploitationMatch::Request& req,
hbba_msgs::RegisterExploitationMatch::Response&)
{
registerMatches(req.priority, req.classes);
return true;
}
void ExploitationMatcher::registerMatches(
const hbba_msgs::ExploitationMatch& matches)
{
registerMatches(matches.priority, matches.classes);
}
void ExploitationMatcher::registerMatches(
int priority, const StringVector& classes)
{
if (priority_map_.find(priority) == priority_map_.end())
priority_map_[priority] = StringVector();
StringVector& list = priority_map_[priority];
list.reserve(list.size() + classes.size());
list.insert(list.end(), classes.begin(), classes.end());
}
| true |
7048c26ed27e6484963a466bfa6e46107e56d6e3 | C++ | DogAddan/FTPClient | /socket.h | UTF-8 | 723 | 2.640625 | 3 | [] | no_license | #ifndef SOCKET_H
#define SOCKET_H
#include <string>
#include <arpa/inet.h>
#include <QtDebug>
using namespace std;
class Socket
{
public:
//构造
Socket(int port,const char* ip_addr);
//析构
~Socket(void);
//发送
void sendMsg(const char* command,const char* content);
void sendMsg(const char* command);
int sendMsg(const string& buf);
//接收
int recvMsg(void);
int recvMsg(string& buf);
private:
//套接字描述符
int sockfd;
//目标地址
sockaddr_in* addr;
//创建socket对象
void createSocket(void);
//准备IP地址
void initSocket(int port,const char* ip_addr);
//连接
void linkSocket(void);
};
#endif // SOCKET_H
| true |
d79899d38f98f3de45202be03d12284d0afc41fa | C++ | danielbjorkman88/Cpp | /OpenGL/NbodyVis/Visualizer.cpp | UTF-8 | 7,870 | 2.546875 | 3 | [] | no_license |
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <cassert>
#include <nbody/Body.h>
#include <nbody/Vector3.h>
#include <chrono>
#include <thread>
#include "Renderer.h"
#include "VertexBuffer.h"
#include "IndexBuffer.h"
# define PI 3.14159265358979323846 /* pi */
struct ShaderProgramSource {
std::string VertexSource;
std::string FragmentSource;
};
struct circleLocations {
std::vector<float> xes;
std::vector<float> yes;
};
struct circles {
std::vector<circleLocations> circle;
};
int getBodiesCount(const std::string& filepath) {
std::ifstream stream(filepath);
std::string line;
getline(stream, line);
int nbodies = std::stoi(line);
return nbodies;
}
circles readSim(const std::string &filepath, std::string& filename, int nbodies, int nFiles) {
circles mycircles;
//circleLocations thisCircle;
//std::ifstream stream(filepath);
//std::string line;
//getline(stream, line);
for (int i = 0; i < nbodies; ++i) {
circleLocations thisCircle;
mycircles.circle.push_back(thisCircle);
}
std::cout << filepath << std::endl;
std::cout << filename << std::endl;
std::string secondPart;
int firstStop;
int secondStop;
float x;
float y;
///int j = 10;
for (int j = 0; j < nFiles; ++j) {
secondPart = filename;
secondPart.replace(0, 1, std::to_string(j));
std::cout << secondPart << std::endl;
std::ifstream stream(filepath + secondPart);
std::string line;
getline(stream, line);
//nbodies = std::stoi(line);
//std::cout << nbodies << std::endl;
for (int i = 0; i < nbodies; ++i) {
getline(stream, line);
firstStop = line.find(' ');
x = stof(line.substr(0, firstStop));
///std::cout << x << std::endl;
secondStop = line.substr(firstStop + 1, 20).find(" ");
y = stof(line.substr(firstStop + 1, secondStop));
///std::cout << y << std::endl;
mycircles.circle[i].xes.push_back(x);
mycircles.circle[i].yes.push_back(y);
}
}
for (int i = 0; i < nFiles; ++i) {
std::cout << i << " " << mycircles.circle[0].xes[i] << " " << mycircles.circle[0].yes[i] << std::endl;
}
//std::cout << mycircles.circle[1].xes[0] << " " << mycircles.circle[1].yes[0] << std::endl;
//while (getline(stream, line)) {
// std::cout << line << std::endl;
//}
return mycircles;
}
static ShaderProgramSource ParseShader(const std::string &filepath) {
std::ifstream stream(filepath);
enum class ShaderType {
NONE = -1, vertex = 0, fragment = 1
};
std::stringstream ss[2];
ShaderType type = ShaderType::NONE;
std::string line;
while (getline(stream, line)) {
if (line.find("#shader") != std::string::npos) {
if (line.find("vertex") != std::string::npos) {
type = ShaderType::vertex;
}
else if (line.find("fragment") != std::string::npos) {
type = ShaderType::fragment;
}
}
else {
ss[(int)type] << line << '\n';
}
}
return { ss[0].str() , ss[1].str() };
}
static unsigned int CompileShader(unsigned int type, const std::string& source) {
unsigned int id = glCreateShader(type);
const char* src = source.c_str();
glShaderSource(id, 1, &src, nullptr);
glCompileShader(id);
int result;
glGetShaderiv(id, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE) {
int length;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);
char *message = (char*)alloca(length * sizeof(char));
glGetShaderInfoLog(id, length, &length, message);
std::cout << "Failed to compile " << (type == GL_VERTEX_SHADER ? "vertex" : "fragment") << " shader!" << std::endl;
std::cout << message << std::endl;
glDeleteShader(id);
return 0;
}
return id;
}
static unsigned int CreateShader(const std::string& vertexShader, const std::string& fragmentShader) {
unsigned int program = glCreateProgram();
unsigned int vs = CompileShader(GL_VERTEX_SHADER, vertexShader);
unsigned int fs = CompileShader(GL_FRAGMENT_SHADER, fragmentShader);
glAttachShader(program, vs);
glAttachShader(program, fs);
glLinkProgram(program);
glValidateProgram(program);
glDeleteShader(vs);
glDeleteShader(fs);
return program;
}
void drawFilledCircle(GLfloat x, GLfloat y, GLfloat radius) {
int i;
int triangleAmount = 20; //# of triangles used to draw circle
//GLfloat radius = 0.8f; //radius
GLfloat twicePi = 2.0f * PI;
glBegin(GL_TRIANGLE_FAN);
glVertex2f(x, y); // center of circle
for (i = 0; i <= triangleAmount; i++) {
glVertex2f(
x + (radius * cos(i * twicePi / triangleAmount)),
y + (radius * sin(i * twicePi / triangleAmount))
);
}
glEnd();
}
int main(void)
{
GLFWwindow* window;
/* Initialize the library */
if (!glfwInit())
return -1;
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
glfwSwapInterval(1);
/* Make the window's context current */
glfwMakeContextCurrent(window);
if (glewInit() != GLEW_OK) {
std::cout << "Error! GLEW not working" << std::endl;
}
std::cout << "GL Version: " << glGetString(GL_VERSION) << std::endl;
float positions[] = {
-0.5f, -0.5f,
0.5f, -0.5f,
0.5f, 0.5f,
-0.5f, 0.5f,
};
unsigned int indicies[] = {
0,1,2,
2,3,0
};
/// Vertex Buffer
VertexBuffer vb(positions, 4 * 2 * sizeof(float));
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_TRUE, sizeof(float) * 2, 0); // 0 = first attribute, 2 = size of vertex
/// Index Buffer
IndexBuffer ib(indicies, 6);
ShaderProgramSource source = ParseShader("myshader.shader");
std::string filename = "0200923827-sim.txt";
std::string filepath = "C:/Users/malyr/OneDrive/Dokument/GitHub/Cpp/MIT Course Effective Programming in C and C++/N-body problem/";
int nFiles = 81;
int nbodies = getBodiesCount(filepath + filename);
circles mycircles = readSim(filepath , filename, nbodies, nFiles);
unsigned int shader = CreateShader(source.VertexSource, source.FragmentSource);
glUseProgram(shader);
int location = glGetUniformLocation(shader, "u_Color");
assert(location != -1);
int i = 0;
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window) )
{
/* Render here */
glClear(GL_COLOR_BUFFER_BIT);
///glDrawArrays(GL_TRIANGLES, 0, 6); /// Draw call
GLClearError();
glUniform4f(location, 0.0f, 1.0f, 1.0f, 1.0f);
ib.Bind();
///glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
GLfloat radius = 0.01;
for (int j = 0; j < nbodies ; ++j){
GLfloat x = mycircles.circle[j].xes[i];
GLfloat y = mycircles.circle[j].yes[i];;
drawFilledCircle(x , y , radius);
}
GLCheckError();
i += 1;
if (i >= nFiles) {
i = 0;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glDeleteProgram(shader);
glfwTerminate();
return 0;
} | true |
e9b5d80ef611955d2dc2ffe1d31a24b7112bdb52 | C++ | kwansu/3DGraphicsFramework_Practice | /3D_Game_API1.2/3D_Game_API/cVector3.cpp | UTF-8 | 1,538 | 3.25 | 3 | [] | no_license | #include "StdAfx.h"
#include "cVector3.h"
cVector3::cVector3()
: x(0), y(0), z(0)
{
}
cVector3::cVector3(float _x, float _y, float _z)
: x(_x), y(_y), z(_z)
{
}
cVector3::~cVector3()
{
}
bool cVector3::operator==(const cVector3& vec)
{
if (!EqualFloat(x, vec.x))
return false;
if (!EqualFloat(y, vec.y))
return false;
if (!EqualFloat(z, vec.z))
return false;
return true;
}
bool cVector3::operator!=(const cVector3& vec)
{
return !this->operator==(vec);
}
cVector3 cVector3::operator+(const cVector3& vec)
{
return cVector3(x + vec.x, y + vec.y, z + vec.z);
}
cVector3 cVector3::operator-(const cVector3& vec)
{
return cVector3(x - vec.x, y - vec.y, z - vec.z);
}
cVector3 cVector3::operator*(float scalar)
{
return cVector3(x*scalar, y*scalar, z*scalar);
}
cVector3 cVector3::operator/(float scalar)
{
return this->operator*(1 / scalar);
}
float cVector3::Length()
{
return sqrt(x*x + y*y + z*z);
}
cVector3 cVector3::Normalize()
{
return this->operator/(Length());
}
float cVector3::Dot(const cVector3& v1, const cVector3& v2)
{
return (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z);
}
cVector3 cVector3::Cross(const cVector3& v1, const cVector3& v2)
{
return cVector3(v1.y*v2.z - v1.z*v2.y
, v1.z*v2.x - v1.x*v2.z
, v1.x*v2.y - v1.y*v2.x);
}
cVector3 operator*(float scalar, cVector3& vec)
{
return vec.operator*(scalar);
}
cVector3 operator-(cVector3& vec)
{
return vec.operator*(-1);
}
| true |
0c2b1c5493254a2f8d3c9df4681feb39ce30f392 | C++ | thefullarcticfox/ft_containers | /algorithm.hpp | UTF-8 | 5,551 | 3.125 | 3 | [] | no_license | #ifndef ALGORITHM_HPP
#define ALGORITHM_HPP
#include "adapted_traits.hpp"
#include "functional.hpp"
namespace ft {
template <class T1, class T2>
struct _equal_twotypes : binary_function<T1, T2, bool> {
bool operator()(const T1& x, const T2& y) const
{ return (x == y); }
};
template <class T1, class T2>
struct _less_twotypes : binary_function<T1, T2, bool> {
bool operator()(const T1& x, const T2& y) const
{ return (x < y); }
};
template <class InputIterator1, class InputIterator2, class BinaryPredicate>
bool equal(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, BinaryPredicate pred)
{
while (first1 != last1)
{
if (!pred(*first1, *first2))
return (false);
++first1; ++first2;
}
return (true);
}
template <class InputIterator1, class InputIterator2, class Compare>
bool lexicographical_compare(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2, Compare comp)
{
while (first1 != last1)
{
if (first2 == last2 || comp(*first2, *first1))
return (false);
else if (comp(*first1, *first2))
return (true);
++first1; ++first2;
}
return (first2 != last2);
}
template <class InputIterator1, class InputIterator2>
bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2)
{
typedef typename ft::iterator_traits<InputIterator1>::value_type type1;
typedef typename ft::iterator_traits<InputIterator2>::value_type type2;
return (ft::equal(first1, last1, first2, _equal_twotypes<type1, type2>()));
}
template <class InputIterator1, class InputIterator2>
bool lexicographical_compare(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2)
{
typedef typename ft::iterator_traits<InputIterator1>::value_type type1;
typedef typename ft::iterator_traits<InputIterator2>::value_type type2;
return (ft::lexicographical_compare(first1, last1, first2, last2, _less_twotypes<type1, type2>()));
}
template <class Iterator>
typename iterator_traits<Iterator>::difference_type
_find_distance(Iterator first, Iterator last, std::input_iterator_tag)
{
typename iterator_traits<Iterator>::difference_type res = 0;
for (; first != last; first++)
++res;
return (res);
}
template <class Iterator>
typename iterator_traits<Iterator>::difference_type
_find_distance(Iterator first, Iterator last, std::random_access_iterator_tag)
{ return (last - first); }
template <class InputIterator>
typename iterator_traits<InputIterator>::difference_type
distance(InputIterator first, InputIterator last)
{
return (_find_distance(first, last,
typename iterator_traits<InputIterator>::iterator_category()));
}
// additional function for heap algorithm
template <class Iterator>
void _swap_values(Iterator first, Iterator second)
{
typename iterator_traits<Iterator>::value_type tmp = *first;
*first = *second;
*second = tmp;
}
/* heap algorithm */
template <class Iterator, class Compare, class DiffType>
void _heapify(Iterator first, Iterator last, Compare comp, DiffType index)
{
DiffType size = distance(first, last);
DiffType left = index * 2;
DiffType right = index * 2 + 1;
DiffType largest = index;
if (left <= size && comp(first[largest - 1], first[left - 1]))
largest = left;
if (right <= size && comp(first[largest - 1], first[right - 1]))
largest = right;
if (index != largest) {
_swap_values(first + (index - 1), first + (largest - 1));
_heapify(first, last, comp, largest);
}
}
template <class RandomAccessIterator, class Compare>
void make_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp)
{
typedef typename iterator_traits<RandomAccessIterator>::difference_type t_diff;
for (t_diff i = distance(first, last) / 2; i >= 1; i--)
_heapify(first, last, comp, i);
}
template <class RandomAccessIterator>
void make_heap(RandomAccessIterator first, RandomAccessIterator last)
{
make_heap(first, last, less<typename iterator_traits<RandomAccessIterator>::value_type>());
}
template <class RandomAccessIterator, class Compare>
void push_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp)
{
typedef iterator_traits<RandomAccessIterator> traits;
typename traits::difference_type i = distance(first, last);
while (i > 1 && comp(first[i / 2 - 1], first[i - 1])) {
_swap_values(first + (i / 2 - 1), first + (i - 1));
i /= 2;
}
}
template <class RandomAccessIterator>
void push_heap(RandomAccessIterator first, RandomAccessIterator last)
{
push_heap(first, last, less<typename iterator_traits<RandomAccessIterator>::value_type>());
}
template <class RandomAccessIterator, class Compare>
void pop_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp)
{
_swap_values(first, --last);
make_heap(first, last, comp);
}
template <class RandomAccessIterator>
void pop_heap(RandomAccessIterator first, RandomAccessIterator last)
{
pop_heap(first, last, less<typename iterator_traits<RandomAccessIterator>::value_type>());
}
template <class RandomAccessIterator, class Compare>
void sort_heap(RandomAccessIterator first, RandomAccessIterator last, Compare comp)
{
while (distance(first, last) > 1)
pop_heap(first, last--, comp);
}
template <class RandomAccessIterator>
void sort_heap(RandomAccessIterator first, RandomAccessIterator last)
{
sort_heap(first, last, less<typename iterator_traits<RandomAccessIterator>::value_type>());
}
}
#endif
| true |
733b77c6aa5af76a7ba38b372ae273dbb862e5aa | C++ | LukMercury/Simple-Programs | /Converters/cel.cpp | UTF-8 | 708 | 3.375 | 3 | [] | no_license |
// Convert height in cm to feet and inches
// Usage: cm <value1> <value2> ...
#include "std_lib_facilities.h"
constexpr int offset = 32;
constexpr double scale = 1.8;
double cstring_to_double(char* s)
{
istringstream is {s};
double d;
if (!(is >> d))
error("Couldn't get double argument");
return d;
}
int main(int argc, char* argv[])
try{
cout << fixed << setprecision(2);
for (int i = 1; i < argc; ++i) {
double cel = cstring_to_double(argv[i]);
double far = scale * cel + offset;
cout << far << " F\n";
}
}
catch(exception& e) {
cout << e.what() << '\n';
}
catch(...) {
cout << "Unknown error\n";
} | true |
89cdc603757f6efd0d6519747891c5c1b255525d | C++ | fadeto404/dynamixel-p2 | /src/dynamixel_p2/Matlab_Comms_V2/Matlab_Comms_V2.ino | UTF-8 | 1,940 | 2.734375 | 3 | [
"MIT"
] | permissive | #include <dynamixel_p2.h>
Dynamixel_p2 TEST(13);
bool receive = true; // Used to switch between recieve and transmit mode.
byte rxpacket[8]; //Holds Current1,2,3 and Event.
void setup() {
Serial.begin(57600);
TEST.begin(57600);
TEST.setTorqueEnable(0xFE,true);
//Debug
}
void loop() {
if(receive) {
while (Serial1.available()){
Serial1.read();
}
TEST.MatlabTransmit();
receive = false;
}
if (Serial.available() > 8){ // This is for marco.
if(bitconstruct() == 5000){
short current1 = bitconstruct();
short current2 = bitconstruct();
short current3 = bitconstruct();
char event = Serial.read();
//TEST.setGoalCurrent(0x01, current1);
TEST.setGoalCurrent(0x02, current2);
TEST.setGoalCurrent(0x03, current3);
receive = true;
}
}
/*
if(Serial.available() > 6){
int data[3];
for (int i = 0; i<3; i++){ //Fills in data array with currents for ID 1, 2 and 3.
data[i] = bitconstruct();
}
TEST.setGoalCurrent(1, data[0]); //Set Current for dynamixel 1.
TEST.setGoalCurrent(2, data[1]); //Set Current for dynamixel 2.
TEST.setGoalCurrent(3, data[2]); //Set Current for dynamixel 3.
switch (Serial.read()){ //Switch case for events (Gestures)
case 1: //Opens Gripper
TEST.setGoalPosition(5, 3072);
TEST.setGoalPosition(4, 1024);
break;
case 2: //Closes Gripper
TEST.setGoalPosition(5, 2048);
TEST.setGoalPosition(4, 2048);
break;
case 4:
//STUFF
break;
case 8:
//STUFF
break;
case 16:
//STUFF
break;
default:
break;
}
receive = true;
}*/
}
short bitconstruct(){ //Reads 2 bytes and turn them into an int (Used for the currents.)
short value = 0;
for (int i = 0; i < 2; i++){
value += (Serial.read() << 8*i) & (0x000000FF << 8*i);
}
return value;
}
| true |
017db3d3a10ce28cee9c03b45f921cd53a40f846 | C++ | safwankdb/Leetcode-Patterns-Cpp | /Word Search II.cpp | UTF-8 | 2,031 | 3.1875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
struct TrieNode {
bool isWord = false, counted = false;
TrieNode* children[26];
string word;
TrieNode() {
for (int i = 0; i < 26; i++) children[i] = NULL;
}
};
struct Trie {
TrieNode* root;
Trie() { root = new TrieNode(); }
void insert(string s) {
TrieNode* x = root;
int idx;
for (char c : s) {
idx = c - 'a';
if (x->children[idx] == NULL) {
x->children[idx] = new TrieNode();
x->children[idx]->word = x->word + c;
}
x = x->children[idx];
}
x->isWord = true;
}
};
void dfs(int x, int y, vector<vector<char>>& board, TrieNode* root,
vector<string>& ans) {
int m = board.size(), n = board[0].size();
if (board[x][y] == '#') return;
root = root->children[board[x][y] - 'a'];
if (root == NULL) return;
if (root->isWord && !root->counted) {
ans.push_back(root->word);
root->counted = true;
}
const int dx[] = {1, 0, -1, 0}, dy[] = {0, 1, 0, -1};
char temp = board[x][y];
board[x][y] = '#';
for (int i = 0; i < 4; i++) {
int p = x + dx[i], q = y + dy[i];
if (p < 0 || p >= m || q < 0 || q >= n) continue;
dfs(p, q, board, root, ans);
}
board[x][y] = temp;
}
vector<string> findWords(vector<vector<char>>& board,
vector<string>& words) {
Trie* T = new Trie();
for (string word : words) T->insert(word);
vector<string> ans;
int m = board.size(), n = board[0].size();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
dfs(i, j, board, T->root, ans);
}
}
return ans;
}
}; | true |
b6a9686bf9f890f9d44395d8dc746d422beb3c17 | C++ | qianlv/learning | /cplusplusprimer/9/9_5.cpp | UTF-8 | 1,028 | 3.09375 | 3 | [] | no_license | /*
* =====================================================================================
*
* Filename: 9_5.cpp
*
* Description: 9.5
*
* Version: 1.0
* Created: 2015年12月21日 20时57分14秒 CST
* Revision: none
* Compiler: gcc
*
* Author: qianlv (), qianlv7@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <vector>
using std::vector;
vector<int>::const_iterator find_element(vector<int>::const_iterator beg,
vector<int>::const_iterator end, const int elem)
{
for (; beg != end; ++beg)
if (*beg == elem) return beg;
return end;
}
int main()
{
vector<int> ivec = {1, 2, 40, 3};
auto iter = find_element(ivec.begin(), ivec.end(), 0);
if (iter != ivec.end())
cout << *iter << endl;
else
cout << "Not Find Data" << endl;
}
| true |
bee04ab615822d91c446eeb14491fcc9ad9e5abc | C++ | sl950313/SEDA-framework | /sender.cpp | UTF-8 | 1,417 | 2.671875 | 3 | [] | no_license | #include "sender.h"
#include "log.h"
#include <assert.h>
#include <zmq.h>
#include <unistd.h>
sender::sender() {
//init();
running = true;
}
bool sender::sendMsg(IElement *ie) {
LogUtil::debug("sender : [sendMsg] ie : %s, %d", ie->getElement(), ie->length());
int ret = zmq_send(publisher, ie->getElement(), ie->length(), ZMQ_DONTWAIT);
if (ret != 0) {
if (zmq_errno() == EAGAIN) {
LogUtil::debug("sender : [sendMsg] the message cannot be sent at the moment");
return false;
}
}
LogUtil::debug("sender : [sendMsg] %s, %s", (ret == 0) ? "success" : "fail", (ret == 0) ? "" : strerror(errno));
//assert(ret == 0);
return true;
}
void sender::init() {
LogUtil::debug("sender : [init] begin");
void *context = zmq_ctx_new();
assert(context != NULL);
//int ret = zmq_ctx_set(context, ZMQ_MAX_SOCKETS, 1);
//assert(ret == 0);
publisher = zmq_socket(context, ZMQ_PUB);
assert(publisher != NULL);
int ret = zmq_bind(publisher, addr.c_str());
LogUtil::debug("sender : [init] addr=%s", addr.c_str());
if (ret != 0) {
LogUtil::debug("sender : [init] zmq_bind fail. ret = %d, %s", zmq_errno(), zmq_strerror(zmq_errno()));
sleep(3);
exit(-1);
}
LogUtil::debug("sender : [init] success");
}
void *sender::run(void *arg) {
sender *sd = (sender *)arg;
while (sd->running) {
break;
}
return sd;
}
| true |
550d96cab4bb55c22cfc3422f5741ab2e8c95b76 | C++ | rummens1337/programmeertalen | /week7-team/evaluator/Matrix.h | UTF-8 | 6,544 | 3.75 | 4 | [
"MIT"
] | permissive | /*
* Names: Michel Rummens, Thomas Vos
* StudentIDs:13108093, 12829501
* This program defines a matrix with doubles, and the operations +,-,~,* and
* transpose.
*/
#ifndef MATRIX_INCLUDED
#define MATRIX_INCLUDED
#include <vector>
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <utility>
#include <numeric>
#include <iomanip>
#include "evaluator_exception.h"
#include "evaluator_string_tools.h"
/*! Represents a 2 dimensional matrix of doubles.*/
class Matrix
{
int m_rows, m_cols;
std::vector<double> m_data;
public:
/* Constructors for no data, and for a given amount of rows and cols. */
Matrix() : m_rows{0}, m_cols{0} {}
Matrix(int rows, int cols) : m_rows{rows}, m_cols{cols},
m_data(rows * cols) {}
/* Functions below return and/or change data of the class variables. */
std::vector<double> &vec() { return m_data; }
const std::vector<double> &vec() const { return m_data; }
int nr_rows() const { return m_rows; }
int nr_cols() const { return m_cols; }
double &operator()(int r, int c) { return m_data[r * m_cols + c]; }
const double &operator()(int r, int c) const
{
return m_data[r * m_cols + c];
}
friend std::istream &operator>>(std::istream &is, Matrix &matrix);
};
/*
* Reads a Matrix from 'is' stream.
*
* @param is Input stream, with a string.
* @param matrix An empty matrix.
* @return the now empty input stream.
*/
std::istream &operator>>(std::istream &is, Matrix &matrix)
{
std::vector<double> data;
double num_var = 0;
int rows = 0;
std::string temp;
std::string stringMatrix;
/* This reads all input from the istream per line, and constructs it all
into one string. Also counts the amount of rows. */
while (getline(is, temp))
{
temp += ", ";
rows++;
stringMatrix += temp;
}
std::stringstream ss(stringMatrix);
char junk;
is >> std::fixed;
is >> std::setprecision(2);
/* Code below reads the constructed string for doubles. The doubles are
placed in a list, while the comma's are thrown into the var 'junk'. */
while (ss >> num_var)
{
ss >> junk;
data.push_back(num_var);
}
/* Lastly, the three class variables of the matrix are defined. */
matrix.m_rows = rows;
matrix.m_data = data;
matrix.m_cols = matrix.m_data.size() / rows;
return is;
}
/*
* Writes Matrix 'matrix' to 'os' stream.
*
* @param os Output stream, empty at first.
* @param matrix A matrix, to be put into the output stream.
* @return the output stream, with the contents of the matrix as a string.
*/
std::ostream &operator<<(std::ostream &os, const Matrix &matrix)
{
int cols = matrix.nr_cols();
std::vector<double> data = matrix.vec();
/* Loop below Puts every number into the ostream, followed by a comma or
a newline (if all the numbers of a row have been added) */
for (unsigned int i = 0; i < data.size(); i++)
{
os << data[i];
if ((i + 1) % cols == 0)
{
os << "\n";
}
else
{
os << ",";
}
}
return os;
}
/*
* Returns a new Matrix that is the negation of 'matrix'.
*
* @param matrix A matrix, to be negated.
* @return the negated matrix.
*/
Matrix operator-(const Matrix &matrix)
{
Matrix newMatrix(matrix.nr_rows(), matrix.nr_cols());
for (unsigned int i = 0; i < matrix.vec().size(); i++)
newMatrix.vec()[i] = matrix.vec()[i] * -1;
return newMatrix;
}
/*
* Returns a new Matrix that is the transpose of 'matrix'.
*
* @param matrix A matrix, to be transposed.
* @return the transposed matrix.
*/
Matrix transpose(const Matrix &matrix)
{
int rows = matrix.nr_rows();
int cols = matrix.nr_cols();
Matrix newMatrix(cols, rows);
int c = 0;
int count = 0;
/* The for-loops below put the numbers in the correct place of the
transposed matrix. */
for (int i = 0; i < cols; i++)
{
c = 0;
for (int j = 0; j < rows; j++)
{
newMatrix.vec()[count] = matrix.vec()[i + c];
c += cols;
count += 1;
}
}
return newMatrix;
}
/*
* Returns a new Matrix that is equal to 'm1+m2'.
*
* @param m1/m2 The two matrices that need to be added.
* @return the matrix that is the result of the addition.
*/
Matrix operator+(const Matrix &m1, const Matrix &m2)
{
Matrix newMatrix(m1.nr_rows(), m1.nr_cols());
for (unsigned int i = 0; i < m1.vec().size(); i++)
newMatrix.vec()[i] = m1.vec()[i] + m2.vec()[i];
return newMatrix;
}
/*
* Returns a new Matrix that is equal to 'm1-m2'.
*
* @param m1/m2 The two matrices that need to be subtracted from each other.
* @return the matrix that is the result of the subtraction.
*/
Matrix operator-(const Matrix &m1, const Matrix &m2)
{
Matrix newMatrix(m1.nr_rows(), m1.nr_cols());
for (unsigned int i = 0; i < m1.vec().size(); i++)
newMatrix.vec()[i] = m1.vec()[i] - m2.vec()[i];
return newMatrix;
}
/*
* Returns a new Matrix that is equal to 'm1*m2'.
*
* @param m1/m2 The two matrices that need to be multiplied with each other.
* @return the matrix that is the result of the multiplication.
*/
Matrix operator*(const Matrix &m1, const Matrix &m2)
{
int rows1 = m1.nr_rows();
int rows2 = m2.nr_rows();
int cols1 = m1.nr_cols();
int cols2 = m2.nr_cols();
if (cols1 != rows2)
{
throw new Evaluator_exception("Invalid dimensions");
}
int size = rows1 * cols1;
Matrix matrixTransposed = transpose(m2);
Matrix newMatrix(rows1, cols2);
int newSize = rows1 * cols2;
double total = 0;
int i = 0;
int j = 0;
int c = 0;
/* The loop below multiplies every number in a row with every number in a
column, adding the results in the process. If all numbers in a row have
been multiplied with a all numbers in a column, the final answer is put
into the new matrix and the loop will continue to fill the next spots. */
while (c < newSize)
{
total += (m1.vec()[i] * matrixTransposed.vec()[j]);
i++;
j++;
if (i % cols1 == 0)
{
newMatrix.vec()[c] = total;
total = 0;
c++;
i -= cols1;
if (j == size)
{
i += cols1;
j = 0;
}
}
}
return newMatrix;
}
#endif
| true |
a7800342d41585bea6a4c4b2a999f6c2672be975 | C++ | lvningyuan/pdlbox | /threadpool.cpp | UTF-8 | 4,824 | 3.390625 | 3 | [] | no_license | //#ifndef __M_POOL_H__
#define __M_POOL_H__
#include <iostream>
#include <queue>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX_THREAD 3 //最大线程数
#define MAX_QUEUE 10 //队列长度
class MyTask
{
private:
int data;
public:
MyTask(){}
~MyTask(){}
void SetData(int _data)
{
data =_data;
}
void Run()
{
int t = rand()% 5;
printf("thread : %lu sleep %d sec ,execute data : %d\n",pthread_self(),t,data);
sleep(1);
}
};
class MyThreadPool
{
private:
int max_thread;//线程池中最大线程数
int cur_thread;//当前线程数
int keep_running;//用于停止线程池中线程的标志
int max_queue;//队列中最大节点数
pthread_t* tid;//线程id
std::queue<MyTask*> task_list;//任务列表
pthread_mutex_t mutex; //互斥量
pthread_cond_t empty;//条件
pthread_cond_t full;//条件
void ThreadLock()
{
pthread_mutex_lock(&mutex);
}
void ThreadUnLock()
{
pthread_mutex_unlock(&mutex);
}
void ConsumeWait()
{
pthread_cond_wait(&empty,&mutex);
}
void ProductWait()
{
pthread_cond_wait(&full,&mutex);
}
void ConsumeNotify()
{
pthread_cond_signal(&empty);
}
void ProductNotify()
{
pthread_cond_broadcast(&full);
}
bool ThreadIsRunning()
{
return keep_running ==0;
}
void ThreadExit()
{
cur_thread--;//当前线程数-1
printf("thread :%lu exit\n",pthread_self());
// 通知主线程线程池中有线程退出
ProductNotify();
//释放线程资源
pthread_exit(NULL);
}
bool QueueIsEmpty()
{
return task_list .size() == 0;
}
bool QueueIsFull()
{
return task_list.size() == max_queue;
}
void PopTask(MyTask** task)
{
*task = task_list.front();
task_list.pop();
}
void PushTask(MyTask* task)
{
task_list.push(task);
}
static void* thread_routine(void *arg)
{
MyThreadPool *pthreadpool = (MyThreadPool*) arg;
while(1)
{
pthreadpool ->ThreadLock();
//如果当前是运行状态, 并且没有任务则挂起等待
while(pthreadpool->QueueIsEmpty() && pthreadpool->ThreadIsRunning())
pthreadpool->ConsumeWait();
//若果当前不是运行状态,并且没有任务,那么退出线程
//非运行 队列中有任务则需要将任务执行完毕后才可退出
if(! pthreadpool->ThreadIsRunning() && pthreadpool->QueueIsEmpty() )
{
pthreadpool->ThreadUnLock();
pthreadpool->ThreadExit();
}
//能执行到这里,说明Queue任务队列 不为空
MyTask *task;
pthreadpool->PopTask(&task);
pthreadpool->ProductNotify();
pthreadpool->ThreadUnLock();
//不能在锁内执行任务,否则导致其他线程饥饿
task->Run();
}
return NULL;
}
public:
MyThreadPool(int _max_thread = MAX_THREAD,int _max_queue = MAX_QUEUE)
:max_thread(_max_thread)
,cur_thread(_max_thread)
,max_queue(_max_queue)
,keep_running(1)
{
int i =0;
printf("create thread %d-%d\n",max_thread,max_queue);
tid = (pthread_t*)malloc(sizeof(pthread_t)* _max_thread);
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&empty,NULL);
pthread_cond_init(&full,NULL);
// 创建笃定数量的线程 等待执行任务
//
for(i=0;i<_max_thread;++i)
{
int ret = pthread_create(&tid[i],NULL,thread_routine,(void*)this);
if(ret != 0)
{
printf("create thread errorn\n");
exit(0);
}
pthread_detach(tid[i]);
}
}
~MyThreadPool()
{
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&full);
pthread_cond_destroy(&empty);
}
bool AddTaskToPool(MyTask* task)
{
ThreadLock();
while(QueueIsFull())
{
ProductWait();
}
PushTask(task);
printf("add task to pool\n");
ConsumeNotify();
ThreadUnLock();
return true;
}
void StopThreadPool()
{
//如果已经调用过线程池退出,那么返回
if(keep_running == 0)
return ;
ThreadLock();
keep_running = 0;
//如果还有线程 没退出,挂起等待,直到所有线程执行完毕后退出
while(cur_thread > 0)
{
ProductWait();
}
ThreadUnLock();
}
};
int main()
{
MyTask task[10];
int i;
MyThreadPool pool;
for(i=0; i <10; ++i)
{
task[i].SetData(i);
pool.AddTaskToPool(&task[i]);
}
pool.StopThreadPool();
return 0;
}
| true |
f217e5862a597c5c18b3748595ac1acd9c0b0b77 | C++ | ChristianLebeda/HomSub | /homomorphism/src/iterator_introduce_handler.cpp | UTF-8 | 1,589 | 2.671875 | 3 | [
"MIT"
] | permissive | #include "homomorphism/iterator_introduce_handler.h"
#include <memory>
#include <vector>
#include "homomorphism/graph.h"
#include "homomorphism/mapping_iterator.h"
std::vector<size_t>& IteratorIntroduceHandler::introduceLast(std::vector <size_t> &input, std::vector <size_t> &output,
std::vector <size_t>& bag, std::shared_ptr<Graph> h,
std::shared_ptr<Graph> g, size_t n, size_t x) {
if(input.size() == 1) {
for(unsigned long & i : output) {
i = input[0];
}
return output;
}
// Figure out which vertices in H are connected to the introduced vertex
std::vector<unsigned char> connected;
for (size_t v : bag)
{
connected.push_back(h->edgeExist(x, v));
}
MappingIterator it(n, bag.size());
//for(size_t idx = 0; idx < input.size(); idx++) {
while(it.idx < input.size()) {
size_t count = input[it.idx];
size_t newidx = it.idx * n;
// Add all valid assignments of vertex x
for (size_t i = 0; i < n; i++)
{
// Ensure that all edges of H are also present in G
bool valid = true;
for (size_t j = 0; j < connected.size(); j++)
{
if (connected[j] && !g->edgeExist(i, it.mapping[j])) {
valid = false;
break;
}
}
output[newidx + i] = valid ? count : 0;
}
it.Increment();
}
return output;
}
| true |
e6eaca5bccc4df2ed8f2cd95792429aeb0412baa | C++ | TehWeifu/SMR | /Programacion/1st Quarter/Ej 46 - 49/Ejercicio 47 - Julian.cpp | UTF-8 | 1,472 | 3.8125 | 4 | [] | no_license | #include <iostream>
int main() {
const short SIZE{ 40 };
float vecGrades[SIZE];
int sum{ 0 };
int max{ -1 };
int maxPos{ 0 };
int min{ 11 };
int minPos{ 0 };
int menu{ -1 };
for (int i = 0; i < SIZE; i++) {
do {
std::cout << "Introduzca la nota del alumno (" << i + 1 << "/" << SIZE << "): ";
std::cin >> vecGrades[i];
if (vecGrades[i] < 0.0 || vecGrades[i] > 10.0) {
std::cout << "Error la nota tiene que estar entre 0 y 10." << std::endl;
}
} while (vecGrades[i] < 0.0 || vecGrades[i] > 10.0);
if (vecGrades[i] < min) {
min = vecGrades[i];
minPos = i;
}
if (vecGrades[i] > max) {
max = vecGrades[i];
maxPos = i;
}
sum += vecGrades[i];
}
std::cout << "\nElija una opcion:\n\t1. Listar notas\n\t2. Calcular la media\n\t3. Calcular el menor\n\t4. Calcular el mayor" << std::endl;
while (menu != 0) {
if (menu == 1) {
for (int i = 0; i < SIZE; i++) {
std::cout << "La nota del alumno " << i + 1 << " es: " << vecGrades[i] << std::endl;
}
}
else if (menu == 2) {
std::cout << "La media de clase es: " << static_cast<float>(sum) / SIZE << std::endl;
}
else if (menu == 3) {
std::cout << "La menor nota es un " << min << " del alumno " << minPos + 1 << std::endl;
}
else if (menu == 4) {
std::cout << "La mayor nota es un " << max << " del alumno " << maxPos + 1 << std::endl;
}
std::cout << "\nIntroduzca una opcion (0 para salir): ";
std::cin >> menu;
}
return 0;
} | true |
be48ee78feab9ee0c02dfa9b9af663789c62d4b2 | C++ | zhangbo-tj/2048InQT | /2048InQt/GameOverWindow.cpp | GB18030 | 1,322 | 2.8125 | 3 | [] | no_license | #include "GameOverWindow.h"
#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QDebug>
/*
* Ϸʧܽ
*/
GameOverWindow::GameOverWindow(QWidget* parent):QWidget(parent){
setStyleSheet("GameOverWindow{background: rgb(237,224,200);}");
setFixedSize(425, 200);
//ʼؼ
QVBoxLayout* layout = new QVBoxLayout(this);
QLabel* gameover_label = new QLabel("Game Over", this);
gameover_label->setStyleSheet(
"QLabel{ font:40pt bold \"Arial\";}"
);
score_label_ = new QLabel(this);
score_label_->setStyleSheet("QLabel{color:rgb(119,110,101);font:20pt \"Arial\";}");
reset_button_ = new QPushButton("Try Again",this);
reset_button_->setFixedSize(120, 60);
reset_button_->setStyleSheet(
"QPushButton{background-color: rgb(143, 122, 102); border-radius:10px;font:15pt \"Arial\"; color:white; }"
);
layout->insertWidget(1, gameover_label, 0, Qt::AlignCenter);
layout->insertWidget(2, score_label_, 0, Qt::AlignCenter);
layout->insertWidget(3, reset_button_, 0, Qt::AlignCenter);
}
/*
*
*/
GameOverWindow::~GameOverWindow(){
}
/*
* ȡ¿ʼϷť
*/
QPushButton* GameOverWindow::GetResetButton()const {
return reset_button_;
}
/*
* ȡǩ
*/
QLabel* GameOverWindow::GetScoreLabel() {
return score_label_;
}
| true |
2c16130b33605978c969ca3b3b816f6884b48e43 | C++ | VinInn/ctest | /bitcompress.cpp | UTF-8 | 3,907 | 2.6875 | 3 | [] | no_license | /*
* bitcompress.cpp
*
*
* Created by Vincenzo on 29-03-2006.
* Copyright 2006 __MyCompanyName__. All rights reserved.
*
*/
// #include "bitcompress.h"
#include <cstdio>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <vector>
#include <string>
bool debug() {
return true;
}
/*
* generates a tag
* assume
* 256 trigger-paths 20% overlap??
* 256 offline confirmations (full correlation with above?)
* 256 physics selections (selectivity (on confirmed) as required, 10% overlap)
* 128 "user" bits (many on, say 10 random???)
*/
class EvTag {
public:
void dump(int lev=0) const {
std::cout << "sizes "
<< triggerPaths.size() << " "
<< confirmations.size() << " "
<< selections.size() << " "
<< user.size() << std::endl;
}
public:
std::vector<unsigned char> triggerPaths;
std::vector<unsigned char> confirmations;
std::vector<unsigned char> selections;
std::vector<unsigned char> user;
};
double frand() {
static const double rmax = 1./double(RAND_MAX);
return double(::rand())*rmax;
};
union FourByte {
int i;
unsigned char c[4];
};
class TagGenerator {
public:
explicit TagGenerator(double isel) : selectivity(isel) {}
void generate(EvTag& tag);
private:
double selectivity;
};
void TagGenerator::generate(EvTag& tag) {
FourByte r1;
for(;;) {
r1.i=::rand();
tag.triggerPaths.push_back(r1.c[3]);
tag.confirmations.push_back(r1.c[3]);
if (r1.c[0]>25) break; // c[0]<127 - 0.2*127=25
}
double psel = frand();
if (psel>selectivity) return;
tag.selections.push_back(r1.c[2]);
if (psel<0.1*selectivity) tag.selections.push_back(r1.c[1]); // aprox 10% multiple tag
// user word: min 4, max 15 bits (out of 128) // not so uniform
int nub = int(r1.c[0])%16; if (nub<4) nub=4;
for (int i=0; i<nub; i+=4) {
FourByte r2; r2.i=::rand();
for (int j=0; j<std::min(4,nub-i);j++) tag.user.push_back(r2.c[j]);
}
if (tag.user.size()!=nub) std::cout <<"error " << nub << " " << tag.user.size() << std::endl;
}
class CompactStream {
public:
CompactStream(const std::string&iname, bool w) : file(iname.c_str(), w ?std::ios::out:std::ios::in){
std::cout << "file is " << iname << std::endl;
}
operator bool () const { return file;}
void dump(const EvTag& tag) {
dump(tag.triggerPaths);
dump(tag.confirmations);
dump(tag.selections);
dump(tag.user);
}
void dump(const std::vector<unsigned char>& v) {
unsigned char s(v.size());
file.write((char*)(&s),1);
if (!v.empty()) file.write((char*)(&v.front()),v.size());
}
void read(EvTag& tag) {
read(tag.triggerPaths);
read(tag.confirmations);
read(tag.selections);
read(tag.user);
}
void read(std::vector<unsigned char>& v) {
unsigned char s;
file.read((char *)(&s),1);
if (s) {
v.resize(s);
file.read((char*)(&v.front()),v.size());
}
}
private:
std::fstream file;
};
void write(char * selchar="10");
void read(char * selchar="10");
int main(int argc, char * argv[]) {
char * w ="r";
if (argc>1) w = argv[1];
if (w[0]=='w') {
if (argc>2) write(argv[2]);
else write();
} else {
if (argc>2) read(argv[2]);
else read();
}
return 0;
}
void write(char * selchar) {
// selectivity factor in %
// default 10%
int sf= 10;
sf = ::atoi(selchar);
float sel = 0.01*float(sf);
std::cout << "selectivity will be " << sel << std::endl;
// number of events
size_t nev = 100000;
CompactStream cs(std::string("compact_")+std::string(selchar),true);
TagGenerator gen(sel);
for (size_t iev=0; iev<nev; iev++)
{
EvTag tag;
gen.generate(tag);
if (iev%1000==0) tag.dump();
cs.dump(tag);
}
}
void read(char * selchar) {
CompactStream cs(std::string("compact_")+std::string(selchar),false);
size_t iev(0);
while (cs) {
iev++;
EvTag tag;
cs.read(tag);
if (iev%1000==1) tag.dump();
}
std::cout << "read " << iev << " events " << std::endl;
} | true |
eaed52301542aaf0c95a44d8eb7ff1379d3a8c3d | C++ | Kangulu/plt | /src/client/render/PlayerRenderer.cpp | UTF-8 | 7,886 | 2.578125 | 3 | [] | no_license | #include "PlayerRenderer.h"
using namespace render;
using namespace std;
std::string dif2string(int ressource){
if(ressource>=0){
return string("+") + to_string(ressource);
}
else{
return to_string(ressource);
}
}
PlayerRenderer::PlayerRenderer(std::shared_ptr<state::Player> player, sf::Vector2f position){
this->setPosition(position);
this->name = player->name;
this->ressources = make_shared<state::Ressources>(player->ressources->serialize());
this->texture.loadFromFile("res/textures/playerSprite.png");
this->font.loadFromFile("res/fonts/arial.ttf");
sf::Texture _waterTexture;
_waterTexture.loadFromFile("res/textures/waterToken.png");
_waterTexture.setSmooth(true);
this->ressourcesTextures["water"] = _waterTexture;
sf::Texture _stoneTexture;
_stoneTexture.loadFromFile("res/textures/stoneToken.png");
_stoneTexture.setSmooth(true);
this->ressourcesTextures["stone"] = _stoneTexture;
sf::Texture _woodTexture;
_woodTexture.loadFromFile("res/textures/woodToken.png");
_woodTexture.setSmooth(true);
this->ressourcesTextures["wood"] = _woodTexture;
sf::Texture _crownTexture;
_crownTexture.loadFromFile("res/textures/victoryToken.png");
_crownTexture.setSmooth(true);
this->ressourcesTextures["crown"] = _crownTexture;
sf::Texture _waterTextureInc;
_waterTextureInc.loadFromFile("res/textures/waterTokenInc.png");
_waterTextureInc.setSmooth(true);
this->ressourcesTextures["waterInc"] = _waterTextureInc;
sf::Texture _stoneTextureInc;
_stoneTextureInc.loadFromFile("res/textures/stoneTokenInc.png");
_stoneTextureInc.setSmooth(true);
this->ressourcesTextures["stoneInc"] = _stoneTextureInc;
sf::Texture _woodTextureInc;
_woodTextureInc.loadFromFile("res/textures/woodTokenInc.png");
_woodTextureInc.setSmooth(true);
this->ressourcesTextures["woodInc"] = _woodTextureInc;
sf::Texture _crownTextureInc;
_crownTextureInc.loadFromFile("res/textures/victoryTokenInc.png");
_crownTextureInc.setSmooth(true);
this->ressourcesTextures["crownInc"] = _crownTextureInc;
}
void PlayerRenderer::draw(sf::RenderTarget &target, sf::RenderStates states) const{
sf::Vector2f _position = this->getPosition();
sf::Sprite _sprite(this->texture);
_sprite.setScale(400/_sprite.getLocalBounds().width,400/_sprite.getLocalBounds().height);
_sprite.setPosition(_position.x,_position.y);
_position += sf::Vector2f(35,37);
target.draw(_sprite);
sf::Text _nameText(this->name,this->font, 40);
_nameText.setColor(sf::Color::Black);
_nameText.setPosition(_position.x,_position.y);
target.draw(_nameText);
sf::Color darkgreen(0,147,0,255);
sf::Vector2f _positionRes;
_positionRes = _position + sf::Vector2f(0,90);
sf::Sprite _stoneSprite(this->ressourcesTextures.find("stone")->second);
_stoneSprite.setScale(50/_stoneSprite.getLocalBounds().width,50/_stoneSprite.getLocalBounds().height);
_stoneSprite.setPosition(_positionRes.x,_positionRes.y);
target.draw(_stoneSprite);
sf::Text _stoneText(to_string(this->ressources->stone) + string("\n"),this->font, 30);
_stoneText.setPosition(_positionRes + sf::Vector2f(_stoneSprite.getGlobalBounds().width + 10,5));
_stoneText.setColor(sf::Color::Black);
target.draw(_stoneText);
sf::Sprite _stoneSpriteInc(this->ressourcesTextures.find("stoneInc")->second);
_stoneSpriteInc.setScale(50/_stoneSpriteInc.getLocalBounds().width,50/_stoneSpriteInc.getLocalBounds().height);
_stoneSpriteInc.setPosition(_positionRes.x + 125,_positionRes.y);
target.draw(_stoneSpriteInc);
sf::Text _stoneTextInc(dif2string(this->ressources->stoneIncome) + string("\n"),this->font, 30);
_stoneTextInc.setPosition(_positionRes + sf::Vector2f(125 + _stoneSpriteInc.getGlobalBounds().width + 10,5));
_stoneTextInc.setColor(darkgreen);
target.draw(_stoneTextInc);
_positionRes = sf::Vector2f(_positionRes.x,_stoneText.getGlobalBounds().top+_stoneText.getGlobalBounds().height);
sf::Sprite _woodSprite(this->ressourcesTextures.find("wood")->second);
_woodSprite.setScale(50/_woodSprite.getLocalBounds().width,50/_woodSprite.getLocalBounds().height);
_woodSprite.setPosition(_positionRes.x,_positionRes.y);
target.draw(_woodSprite);
sf::Text _woodText(to_string(this->ressources->wood) + string("\n"),this->font, 30);
_woodText.setPosition(_positionRes + sf::Vector2f(_woodSprite.getGlobalBounds().width + 10,5));
_woodText.setColor(sf::Color::Black);
target.draw(_woodText);
sf::Sprite _woodSpriteInc(this->ressourcesTextures.find("woodInc")->second);
_woodSpriteInc.setScale(50/_woodSpriteInc.getLocalBounds().width,50/_woodSpriteInc.getLocalBounds().height);
_woodSpriteInc.setPosition(_positionRes.x + 125,_positionRes.y);
target.draw(_woodSpriteInc);
sf::Text _woodTextInc(dif2string(this->ressources->woodIncome) + string("\n"),this->font, 30);
_woodTextInc.setPosition(_positionRes + sf::Vector2f(125 + _woodSpriteInc.getGlobalBounds().width + 10,5));
_woodTextInc.setColor(darkgreen);
target.draw(_woodTextInc);
_positionRes = sf::Vector2f(_positionRes.x,_woodText.getGlobalBounds().top+_woodText.getGlobalBounds().height);
sf::Sprite _waterSprite(this->ressourcesTextures.find("water")->second);
_waterSprite.setScale(50/_waterSprite.getLocalBounds().width,50/_waterSprite.getLocalBounds().height);
_waterSprite.setPosition(_positionRes.x,_positionRes.y);
target.draw(_waterSprite);
sf::Text _waterText(to_string(this->ressources->water) + string("\n"),this->font, 30);
_waterText.setPosition(_positionRes + sf::Vector2f(_waterSprite.getGlobalBounds().width + 10,5));
_waterText.setColor(sf::Color::Black);
target.draw(_waterText);
sf::Sprite _waterSpriteInc(this->ressourcesTextures.find("waterInc")->second);
_waterSpriteInc.setScale(50/_waterSpriteInc.getLocalBounds().width,50/_waterSpriteInc.getLocalBounds().height);
_waterSpriteInc.setPosition(_positionRes.x + 125,_positionRes.y);
target.draw(_waterSpriteInc);
sf::Text _waterTextInc(dif2string(this->ressources->waterIncome) + string("\n"),this->font, 30);
_waterTextInc.setPosition(_positionRes + sf::Vector2f(125 + _waterSpriteInc.getGlobalBounds().width + 10,5));
_waterTextInc.setColor(darkgreen);
target.draw(_waterTextInc);
_positionRes = sf::Vector2f(_positionRes.x,_waterText.getGlobalBounds().top+_waterText.getGlobalBounds().height);
sf::Sprite _victoryPointSprite(this->ressourcesTextures.find("crown")->second);
_victoryPointSprite.setScale(50/_victoryPointSprite.getLocalBounds().width,50/_victoryPointSprite.getLocalBounds().height);
_victoryPointSprite.setPosition(_positionRes.x,_positionRes.y);
target.draw(_victoryPointSprite);
sf::Text _victoryPointText(to_string(this->ressources->victoryPoint) + string("\n"),this->font, 30);
_victoryPointText.setPosition(_positionRes + sf::Vector2f(_victoryPointSprite.getGlobalBounds().width + 10,5));
_victoryPointText.setColor(sf::Color::Black);
target.draw(_victoryPointText);
sf::Sprite _victoryPointSpriteInc(this->ressourcesTextures.find("crownInc")->second);
_victoryPointSpriteInc.setScale(50/_victoryPointSpriteInc.getLocalBounds().width,50/_victoryPointSpriteInc.getLocalBounds().height);
_victoryPointSpriteInc.setPosition(_positionRes.x + 125,_positionRes.y);
target.draw(_victoryPointSpriteInc);
sf::Text _victoryPointTextInc(dif2string(this->ressources->victoryPointIncome) + string("\n"),this->font, 30);
_victoryPointTextInc.setPosition(_positionRes + sf::Vector2f(125 + _victoryPointSpriteInc.getGlobalBounds().width + 10,5));
_victoryPointTextInc.setColor(darkgreen);
target.draw(_victoryPointTextInc);
} | true |
e1e0095f86cb71137aa3eed80e95fa58af43bd7c | C++ | accb529/Kassiopeia | /KGeoBag/Source/Extensions/Mesh/Complex/Source/KGRotatedSurfaceMesher.cc | UTF-8 | 12,101 | 2.8125 | 3 | [] | no_license | #include "KGRotatedSurfaceMesher.hh"
#include "KGMeshTriangle.hh"
namespace KGeoBag
{
void KGRotatedSurfaceMesher::VisitWrappedSurface( KGWrappedSurface< KGRotatedObject >* rotatedSurface )
{
std::shared_ptr< KGRotatedObject > rotatedObject = rotatedSurface->GetObject();
double length = 0.;
for( unsigned int i = 0; i < rotatedObject->GetNSegments(); i++ )
length += rotatedObject->GetSegment( i )->GetLength();
double tmp_len = 0;
unsigned int nPolyBegin_seg = rotatedObject->GetNPolyBegin();
unsigned int nPolyEnd_seg = 0;
if( rotatedObject->GetNSegments() == 1 )
nPolyEnd_seg = rotatedObject->GetNPolyEnd();
else
{
for( unsigned int i = 1; i < rotatedObject->GetNSegments(); i++ )
{
tmp_len += rotatedObject->GetSegment( i - 1 )->GetLength();
double ratio = tmp_len / length;
nPolyEnd_seg = ceil( (1. - ratio) * rotatedObject->GetNPolyBegin() + (ratio) * rotatedObject->GetNPolyEnd() );
DiscretizeSegment( rotatedObject->GetSegment( i - 1 ), nPolyBegin_seg, nPolyEnd_seg );
nPolyBegin_seg = nPolyEnd_seg;
}
}
DiscretizeSegment( rotatedObject->GetSegment( rotatedObject->GetNSegments() - 1 ), nPolyBegin_seg, nPolyEnd_seg );
}
//____________________________________________________________________________
void KGRotatedSurfaceMesher::DiscretizeSegment( const KGRotatedObject::Line* line, const unsigned int nPolyBegin, const unsigned int nPolyEnd )
{
if( const KGRotatedObject::Arc* arc = dynamic_cast< const KGRotatedObject::Arc* >( line ) )
return DiscretizeSegment( arc, nPolyBegin, nPolyEnd );
// First, we find the length of a side of the polygon in the middle of the
// segment
double rMid = fabs( line->GetP1( 1 ) + line->GetP2( 1 ) ) * .5;
int nPolyMid = .5 * (nPolyBegin + nPolyEnd);
double lenSeg = 2. * rMid * sin( M_PI / nPolyMid );
// We then use this value to determine the # of discretizations along the
// segment
int nDisc = ceil( line->GetLength() / lenSeg ) + 1;
// unit: a unit vector pointing from the start point to the end point
double unit[ 2 ] =
{ (line->GetP2( 0 ) - line->GetP1( 0 )) / line->GetLength(), (line->GetP2( 1 ) - line->GetP1( 1 )) / line->GetLength() };
// dlen: an incremental length from 0. to GetLength()
std::vector< double > dlen( nDisc, 0 );
// alpha: incrementally increases from 0. to 1.
std::vector< double > alpha( nDisc, 0 );
// nPoly: incrementally goes from nPolyBegin to nPolyEnd
std::vector< int > nPoly( nDisc, 0 );
DiscretizeInterval( line->GetLength(), nDisc - 1, 2., dlen );
DiscretizeInterval( 1., nDisc - 1, 1, alpha );
// By adding each prior interval to the one after it, we get a series of
// increasing lengths, the last being the sum total of the discretized
// interval.
for( int i = 1; i < nDisc; i++ )
{
dlen[ i ] += dlen[ i - 1 ];
alpha[ i ] += alpha[ i - 1 ];
}
// We modify alpha to go from 0. to 1.
for( int i = nDisc - 1; i > 0; i-- )
{
dlen[ i ] = dlen[ i - 1 ];
alpha[ i ] = alpha[ i - 1 ];
}
dlen[ 0 ] = 0.;
alpha[ 0 ] = 0.;
// We use alpha to figure out the nPoly array
for( int i = 0; i < nDisc; i++ )
nPoly[ i ] = nPolyEnd * alpha[ i ] + nPolyBegin * (1. - alpha[ i ]) + .5;
if( nDisc > 3 )
{
nPoly[ 1 ] = nPoly[ 0 ] = nPolyBegin;
nPoly[ nDisc - 2 ] = nPoly[ nDisc - 1 ] = nPolyEnd;
}
// Now, we create our triangles
KGMeshTriangle* t;
double p0[ 3 ];
double p1[ 3 ];
double p2[ 3 ];
int nThetaMax = (nPolyBegin > nPolyEnd) ? nPolyBegin : nPolyEnd;
double r = 0;
double r_last = line->GetP1( 1 );
std::vector< double > theta( nThetaMax, 0 );
std::vector< double > theta_last( nThetaMax, 0 );
for( int i = 0; i < nPoly[ 0 ]; i++ )
theta_last[ i ] = i * (2. * M_PI / nPoly[ 0 ]);
for( int i = 1; i < nDisc; i++ )
{
// First, we compute our theta arrays for this pass
for( int j = 0; j < nPoly[ i ]; j++ )
theta[ j ] = j * (2. * M_PI / nPoly[ i ]);
// We traverse along the unit vector a distance dlen[i]
r = line->GetP1( 1 ) + unit[ 1 ] * dlen[ i ];
// We first construct the triangles whose edges correspond to theta_last
p0[ 2 ] = p2[ 2 ] = line->GetP1( 0 ) + unit[ 0 ] * dlen[ i - 1 ];
p1[ 2 ] = line->GetP1( 0 ) + unit[ 0 ] * dlen[ i ];
if( r_last > 0. )
{
for( int j = 0; j < nPoly[ i - 1 ]; j++ )
{
p0[ 0 ] = r_last * cos( theta_last[ j ] );
p0[ 1 ] = r_last * sin( theta_last[ j ] );
p2[ 0 ] = r_last * cos( theta_last[ (j + 1) % nPoly[ i - 1 ] ] );
p2[ 1 ] = r_last * sin( theta_last[ (j + 1) % nPoly[ i - 1 ] ] );
int th_index = 0;
while( theta_last[ j ] >= theta[ th_index ] )
{
th_index++;
if( th_index == nPoly[ i ] )
break;
}
if( j == nPoly[ i - 1 ] - 1 )
th_index = nPoly[ i ] - 1;
p1[ 0 ] = r * cos( theta[ th_index % nPoly[ i ] ] );
p1[ 1 ] = r * sin( theta[ th_index % nPoly[ i ] ] );
t = new KGMeshTriangle( p0, p2, p1 );
AddElement( t );
}
}
// We then construct the triangles whose edges correspond to theta
p0[ 2 ] = p2[ 2 ] = line->GetP1( 0 ) + unit[ 0 ] * dlen[ i ];
p1[ 2 ] = line->GetP1( 0 ) + unit[ 0 ] * dlen[ i - 1 ];
if( r > 0 )
{
for( int j = 0; j < nPoly[ i ]; j++ )
{
p0[ 0 ] = r * cos( theta[ j ] );
p0[ 1 ] = r * sin( theta[ j ] );
p2[ 0 ] = r * cos( theta[ (j + 1) % nPoly[ i ] ] );
p2[ 1 ] = r * sin( theta[ (j + 1) % nPoly[ i ] ] );
int th_index = 0;
// while (theta_last[th_index]<theta[(j+1)%nPoly[i]])
if( j == 0 || j == nPoly[ i ] - 1 )
th_index = 0;
else
{
while( theta_last[ th_index ] < theta[ (j) % nPoly[ i ] ] )
{
th_index++;
if( th_index == nPoly[ i - 1 ] )
{
th_index = nPoly[ i - 1 ] - 1;
break;
}
}
}
p1[ 0 ] = r_last * cos( theta_last[ th_index % nPoly[ i - 1 ] ] );
p1[ 1 ] = r_last * sin( theta_last[ th_index % nPoly[ i - 1 ] ] );
t = new KGMeshTriangle( p0, p1, p2 );
AddElement( t );
}
}
// Finally, we set our variables for the next iteration
for( int j = 0; j < nPoly[ i ]; j++ )
theta_last[ j ] = theta[ j ];
r_last = r;
}
}
//____________________________________________________________________________
void KGRotatedSurfaceMesher::DiscretizeSegment( const KGRotatedObject::Arc* arc, const unsigned int nPolyBegin, const unsigned int nPolyEnd )
{
double rMid = fabs( arc->GetCenter( 1 ) + arc->GetRadius() * sin( arc->GetPhiMid() ) );
int nPolyMid = .5 * (nPolyBegin + nPolyEnd);
double lenSeg = 2. * rMid * sin( M_PI / nPolyMid );
// We then use this value to determine the # of discretizations along the
// segment
int nDisc = ceil( arc->GetLength() / lenSeg ) + 1;
double deltaPhi = arc->GetPhiEnd() - arc->GetPhiStart();
std::vector< int > nPoly( nDisc, 0 );
for( int i = 0; i < nDisc; i++ )
nPoly[ i ] = nPolyEnd * i / (nDisc - 1.) + nPolyBegin * (1. - i / (nDisc - 1.)) + .5;
// Now, we create our triangles
KGMeshTriangle* t;
double p0[ 3 ];
double p1[ 3 ];
double p2[ 3 ];
int nThetaMax = nPolyBegin > nPolyEnd ? nPolyBegin : nPolyEnd;
double r = 0;
double r_last = arc->GetP1( 1 );
std::vector< double > theta( nThetaMax, 0 );
std::vector< double > theta_last( nThetaMax, 0 );
for( int i = 0; i < nPoly[ 0 ]; i++ )
theta_last[ i ] = i * (2. * M_PI / nPoly[ 0 ]);
for( int i = 1; i < nDisc; i++ )
{
// First, we compute our theta arrays for this pass
for( int j = 0; j < nPoly[ i ]; j++ )
theta[ j ] = j * (2. * M_PI / nPoly[ i ]);
// We traverse along the arc a distance i/(nDisc-1.)*deltaPhi
r = arc->GetCenter( 1 ) + arc->GetRadius() * sin( arc->GetPhiStart() + i / (nDisc - 1.) * deltaPhi );
// We first construct the triangles whose edges correspond to theta_last
p0[ 2 ] = p2[ 2 ] = arc->GetCenter( 0 ) + arc->GetRadius() * cos( arc->GetPhiStart() + (i - 1) / (nDisc - 1.) * deltaPhi );
p1[ 2 ] = arc->GetCenter( 0 ) + arc->GetRadius() * cos( arc->GetPhiStart() + (i) / (nDisc - 1.) * deltaPhi );
for( int j = 0; j < nPoly[ i - 1 ]; j++ )
{
p0[ 0 ] = r_last * cos( theta_last[ j ] );
p0[ 1 ] = r_last * sin( theta_last[ j ] );
p2[ 0 ] = r_last * cos( theta_last[ (j + 1) % nPoly[ i - 1 ] ] );
p2[ 1 ] = r_last * sin( theta_last[ (j + 1) % nPoly[ i - 1 ] ] );
int th_index = 0;
while( theta_last[ j ] >= theta[ th_index ] )
{
th_index++;
if( th_index == nPoly[ i ] )
break;
}
th_index--;
if( th_index < 0 )
th_index = nPoly[ i ] - 1;
p1[ 0 ] = r * cos( theta[ th_index % nPoly[ i ] ] );
p1[ 1 ] = r * sin( theta[ th_index % nPoly[ i ] ] );
t = new KGMeshTriangle( p0, p2, p1 );
AddElement( t );
}
// We then construct the triangles whose edges correspond to theta
p0[ 2 ] = p2[ 2 ] = arc->GetCenter( 0 ) + arc->GetRadius() * cos( arc->GetPhiStart() + (i) / (nDisc - 1.) * deltaPhi );
p1[ 2 ] = arc->GetCenter( 0 ) + arc->GetRadius() * cos( arc->GetPhiStart() + (i - 1) / (nDisc - 1.) * deltaPhi );
for( int j = 0; j < nPoly[ i ]; j++ )
{
p0[ 0 ] = r * cos( theta[ j ] );
p0[ 1 ] = r * sin( theta[ j ] );
p2[ 0 ] = r * cos( theta[ (j + 1) % nPoly[ i ] ] );
p2[ 1 ] = r * sin( theta[ (j + 1) % nPoly[ i ] ] );
int th_index = 0;
while( (theta_last[ th_index ] < theta[ (j + 1) % nPoly[ i ] ] ) && (th_index < nThetaMax) )
th_index++;
p1[ 0 ] = r_last * cos( theta_last[ th_index % nPoly[ i - 1 ] ] );
p1[ 1 ] = r_last * sin( theta_last[ th_index % nPoly[ i - 1 ] ] );
t = new KGMeshTriangle( p0, p1, p2 );
AddElement( t );
}
// Finally, we set our variables for the next iteration
for( int j = 0; j < nPoly[ i ]; j++ )
theta_last[ j ] = theta[ j ];
r_last = r;
}
}
}
| true |
485f17a360d7268d946d1a92c11ac59e0c0ad06e | C++ | nfwaldron/CPlayground | /RandomNumberGenerator/RandomNumberGenerator/Generator.h | UTF-8 | 701 | 2.640625 | 3 | [] | no_license | // Generator.h
// RandomNumberGenerator
// Created by Admin on 2/27/15.
// Copyright (c) 2015 Admin. All rights reserved.
//
#ifndef __RandomNumberGenerator__Generator__
#define __RandomNumberGenerator__Generator__
#include <stdio.h>
class Generator
{
public:
Generator(); // Constructor
unsigned long int random(int bitCount); // Random number generator
bool chiSquare(int a [], int N, int R); // Chi Square test implementation
// Virtual function modifiable for uniform generator class, and exponential generator class
//virtual float random () = 0;
private:
unsigned long int sequence;
};
#endif /* defined(__RandomNumberGenerator__Generator__) */
| true |
120bbb54925b35640d7b688ffbd5f93a04991031 | C++ | natanelia/grafika | /Line.cpp | UTF-8 | 13,839 | 3.109375 | 3 | [] | no_license | #include "Line.h"
Line::Line(vector<Point>& points) : Drawing(points) {}
Line::Line(Point points[], int n) : Drawing(points, n) {}
Line::Line(Point p1, Point p2){
points.push_back(p1);
points.push_back(p2);
}
void Line::draw(ShadowBuffer& sb) {
int x1 = (int)points[0].x;
int y1 = (int)points[0].y;
int x2 = (int)points[1].x;
int y2 = (int)points[1].y;
float deltaX = (x2 - x1);
float deltaY = (y2 - y1);
float error = 0;
float deltaErr = fabs(deltaY/deltaX);
if (x1 > x2) {
int temp = x1;
x1 = x2;
x2 = temp;
temp = y1;
y1 = y2;
y2 = temp;
}
int y = (int)y1;
for (int x = (int)x1; x <= (int)x2; x++) {
sb.plot(x,y, color);
error = error + deltaErr;
while (error >= 0.5 && y != y2) {
sb.plot(x,y, color);
int sign = (y2 > y1) ? 1: -1;
y = y + sign;
error = error - 1;
}
}
}
map<int,int> Line::getLinePoints() {
map<int,int> lineYtoX;
int x1 = (int)points[0].x;
int y1 = (int)points[0].y;
int x2 = (int)points[1].x;
int y2 = (int)points[1].y;
float deltaX = (x2 - x1);
float deltaY = (y2 - y1);
float error = 0;
float deltaErr = fabs(deltaY/deltaX);
if (x1 > x2) {
int temp = x1;
x1 = x2;
x2 = temp;
temp = y1;
y1 = y2;
y2 = temp;
}
int z = 0;
int y = (int)y1;
for (int x = (int)x1; x <= (int)x2; x++) {
lineYtoX[y] = x;
error = error + deltaErr;
while (error >= 0.5 && y != y2) {
lineYtoX[y] = x;
int sign = (y2 > y1) ? 1: -1;
y = y + sign;
error = error - 1;
}
}
return lineYtoX;
}
void Line::draw(ShadowBuffer& sb, Point const baseStart, int const radius, Color startColor, Color endColor) {
//Create color which has rgb values of differences between startColor and endColor
Color diffStartEnd(endColor.r, endColor.g, endColor.b);
diffStartEnd.r -= startColor.r;
diffStartEnd.g -= startColor.g;
diffStartEnd.b -= startColor.b;
int x1 = (int)points[0].x;
int y1 = (int)points[0].y;
int x2 = (int)points[1].x;
int y2 = (int)points[1].y;
float deltaX = (x2 - x1);
float deltaY = (y2 - y1);
float error = 0;
float deltaErr = fabs(deltaY/deltaX);
if (x1 > x2) {
int temp = x1;
x1 = x2;
x2 = temp;
temp = y1;
y1 = y2;
y2 = temp;
}
Color c;
float d;
int y = (int)y1;
for (int x = (int)x1; x <= (int)x2; x++) {
d = sqrt(fabs(pow(baseStart.x - x, 2) + pow(baseStart.y - y, 2)));
float percentage = ((d / radius));
if (percentage > 1) percentage = 1;
c.r = startColor.r + diffStartEnd.r * percentage;
c.g = startColor.g + diffStartEnd.g * percentage;
c.b = startColor.b + diffStartEnd.b * percentage;
sb.plot(x, y, c);
error = error + deltaErr;
while (error >= 0.5 && y != y2) {
int sign = (y2 > y1) ? 1: -1;
y = y + sign;
error = error - 1;
sb.plot(x, y, c);
d = sqrt(fabs(pow(baseStart.x - x, 2) + pow(baseStart.y - y, 2)));
int percentage = ((d / radius));
if (percentage > 1) percentage = 1;
c.r = startColor.r + diffStartEnd.r * percentage;
c.g = startColor.g + diffStartEnd.g * percentage;
c.b = startColor.b + diffStartEnd.b * percentage;
}
}
}
void Line::draw(ShadowBuffer& sb, Point const baseStart, float * radius, Color * colors, int n) {
if (radius[0] != 0) cout << "WARNING: First element of radius should be a ZERO" << endl;
//Create color which has rgb values of differences between startColor and endColor
int x1 = (int)points[0].x;
int y1 = (int)points[0].y;
int x2 = (int)points[1].x;
int y2 = (int)points[1].y;
float deltaX = (x2 - x1);
float deltaY = (y2 - y1);
float error = 0;
float deltaErr = fabs(deltaY/deltaX);
if (x1 > x2) {
int temp = x1;
x1 = x2;
x2 = temp;
temp = y1;
y1 = y2;
y2 = temp;
}
Color c;
float d;
int y = (int)y1;
for (int x = (int)x1; x <= (int)x2; x++) {
d = sqrt(fabs(pow(baseStart.x - x, 2) + pow(baseStart.y - y, 2)));
int segmentId = 1;
while (d > radius[segmentId] && segmentId < n - 1) {
++segmentId;
}
double percentage;
if (segmentId == n) {
percentage = 1;
} else {
percentage = (d - radius[segmentId - 1]) / (radius[segmentId] - radius[segmentId - 1]);
}
if (percentage > 1) percentage = 1;
c.r = colors[segmentId - 1].r + (colors[segmentId].r - colors[segmentId - 1].r) * percentage;
c.g = colors[segmentId - 1].g + (colors[segmentId].g - colors[segmentId - 1].g) * percentage;
c.b = colors[segmentId - 1].b + (colors[segmentId].b - colors[segmentId - 1].b) * percentage;
sb.plot(x, y, c);
error = error + deltaErr;
while (error >= 0.5 && y != y2) {
int sign = (y2 > y1) ? 1: -1;
y = y + sign;
error = error - 1;
sb.plot(x, y, c);
d = sqrt(fabs(pow(baseStart.x - x, 2) + pow(baseStart.y - y, 2)));
int segmentId = 1;
while (d > radius[segmentId] && segmentId < n - 1) {
++segmentId;
}
double percentage;
if (segmentId == n) {
percentage = 1;
} else {
percentage = (d - radius[segmentId - 1]) / (radius[segmentId] - radius[segmentId - 1]);
}
if (percentage > 1) percentage = 1;
c.r = colors[segmentId - 1].r + (colors[segmentId].r - colors[segmentId - 1].r) * percentage;
c.g = colors[segmentId - 1].g + (colors[segmentId].g - colors[segmentId - 1].g) * percentage;
c.b = colors[segmentId - 1].b + (colors[segmentId].b - colors[segmentId - 1].b) * percentage;
}
}
}
void Line::drawChopped(ShadowBuffer& sb, Point const baseStart, int const radius, Color startColor, Color endColor, int n) {
//Create color which has rgb values of differences between startColor and endColor
Color diffStartEnd(endColor.r, endColor.g, endColor.b);
diffStartEnd.r -= startColor.r;
diffStartEnd.g -= startColor.g;
diffStartEnd.b -= startColor.b;
int x1 = (int)points[0].x;
int y1 = (int)points[0].y;
int x2 = (int)points[1].x;
int y2 = (int)points[1].y;
float deltaX = (x2 - x1);
float deltaY = (y2 - y1);
float error = 0;
float deltaErr = fabs(deltaY/deltaX);
if (x1 > x2) {
int temp = x1;
x1 = x2;
x2 = temp;
temp = y1;
y1 = y2;
y2 = temp;
}
Color c;
float d;
float * segmentPercentage = new float[n];
for (int i = 0; i < n; i++) {
segmentPercentage[i] = (float)i / n;
}
int y = (int)y1;
for (int x = (int)x1; x <= (int)x2; x++) {
d = sqrt(fabs(pow(baseStart.x - x, 2) + pow(baseStart.y - y, 2)));
float percentage = ((d / radius));
int segmentId = 0;
while (segmentPercentage[segmentId] < percentage && segmentId < n) {
++segmentId;
}
percentage = segmentPercentage[segmentId];
if (percentage > 1) percentage = 1;
c.r = startColor.r + diffStartEnd.r * percentage;
c.g = startColor.g + diffStartEnd.g * percentage;
c.b = startColor.b + diffStartEnd.b * percentage;
sb.plot(x, y, c);
error = error + deltaErr;
while (error >= 0.5 && y != y2) {
int sign = (y2 > y1) ? 1: -1;
y = y + sign;
error = error - 1;
sb.plot(x, y, c);
d = sqrt(fabs(pow(baseStart.x - x, 2) + pow(baseStart.y - y, 2)));
int percentage = ((d / radius));
int segmentId = 0;
while (segmentPercentage[segmentId] < percentage && segmentId < n) {
++segmentId;
}
percentage = segmentPercentage[segmentId];
if (percentage > 1) percentage = 1;
c.r = startColor.r + diffStartEnd.r * percentage;
c.g = startColor.g + diffStartEnd.g * percentage;
c.b = startColor.b + diffStartEnd.b * percentage;
}
}
}
void Line::drawChopped(ShadowBuffer& sb, Point const baseStart, float * radius, Color * colors, int n, int nSegment) {
if (radius[0] != 0) cout << "WARNING: First element of radius should be a ZERO" << endl;
//Create color which has rgb values of differences between startColor and endColor
int x1 = (int)points[0].x;
int y1 = (int)points[0].y;
int x2 = (int)points[1].x;
int y2 = (int)points[1].y;
float deltaX = (x2 - x1);
float deltaY = (y2 - y1);
float error = 0;
float deltaErr = fabs(deltaY/deltaX);
if (x1 > x2) {
int temp = x1;
x1 = x2;
x2 = temp;
temp = y1;
y1 = y2;
y2 = temp;
}
Color c;
float d;
float * segmentPercentage = new float[nSegment + 1];
for (int i = 0; i <= nSegment; i++) {
segmentPercentage[i] = (float)i / nSegment;
}
int y = (int)y1;
for (int x = (int)x1; x <= (int)x2; x++) {
d = sqrt(fabs(pow(baseStart.x - x, 2) + pow(baseStart.y - y, 2)));
int segmentId = 1;
while (d > radius[segmentId] && segmentId < n - 1) {
++segmentId;
}
double percentage;
if (segmentId == n) {
percentage = 1;
} else {
percentage = (d - radius[segmentId - 1]) / (radius[segmentId] - radius[segmentId - 1]);
int choppedSegmentId = 0;
while (segmentPercentage[choppedSegmentId] < percentage && choppedSegmentId <= nSegment) {
++choppedSegmentId;
}
percentage = segmentPercentage[choppedSegmentId];
}
if (percentage > 1) percentage = 1;
c.r = colors[segmentId - 1].r + (colors[segmentId].r - colors[segmentId - 1].r) * percentage;
c.g = colors[segmentId - 1].g + (colors[segmentId].g - colors[segmentId - 1].g) * percentage;
c.b = colors[segmentId - 1].b + (colors[segmentId].b - colors[segmentId - 1].b) * percentage;
sb.plot(x, y, c);
error = error + deltaErr;
while (error >= 0.5 && y != y2) {
int sign = (y2 > y1) ? 1: -1;
y = y + sign;
error = error - 1;
sb.plot(x, y, c);
d = sqrt(fabs(pow(baseStart.x - x, 2) + pow(baseStart.y - y, 2)));
int segmentId = 1;
while (d > radius[segmentId] && segmentId < n - 1) {
++segmentId;
}
double percentage;
if (segmentId == n) {
percentage = 1;
} else {
percentage = (d - radius[segmentId - 1]) / (radius[segmentId] - radius[segmentId - 1]);
int choppedSegmentId = 0;
while (segmentPercentage[choppedSegmentId] < percentage && choppedSegmentId <= nSegment) {
++choppedSegmentId;
}
percentage = segmentPercentage[choppedSegmentId];
}
if (percentage > 1) percentage = 1;
c.r = colors[segmentId - 1].r + (colors[segmentId].r - colors[segmentId - 1].r) * percentage;
c.g = colors[segmentId - 1].g + (colors[segmentId].g - colors[segmentId - 1].g) * percentage;
c.b = colors[segmentId - 1].b + (colors[segmentId].b - colors[segmentId - 1].b) * percentage;
}
}
}
void Line::drawTextured(ShadowBuffer& sb, Point const baseStart, int textureWidth, int textureHeight, Color ** texture) {
int x1 = (int)points[0].x;
int y1 = (int)points[0].y;
int x2 = (int)points[1].x;
int y2 = (int)points[1].y;
float deltaX = (x2 - x1);
float deltaY = (y2 - y1);
float error = 0;
float deltaErr = fabs(deltaY/deltaX);
if (x1 > x2) {
int temp = x1;
x1 = x2;
x2 = temp;
temp = y1;
y1 = y2;
y2 = temp;
}
int y = (int)y1;
for (int x = (int)x1; x <= (int)x2; x++) {
sb.plot(x, y, texture[abs((y - (int)baseStart.y) % textureHeight)][abs((x - (int)baseStart.x) % textureWidth)]);
error = error + deltaErr;
while (error >= 0.5 && y != y2) {
int sign = (y2 > y1) ? 1: -1;
y = y + sign;
error = error - 1;
sb.plot(x, y, texture[abs((y - (int)baseStart.y) % textureHeight)][abs((x - (int)baseStart.x) % textureWidth)]);
}
}
}
Point Line::getPoint1(){
return points[0];
}
Point Line::getPoint2(){
return points[1];
}
Point Line::projectPointToLine(Point const p) {
Point p1 = points[0];
Point p2 = points[1];
//get the formula of current line
//get the gradient
float lineGradient = (p2.y - p1.y) / (p2.x - p1.x);
//the formula will be y = m(x - getPoint1.x) + getPoint1.y
//get the perpendicular gradient
float perpendicularGradient = -1 / lineGradient;
//get the c of the perpendicular line y = m(x) + c
float c = p.y - (perpendicularGradient * p.x);
//the formula of perpendicular line will be y = m(x) + c
//now equalize both formula to find the projected point in line
//kOfX is coefficient of x
float kOfX = perpendicularGradient - lineGradient;
float rem = (-lineGradient * p1.x) + p1.y + c;
float x = rem / kOfX;
float y = lineGradient * (x - p1.x) + p1.y;
float z = 0;
return Point(x, y, z);
} | true |
28e5f88c1c21c7000b473c4a74048f6e8f94ddda | C++ | Eduardo2712/Estrutura_de_dados | /Insertion sort.cpp | UTF-8 | 854 | 3 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
#include<conio.h>
#include<cstdio>
#include<ctime>
using namespace std;
const int TAM = 12;
int vetor[TAM] = {9, 27, 14, 6, 2, 8, 9, 17, 25, 17, 15, 6};
void gerar()
{
for(int i=0; i<TAM; i++)
{
vetor[i]=rand();
}
}
void insertion()
{
int atual = 0;
int j;
for (int i = 0; i < TAM; i++)
{
atual = vetor[i];
j = i - 1;
while ((j >= 0) && (atual < vetor[j]))
{
vetor[j + 1] = vetor[j];
j = j - 1;
}
vetor[j + 1] = atual;
for(int i=0; i<TAM; i++)
{
cout << "" << vetor[i]<< " ";
}
cout << endl;
}
}
main()
{
clock_t tempo1,tempo2;
tempo1 = clock();
insertion();
tempo2 = clock() - tempo1;
printf("\n%f", (float) tempo2/CLOCKS_PER_SEC);
}
| true |
78c744ca9478a73fd96e66425b93694489f959fc | C++ | VarickQ/ACM | /HaveDone/HDU/最优页面调度算法(贪心+优先队列)4398.cpp | GB18030 | 1,560 | 2.53125 | 3 | [] | no_license | /*
еƫ⡣ϵͳеҳ㷨̰ġҪ̭ijģʱ̭ǰԶĽŻᱻõԺԶõǸ
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
const int N = 100010;
const int inf = 2000000000;
typedef __int64 LL;
int a[N],p[N];
map<int,int> ma;
map<int,bool> v;
struct Node{
int dis,id;
bool operator < (const Node &a) const{
return dis < a.dis;
}
};
priority_queue<Node> qu;
int main(){
int n,m;
while( scanf("%d%d", &n, &m) != EOF ){
while(!qu.empty()) qu.pop();
ma.clear();
v.clear();
for(int i=1 ; i <= n ; ++i){
scanf("%d", &a[i]);
v[a[i]] = false;
p[i] = inf;
}
for(int i=n ; i >= 1 ; --i){
if( ma.find(a[i]) == ma.end() )
ma[a[i]] = i;
else {
p[i] = ma[a[i]];
ma[a[i]] = i;
}
}
for(int i=1 ; i <= m ; ++i){
Node t;
if( ma.find(i) == ma.end() )
t.dis = ma[i] = inf;
else t.dis = ma[i];
t.id = i;
v[i] = true;
qu.push(t);
}
int ans = 0;
for(int i=1 ; i <= n ; ++i){
Node t;
t.dis = p[i];
t.id = a[i];
if( !v[a[i]] ){
ans++;
v[a[i]] = true;
qu.push(t);
t = qu.top(); qu.pop();
v[t.id] = false;
} else qu.push(t);
}
printf("%d\n", ans);
}
return 0;
} | true |
a18a7e2a0118d8f0064f8e7f067390172f32085c | C++ | RabbitMC/MixingCppObjC | /MixingCppObjC/MixingCppObjC/C++/Cat.hpp | UTF-8 | 429 | 2.671875 | 3 | [
"MIT"
] | permissive | //
// Cat.hpp
// MixingCppObjC
//
// Created by Miralem Cebic on 27.07.17.
// Copyright © 2017 Miralem Cebic. All rights reserved.
//
#ifndef Cat_hpp
#define Cat_hpp
#include <stdio.h>
#include <iostream>
class Cat
{
public:
Cat(int initialAge);
Cat(const Cat& copy_from);
~Cat();
int GetAge() const;
void SetAge(int age);
void Meow();
private:
int itsAge;
char * string;
};
#endif /* Cat_hpp */
| true |
d1c7670a5197a004a2199f625997b3c190412a2a | C++ | Albertogk/competitive_programming | /uva/621-secret.cpp | UTF-8 | 608 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int main() {
int t;
string read;
cin >> t;
cin.ignore();
for(int i=0; i < t; i++) {
getline(cin, read);
const int n = read.size();
if (read == "1" || read == "4" || read == "78") {
cout << "+" << endl;
}
else if (read[n-1] == '5' && read[n-2] == '3') {
cout << "-" << endl;
}
else if (read[0] == '9' && read[n-1] == '4') {
cout << "*" << endl;
}
else {
cout << "?" << endl;
}
}
return 0;
} | true |
d8f80d895c348578e13d5a8cf52fc9a5446fada2 | C++ | Ali-externe/Epitech-Second-Year | /CCP_plazza_2018/main.cpp | UTF-8 | 4,914 | 2.84375 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2019
** plazza
** File description:
** main
*/
#include "reception.hpp"
/*
int incrementCounter(int &counter)
{
while (counter != 10) {
std::cout << "Turns : " << counter << std::endl;
counter++;
}
return (counter);
}
int main(void)
{
std::mutex mtx;
mtx.lock();
int i = 0;
pthread_t t1;
pthread_t t2;
mtx.unlock();
//pthread_create(&t1, NULL, &incrementCounter, NULL);
t1 = incrementCounter(i);
t2 = incrementCounter(i);
std::cout << "Turnst1 : " << t1 << std::endl << "Turnst2 : " << t2 << std::endl;
return (0);
}*/
int get_command(std::string command)
{
if (command.compare("status") == 0) {
std::cout << "Status is : " << "..." << std::endl;
return (0);
}
else if (command.compare("exit") == 0)
return (2);
else
return (3);
return (0);
}
int check_num(std::string check)
{
int a = 0;
for(int i = 0; i != check.length(); i++) {
if (std::isdigit(check[i]) != 0)
a = 1;
else
return 1;
}
if (a == 1)
return 0;
return (0);
}
int parsing_bis(std::string str, std::string st[])
{
size_t pos = 0;
std::string token;
int space = 0;
int counter = 0;
std::string delimiter = " ";
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == ' ')
space++;
}
std::string tab[space + 1];
while ((pos = str.find(delimiter)) != std::string::npos) {
token = str.substr(0, pos);
tab[counter] = token;
str.erase(0, pos + delimiter.length());
counter++;
}
return (counter);
}
std::string *parsing(std::string str, std::string st[])
{
size_t pos = 0;
std::string token;
int space = 0;
int counter = 0;
std::string delimiter = " ";
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == ' ')
space++;
}
std::string tab[space + 1];
while ((pos = str.find(delimiter)) != std::string::npos) {
token = str.substr(0, pos);
tab[counter] = token;
str.erase(0, pos + delimiter.length());
counter++;
}
st = tab;
return (st);
}
void kitchen(struct s_struct *s_plazza) {
//if (fork() == 0)
cooks(s_plazza);
}
void go_to_kitchen(struct s_struct *s_plazza)
{
std::string pizza = s_plazza->tab[0];
std::string size = s_plazza->tab[1];
std::string speed = s_plazza->tab[2];
std::transform(pizza.begin(), pizza.end(), pizza.begin(), ::tolower);
std::transform(size.begin(), size.end(), size.begin(), ::tolower);
std::transform(speed.begin(), speed.end(), speed.begin(), ::tolower);
if ((check_pizza(pizza, s_plazza) == 0), (check_size(size, s_plazza)) == 0) {
if (speed.compare(0,1, "x") == 0) {
if (std::isdigit(speed[1]) != 0) {
std::cout << "You ordered " << speed[1] << " pizza(s)" << std::endl;
s_plazza->nb_pizza = speed[1];
kitchen(s_plazza);
}
else
std::cout << "That's not a number" << std::endl;
}
else
std::cout << "That's not a number" << std::endl;
}
}
void printer(std::vector<std::string> const &input)
{
for (int i = 0; i < input.size(); i++) {
std::cout << input.at(i) << '\n';
}
}
std::vector<std::string> splitter(std::string strToSplit)
{
std::stringstream ss(strToSplit);
std::string item;
std::vector<std::string> splittedStrings;
while (std::getline(ss, item, ';')) {
splittedStrings.push_back(item);
}
return splittedStrings;
}
void plazza_func(char **arguments)
{
int val = 0;
static int cou = 0;
std::string command;
std::stringstream copy;
std::string sttt[1];
std::string a_command;
std::string s_command;
std::vector<std::string> seg_command;
struct s_struct *s_plazza = new struct s_struct;
s_plazza->multiplier = atof(arguments[1]);
s_plazza->cook_p_k = atoi(arguments[2]);
s_plazza->time_restock = atoi(arguments[3]);
std::cout << "plazza > ";
while (1) {
std::getline (std::cin,command);
seg_command = splitter(command);
for (int i = 0; i < seg_command.size(); i++) {
command = seg_command.at(i);
command.insert(command.end(), ' ');
if (cou == 0)
s_command = command;
cou++;
s_plazza->tab = parsing(command, sttt);
s_plazza->nb_tab = parsing_bis(command, sttt);
if (s_plazza->nb_tab != 3) {
val = get_command(s_plazza->tab[0]);
if (val == 3)
continue;
if (val == 2)
break;
}
else {
if (s_command != command || cou == 1) {
create_kitchen(s_plazza);
s_command = command;
}
go_to_kitchen(s_plazza);
}
}
}
}
int main(int argc, char **argv)
{
if (argc != 4) {
std::cout << "Error arguments" << std::endl;
return 84;
}
if (check_num(argv[2]) != 0 || check_num(argv[3]) != 0) {
std::cout << "Error arguments" << std::endl;
return 84;
}
plazza_func(argv);
}
| true |
dbbc9efd09255c5017aafe8b051c1858691f850b | C++ | maguilo11/locus | /xgen/include/OptimalityCriteria/Locus_OptimalityCriteriaTestInequalityOne.hpp | UTF-8 | 3,384 | 2.671875 | 3 | [] | no_license | /*
* Locus_OptimalityCriteriaTestInequalityOne.hpp
*
* Created on: Oct 17, 2017
* Author: Miguel A. Aguilo Valentin
*/
#ifndef LOCUS_OPTIMALITYCRITERIATESTINEQUALITYONE_HPP_
#define LOCUS_OPTIMALITYCRITERIATESTINEQUALITYONE_HPP_
#include <cmath>
#include <memory>
#include <cassert>
#include "Locus_Criterion.hpp"
#include "Locus_MultiVector.hpp"
namespace locus
{
template<typename ScalarType, typename OrdinalType = size_t>
class OptimalityCriteriaTestInequalityOne : public locus::Criterion<ScalarType, OrdinalType>
{
public:
explicit OptimalityCriteriaTestInequalityOne() :
mBound(1.)
{
}
virtual ~OptimalityCriteriaTestInequalityOne()
{
}
void cacheData()
{
return;
}
ScalarType value(const locus::MultiVector<ScalarType, OrdinalType> & aControl)
{
const OrdinalType tVectorIndex = 0;
assert(aControl[tVectorIndex].size() == static_cast<OrdinalType>(5));
const ScalarType tPower = 3.;
ScalarType tFirstTerm = static_cast<ScalarType>(61.) / std::pow(aControl(tVectorIndex,0), tPower);
ScalarType tSecondTerm = static_cast<ScalarType>(37.) / std::pow(aControl(tVectorIndex,1), tPower);
ScalarType tThirdTerm = static_cast<ScalarType>(19.) / std::pow(aControl(tVectorIndex,2), tPower);
ScalarType tFourthTerm = static_cast<ScalarType>(7.) / std::pow(aControl(tVectorIndex,3), tPower);
ScalarType tFifthTerm = static_cast<ScalarType>(1.) / std::pow(aControl(tVectorIndex,4), tPower);
ScalarType tValue = tFirstTerm + tSecondTerm + tThirdTerm + tFourthTerm + tFifthTerm;
ScalarType tOutput = tValue - mBound;
return (tOutput);
}
void gradient(const locus::MultiVector<ScalarType, OrdinalType> & aControl,
locus::MultiVector<ScalarType, OrdinalType> & aGradient)
{
const OrdinalType tVectorIndex = 0;
assert(aControl[tVectorIndex].size() == static_cast<OrdinalType>(5));
const ScalarType tPower = 4;
const ScalarType tScaleFactor = -3.;
aGradient(tVectorIndex,0) = tScaleFactor * (static_cast<ScalarType>(61.) / std::pow(aControl(tVectorIndex,0), tPower));
aGradient(tVectorIndex,1) = tScaleFactor * (static_cast<ScalarType>(37.) / std::pow(aControl(tVectorIndex,1), tPower));
aGradient(tVectorIndex,2) = tScaleFactor * (static_cast<ScalarType>(19.) / std::pow(aControl(tVectorIndex,2), tPower));
aGradient(tVectorIndex,3) = tScaleFactor * (static_cast<ScalarType>(7.) / std::pow(aControl(tVectorIndex,3), tPower));
aGradient(tVectorIndex,4) = tScaleFactor * (static_cast<ScalarType>(1.) / std::pow(aControl(tVectorIndex,4), tPower));
}
std::shared_ptr<locus::Criterion<ScalarType, OrdinalType>> create() const
{
std::shared_ptr<locus::Criterion<ScalarType, OrdinalType>> tOutput =
std::make_shared<locus::OptimalityCriteriaTestInequalityOne<ScalarType, OrdinalType>>();
return (tOutput);
}
private:
ScalarType mBound;
private:
OptimalityCriteriaTestInequalityOne(const locus::OptimalityCriteriaTestInequalityOne<ScalarType, OrdinalType>&);
locus::OptimalityCriteriaTestInequalityOne<ScalarType, OrdinalType> & operator=(const locus::OptimalityCriteriaTestInequalityOne<ScalarType, OrdinalType>&);
};
}
#endif /* LOCUS_OPTIMALITYCRITERIATESTINEQUALITYONE_HPP_ */
| true |
10430ed5fce35af095fe4437b31051b5134740c0 | C++ | FatemaOthman/Paint-For-Kids | /Figures/CFigure.cpp | UTF-8 | 1,645 | 2.96875 | 3 | [] | no_license | #include "CFigure.h"
#include<iostream>
#include<fstream>
CFigure::CFigure(GfxInfo FigureGfxInfo)
{
FigGfxInfo= FigureGfxInfo; //Default status is non-filled.
Selected = false;
ID=++ID;
}
void CFigure::SetSelected(bool s)
{ Selected = s; }
bool CFigure::IsSelected() const
{ return Selected; }
void CFigure::ChngDrawClr(color Dclr)
{ FigGfxInfo.DrawClr = Dclr; }
float CFigure::CalcTriArea(Point *v1, Point *v2, Point *v3)
{
float det = 0.0f;
det = (v2->x*v3->y - v3->x*v2->y) - (v1->x*v3->y - v1->y*v3->x) + (v1->x*v2->y - v1->y*v2->x);
det = abs(det);
return (det / 2.0f);
}
float CFigure::Dist(Point p1, Point p2)
{
return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));
}
int CFigure::GetID()
{
return ID;
}
string CFigure::ColorToString(color c)
{
if (!FigGfxInfo.isFilled)
return "Non Filled";
if (c==RED)
return "Red";
else if (c==GREEN)
return "Green";
else if (c==BLUE)
return "Blue";
else if (c==WHITE)
return "White";
else if (c==BLACK)
return "Black";
}
color CFigure::GetDrawColor()
{
return FigGfxInfo.DrawClr;
}
color CFigure::GetFillColor()
{
if (FigGfxInfo.isFilled)
return FigGfxInfo.FillClr;
}
void CFigure::Readcolor(ofstream&fout, color c)
{
if (c==BLUE)
fout << "BLUE";
if (c==BLACK)
fout << "BLACK";
if (c==WHITE)
fout << "WHITE";
if (c==GREEN)
fout << "GREEN";
if (c==RED)
fout << "RED";
}
bool CFigure::SameFillColor(CFigure *C)
{
if (FigGfxInfo.isFilled != C->FigGfxInfo.isFilled)
return false;
return FigGfxInfo.FillClr == C->FigGfxInfo.FillClr;
} | true |
8400c10f45821ba18420b69535978acc8fb4c539 | C++ | alexkeel/Bruskey | /Components/SyntaxTree/src/FunctionCall.cpp | UTF-8 | 794 | 3.0625 | 3 | [] | no_license | #include "FunctionCall.hpp"
FunctionCall::FunctionCall(Expression *ident, Expression *argument)
{
this->expression = ident->toCode() + "(" + argument->toCode() + ")";
}
FunctionCall::FunctionCall(Expression *ident, std::vector<Expression *> *arguments)
{
this->expression = ident->toCode();
this->expression += "(";
for(int i = 0; i < arguments->size(); i++)
{
if(i == arguments->size() - 1)
{
this->expression += (arguments->at(i)->toCode());
}
else
{
this->expression += (arguments->at(i)->toCode() + ",");
}
}
this->expression += ")";
}
FunctionCall::FunctionCall(Expression *ident)
{
this->expression = ident->toCode() + "()";
}
FunctionCall::~FunctionCall()
{
} | true |
f8a360c64bf82dfc8980d7028705f6793f1ad9a3 | C++ | junghoon88/starcraft | /tile.h | UHC | 1,736 | 3.03125 | 3 | [] | no_license | #pragma once
#include "gameNode.h"
class tile : public gameNode
{
private:
int _idX;
int _idY;
POINT _center;
RECT _rc;
//F = G + H
// F ==
// G == κ (Ÿ) κ
// H == (Ÿ) κ
float _totalCost; //F
float _costFromStart; //G
float _costToGoal; //H
bool _isOpen;
bool _isFind;
tile* _parentNode;
DWORD _obj;
DWORD _attribute;
public:
tile();
~tile();
HRESULT init(int idX, int idY);
HRESULT init(int idX, int idY, RECT rc);
void release();
void update();
void render();
int getIdX(void) { return _idX; }
int getIdY(void) { return _idY; }
RECT getRect() { return _rc; }
void setCenter(POINT center) { _center = center; }
POINT getCenter() { return _center; }
void setObject(DWORD obj) { _obj = obj; }
DWORD getObject(void) { return _obj; }
void setAttribute(DWORD attr) { _attribute = attr; }
DWORD getAttribute() { return _attribute; }
void setTotalCost(float totalCost) { _totalCost = totalCost; }
float getTotalCost() { return _totalCost; }
void setCostFromStart(float costFromStart) { _costFromStart = costFromStart; }
float getCostFromStart() { return _costFromStart; }
void setCostToGoal(float costToGoal) { _costToGoal = costToGoal; }
float getCostToGoal() { return _costToGoal; }
void setParentNode(tile* t) { _parentNode = t; }
tile* getParentNode() { return _parentNode; }
void setIsOpen(bool isOpen) { _isOpen = isOpen; }
bool getIsOpen() { return _isOpen; }
inline void setIsFind(bool isFind) { _isFind = isFind; }
inline bool getIsFind(void) { return _isFind; }
};
typedef vector<tile*> vTile;
typedef vector<tile*>::iterator vTileIter;
| true |
943e8cfc0c0bb0ba3d5d38cafad51a39401e3ac2 | C++ | evarnazi/CompPhyFinalC | /cpt/linalg.hpp | UTF-8 | 5,008 | 2.8125 | 3 | [] | no_license | #ifndef CPT_LINALG_HPP
#define CPT_LINALG_HPP
#include <algorithm>
#include <cmath>
#include <complex>
#include <iostream>
#include <string>
#include "matrix.hpp"
namespace cpt
{
Matrix<double,2> transpose(const Matrix<double,2>&);
double inverse( Matrix<double,2> m, Matrix<double,2> & minv);
void solve_Gauss_Jordan(Matrix<double,2>& A, Matrix<double,2>& B);
void solve_LU_decompose(Matrix<double,2>& A, Matrix<double,2>& B);
Matrix<double,1> solve_eigen_symmetric(Matrix<double,2>& A);
Matrix<double,1> solve_eigen_generalized(Matrix<double,2>& A,
Matrix<double,2>& S,
bool verbose=false);
Matrix<double,1> solve_tridiag( Matrix<double,1> const & a,
Matrix<double,1> const & b,
Matrix<double,1> const & c,
Matrix<double,1> const & r,
unsigned long n);
template<class T> Matrix<T,2> operator+(
const Matrix<T,2>& m1, const Matrix<T,2>&m2)
{
int rows = m1.dim1();
int cols = m1.dim2();
if (rows != m2.dim1() || cols != m2.dim2())
error("linalg: matrix dimension mismatch");
Matrix<T,2> m1_plus_m2(rows, cols);
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
m1_plus_m2[i][j] = m1[i][j] + m2[i][j];
return m1_plus_m2;
}
template<class T> Matrix<T,2> operator-(
const Matrix<T,2>& m1, const Matrix<T,2>&m2)
{
int rows = m1.dim1();
int cols = m1.dim2();
if (rows != m2.dim1() || cols != m2.dim2())
error("linalg: matrix dimension mismatch");
Matrix<T,2> m1_minus_m2(rows, cols);
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
m1_minus_m2[i][j] = m1[i][j] - m2[i][j];
return m1_minus_m2;
}
template<class T> Matrix<T,2> operator*(
const Matrix<T,2>& m1, const Matrix<T,2>&m2)
{
int n = m1.dim2();
if (n != m2.dim1())
error("linalg: matrix dimension mismatch");
int rows = m1.dim1();
int cols = m2.dim2();
Matrix<T,2> product(rows, cols);
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
for (int k = 0; k < n; k++)
product[i][j] += m1[i][k] * m2[k][j];
return product;
}
template<class T> Matrix<T,1> operator+(
const Matrix<T,1>& v1, const Matrix<T,1>& v2)
{
if (v1.dim1() != v2.dim1())
error("linalg: matrix dimension mismatch");
Matrix<T,1> v1_plus_v2(v1.dim1());
for (int i = 0; i < v1.dim1(); i++)
v1_plus_v2[i] = v1[i] + v2[i];
return v1_plus_v2;
}
template<class T> Matrix<T,1> operator-(
const Matrix<T,1>& v1, const Matrix<T,1>& v2)
{
if (v1.dim1() != v2.dim1())
error("linalg: matrix dimension mismatch");
Matrix<T,1> v1_minus_v2(v1.dim1());
for (int i = 0; i < v1.dim1(); i++)
v1_minus_v2[i] = v1[i] - v2[i];
return v1_minus_v2;
}
template<class T> T dot(const Matrix<T,1>& v1, const Matrix<T,1>& v2)
{
T dot = 0;
for (int i = 0; i < v1.size(); i++)
dot += v1[i] * v2[i];
return dot;
}
// FFT Routines
void fft(Matrix<std::complex<double>,1>&,
const bool inverse=false);
inline void fft_inv(Matrix<std::complex<double>,1>& v) { fft(v, true); }
void fft(Matrix<std::complex<double>,2>&,
const bool inverse=false);
inline void fft_inv(Matrix<std::complex<double>,2>& m) { fft(m, true); }
// Least Squares and Chi-Square Fits
void least_squares_fit( // makes a linear least-squares fit
const Matrix<double,1>& x, // vector of x values - input
const Matrix<double,1>& y, // vector of y values - input
double& a, // fitted intercept - output
double& b, // fitted slope - output
double& sigma_a, // estimated error in intercept - output
double& sigma_b, // estimated error in slope - output
double& sigma); // estimated error bar in y
void chi_square_fit( // makes a linear chi-square fit
const Matrix<double,1>& x, // vector of x values - input
const Matrix<double,1>& y, // vector of y values - input
const Matrix<double,1>& err, // vector of y error values - input
double& a, // fitted intercept - output
double& b, // fitted slope - output
double& sigma_a, // estimated error in intercept - output
double& sigma_b, // estimated error in slope - output
double& chi_square); // minimized chi-square sum - output
} /* namespace cpt */
#endif /* CPT_LINALG_HPP */
| true |
1487f921861efc6dce2887958380493c2956de45 | C++ | caojiying002/Source_Code_of_Books | /C++_for_Java_Programmers_Mark_A_Weiss/leak.cpp | UTF-8 | 380 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
// leaks memory on systems that don't garbage collect
void leak( int i )
{
vector<int> *ptrToVector = new vector<int>( i );
if( i % 2 == 1 )
return;
ptrToVector->push_back( i );
delete ptrToVector;
}
int main( )
{
for( int i = 0; i < 10000; i++ )
leak( 500001 );
return 0;
} | true |
2a932628a2e05eb8f2e66e369c62cfe8d383a513 | C++ | edgarreb/ee355 | /lab/PA1/PA1/helper.cpp | UTF-8 | 311 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string func(string str1, string str2)
{
string res = str1 + str2;
transform(res.begin(), res.end(), res.begin(), tolower);
};
int main()
{
string fname = "Edgar Roy";
string lname = "Martinez";
func(fname, lname);
}
| true |
0d7769843a6c332fef5c33f6a4459a8c64f20f12 | C++ | mveregge23/Cpp-Projects | /Langtons Ant/Location.cpp | UTF-8 | 656 | 3.59375 | 4 | [] | no_license | // Program name: Location.ccp
// Author: Max Veregge
// Description: This is an implementation of the Location class, used to represent the location of an Ant
// on a Board
#include "Location.h"
// setX takes an int to set the xC
void Location::setX(int x) {
xC = x;
}
// setY takes an int to set the yC
void Location::setY(int y) {
yC = y;
}
// getX returns the current xC
int Location::getX() {
return xC;
}
// getY returns the current yC
int Location::getY() {
return yC;
}
// Location constructor takes two ints to initialize the xC and yC
Location::Location(int x, int y) {
xC = x;
yC = y;
}
// Default constructor
Location::Location() {
;
} | true |
307e00ec311350a9df41dfe2545aac0fa80820b3 | C++ | chiahsun/problem_solving | /HackerRank/Algorithms/Sorting/Closest Numbers/solve1.cc | UTF-8 | 975 | 3.15625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
vector <int> closestNumbers(vector <int> arr) {
std::vector<int> ans;
ans.push_back(arr[0]);
ans.push_back(arr[1]);
// Complete this function
std::sort(arr.begin(), arr.end());
int dmin = arr[1] - arr[0];
for (int i = 2; i < arr.size(); ++i) {
int last = arr[i-1];
int cur = arr[i];
int d = cur - last;
if (d <= dmin) {
if (d < dmin) {
dmin = d;
ans.clear();
}
ans.push_back(last);
ans.push_back(cur);
}
}
return ans;
}
int main() {
int n;
cin >> n;
vector<int> arr(n);
for(int arr_i = 0; arr_i < n; arr_i++){
cin >> arr[arr_i];
}
vector <int> result = closestNumbers(arr);
for (ssize_t i = 0; i < result.size(); i++) {
cout << result[i] << (i != result.size() - 1 ? " " : "");
}
cout << endl;
return 0;
}
| true |
ab6213ee78405c66388b3bc6d973c3a42f8b95e1 | C++ | stranger900/abramian | /Proc/Proc38/main.cpp | UTF-8 | 965 | 2.9375 | 3 | [] | no_license | # include <iostream>
# include <windows.h>
# include <cmath>
# include <cmath>
#include <vector>
using namespace std;
double Power2(double a, int n);
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
//srand(time(NULL));
double a, k, L, m;
cout << "Внесіть число A : " << endl;
cin >> a;
cout << "Внесіть число K : " << endl;
cin >> k;
cout << "Внесіть число L : " << endl;
cin >> L;
cout << "Внесіть число M : " << endl;
cin >> m;
cout << endl;
cout << Power2(a, k) << endl;
cout << Power2(a, L) << endl;
cout << Power2(a, m) << endl;
return 0;
}
double Power2(double a, int n)
{
int *pn = &n;
double rez = 1;
if (n == 0) {
return 1;
}
else if (n > 0) {
while (*pn > 0) {
rez *= a;
--(*pn);
}
return rez;
}
else if (n < 0) {
while (*pn < 0) {
rez *= a;
++(*pn);
}
return (1.0/rez);
}
} | true |
7df5fae43c84487a474db3258dd08c0c6c0b678d | C++ | vladimir-nazarenko/spbu | /Homeworks1/mergeSortList/mergeSortList/List.h | UTF-8 | 2,797 | 3.9375 | 4 | [] | no_license | #pragma once
#include <iostream>
template <typename T>
class List
{
public:
struct Node
{
T item;
Node* next;
};
typedef Node* Position;
List()
{
count = 0;
head = new Node();
head->next = nullptr;
e = nullptr;
}
//Constructor, initializes list with value
List(T value)
{
head = new Node;
head->next = new Node;
head->next->item = value;
head->next->next = nullptr;
count = 1;
e = nullptr;
}
~List()
{
if (count != 0)
{
Position current = head;
Position following = head->next;
while (following != e)
{
delete current;
current = following;
following = current->next;
}
delete current;
}
else
{
delete head;
}
}
//insert item to position p
void insert(T element, Position p)
{
Node* newElem = new Node;
newElem->item = element;
newElem->next = p->next;
p->next = newElem;
++count;
}
//insert just after head
void insert(T element)
{
insert(element, head);
}
//find by value, end() if there is no such item
Position find(T element)
{
Position toFind = first();
while (toFind != end() && toFind->item != element)
{
toFind = toFind->next;
}
return toFind;
}
//get value on position
T retrieve(Position p)
{
return p->item;
}
//delete element, returns position of the element after deleted element
Position remove(Position p)
{
if (count != 0)
{
Position get = p->next;
Position temp = head;
while (temp->next != p)
temp = temp->next;
temp->next = p->next;
if (p == end())
setEnd(get);
delete p;
--count;
return get;
}
return nullptr;
}
//position of first element in the list, head if list is empty
Position first()
{
if (count != 0)
return head->next;
Node* const PointerToHead = const_cast<Node*>(head);
return PointerToHead;
}
//send list to a stream with separator
void printList(std::ostream &stream, char* separator = "\0")
{
Position toPrint = first();
while (toPrint != end())
{
stream << toPrint->item << separator;
toPrint = toPrint->next;
}
}
//position of the end of the list
Position end()
{
return e;
}
//number of elements in the list
int size()
{
return count;
}
//position of the element right after element on a gotten position
Position next(Position p)
{
if (p != end())
return p->next;
else
return end();
}
//change end() value
void setEnd(Position p)
{
if (count != 0)
{
Position i = first();
while (i->next != end())
i = i->next;
i->next = p;
}
e = p;
}
//apply action on every list element
void iterate(void (*action)(T&))
{
Position seek = first();
while (seek != end())
{
action(seek->item);
seek = seek->next;
}
}
private:
int count;
Node* head;
Position e;
};
| true |
0de55bb3f5dbbb6b642751d4a40810a84ce08d8b | C++ | a62mds/exercism | /cpp/nucleotide-count/nucleotide_count.h | UTF-8 | 1,158 | 3.21875 | 3 | [] | no_license | #ifndef NUCLEOTIDE_COUNT_H
#define NUCLEOTIDE_COUNT_H
#include<stdexcept>
#include<map>
#include<string>
namespace dna {
class counter {
public:
std::string m_seq;
std::map<char,int> m_count;
counter(std::string seq) : m_seq(seq), m_count(seq_count(seq)) {}
std::map<char,int> nucleotide_counts() const { return m_count; }
int count(char) const;
private:
std::map<char,int> seq_count(std::string&);
bool is_in(char,std::string) const;
};
}
std::map<char,int> dna::counter::seq_count(std::string& seq) {
std::map<char,int> count{{'A',0},{'T',0},{'C',0},{'G',0}};
for (std::string::iterator it=seq.begin(); it!=seq.end(); ++it) {
switch (*it) {
case 'A': count['A']++; break;
case 'T': count['T']++; break;
case 'C': count['C']++; break;
case 'G': count['G']++; break;
default: throw std::invalid_argument(*it+" is invalid");
}
}
return count;
}
int dna::counter::count(char nuc) const {
if (!is_in(nuc,"ATCG"))
throw std::invalid_argument(nuc+" is invalid");
return m_count.at(nuc);
}
bool dna::counter::is_in(char nuc, std::string seq) const {
return seq.find(nuc) != std::string::npos;
}
#endif
| true |
15d57800661d3f29dea5a5a1674f28812fabf078 | C++ | roshankshaw/programming-challenges | /huffman_decoding.cpp | UTF-8 | 567 | 3.046875 | 3 | [] | no_license |
/*
The structure of the node is
typedef struct node {
int freq;
char data;
node * left;
node * right;
} node;
*/
void decode_huff(node * root, string s) {
string res="";
node *cur=root;
int len=s.length();
for(int i=0;i<len;i++)
{
if(s[i]=='0')
cur=cur->left;
else
cur=cur->right;
if(cur->left==NULL&&cur->right==NULL)
{
res=res+cur->data;
cur=root;
}
}
//res=res+'\0';
cout<<res;
}
| true |
cc9cd1753021e4bc9952fe05213c8a064ae15f27 | C++ | a1q123456/H264Decoder | /H264Decoder/Data/NALU/SEI/MultiviewAcquisitionInfo.h | UTF-8 | 4,613 | 2.546875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <IO/BitstreamReader.h>
#include <Data/DecimalValue.h>
struct MultiviewAcquisitionInfo
{
struct ParamSet
{
DecimalValue focalLengthX;
DecimalValue focalLengthY;
DecimalValue principalPointX;
DecimalValue principalPointY;
DecimalValue skew;
ParamSet() = default;
explicit ParamSet(BitstreamReader& reader, int precFocalLength, int precPrincipalPoint, int precSkewFactor)
{
focalLengthX.sign = reader.readBits<std::uint8_t, 1>();
focalLengthX.exponent = reader.readBits<std::uint8_t, 6>();
focalLengthX.mantissa = reader.readBits<std::uint32_t>(getMantisaLength(focalLengthX.exponent, precFocalLength));
focalLengthY.sign = reader.readBits<std::uint8_t, 1>();
focalLengthY.exponent = reader.readBits<std::uint8_t, 6>();
focalLengthY.mantissa = reader.readBits<std::uint32_t>(getMantisaLength(focalLengthY.exponent, precFocalLength));
principalPointX.sign = reader.readBits<std::uint8_t, 1>();
principalPointX.exponent = reader.readBits<std::uint8_t, 6>();
principalPointX.mantissa = reader.readBits<std::uint32_t>(getMantisaLength(principalPointX.exponent, precPrincipalPoint));
principalPointY.sign = reader.readBits<std::uint8_t, 1>();
principalPointY.exponent = reader.readBits<std::uint8_t, 6>();
principalPointY.mantissa = reader.readBits<std::uint32_t>(getMantisaLength(principalPointY.exponent, precPrincipalPoint));
skew.sign = reader.readBits<std::uint8_t, 1>();
skew.exponent = reader.readBits<std::uint8_t, 6>();
skew.mantissa = reader.readBits<std::uint32_t>(getMantisaLength(skew.exponent, precSkewFactor));
}
};
struct ExtrinsicParam
{
DecimalValue rotation[4][4];
DecimalValue translation[4];
ExtrinsicParam() = default;
explicit ExtrinsicParam(BitstreamReader& reader, int precRotationParam, int precTranslationParam)
{
for (auto j = 1; j <= 3; j++)
{
for (auto k = 1; k <= 3; k++)
{
rotation[j][k].sign = reader.readBits<std::uint8_t, 1>();
rotation[j][k].exponent = reader.readBits<std::uint8_t, 6>();
rotation[j][k].mantissa = reader.readBits<std::uint32_t>(getMantisaLength(rotation[j][k].exponent, precRotationParam));
}
translation[j].sign = reader.readBits<std::uint8_t, 1>();
translation[j].exponent = reader.readBits<std::uint8_t, 6>();
translation[j].mantissa = reader.readBits<std::uint32_t>(getMantisaLength(translation[j].exponent, precTranslationParam));
}
}
};
std::uint16_t numViewsMinus1 = 0;
bool intrinsicParamFlag = false;
bool extrinsicParamFlag = false;
bool intrinsicParamsEqual = false;
std::uint32_t precFocalLength = 0;
std::uint32_t precPrincipalPoint = 0;
std::uint32_t precSkewFactor = 0;
std::vector<ParamSet> paramSets;
std::uint32_t precRotationParam = 0;
std::uint32_t precTranslationParam = 0;
std::vector<ExtrinsicParam> extrinsicParams;
MultiviewAcquisitionInfo() = default;
explicit MultiviewAcquisitionInfo(BitstreamReader& reader)
{
numViewsMinus1 = reader.readExpoGlomb();
intrinsicParamFlag = reader.readBits<bool, 1>();
extrinsicParamFlag = reader.readBits<bool, 1>();
if (intrinsicParamFlag)
{
intrinsicParamsEqual = reader.readBits<bool, 1>();
precFocalLength = reader.readExpoGlomb();
precPrincipalPoint = reader.readExpoGlomb();
precSkewFactor = reader.readExpoGlomb();
auto numOfParamSets = 0;
if (intrinsicParamsEqual)
{
numOfParamSets = 1;
}
else
{
numOfParamSets = numViewsMinus1 + 1;
}
for (auto i = 0; i < numOfParamSets; i++)
{
paramSets.emplace_back(reader, precFocalLength, precPrincipalPoint, precSkewFactor);
}
}
if (extrinsicParamFlag)
{
precRotationParam = reader.readExpoGlomb();
precTranslationParam = reader.readExpoGlomb();
for (auto i = 0; i <= numViewsMinus1; i++)
{
extrinsicParams.emplace_back(reader, precRotationParam, precTranslationParam);
}
}
}
};
| true |
9f63308f62205ebdfcf0e04be1450dde38790a0b | C++ | arnabs542/leetcode-2 | /src/weekly/week193_2.cpp | UTF-8 | 909 | 3.390625 | 3 | [] | no_license | // 20200614
// 2. 不同整数的最少数目
/*
* 给你一个整数数组 arr 和一个整数 k 。现需要从数组中恰好移除 k 个元素,请找出移除后数组中不同整数的最少数目。
*/
/*
* 提示:
*
* 1 <= arr.length <= 10^5
* 1 <= arr[i] <= 10^9
* 0 <= k <= arr.length
*/
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution {
public:
int findLeastNumOfUniqueInts(vector<int>& arr, int k) {
unordered_map<int, int> cnt;
for(int a: arr)
++cnt[a];
vector<int> cnts;
for(auto item: cnt)
cnts.push_back(item.second);
sort(cnts.begin(), cnts.end());
int N = cnts.size();
for(int i = 1; i < N; ++i)
cnts[i] += cnts[i - 1];
auto it = lower_bound(cnts.begin(), cnts.end(), k + 1);
return cnts.end() - it;
}
};
| true |
4dd7e475b5fda78b193cc76118711e5ec962a373 | C++ | Bagja9102Kurniawan/TP-DAP-2019 | /C++/TP-DAP-MOD2-SelisihBeratModifikasi.cpp | UTF-8 | 665 | 3.1875 | 3 | [] | no_license | /* NIM : 1301194020
NAMA : BAGJA 9102 KURNIAWAN
Program ini adalah program pengecekan selisih
berat benda yang akan dibawa pada motor.
motor akan oleng ke satu bagian jika
selisihnya lebih dari sama dengan 9kg dengan output
bernilai true(motor oleng),
program akan berhenti jika isi kedua kantong melebihi 150kg
atau salah satu kantong bernilai negatif.
*/
#include <iostream>
using namespace std;
float i,c;
int main (){
while ((i+c<150) && (i>=0&&c>=0))
{
cout << "Masukkan berat belanjaan di kedua kantong : \n";
cin >> i >> c;
cout <<"\nSepeda motor pak Andi akan oleng :" << (i-c>=9||c-i>=9);
}
cout << "Proses selesai.";
return 0;
}
| true |
c503bcdb81c4fe60cf53042f641e49a20994cb22 | C++ | Psingh12354/Cpp-Codes | /PowerFunction.cpp | UTF-8 | 252 | 3.109375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int pow(int x,int y)
{
int res=1;
while(y>0)
{
if(y%2!=0)
{
res*=x;
y--;
}
else
{
y=y/2;
x=x*x;
}
}
return res;
}
int main()
{
cout<<pow(2,7);
return 0;
}
| true |
45c36840511286841a7a6182549f268f9dcd8766 | C++ | gaborcsardi/finmix | /src/rtruncnorm.h | UTF-8 | 5,517 | 2.546875 | 3 | [] | no_license | /******************************************************************************
*
* TODO: Project Title
*
* Copyright (C) 2003-2009 ascolab GmbH. All Rights Reserved.
* Web: http://www.ascolab.com
*
* Author: Gerhard Gappmeier <gerhard.gappmeier@ascolab.com>
*
* This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
* WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
******************************************************************************/
#ifndef __FINMIX_RTRUNCNORM_H__
#define __FINMIX_RTRUNCNORM_H__
#define _USE_MATH_DEFINES
#define M1_SQRT_2PI std::sqrt(2 * M_PI)
#include <cmath>
#include <RcppArmadillo.h>
static const double t1 = 0.15;
static const double t2 = 2.18;
static const double t3 = 0.725;
static const double t4 = 0.45;
inline
static double ers_a_inf (const double& a)
{
const double ainv = 1.0 / a;
double x, rho;
do {
x = R::rexp(ainv) + a; /* rexp works with 1/lambda */
rho = std::exp(-0.5 * std::pow((x - a), 2.0));
} while (R::runif(0.0, 1.0) > rho);
return x;
}
/* Exponential rejection sampling (a,b) */
inline
static double ers_a_b (const double& a, const double& b)
{
const double ainv = 1.0 / a;
double x, rho;
do {
x = R::rexp(ainv) + a; /* rexp works with 1/lambda */
rho = exp(-0.5 * std::pow((x - a), 2.0));
} while (R::runif(0.0, 1.0) > rho || x > b);
return x;
}
/* Normal rejection sampling (a,b) */
inline
static double nrs_a_b (const double& a, const double& b)
{
double x = a - 1.0;
while (x < a || x > b) {
x = R::rnorm(0.0, 1.0);
}
return x;
}
/* Normal rejection sampling (a,inf) */
inline
static double nrs_a_inf (const double & a)
{
double x = a - 1.0;
while (x < a) {
x = R::rnorm(0.0, 1.0);
}
return x;
}
/* Half-normal rejection sampling */
inline
static double hnrs_a_b (const double& a, const double& b)
{
double x = a - 1.0;
while (x < a || x > b) {
x = R::rnorm(0.0, 1.0);
x = std::fabs(x);
}
return x;
}
/* Uniform rejection sampling */
inline
static double urs_a_b (const double& a, const double& b)
{
const double phi_a = R::dnorm(a, 0.0, 1.0, 0);
double x = 0.0, u = 0.0;
/* Upper bound of normal density on [a,b] */
const double ub = a < 0.0 && b > 0.0 ? M1_SQRT_2PI : phi_a;
do {
x = R::runif(a, b);
} while (R::runif(0.0, 1.0) * ub > R::dnorm(x, 0.0, 1.0, 0));
return x;
}
/* Previously this was referred to as type 1 sampling: */
inline
static double r_lefttruncnorm (const double& a, const double& mean,
const double& sd)
{
const double alpha = (a - mean) / sd;
if (alpha < t4) {
return mean + sd * nrs_a_inf(alpha);
} else {
return mean + sd * ers_a_inf(alpha);
}
}
inline
static double r_righttruncnorm (const double& b, const double& mean,
const double& sd)
{
const double beta = (b - mean) / sd;
/* Exploit symmetry */
return mean + sd * r_lefttruncnorm(-beta, 0.0, 1.0);
}
inline
static double r_truncnorm (const double& a, const double& b,
const double& mean, const double& sd)
{
const double alpha = (a - mean) / sd;
const double beta = (b - mean) / sd;
const double phi_a = R::dnorm(alpha, 0.0, 1.0, 0);
const double phi_b = R::dnorm(beta, 0.0, 1.0, 0);
if (beta <= alpha) {
return NA_REAL;
} else if (alpha <= 0.0 && 0 <= beta) {
if (phi_a <= t1 || phi_b <= t1) {
return mean + sd * nrs_a_b(alpha, beta);
} else {
return mean + sd * urs_a_b(alpha, beta);
}
} else if (alpha > 0) {
if (phi_a / phi_b <= t2) {
return mean + sd * urs_a_b(alpha, beta);
} else {
if (alpha < t3) {
return mean + sd * hnrs_a_b(alpha, beta);
} else {
return mean + sd * ers_a_b(alpha, beta);
}
}
} else {
if (phi_b / phi_a <= t2) {
return mean + sd * urs_a_b(-beta, -alpha);
} else {
if (beta > -t3) {
return mean + sd * hnrs_a_b(-beta, -alpha);
} else {
return mean + sd * ers_a_b(-beta, -alpha);
}
}
}
}
inline
arma::vec do_rtruncnorm (const unsigned int& n, const double& a,
const double& b, const double& mean, const double& sd)
{
arma::vec output(n);
Rcpp::RNGScope scope;
for (unsigned int i = 0; i < n; ++i) {
if (R_FINITE(a) && R_FINITE(b)) {
output(i) = r_truncnorm(a, b, mean, sd);
} else if (R_NegInf == a && R_FINITE(b)) {
output(i) = r_righttruncnorm(b, mean, sd);
} else if (R_FINITE(a) && R_PosInf == b) {
output(i) = r_lefttruncnorm(a, mean, sd);
} else if (R_NegInf == a && R_PosInf == b) {
output(i) = R::rnorm(mean, sd);
} else {
output(i) = NA_REAL;
}
}
return output;
}
inline
double do_dtruncnorm (const double& x, const double& a,
const double& b, const double& mean,
const double& sd)
{
double output = 0.0;
if (a <= x && x <= b) { /* in range */
const double c1 = R::pnorm(a, mean, sd, 1, 0);
const double c2 = R::pnorm(b, mean, sd, 1, 0);
const double c3 = sd * (c2 - c1);
const double c4 = R::dnorm((x - mean)/sd, 0.0, 1.0, 0);
output = c4 / c3;
}
return output;
}
#endif /* __FINMIX_RTRUNCNORM_H__ */
| true |
384bcc8972921499fffb8f10b9e05609f2f13ad7 | C++ | jalexanderqed/cs280_repo | /john_alexander_proj5/Glitter/Glitter/Headers/light.hpp | UTF-8 | 1,667 | 2.984375 | 3 | [
"MIT"
] | permissive | #ifndef LIGHT_H
#define LIGHT_H
#include <glad\glad.h>
#include <string>
#include <sstream>
#include <iostream>
class Light {
private:
glm::vec3 position;
glm::vec3 ambient;
glm::vec3 diffuse;
glm::vec3 specular;
int index;
std::string myPre;
public:
Light() :
position(glm::vec3()),
ambient(glm::vec3()),
diffuse(glm::vec3()),
specular(glm::vec3()),
index(0)
{}
Light(glm::vec3 pos, glm::vec3 amb, glm::vec3 diff, glm::vec3 spec, int ind) :
position(pos),
ambient(amb),
diffuse(diff),
specular(spec),
index(ind)
{
std::ostringstream pred;
pred << "pointLights[" << index << "]";
myPre = pred.str();
}
void update(const Shader& shader) {
glUniform3fv(glGetUniformLocation(shader.Program, (myPre + ".position").c_str()), 1, glm::value_ptr(position));
glUniform3fv(glGetUniformLocation(shader.Program, (myPre + ".ambient").c_str()), 1, glm::value_ptr(ambient));
glUniform3fv(glGetUniformLocation(shader.Program, (myPre + ".diffuse").c_str()), 1, glm::value_ptr(diffuse));
glUniform3fv(glGetUniformLocation(shader.Program, (myPre + ".specular").c_str()), 1, glm::value_ptr(specular));
}
glm::vec3 getPos() {
return position;
}
void ProcessKeyboard(Camera_Movement direction, GLfloat deltaTime, glm::vec3 front, glm::vec3 right)
{
GLfloat velocity = 3 * deltaTime;
if (direction == FORWARD)
this->position += front * velocity;
if (direction == BACKWARD)
this->position -= front * velocity;
if (direction == LEFT)
this->position -= right * velocity;
if (direction == RIGHT)
this->position += right * velocity;
}
};
#endif
| true |
6857edef213555a8ca75d731cf818f5edadbab85 | C++ | gyulalaszlo/mkzbase | /maybe.h | UTF-8 | 1,896 | 2.890625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <memory>
#include "mkz.h"
namespace mkz {
template<typename A>
class Maybe;
template<typename A>
inline Maybe<A> just(A a);
template<typename A>
inline Maybe<A> nothing();
// shortcut for removing nothing<decltype(something)>() to nothing(something)
template<typename A>
inline Maybe<A> nothing(const A &sampleT);
template<typename A>
class Maybe {
public:
Maybe() : kind(kNOTHING) {}
Maybe(A a) : _just(std::move(a)), kind(kJUST) {}
// disallow copying for now (only moves)
Maybe(const Maybe &other) = delete;
Maybe &operator=(const Maybe &other) = delete;
Maybe(Maybe &&other) = default;
Maybe &operator=(Maybe &&other) = default;
inline bool ok() const { return kind == kJUST; }
template<typename D>
inline const Maybe<A> &onJust(D delegate) const {
if (ok()) { delegate(_just); }
return *this;
}
template<typename D>
inline const Maybe<A> &onNothing(D delegate) const {
if (!ok()) { delegate(); }
return *this;
}
// Chain maybes
template<typename D>
inline auto then(D delegate) const {
return ok()
? delegate(_just)
: nothing<decltype(delegate(_just))>();
}
private:
enum Kind {
kNOTHING = 0, kJUST = 1,
};
union {
A _just;
};
Kind kind;
};
template<typename A>
inline Maybe<A> just(A a) { return Maybe<A>(std::move(a)); }
template<typename A>
inline Maybe<A> nothing() { return Maybe<A>(); }
// shortcut for removing nothing<decltype(something)>() to nothing(something)
template<typename A>
inline Maybe<A> nothing(const A &sampleT) { return Maybe<A>(); }
}
| true |
314d9f2a3bbc75d4800c24b432f620eac302f867 | C++ | redizaar/safetyrepo | /Dolgozo , observer/main.cpp | UTF-8 | 6,945 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <thread>
#include <vector>
#include <ctime>
#include <mutex>
#include "dolgozo.h"
#include "programmer.h"
#include "workerregister.h"
#include "operator.h"
#include "thecompany.h"
#include "project.h"
#include "audiprojects.h"
#include "bmwprojects.h"
using namespace std;
void welcoming(Dolgozo* obj)
{
obj->welcoming();
}
void work_area(Dolgozo* obj)
{
obj->working_area();
}
void visualization(map<string,Project*> projects,map<string,Project*>::iterator)
{
cout<<"A project idoben valo elkeszulesenek eselye: "<<endl;
srand(time(0));
for(auto it : projects)
{
int chances = rand() % 10+1;
if(it.second!=0)
{
cout<<"\t";
if(it.second->getWorkersNum()%2==0)
{
if(chances==8)
chances++;
else if(chances==10)
chances--;
else if(chances==9)
{
}
else
chances++;
}
else if(it.second->getWorkersNum()==0)
{
chances=0;
}
cout<<chances*10<<" %"<<endl;
for(int i=0;i<1;i++)
{
cout<<"|";
for(int j=0;j<10;j++)
{
if(chances>0)
{
cout<<"*|";
}
else
{
cout<<" |";
}
chances--;
}
cout<<endl;
}
}
}
}
void estimatedWorkTime(vector<pair<Project*,int>> startedProjects)
{
for(auto it : startedProjects)
{
cout<<"Estimated worktime for : "<<it.first->getModelName()<<endl;
cout<<"Based on a very scientific alogithm"<<endl;
int workerNum=it.second;
if(workerNum>1)
{
cout<<"Calculating..."<<endl;
this_thread::sleep_for(chrono::milliseconds(3000));
srand(time(0));
int days=rand()%75+1;
int hours=rand()%23+1;
int minutes=rand()%59+1;
if(workerNum%2==0)
{
cout<<"The estimated worktime is : "<<days<<" days , "<<hours<<" hours ,"<<minutes<<" minutes "<<endl;
cout<<"-- According to these estimations which are super accurate --"<<endl;
cout<<"This project's will be completed on : ";
}
else
{
days+=rand()%15+5;
cout<<"The estimated worktime is : "<<days<<" days , "<<hours<<" hours ,"<<minutes<<" minutes "<<endl;
cout<<"-- Note: according to statistics it is prefered to work in groups which are even --"<<endl;
cout<<"-- it can the teams workflow --"<<endl;
cout<<"This project's will be completed on : ";
}
typedef std::chrono::system_clock Clock;
auto now = Clock::now();
time_t now_c = Clock::to_time_t(now);
struct tm *parts = localtime(&now_c);
int months=0;
while(days>=20)
{
months++;
days-=20;
}
if(parts->tm_mday+days>31)
{
months++;
days=days-31;
}
cout << 1900 + parts->tm_year<<".";
cout << 1 + months + parts->tm_mon<<".";
cout << days + parts->tm_mday << endl;
}
else
{
this_thread::sleep_for(chrono::milliseconds(1500));
cout<<endl;
cout<<"### Warning ###"<<endl;
cout<<"Project can't be started with only one person added to it!"<<endl;
cout<<"Project manager warned!"<<endl;
//todo observer
}
cout<<endl;
}
}
void workingOnProjects()
{
vector<pair<Project*,int>> projectStarted;
map<string,Project*> projects=Project::Projectlist();
for(auto it : projects)
{
if(it.second!=nullptr)
{
cout<<"Project name: "<<it.first<<endl;
cout<<"\tWorkers added: "<<endl;
int workersNum=it.second->listWorkers();
if(workersNum!=0)
{
projectStarted.push_back(make_pair(it.second,workersNum));
cout<<"Project started , with "<<workersNum<<" workers!"<<endl;
}
else
{
cout<<"So, "<<it.first<<" named project can't be started with 0 workers added to it!"<<endl;
}
}
cout<<endl;
}
estimatedWorkTime(projectStarted);
}
int main()
{
Programmer Pista("Pista",25,7,350000,"development",3,"c++");
Operator Feri("Ferenc",30,101,120000,"assemblying",10);
welcoming(&Pista);
work_area(&Pista);
welcoming(&Feri);
work_area(&Feri);
WorkerRegister obj("OrbanViktor");
Programmer Warren("Warren Buffet",60,78,880000,"development",35,"c++");
Operator NagyArpi("Nagy Arapd",44,150,180000,"assemblying",70);
obj.addObserver(&Pista);
obj.addObserver(&Feri);
obj.registerWorker(Warren);
obj.registerWorker(NagyArpi);
TheCompany::getInstance().initalizeCompany();
TheCompany::getInstance().addDolgozo(&Warren);
TheCompany::getInstance().addDolgozo(&Pista);
TheCompany::getInstance().addDolgozo(&Feri);
TheCompany::getInstance().listDolgozok();
AudiProjects i8("A2018_i8_1337",4,"Nagyon Gyors");
BmwProjects M5("BMW2015_M5_4762",4,"Bunozo kedvenc");
BmwProjects M6("BMW2011_M6_4587",4,"Uj gazdag kedvenc");
i8.addProject();
M5.addProject();
M6.addProject();
//a statikus map alapértékadásánál null-al töltöttem fel
//kiirásnál rá kell szürni hogy nem-e null amit ki akarunk irni
map<string,Project*> projects=Project::Projectlist();
for(auto it : projects)
{
if(it.second!=nullptr)
{
cout<<"Projekt neve : "<<it.second->getModelName()<<endl;
}
}
M5.listProjects();
BmwProjects M7("BMW2012_M7_4712",4,"Vin Diesel kedvence");
M7.addWorkerToProject(&Warren); // meg nem .addProject()-eltünk
M5.addWorkerToProject(&Warren);
i8.addWorkerToProject(&Feri);
i8.addWorkerToProject(&Pista);
M6.addWorkerToProject(&Pista);
map<string,int> p_properites=i8.projectProperties();
for(auto it : p_properites)
{
cout<<"Project neve: "<<it.first<<" ,projecten dolgozok szama: "<<it.second<<endl;
}
i8.listWorkers();
cout<<endl;
cout<<"Starting projects "<<endl;
//thread calcWorkTime(workingOnProjects);
//calcWorkTime.join();
return 0;
}
| true |
f268482d8ed85719a823cf73a84d3ab8f0e0e796 | C++ | GabeOchieng/ggnn.tensorflow | /program_data/PKU_raw/79/2379.c | UTF-8 | 447 | 2.578125 | 3 | [] | no_license | int killer(int n,int m)
{
int a[301]={0},i=0,j=1,k=n;
while(k>1)
{
if(a[i]==0)
if(j==m) {a[i]=1;k--;j=1;}
else j++;
i++;
if(i>=n) i=0;
}
for(i=0;i<n;i++)
if(a[i]==0) return i+1;
}
main()
{
int n,m;
scanf("%d %d",&n,&m);
while(n!=0)
{
printf("%d\n",killer(n,m));
scanf("%d %d",&n,&m);
}
} | true |
6d2ea3de4695296c11f0f6202a5d54584aae999f | C++ | kuflex/KuStudio | /KuStudio/src/kummon/kuButton.cpp | UTF-8 | 4,533 | 2.78125 | 3 | [] | no_license | #include "kuButton.h"
//---------------------------------------------------------------------
void kuButton::setup( string iconFile, float X, float Y ) {
X_ = X;
Y_ = Y;
ofLoadImage( icon_, iconFile );
W_ = icon_.getWidth();
H_ = icon_.getHeight();
toggle_ = false;
enabled_ = true;
visible_ = true;
down_ = false;
state_ = 0;
pressed_ = 0;
}
//---------------------------------------------------------------------
void kuButton::update( float dt ) {
pressed_ = 0;
}
//---------------------------------------------------------------------
void kuButton::draw() {
if ( visible_ ) {
ofColor mainColor = ( enabled_ ) ? ofColor( 255 ) : ofColor( 128 );
ofSetColor( mainColor );
icon_.draw(X_, Y_);
if ( down_ || state_ ) {
ofColor overColor = ( state_ ) ? ofColor( 160 ) : ofColor( 128 );
ofSetColor( overColor );
ofFill();
ofEnableBlendMode( OF_BLENDMODE_ADD );
ofRect( X_, Y_, W_, H_ );
ofEnableAlphaBlending();
}
}
}
//---------------------------------------------------------------------
void kuButton::setToggle( bool toggle ) {
toggle_ = toggle;
}
//---------------------------------------------------------------------
void kuButton::setEnabled( bool enabled ) {
enabled_ = enabled;
}
//---------------------------------------------------------------------
void kuButton::setDown( bool down ) {
down_ = down;
}
//---------------------------------------------------------------------
void kuButton::setVisible( bool visible ) {
visible_ = visible;
}
//---------------------------------------------------------------------
void kuButton::setPressed() { //эмуляция нажатой кнопки - только если она включена
if ( visible_ && enabled_ ) {
pressed_ = true;
if ( toggle_ ) {
down_ = !down_;
}
}
}
//---------------------------------------------------------------------
//type 0 - move, 1 - press, 2 - drag, 3 - release
void kuButton::mouse( int x, int y, int button, void *&mouseState, int type ) {
bool mouseCaptured = ( mouseState != 0 );
bool captured = mouseCaptured && (mouseState == this);
if ( mouseCaptured && !captured ) { return; }
if ( !visible_ || !enabled_ ) {
if ( captured ) {
mouseState = 0;
state_ = 0;
}
return;
}
if ( type == 0 ) { //move
return;
}
if ( type == 1 ) { //press
if ( ofInRange( x, X_, X_ + W_ ) && ofInRange( y, Y_, Y_ + H_ ) ) {
state_ = 1;
mouseState = this;
pressed_ = true;
if ( toggle_ ) {
down_ = !down_;
}
}
return;
}
if ( !captured ) { return; }
if ( type == 2 ) { //drag
return;
}
if ( type == 3 ) { //release
state_ = 0;
mouseState = 0;
return;
}
}
//---------------------------------------------------------------------
//---------------------------------------------------------------------
//---------------------------------------------------------------------
void kuButtons::setup( int maxButtons ) {
button_.resize( maxButtons );
n_ = 0;
}
//---------------------------------------------------------------------
kuButton *kuButtons::addButton( string iconFile, float X, float Y ) {
if ( n_ < button_.size() ) {
int id = n_;
n_++;
button_[id].setup( iconFile, X, Y );
return &button_[id];
}
else {
return 0;
}
}
//---------------------------------------------------------------------
void kuButtons::update( float dt ) {
for (int i=0; i<n_; i++) {
button_[i].update( dt );
}
}
//---------------------------------------------------------------------
void kuButtons::draw() {
for (int i=0; i<n_; i++) {
button_[i].draw();
}
}
//---------------------------------------------------------------------
//обработка событий мыши
//type 0 - move, 1 - press, 2 - drag, 3 - release
//mouseState - указатель, использует ли кто-то мышь
void kuButtons::mouse( int x, int y, int button, void *&mouseState, int type ) {
for (int i=0; i<n_; i++) {
button_[i].mouse( x, y, button, mouseState, type );
}
}
//---------------------------------------------------------------------
| true |
4f4f854dfeb227074091f4d2429d571ec70c6694 | C++ | mbrock/moppe | /moppe/map/generate.hh | UTF-8 | 5,215 | 2.859375 | 3 | [] | no_license |
#ifndef MOPPE_GENERATE_HH
#define MOPPE_GENERATE_HH
#include <moppe/gfx/math.hh>
#include <boost/multi_array.hpp>
#include <boost/random.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
namespace moppe {
namespace map {
class NormalMap {
public:
NormalMap (int width, int height);
inline const Vector3D& at (int x, int y) const
{ return m_data[y][x]; }
void reset ();
void add (int x, int y, const Vector3D& v);
void normalize_all ();
private:
typedef boost::multi_array<Vector3D, 2> array_t;
typedef array_t::index index_t;
array_t m_data;
const int m_width;
const int m_height;
};
class HeightMap {
public:
HeightMap (int width, int height, const Vector3D& size)
: m_width (width), m_height (height),
m_scale (size.x / width, size.y, size.z / height)
{ }
virtual ~HeightMap () { }
virtual float get (int x, int y) const = 0;
virtual Vector3D normal (int x, int y) const = 0;
Vector3D vertex (int x, int y) const;
Vector3D triangle_normal (int x1, int y1,
int x2, int y2,
int x3, int y3) const;
Vector3D center () const
{ return vertex (m_width / 2, m_height / 2); }
bool in_bounds (float x, float y) const {
int xi = x / m_scale.x;
int yi = y / m_scale.z;
return !(xi < 0 || xi > (m_width - 2) || yi < 0 || yi > (m_height - 2));
}
float interpolated_height (float x, float y) const {
int xi = x / m_scale.x, yi = y / m_scale.z;
clamp (xi, 0, m_width - 2);
clamp (yi, 0, m_height - 2);
float ax = x / m_scale.x - xi;
float ay = y / m_scale.z - yi;
float r1 = linear_interpolate (get (xi, yi),
get (xi + 1, yi),
ax);
float r2 = linear_interpolate (get (xi, yi + 1),
get (xi + 1, yi + 1),
ax);
return m_scale.y * linear_interpolate (r1, r2, ay);
// return m_scale.y * get (x / m_scale.x, y / m_scale.z);
}
Vector3D interpolated_normal (float x, float y) const {
int xi = x / m_scale.x, yi = y / m_scale.z;
clamp (xi, 0, m_width - 2);
clamp (yi, 0, m_height - 2);
float ax = x / m_scale.x - xi;
float ay = y / m_scale.z - yi;
Vector3D r1 = linear_vector_interpolate (normal (xi, yi),
normal (xi + 1, yi),
ax);
Vector3D r2 = linear_vector_interpolate (normal (xi, yi + 1),
normal (xi + 1, yi + 1),
ax);
return linear_vector_interpolate (r1, r2, ay);
}
inline int width () const { return m_width; }
inline int height () const { return m_height; }
inline Vector3D scale () const { return m_scale; }
inline Vector3D size () const
{ return Vector3D (m_scale.x * m_width,
m_scale.y,
m_scale.z * m_height); }
float min_value () const;
float max_value () const;
protected:
const int m_width;
const int m_height;
const Vector3D m_scale;
};
void compute_normal_map (const HeightMap& height_map,
NormalMap& normal_map);
class NormalComputingHeightMap: public HeightMap {
public:
NormalComputingHeightMap (int width, int height,
Vector3D size)
: HeightMap (width, height, size),
m_normals (width, height)
{ }
void recompute_normals ()
{ compute_normal_map (*this, m_normals); }
Vector3D normal (int x, int y) const
{ return m_normals.at (x, y); }
private:
NormalMap m_normals;
};
class RandomHeightMap: public NormalComputingHeightMap {
public:
RandomHeightMap (int width, int height,
const Vector3D& size,
int seed = 0);
inline float get (int x, int y) const
{ return m_data[y][x]; }
inline void set (int x, int y, float value)
{ m_data[y][x] = value; }
void normalize ();
void translate (float d);
void rescale (float k);
void randomize_uniformly ();
void randomize_plasmally (float roughness);
private:
typedef boost::multi_array<float, 2> array_t;
typedef array_t::index index_t;
array_t m_data;
boost::mt19937 m_rng;
};
class InterpolatingHeightMap: public HeightMap {
public:
InterpolatingHeightMap (boost::shared_ptr<HeightMap> from,
boost::shared_ptr<HeightMap> to,
const Vector3D& size)
: HeightMap (from->width (), from->height (), size),
m_from (from),
m_to (to),
m_alpha (0.0)
{ }
float get (int x, int y) const;
Vector3D normal (int x, int y) const;
void set_blending_factor (float alpha);
void increase_blending_factor (float delta);
void change_maps (boost::shared_ptr<HeightMap> from,
boost::shared_ptr<HeightMap> to)
{
m_from = from;
m_to = to;
}
bool done () const { return m_alpha >= 1.0; }
private:
boost::shared_ptr<HeightMap> m_from;
boost::shared_ptr<HeightMap> m_to;
float m_alpha;
};
void
write_tga (std::ostream& stream, const HeightMap& map);
}
}
#endif
| true |
1586a18dff3eaabc4f83eb58ec1833201cd2f3fe | C++ | aurtg/open-david | /src/cnv.h | UTF-8 | 14,272 | 2.734375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <memory>
#include <functional>
#include "./pg.h"
#include "./ilp.h"
#include "./json.h"
namespace dav
{
/** Enumerator to specify the direction of a unification-edge. */
enum unification_direction_e
{
FORWARD_DIRECTION = 1,
UNDEFINED_DIRECTION = 0,
BACKWARD_DIRECTION = -1
};
namespace cnv
{
class cost_provider_t;
class weight_provider_t;
}
/**
* @brief Base class of components for ILP-conversion.
* @details The result of ILP conversion will be put to `out`.
*/
class ilp_converter_t : public component_t
{
public:
/**
* @brief Constructor.
* @param[in] m Pointer to dav::kernel_t instance that will has this instance.
*/
ilp_converter_t(const kernel_t *m);
virtual void validate() const override;
/**
* @brief Writes the detail of this instance as JSON.
* @param wr Reference of the writer for JSON.
*/
virtual void write_json(json::object_writer_t &wr) const override;
/**
* @brief Gets whether ILP conversion has been run.
* @return True if ilp_converter_t::out contains some instance, otherwise false.
*/
virtual bool empty() const override { return not (bool)out; }
/**
* @brief Gets whether ILP problem returned is maximization problem.
* @return True if ILP problem returned is maximization problem, otherwise false.
*/
virtual bool do_maximize() const = 0;
/**
* @brief Gets whether ILP problem returned is based on the Closed World Assumption.
* @return True if ILP problem returned is based on the CWA, otherwise false.
*/
virtual bool do_make_cwa() const { return false; }
/**
* @brief Gets which one explains another, in order of cycle detection in LHS.
* @param i Index of node, which is unifiable with j-th node.
* @param j Index of node, which is unifiable with i-th node.
* @return True iff i-th node explains j-th node, otherwise false.
*/
virtual unification_direction_e get_unification_direction_of(pg::node_idx_t i, pg::node_idx_t j) const = 0;
/**
* @brief Returns ILP-variable which corresponds to given edge being given direction.
* @param ei Index of target edge.
* @param is_back Boolean to express direction of the edge.
* @details `is_back` will be ignored if the converter does not make ILP variables of an edge for each direction.
*/
virtual ilp::variable_idx_t get_directed_edge_variable(pg::edge_idx_t ei, is_backward_t is_back) const;
/** Returns the maximum length of loops to prevent. */
inline const limit_t<int> max_loop_length() const { return m_max_loop_length; }
inline bool do_allow_unification_between_facts() const { return m_do_allow_unification_between_facts; }
inline bool do_allow_unification_between_queries() const { return m_do_allow_unification_between_queries; }
inline bool do_allow_backchain_from_facts() const { return m_do_allow_backchain_from_facts; }
/**
* @brief Output of ILP conversion.
* @details
* You can check the running state of ILP converter by checking boolean value of this.
* The boolean vlaue of this is false if ILP conversion has not been run.
*/
std::shared_ptr<ilp::problem_t> out;
/** Cost-provider for facts. */
std::unique_ptr<cnv::cost_provider_t> fact_cost_provider;
/** Cost-provider for queries. */
std::unique_ptr<cnv::cost_provider_t> query_cost_provider;
/** Instance to assign weights to rules. */
std::unique_ptr<cnv::weight_provider_t> weight_provider;
protected:
enum class cost_assignment_mode_e { PLUS, MULTIPLY };
virtual void process() override;
/** Makes variables that express whether the corresponding exclusion is violated. */
virtual void make_variables_for_exclusions() {};
/**
* Makes components for costs on observable nodes.
* This method uses ilp_converter_t::fact_cost_provider and ilp_converter_t::query_cost_provider.
*/
hash_map_t<pg::node_idx_t, calc::component_ptr_t> get_costs_for_observable_nodes();
/**
* Makes components for costs on hypothesized nodes.
* This method uses ilp_conveter_t::weight_provider in order to obtain weights on edges.
* @details
* If the costs on observable nodes are necessary to compute costs on hypothesized nodes,
* insert those costs to `node2comp` in advance.
* @param mode Specifies way to compute a cost from antecedents' costs.
* @param node2comp Pointer to a map of components.
*/
void assign_hypothesized_node_cost(
cost_assignment_mode_e type,
hash_map_t<pg::node_idx_t, calc::component_ptr_t> *node2comp) const;
/**
* Makes maps from an observable node to ILP-variables of the elements which explain the node.
* @param node2vars Pointer to a map from a node to ILP-variables of its explainers.
*/
void get_antecedents_of_unification(hash_multimap_t<pg::node_idx_t, ilp::variable_idx_t> *node2vars) const;
/** Makes constraints to prevent cyclic structure. */
void prevent_loop();
/**
* @brief Applies perturbation method to the product `out`.
* @detail This method must be called at the end of process() of each super-class.
*/
void apply_perturbation_method();
string_t m_name;
limit_t<int> m_max_loop_length;
bool m_do_allow_unification_between_facts;
bool m_do_allow_unification_between_queries;
bool m_do_allow_backchain_from_facts;
};
/**
* @brief Factory class for super classes of `ilp_converter_t`.
* @details
* This class is implemented with Singleton pattern.
* Use dav::ilp_converter_library_t::instance() and dav::cnv_lib() in order to access the instance.
*/
class ilp_converter_library_t : public component_factory_t<kernel_t, ilp_converter_t>
{
public:
/** Gets pointer to the instance. */
static ilp_converter_library_t* instance();
private:
/** Default constructor. */
ilp_converter_library_t();
static std::unique_ptr<ilp_converter_library_t> ms_instance;
};
/** Abbreviation function of ilp_converter_library_t::instance(). */
inline ilp_converter_library_t* cnv_lib() { return ilp_converter_library_t::instance(); }
namespace cnv
{
using cnv_generator_t = component_generator_t<kernel_t, ilp_converter_t>;
/** Base function class of some procedure for ILP-Converters. */
class function_for_converter_t
{
public:
function_for_converter_t(const ilp_converter_t *m) : m_master(m) {}
/** Writes the detail of this instance as JSON. */
virtual void write_json(json::object_writer_t &wr) const = 0;
protected:
const ilp_converter_t *m_master; //!< Pointer to ILP converter that will has this instance.
};
/** ILP-Converter that does nothing. */
class null_converter_t : public ilp_converter_t
{
public:
/** Generator for cnv::null_converter_t. */
struct generator_t : public cnv_generator_t
{
virtual ilp_converter_t* operator()(const kernel_t*) const override;
};
null_converter_t(const kernel_t *m);
virtual void validate() const override {};
virtual void write_json(json::object_writer_t&) const override;
virtual bool do_keep_validity_on_timeout() const override { return false; }
virtual bool do_maximize() const override { return false; };
virtual unification_direction_e get_unification_direction_of(pg::node_idx_t i, pg::node_idx_t j) const override { return (i < j ? FORWARD_DIRECTION : BACKWARD_DIRECTION); };
protected:
virtual void process() override;
};
/**
* @brief ILP-Converter based on Weighted Abduction.
* @details
* The evaluation function of this converter has following characteristics.
* - Each observable node has cost.
* - Costs will be propagated to hypothesized nodes on backward chaining.
* - The bigger cost will be canceled on unification.
* - The best solution has the minimum value on objective function.
*/
class cost_based_converter_t : public ilp_converter_t
{
public:
typedef hash_map_t<pg::node_idx_t, double> node2cost_map_t;
/** Generator for Weighted Abduction by Hobbs et al. */
struct weighted_generator_t : public cnv_generator_t
{
virtual ilp_converter_t* operator()(const kernel_t*) const override;
};
/** Generator for cnv::cost_based_converter_t on `PLUS` mode. */
struct linear_generator_t : public cnv_generator_t
{
virtual ilp_converter_t* operator()(const kernel_t*) const override;
};
/**
* Generator for Cost-based Abduction which use rules' probabilities as weights.
* The weight of a rule will be `-log(p)`, where `p` is the probability of the rule.
*/
struct probabilistic_generator_t : public cnv_generator_t
{
virtual ilp_converter_t* operator()(const kernel_t*) const override;
};
/** JSON-decorator to write the information about payment of costs. */
struct cost_payment_decorator_t : public json::decorator_t<ilp::solution_t>
{
cost_payment_decorator_t(bool is_full_mode) : do_write_all_nodes(is_full_mode) {};
virtual void operator()(const ilp::solution_t&, json::object_writer_t&) const override;
bool do_write_all_nodes;
};
/** JSON-decorator write probability of the solution based on [Charniak et al., 90]. */
struct probability_decorator_t : public json::decorator_t<ilp::solution_t>
{
virtual void operator()(const ilp::solution_t&, json::object_writer_t&) const override;
};
/**
* @param[in] m Pointer to dav::kernel_t instance that will has this instance.
* @param[in] mode Enumerator to specify the evaluation function.
*/
cost_based_converter_t(const kernel_t *m, cost_assignment_mode_e mode);
virtual void validate() const override;
virtual void write_json(json::object_writer_t&) const override;
virtual void decorate(json::kernel2json_t&) const override;
virtual bool do_keep_validity_on_timeout() const override { return false; }
virtual bool do_maximize() const override { return false; };
virtual unification_direction_e get_unification_direction_of(pg::node_idx_t i, pg::node_idx_t j) const override;
protected:
virtual void process() override;
cost_assignment_mode_e m_mode;
};
/** ILP-converter for Etcetera Abduction by Andrew S. Gordon. */
class etcetera_converter_t : public ilp_converter_t
{
public:
struct etcetera_generator_t : public component_generator_t<kernel_t, ilp_converter_t>
{
virtual ilp_converter_t* operator()(const kernel_t*) const override;
};
/** JSON decorator to output information about cost-payments. */
struct solution_decorator_t : public json::decorator_t<ilp::solution_t>
{
virtual void operator()(const ilp::solution_t&, json::object_writer_t&) const override;
};
etcetera_converter_t(const kernel_t *m);
virtual void validate() const override;
virtual void decorate(json::kernel2json_t&) const override;
virtual bool do_keep_validity_on_timeout() const override { return false; }
virtual bool do_maximize() const override { return false; };
virtual unification_direction_e get_unification_direction_of(pg::node_idx_t i, pg::node_idx_t j) const override;
protected:
virtual void process() override;
/**
* Assigns costs to chaining-edges.
* @details
* If the edge is query-side, assigns a cost based on forward-probability,
* otherwise assigns a cost based on backward-probability.
*/
void assign_chain_cost();
/**
* Assigns costs to fact-nodes.
* @param node2vars Return value of ilp_converter_t::get_antecedents_of_unification().
* @param node2comp Return value of ilp_converter_t::get_costs_for_observable_nodes().
*/
void assign_fact_cost(
const hash_multimap_t<pg::node_idx_t, ilp::variable_idx_t> &node2vars,
const hash_map_t<pg::node_idx_t, calc::component_ptr_t> &node2comp);
/**
* Make constraints that a solution must explain as much query as possible.
* @param node2vars Return value of ilp_converter_t::get_antecedents_of_unification().
*/
void prohibit_hypothesized_node(
const hash_multimap_t<pg::node_idx_t, ilp::variable_idx_t> &node2vars);
};
/** ILP-Converter based on Cost-based Etcetera and Anti-Etcetera Abduction. */
class ceaea_converter_t : public etcetera_converter_t
{
public:
struct ceaea_generator_t : public component_generator_t<kernel_t, ilp_converter_t>
{
virtual ilp_converter_t* operator()(const kernel_t*) const override;
};
struct ceaea_member_t : public optional_member_t<ilp::problem_t>
{
ceaea_member_t(ilp::problem_t *m);
hash_set_t<ilp::variable_idx_t> vars_reward;
hash_map_t<pg::node_idx_t, double> query2reward;
};
struct solution_decorator_t : public json::decorator_t<ilp::solution_t>
{
virtual void operator()(const ilp::solution_t&, json::object_writer_t&) const override;
};
ceaea_converter_t(const kernel_t *m);
virtual void validate() const override;
virtual void decorate(json::kernel2json_t&) const override;
virtual bool do_keep_validity_on_timeout() const override { return false; }
virtual bool do_maximize() const override { return true; };
std::unique_ptr<weight_provider_t> negated_weight_provider;
protected:
virtual void process() override;
/** Makes variables that express whether H violates the corresponding exclusion. */
virtual void make_variables_for_exclusions() override;
/**
* Makes variables and constraints for payment of query-rewards.
* @param node2vars Return value of ilp_converter_t::get_antecedents_of_unification().
* @param node2comp Return value of ilp_converter_t::get_costs_for_observable_nodes().
*/
void assign_query_reward(
const hash_multimap_t<pg::node_idx_t, ilp::variable_idx_t> &node2vars,
const hash_map_t<pg::node_idx_t, calc::component_ptr_t> &node2comp);
/**
* Makes variables and constraints for payment of costs on hypothesized nodes.
* @param node2vars Return value of ilp_converter_t::get_antecedents_of_unification().
*/
void assign_hypothesis_cost(
const hash_multimap_t<pg::node_idx_t, ilp::variable_idx_t> &node2vars);
};
}
}
| true |
d9ada439e5b1ee620fc148c115230f5ef4831b34 | C++ | louen/QtFMP | /src/game/fmpWeather.h | UTF-8 | 674 | 3.25 | 3 | [] | no_license | #ifndef FMP_WEATHER_H
#define FMP_WEATHER_H
// This class is responsible to manage everything related to tides.
// There should be only one instance owned by the game.
class fmpWeather
{
public:
enum Tide
{
LOW =0,
NORMAL,
HIGH,
};
// Tells you the current tide (information available to anyone)
Tide getCurrentTide() const;
// Tells you the state of the tide in numSteps turns (you have to have at least that number of layers).
Tide getNextTide(int numSteps = 1) const;
// Advance the state of the tide.
void advance();
public:
Tide m_currentTide;
};
#endif // !FMP_WEATHER_H
| true |
3dad2ab2e84d98cbc61277cbad6c00a9e16a3abb | C++ | AbdallahHemdan/DidUMean | /Spelling Checker/SpellingCorrector.cpp | UTF-8 | 4,357 | 3.09375 | 3 | [
"MIT"
] | permissive | #include "SpellingCorrector.h"
#define ALPHASIZE 26
SpellingCorrector::SpellingCorrector()
{
TotalWords = 0;
Root = new Trie();
ifstream BigFile;
BigFile.open("Dic.txt");
string Word;
// eof() is an Indecator of The End of The File
// If at The end of the file return (true)
// Else return (false)
while (!BigFile.eof())
{
BigFile >> Word;
Word = TransformIt(Word);
if (Word != "")
{
AddWord(Root, Word);
TotalWords++;
}
}
BigFile.close();
Intro();
}
string SpellingCorrector::TransformIt(string ToTransform)
{
transform(ToTransform.begin(), ToTransform.end(), ToTransform.begin(), ::tolower);
return ToTransform;
}
void SpellingCorrector::AddWord(Trie* Vertex, string Word)
{
if (Word == "")
{
Vertex->Words++;
}
else
{
ll Index = Word[0] - 'a';
if (Vertex->Edges[Index] == nullptr)
{
Vertex->Edges[Index] = new Trie();
}
Word.erase(0, 1);
return AddWord(Vertex->Edges[Index], Word);
}
}
void SpellingCorrector::Intro()
{
cout << endl << "========================================== Welcome To Our Spell Corrector "
"======================================= "
<< endl << endl ;
cout << "- We Check Your Word You Entered " << endl << endl;
cout << "\t\t => If It Valid, No Problem" << endl;
cout << "\t\t => If Not We Recommend Some Similar Words for you..." << endl << endl;
cout <<"- Enter 'exit' OR 'EXIT' To Quit " << endl;
cout << "=================================================== Lets's Go "
"==================================================="
<< endl;
cout << endl << endl;
}
ll SpellingCorrector::Search(Trie* Vertex, string Word)
{
if (Word == "")
{
return Vertex->Words;
}
else
{
ll Index = Word[0] - 'a';
if (Vertex->Edges[Index] == nullptr)
{
return 0;
}
// Delete The First Char
Word.erase(0, 1);
return Search(Vertex->Edges[Index], Word);
}
}
void SpellingCorrector::EditDistance(string Word, ll Current)
{
ll Counter = 0;
ll Length = Word.length();
ll i, j;
for (i = -1; i < Length; i++)
{
for (j = 0; j < ALPHASIZE; j++)
{
char C = 'a' + j;
string NewWord = Word.substr(0, i + 1) + C + Word.substr(i + 1, Length - i - 1);
ll NoOfEqual = Search(Root, NewWord);
NoOfEqual *= -1;
if (NoOfEqual != 0)
{
PossibleWords.insert(make_pair(NoOfEqual, NewWord));
}
if (Current == 0)
{
EditDistance(NewWord, 1);
}
}
}
for (i = 0; i < Length; i++)
{
for (j = 0; j < ALPHASIZE; j++)
{
char C = 'a' + j;
string NewWord = Word.substr(0, i) + C + Word.substr(i + 1, Length - i - 1);
ll NoOfEqual = Search(Root, NewWord);
NoOfEqual *= -1;
if (NoOfEqual != 0)
{
PossibleWords.insert(make_pair(NoOfEqual, NewWord));
}
if (Current == 0)
{
EditDistance(NewWord, 1);
}
}
}
for (i = 0; i < Length; i++)
{
string NewWord = Word.substr(0, i) + Word.substr(i + 1, Length - i - 1);
ll NoOfEqual = Search(Root, NewWord);
NoOfEqual *= -1;
if (NoOfEqual != 0)
{
PossibleWords.insert(make_pair(NoOfEqual, NewWord));
}
if (Current == 0)
{
EditDistance(NewWord, 1);
}
}
for (i = 0; i < Length - 1; i++)
{
char A = Word[i], B = Word[i + 1];
string NewWord = Word.substr(0, i) + B + A + Word.substr(i + 2, Length - i - 2);
ll NoOfEqual = Search(Root, NewWord);
NoOfEqual *= -1;
if (NoOfEqual != 0)
{
PossibleWords.insert(make_pair(NoOfEqual, NewWord));
}
if (Current == 0)
{
EditDistance(NewWord, 1);
}
}
}
void SpellingCorrector::Correct(string Word)
{
// Clear the Set of The Possible Words...
PossibleWords.clear();
Word = TransformIt(Word);
// Number of Equal Words...
ll NoOfEqualWords = Search(Root, Word);
if (NoOfEqualWords == 0)
{
EditDistance(Word, 1);
if (PossibleWords.size() == 0)
{
EditDistance(Word, 0);
}
if (PossibleWords.size() == 0)
{
cout << "\t\tSorry...!!, No Recommendation." << endl;
}
else
{
cout << "\t\t" << "Possible Correct Words :" << endl;
for (auto it : PossibleWords)
{
cout << it.second << endl;
}
}
}
else
{
cout << endl << "Good..!!, You Entered Correct Word." << endl;
}
} | true |
9eb554ddab2cba8881d5f00f7194e0ea637b54a5 | C++ | jinyunx/CoSocket | /CoSocket/net/http/WebSocketParser.h | UTF-8 | 5,921 | 2.53125 | 3 | [] | no_license | #ifndef WEB_SOCKET_PARSER_H
#define WEB_SOCKET_PARSER_H
/*
0 1 2 3
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
| Extended payload length continued, if payload len == 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------- - - - - - - - - - - - - - - - +
: Payload Data continued ... :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Payload Data continued ... |
+---------------------------------------------------------------+
*/
#include "NonCopyable.h"
#include "SimpleLog.h"
#include <arpa/inet.h>
#include <string>
#define ntohll(x) ((((uint64_t)ntohl(x&0xFFFFFFFF)) << 32) + ntohl(x >> 32))
#define htonll(x) ((((uint64_t)htonl(x&0xFFFFFFFF)) << 32) + htonl(x >> 32))
class WebSocketParser : private NonCopyable
{
public:
enum OpCodeType
{
OpCodeType_Continue = 0,
OpCodeType_Text = 1,
OpCodeType_Binary = 2,
OpCodeType_Close = 8,
OpCodeType_Ping = 9,
OpCodeType_Pong = 10,
};
WebSocketParser()
: m_complete(false),
m_headerComplete(false),
m_fin(false),
m_opCode(0),
m_payloadLen(0),
m_offset(0)
{
}
~WebSocketParser()
{
}
bool Parse(const char *data, size_t len)
{
if (!data || !len)
return true;
m_inputCache.append(data, len);
if (!m_headerComplete)
m_headerComplete = ParseHeader();
// Not enough data
if (!m_headerComplete)
return true;
if (!IsValidFrame())
return false;
ProcessPayload();
return true;
}
bool IsComplete() const
{
return m_complete;
}
const char *GetPayLoad() const
{
return m_payload.data();
}
size_t GetPayloadLen() const
{
return m_payload.size();
}
void Reset()
{
ResetCurrentFrame();
m_complete = false;
m_payload.clear();
}
private:
void ResetCurrentFrame()
{
m_headerComplete = false;
m_fin = false;
m_payloadLen = 0;
m_offset = 0;
m_inputCache.clear();
}
const char *GetDataPtr() const
{
return m_inputCache.data() + m_offset;
}
bool HaveBytes(uint64_t len)
{
return m_inputCache.size() - m_offset >= len;
}
bool ParseHeader()
{
m_offset = 0;
if (!HaveBytes(1))
return false;
m_opCode = 0x0F & *GetDataPtr();
m_fin = 0x80 & *GetDataPtr();
m_offset += 1;
if (!HaveBytes(1))
return false;
bool mask = 0x80 & *GetDataPtr();
m_payloadLen = 0x000007FU & (*GetDataPtr());
m_offset += 1;
if (m_payloadLen == 126)
{
if (!HaveBytes(2))
return false;
m_payloadLen = ntohs(*reinterpret_cast<const uint16_t *>(GetDataPtr()));
m_offset += 2;
}
else if (m_payloadLen == 127)
{
if (!HaveBytes(8))
return false;
m_payloadLen = ntohll(*reinterpret_cast<const uint64_t *>(GetDataPtr()));
m_offset += 8;
}
m_maskKey.clear();
if (mask)
{
if (!HaveBytes(4))
return false;
m_maskKey.append(GetDataPtr(), 4);
m_offset += 4;
}
return true;
}
bool IsValidFrame()
{
if (m_maskKey.empty())
{
SIMPLE_LOG("Not support unmask frame");
return false;
}
if (!CheckOpCode())
{
SIMPLE_LOG("Invalid opcode: %d", m_opCode);
return false;
}
if (m_payload.size() + m_payloadLen > kMaxLength)
{
SIMPLE_LOG("Too large payload size: %d",
m_payload.size() + m_payloadLen);
return false;
}
return true;
}
bool CheckOpCode()
{
switch (m_opCode)
{
case OpCodeType_Continue:
if (m_payload.empty())
return false;
case OpCodeType_Text:
case OpCodeType_Binary:
case OpCodeType_Close:
case OpCodeType_Ping:
case OpCodeType_Pong:
return true;
default:
return false;
}
}
void ProcessPayload()
{
// Not enough data
if (!HaveBytes(m_payloadLen))
return;
for (uint64_t i = 0; i < m_payloadLen; ++i, ++m_offset)
m_payload.push_back(*GetDataPtr() ^ m_maskKey[i % m_maskKey.size()]);
m_complete = m_fin;
ResetCurrentFrame();
}
const static int kMaxLength = 10 * 1024 * 1024; // 10MB
bool m_complete;
bool m_headerComplete;
bool m_fin;
int m_opCode;
uint64_t m_payloadLen;
uint64_t m_offset;
std::string m_maskKey;
std::string m_inputCache;
std::string m_payload;
};
#endif // WEB_SOCKET_PARSER_H
| true |
a752bf4491fb238d086e8821e29f637162e678c9 | C++ | mjarret/Clifford-T-Project | /TOperators/Z2.cpp | UTF-8 | 4,069 | 3.875 | 4 | [] | permissive | #include <algorithm>
#include <iostream>
#include "Z2.hpp"
/**
* Constructor that initializes object corresponding to (a+sqrt(2)*b)/(2^c)
* @param a integer part of numerator
* @param b sqrt(2) part of numerator
* @param c log_2 of the denominator
*/
Z2::Z2(int a, int b, int c){
val[0] = a;
val[1] = b;
val[2] = c;
Z2::reduce();
}
/**
* Constructor to initialize Z2 corresponding to 0.
*/
Z2::Z2(){
val[0] = 0;
val[1] = 0;
val[2] = 0;
}
/**
* Overloads + operator for Z2
* @param other reference to Z2 object to be added
* @return summation the sum of other and *this
*/
Z2 Z2::operator+(Z2& other){
int k = std::max(val[2], other[2]);
int* scaled0 = scale(k);
int* scaled1 = other.scale(k);
Z2 summation = Z2(scaled0[0]+scaled1[0], scaled0[1]+scaled1[1], k);
return summation;
}
/**
* Overloads += operator for Z2
* @param other reference to Z2 object to be added to *this
* @return *this reference to this object, onto which other has been added
*/
Z2& Z2::operator+=(Z2& other){
int k = std::max(val[2], other[2]);
int* scaled0 = scale(k);
int* scaled1 = other.scale(k);
val[0] = scaled0[0] + scaled1[0];
val[1] = scaled0[1] + scaled1[1];
val[2] = k;
reduce();
return *this;
}
/**
* Overloads the - operator for Z2
* @param other reference to Z2 object to be subtracted
* @return summation the subtraction *this - other
*/
Z2 Z2::operator-(Z2& other){
int k = std::max(val[2], other[2]);
int* scaled0 = scale(k);
int* scaled1 = other.scale(k);
Z2 subtraction = Z2(scaled0[0]-scaled1[0], scaled0[1]-scaled1[1], k);
return subtraction;
}
/**
* Overloads the * operator for Z2
* @param other reference to Z2 object to be multiplied
* @return
*/
Z2 Z2::operator*(const Z2& other){
return Z2(val[0]*other[0]+2*val[1]*other[1], val[0]*other[1]+val[1]*other[0], val[2]+other[2]);
}
/**
* Overloads the == operator for Z2
* @param other reference to Z2 object to be compared to
* @return whether or not the entries of the two Z2s are equal
*/
bool Z2::operator==(const Z2& other){
return (val[0]==other[0]&& val[1]==other[1] && val[2]==other[2]);
}
/**
* Overloads the = operator for Z2
* @param other reference to object make *this equal to
* @return *this reference to this object which has been made equal to other
*/
Z2& Z2::operator=(const Z2& other){
//assigns an operator
val[0] = other[0];
val[1] = other[1];
val[2] = other[2];
return *this;
}
/**
* Reduces this Z2 to simplest form
* @return *this reference to simplified object
*/
Z2& Z2::reduce(){
// reduces a Z2 to its lowest denominator exponent expression
while(val[0]%2 == 0 && val[1]%2 == 0 && val[2]>0){
val[0] >>= 1;
val[1] >>= 1;
val[2]--;
}
if(val[2]<0){
val[0] <<= -val[2];
val[1] <<= -val[2];
val[2] = 0;
}
return *this;
}
/**
* Scales the Z2 to a different denominator exponent
* @param k the exponent to scale to
* @return reg the workspace array containing the scaled values
*/
int* Z2::scale(const int& k){
// scales a Z2's entries to a given denominator exponent
int expdiff = k - val[2];
reg[0] = val[0] << expdiff;
reg[1] = val[1] << expdiff;
reg[2] = k;
return reg;
}
/**
* Gives the denominator exponent when this operator is reduced with sqrt(2) in the denominator
* @return exponent of sqrt(2) in reduced form of the operator
*/
int Z2::getLDE(){
reg[0] = val[0];
reg[1] = val[1];
reg[2] = 2*val[2];
while(reg[0]%2 == 0 && reg[2]>0){
reg[0] = reg[1];
reg[1] = reg[0] >>= 1;
--reg[2];
}
return(reg[2]);
}
/**
* Overloads << function for Z2
* @param os reference to ostream object needed to implement <<
* @param z reference to Z2 object to be displayed
* @returns reference ostream with the Z2's display form appended
*/
std::ostream& operator<<(std::ostream& os, const Z2& z){
os << '(' << z[0] << '+' << z[1] << "*sqrt(2))/2^" << z[2];
return os;
}
| true |
c3c6528884250901fbc0eb22d4b75099b0bac194 | C++ | aristotelis-bobas/cpp_modules | /mod_08/ex02/mutantstack.ipp | UTF-8 | 1,515 | 2.6875 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* :::::::: */
/* mutantstack.ipp :+: :+: */
/* +:+ */
/* By: abobas <abobas@student.codam.nl> +#+ */
/* +#+ */
/* Created: 2020/07/03 19:10:22 by abobas #+# #+# */
/* Updated: 2020/07/03 20:44:39 by abobas ######## odam.nl */
/* */
/* ************************************************************************** */
template <typename T>
MutantStack<T>::MutantStack():
std::stack<T>()
{
}
template <typename T>
MutantStack<T>::MutantStack(MutantStack<T> const &other):
std::stack<T>(other)
{
}
template <typename T>
MutantStack<T>& MutantStack<T>::operator=(MutantStack<T> const &other)
{
*this = other;
return (*this);
}
template <typename T>
typename std::stack<T>::container_type::iterator MutantStack<T>::begin()
{
return (this->c.begin());
}
template <typename T>
typename std::stack<T>::container_type::iterator MutantStack<T>::end()
{
return (this->c.end());
}
template <typename T>
MutantStack<T>::~MutantStack()
{
}
| true |
85a9792588a9c34aa3924af12257e6ad7972ac97 | C++ | PaulBNolan/TankProgram | /LabProject1/LabProject1/src/Bolt.cpp | UTF-8 | 6,147 | 3.109375 | 3 | [] | no_license | /// <summary>
/// @Author: Paul Nolan
/// @Version 2.0
/// </summary>
#include "Bolt.h"
#include <iostream>
//The bolt and its values are set up here
Bolt::Bolt(KeyHandler const & object) :
m_keyHandler(object)
{
width = 10;
speedX = 4;
speedY = -4;
rectangle.setFillColor(sf::Color::Green);
rectangle.setSize(sf::Vector2f(width, 10));
powerUpMessageSetUp();
setSounds();
}
Bolt::~Bolt()
{
}
sf::Vector2f Bolt::pos()
{
return sf::Vector2f(x(), y());
}
float Bolt::x()
{
return position.x;
}
float Bolt::y()
{
return position.y;
}
float Bolt::recWidth()
{
return width;
}
//This sets up the message showing the number of power ups left
void Bolt::powerUpMessageSetUp()
{
if (m_font.loadFromFile("ASSETS\\FONTS\\arial_narrow_7.ttf"))
{
}
powerUpMessage.setCharacterSize(20);
powerUpMessage.setPosition(640, 0);
powerUpMessage.setFont(m_font);
powerUpMessage.setString("Power Ups Remaining:" + std::to_string(maxUse - noOfUse));
}
//This sets up the soounds used when deflections occur
void Bolt::setSounds()
{
if (m_wallBuffer.loadFromFile("ASSETS\\SOUNDS\\WallDeflect.wav"))
{
}
m_wallDeflect.setBuffer(m_wallBuffer);
if (m_arrayBuffer.loadFromFile("ASSETS\\SOUNDS\\ArrayDeflect.wav"))
{
}
m_arrayDeflect.setBuffer(m_arrayBuffer);
if (m_paddleBuffer.loadFromFile("ASSETS\\SOUNDS\\PaddleDeflect.wav"))
{
}
m_paddleDeflect.setBuffer(m_paddleBuffer);
}
//This updates the games state
void Bolt::update(Paddle & pad, double *eTime)
{
handleKeyInput();
movement();
//The below two situations are for deflections between the bolt and walls/paddle
if ((pad.y() - position.y < 10 && pad.y() - position.y >= 0) &&((position.x + width > pad.x()) && (position.x < pad.x() + pad.recWidth() )))
{
deflectionPad(pad);
}
if (position.x < 0 || position.x + width > 840 || position.y < 0)
{
deflectionWall();
}
//This resspawns the bolt if it goes off screeb
if (position.y > 650)
{
respawn(eTime);
}
//This if sitation helps to limit the power up and limit its duration
if (powerActive == true)
{
powerTimer += 1.0 / 60;
if (powerTimer > timeLimit)
{
powerDown();
}
}
}
//This function draws the bolt
void Bolt::render(sf::RenderWindow &window)
{
window.draw(powerUpMessage);
window.draw(rectangle);
}
//This function sets the bolts position and velocity
void Bolt::setBolt(sf::Vector2f const & pos, sf::Vector2f const & vel)
{
position = pos;
velocity = vel;
startPosition = position;
}
//This function is used to activate the power up
void Bolt::handleKeyInput()
{
if (m_keyHandler.isPressed(sf::Keyboard::Up))
{
if (noOfUse < maxUse && speedX == startSpeed)
{
powerUp();
}
}
}
//Tjjis function moves the bolt
void Bolt::movement()
{
position += velocity;
rectangle.setPosition(position);
}
//This function is used for deflections that concern the paddle
void Bolt::deflectionPad(Paddle & pad)
{
distance = (position.x + width/2) - (pad.x());
deflectionAmount = distance / pad.recWidth() - 0.5;
angle = 90 - (90 * abs(deflectionAmount));
if (deflectionAmount < 0)
{
speedX = -speedX;
}
angle = angle * ((22.0 / 7.0) * 1.0 / 180.0);
velocity.x = cos(angle) * speedX;
velocity.y = sin(angle) * speedY;
if (speedX < 0)
{
speedX = -speedX;
}
m_paddleDeflect.play();
}
void Bolt::deflectionWall()
{
//The below if situations prevent the bolt from leaving the screen by the top, left and right sides.
if (position.x < 0)
{
position.x = 0;
velocity.x = -velocity.x;
}
else if (position.x + width > 840)
{
position.x = 840 - width;
velocity.x = -velocity.x;
}
if (position.y < 0)
{
position.y = 0;
velocity.y = -velocity.y;
}
//This plays the associated sounds
m_wallDeflect.play();
}
void Bolt::deflectionArrays(sf::Vector2f pos, float aWidth, float height)
{
//This is the if situation for y axis deflection. Two velocity changes are used for situations where the bolt strikes two bricks going up at the same time
if ((pos.y > position.y && pos.y < position.y + width) || (pos.y + height > position.y && pos.y + height < position.y + width))
{
if (velocity.y > 0 && (pos.y + height > position.y && pos.y + height < position.y + width))
{
velocity.y = -velocity.y;
}
velocity.y = -velocity.y;
}
//This is the situation used for axis collsions. Note: This situation is not perfect and does not work for upper left corners
else if ((pos.x > position.x && pos.x < position.x + width) || (pos.x + aWidth > position.x && pos.x + aWidth < position.x + width))
{
velocity.x = -velocity.x;
}
//This situation is used for corner collsions
else if ((position.x < pos.x && position.y < pos.y) || (position.x < pos.x + aWidth && position.y < pos.y + height)
||
(position.x < pos.x + aWidth && position.y < pos.y) || (position.x < pos.x && position.y < pos.y + height))
{
float x = pos.x;
float y = pos.y;
if (position.x > pos.x)
{
x += aWidth;
}
if (position.y > pos.y)
{
y += height;
}
//These two are used to find which side the bolt is closest two and so which to deflect from
if (x - position.x < y - position.y)
{
velocity.y = -velocity.y;
}
if (x - position.x > y - position.y)
{
velocity.x = -velocity.x;
}
}
//This plays the associated sounds
m_arrayDeflect.play();
}
//This function resets thee bolt if it goes offscreen and applies a time penalty
void Bolt::respawn(double *eTime)
{
position = startPosition;
rectangle.setPosition(position);
if (speedX == startSpeed * multiplyer)
{
powerDown();
}
*eTime += timePenalty;
}
//This function applies the power up
void Bolt::powerUp()
{
speedX = speedX * multiplyer;
speedY = speedY * multiplyer;
velocity.x = velocity.x * multiplyer;
velocity.y = velocity.y * multiplyer;
noOfUse++;
powerUpMessage.setString("Power Ups Remaining:" + std::to_string(maxUse - noOfUse));
powerActive = true;
}
//This function reverses the changes from the above function
void Bolt::powerDown()
{
speedX = speedX / multiplyer;
speedY = speedY / multiplyer;
velocity.x = velocity.x / multiplyer;
velocity.y = velocity.y / multiplyer;
powerTimer = 0;
powerActive = false;
} | true |
f1c7392b464c9ad0121839175dcc693e835b3bc0 | C++ | deepakchandh/My-files | /tax.cpp | UTF-8 | 1,008 | 3.34375 | 3 | [] | no_license | #include<iostream>
using namespace std;
class employee
{
string name,dept;
int eno;
public:
void getdata()
{
cout<<"\nEMPLOYEE NAME: ";
cin>>name;
cout<<"\nEMPLOYEE NUMBER: ";
cin>>eno;
}
void putdata()
{
cout<<"\nDEPARTMENT:\t";
cin>>dept;
}
};
class PAY
{
protected:
float basicpay,HRA,DA,grosspay;
public:
//float grosspay;
void getpay()
{
cout<<"\nBASICPAY:";
cin>>basicpay;
}
void grosssalary()
{
DA=0.40*basicpay;
HRA=0.20*basicpay;
grosspay=HRA+DA+basicpay;
}
void display()
{
cout<<"\nDA: "<<DA;
cout<<"\nHRA: "<<HRA;
cout<<"\nGROSSPAY: "<<grosspay;
}
};
class TAX:public employee,public PAY
{
double PANno,taxamount;
public:
void calc_tax()
{
cout<<"\nPAN NO:\t";
cin>>PANno;
taxamount=(grosspay*5)/100;
}
void disp_tax()
{
cout<<"\nTAX AMOUNT:"<<taxamount;
}
};
main()
{
TAX t;
t.getdata();
t.putdata();
t.getpay();
t.grosssalary();
t.display();
t.calc_tax();
t.disp_tax();
}
| true |
2130ac3390371314df1cc89004124c05ddb1cad8 | C++ | xhewr/lab-04 | /main.cpp | UTF-8 | 5,214 | 4.21875 | 4 | [] | no_license | // CIS22b
// Lab04
// Name:
/*
Program description: This program demonstrates the functionality of
the minimum(), maximum(), getAbsolute() and total() template
functions when tested with with different data types.
The minimum() template returns the lowest of two passed values.
The maximium() template returns the highest of two passed values.
The getAbsoluteValue() template returns the absolute value of the passed number
The total() template gets user input for values and then returns the sum of all the values entered.
*/
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
//Template to find the minimum value of two variables
//Accepts 2 parameters of type T
//Returns the smallest
//Works with all types that have a < operator (int, double, char, string)
template <class T>
T minimum(T number1, T number2)
{
return (number1 < number2) ? number1 : number2;
}
//Template to find maximum value of two variables
//Accepts 2 parameters type T
//Returns the largest
//Works with all types that have a < operator (int, double, char, string)
template <class T>
T maximum(T number1, T number2)
{
return (number1<number2) ? number2 : number1;
}
//Template to absolute value function
//Accepts single parameter of type T
//Returns the absolute value for the passed value
//Works with all types that can be compared with a "< 0" and have a - operator (not strings)
template <class T>
T getAbsoluteValue(T args)
{
if (args < 0)
{
args = -args;
}
return args;
}
//Template to keep a running total of values entered by the user, then return the sum of all the values entered
//Will return a type T and takes an int as argument
// The int argument represents the number of values the user will enter.
//T cannot be a string because strings can't be set to 0
//cin needs to support type T
template <typename T>
T total(int numInputs)
{
T temp = 0;
T runningTotal = 0;
for (int count = 0; count < numInputs; count++)
{
cout << "Enter a number for value number " << count+1 << ": ";
cin >> temp;
cin.ignore();
runningTotal += temp;
}
return runningTotal;
}
int main()
{
int intergerA = 12, intergerB = 15;
double doubleC = 15.6, doubleD = 2.43;
char characterE = 'f', characterF = 'o';
string stringG = "foo", stringH = "bar";
// Demonstrating minimum template
cout << "Demonstrating minimum() template: " << endl;
cout << "__________________________" << endl;
cout << "Type " << "Values" << " Result" << endl;
cout << "__________________________" << endl;
cout << "Ints " << intergerA << ", " << intergerB << " " << minimum(intergerA, intergerB) << endl;
cout << "Double " << doubleC << ", " << doubleD << " " << minimum(doubleC, doubleD) << endl;
cout << "Char " << characterE << ", " << characterF << " " << minimum(characterE, characterF) << endl;
cout << "String " << stringG << ", " << stringH << " " << minimum(stringG, stringH) << endl;
cout << endl << endl;
// Demonstrating maximum template
cout << "Demonstrating maximum() template: " << endl;
cout << "__________________________" << endl;
cout << "Type " << "Values" << " Result" << endl;
cout << "__________________________" << endl;
cout << "Ints " << intergerA << ", " << intergerB << " " << maximum(intergerA, intergerB) << endl;
cout << "Double " << doubleC << ", " << doubleD << " " << maximum(doubleC, doubleD) << endl;
cout << "Char " << characterE << ", " << characterF << " " << maximum(characterE, characterF) << endl;
cout << "Strings " << stringG << ", " << stringH << " " << maximum(stringG, stringH) << endl;
cout << endl << endl;
int intergerJ = -12, intergerK = 0;
double doubleL = -15.6;
char characterM = -50;
// Demonstrating getAbsoluteValue template
cout << "Demonstrating getAbsoluteValue() template: " << endl;
cout << "________________________________" << endl;
cout << "Type " << "Value" << " Result" << endl;
cout << "________________________________" << endl;
cout << "Positive int " << intergerA << " " << getAbsoluteValue(intergerA) << endl;
cout << "Negative int " << intergerJ << " " << getAbsoluteValue(intergerJ) << endl;
cout << "Positive double " << doubleC << " " << getAbsoluteValue(doubleC) << endl;
cout << "Negative double " << doubleL << " " << getAbsoluteValue(doubleL) << endl;
cout << endl << endl;;
// Demonstrating total template
cout << "Demonstrating total() template: " << endl;
cout << "_______________________________" << endl;
int totalInt = 0;
double totalDouble = 0;
cout << "Running total for two integer values:" << endl;
totalInt = total<int>(2);
cout << "Running total is: " << totalInt << endl << endl;
cout << "_________________________" << endl;
cout << "Running total for three double values: " << endl;
totalDouble = total<double>(3);
cout << "Running total is: " << totalDouble << endl;
cout << endl;
cout << "press Enter to close the program ...";
cin.get();
return 0;
}
| true |
7fb349aad789333b40da04c5c2b4dc7f837db556 | C++ | GeorgiosGiagkas/practice-cpp | /chapter6_classes/lecture58a.cpp | UTF-8 | 715 | 4.0625 | 4 | [] | no_license | //Array of instances of a class
#include<stdio.h>
class integer//class name
{
private:
int number;//private data member
public:
void store(int);//mutator function
int print(void);//accessor function
};
void integer::store(int x){//function definition
number=x;
}
int integer::print(void){//function definition
return number;
}
int main(){
const int size=5;
integer array[size];//instantiation. Array of instancies of class integer.
int i;//counter
for(i=0;i<size;i++){
array[i].store(i);//for each instance(object) of the array store i
}
for(i=0;i<size;i++){
printf("%d\n", array[i].print() );//for each instance(object of the array print i
}
return 0;
}
| true |
790f7cbb53a932f1751781c7425e9ed735cb97d3 | C++ | huobingli/boostProgram | /boost_test/boost_regex_search.cpp | UTF-8 | 1,436 | 2.625 | 3 | [] | no_license |
//********************************************************
//
// FileName: boost_regex_search.cpp
//
// Author: huobingli - huobingli@outlook.com
// Description:
// Create: 2016-12-29 20:03:20
// Last Modified: 2016-12-29 20:03:20
//********************************************************
//
#include <iostream>
#include <boost/xpressive/xpressive_dynamic.hpp>
int main() {
using namespace boost::xpressive;
char* str = "there is a POWER-suit item";
cregex reg = cregex::compile("(power)-(.{4})", icase);
//搜索到字符串
assert(regex_search(str, reg));
cmatch what;
//保存搜索结果
regex_search(str, what, reg);
//三个表达式
assert(what.size() == 3);
std::cout<<what[0] << what[1] << what[2] << std::endl;
assert(!regex_search("error message", reg));
//regex_search()代替string_algo的contains 、starts_with、ends_with和查找算法
std::string str1("readme.TXT");
sregex start_reg = sregex::compile("^re");
sregex end_reg = sregex::compile("txt$", icase);
assert(regex_search(str1, start_reg));
std::cout << regex_search(str1, start_reg) << std::endl;
assert(regex_search(str1, end_reg));
std::cout << regex_search(str1, end_reg) << std::endl;
assert(regex_search(str1, sregex::compile("me"))); //boost书中写错了,sregex写成cregex
std::cout << regex_search(str1, sregex::compile("me")) << std::endl;
}
| true |
effd9fa8f108cb002f0cf1aad56d921b2f6fee25 | C++ | allenARM/Cpp-Piscine | /Day07/ex01/iter.cpp | UTF-8 | 475 | 3.71875 | 4 | [] | no_license | #include <iostream>
#include <string>
template <typename T>
void iter(T const *arr, int num, void (*fun)(T const &))
{
int i = 0;
while (i < num)
{
(*fun)(arr[i]);
i++;
}
}
template <typename T>
void print_arr(T const & name)
{
std::cout << name << std::endl;
}
int main()
{
std::string keker[] = {"lol", "kek", "cheburek"};
int nums[] = {1,2,3,4,5,6,7,8,9,0};
iter(keker, 3, print_arr);
std::cout << "-----------" << std::endl;
iter(nums, 10, print_arr);
} | true |
22888ddd98baba4489adf6b4c3fd8bf9eb58f7e5 | C++ | lhuang9703/SolutionsForLeetcode | /Linked_List_Cycle.cpp | UTF-8 | 1,352 | 3.34375 | 3 | [] | no_license | // Source : https://leetcode-cn.com/problems/linked-list-cycle/description/
// Number : 141
// Author : HL
// Date : 2018-09-03
// Kill : 98.85%,37.14%
/**********************************************************************************
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
**********************************************************************************/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL)
return false;
// 双指针解法
// ListNode *p = head;
// ListNode *q = p->next;
// while(q != p){
// if(q == NULL || q->next == NULL)
// return false;
// p = p->next;
// q = q->next->next;
// }
// return true;
// 哈希解法
map<ListNode*,ListNode*> mp;
ListNode *p = head;
while(p != NULL){
if(mp.find(p->next) != mp.end())
return true;
else{
mp[p] = p->next;
p = p->next;
}
}
return false;
}
};
| true |
5ccdc54826f90395de1329230d4592a4e2ace6b1 | C++ | EnapsTer/StudyCPP | /Day06/ex02/main.cpp | UTF-8 | 1,240 | 3.5 | 4 | [
"MIT"
] | permissive | //
// Created by Андре Шагиджанян on 20.07.2021.
//
#include <iostream>
#include <string>
#include "Base.hpp"
#include "A.hpp"
#include "B.hpp"
#include "C.hpp"
Base * generate() {
Base *base = NULL;
int rand_num = rand() % 3;
if (rand_num == 0) {
base = new A();
std::cout << "Create A class" << std::endl;
}
else if (rand_num == 1) {
base = new B();
std::cout << "Create B class" << std::endl;
}
else if (rand_num == 2) {
base = new C();
std::cout << "Create C class" << std::endl;
}
return base;
}
void identify(Base* p) {
if (dynamic_cast<A *>(p) != NULL)
std::cout << "type is A" << std::endl;
else if (dynamic_cast<B *>(p) != NULL)
std::cout << "type is B" << std::endl;
else
std::cout << "type is C" << std::endl;
}
void identify(Base& p) {
if (dynamic_cast<A *>(&p) != NULL)
std::cout << "type is A" << std::endl;
else if (dynamic_cast<B *>(&p) != NULL)
std::cout << "type is B" << std::endl;
else
std::cout << "type is C" << std::endl;
}
int main() {
srand(time(0));
Base *base = generate();
std::cout << "identify use pointer" << std::endl;
identify(base);
std::cout << "identify use reference" << std::endl;
identify(*base);
delete base;
} | true |
b63a78a995988a4930e71a5cdfdd3c40908d43a7 | C++ | masami87/coroutine-cxx | /coroutine.h | UTF-8 | 1,605 | 2.703125 | 3 | [] | no_license | #pragma once
#include <functional>
#include <ucontext.h>
#include <vector>
#define COROUTINE_DEAD 0
#define COROUTINE_READY 1
#define COROUTINE_RUNNING 2
#define COROUTINE_SUSPEND 3
#define STACK_SIZE (1024 * 1024)
#define DEFAULT_COROUTINE 64
class Coroutine;
class Scheduler;
using coroutine_func = std::function<void(Scheduler *, void *)>;
// coroutine 调度器
class Scheduler final {
public:
Scheduler();
~Scheduler();
// 创建一个协程
int coroutine_new(coroutine_func, void *ud);
void coroutine_resume(int id);
void coroutine_yield();
int coroutine_status(int id);
int coroutine_running() const;
// private:
// 运行时栈
// 栈的地址是由高地址往低地址生长,而数组的首地址又是整个数组的最低地址
// 因此stack的位置是整个共享栈的栈顶,栈底位置在stack + STACK_SIZE
char stack[STACK_SIZE];
ucontext_t main; // 主协程的上下文
int nco; // 当前存活的协程个数
int cap; // 协程管理器的当前最大容量,即可以同时支持多少个协程。如果不够了,则进行扩容
int running; // 正在运行的协程ID
std::vector<Coroutine *> co; // 一个一维数组,用于存放协程
static void mainfunc(void *sptr);
};
// 开启协程调度器
Scheduler *coroutine_open(void);
// 切换到对应协程中执行
void coroutine_resume(Scheduler *, int id);
// 返回协程状态
int coroutine_status(Scheduler *, int id);
// 返回协程是否在运行
int coroutine_running(Scheduler *);
// 切出协程
void coroutine_yield(Scheduler *); | true |
be2e2eb2ba9ae636e4b5f068f6711dfce12d0c95 | C++ | dstrube1/playground | /misc/aooswd/ex/composite/composite.cpp | UTF-8 | 1,809 | 2.953125 | 3 | [] | no_license | class Equipment
{
public:
virtual ~Equipment ();
const char* Name () (return _name;}
virtual Watt Power ();
virtual Currency NewPrice ();
virtual Currency DiscountPrice ();
virtual void Add (Equipment*);
virtual void Remove (Equipment*);
virtual Iterator<Equipment*>* CreateIterator ();
protected:
Equipment (const char*);
private:
const char* _name;
};
class FloppyDisk: public Equipment
{
public:
FloppyDisk (const char*);
virtual ~FloppyDisk ();
virtual Watt Power ();
virtual Currency NetPrice ();
virtual Currency DiscountPrice ();
};
class CompositeEquipment: public Equipment
{
public:
virtual ~CompositeEquipment ();
virtual Watt Power ();
virtual Currency NetPrice ();
virtual Currency DiscountPrice ();
virtual void Add (Equipment*);
virtual void Remove (Equipment*);
virtual Iterate <Equipment*>* CreateIterator;
protected:
CompositeEquipment (const char*);
private:
List<Equipment*> _equipment;
};
Currency CompositeEquipment::NetPrice ()
{
Iterator <Equipment*>* I = CreateIterator ();
Currency total = 0;
for (I -> First (); !I -> IsDone (); I -> Next ())
total += I -> CurrentItem () -> NetPrice ();
delete I;
return total;
}
class Chassis: public CompositeEquipment
{
public:
Chassis (const char*);
virtual ~Chassis ();
virtual Watt Power ();
virtual Currency NetPrice ();
virtual Currency DiscountPrice ();
};
Cabinet* cabinet = new Cabinet ("PC Cabinet");
Chassis* chassis = new Chassis ("PC Chassis");
cabinet -> Add (chassis);
Bus* bus = new Bus ("MCA Bus");
bus -> Add (new Card ("16Mbs Token Ring"));
chassis -> Add (bus);
chassis -> Add (new FloppyDisk ("3.5in Floppy"));
cout << "The net price is " << chassis -> NetPrice () << endl;
| true |
8d8fdc3ca2cba370fba055ecdc7bbe171e341cfe | C++ | PaulaOlivan/2-Evaluacion | /Cuadrado.cpp | ISO-8859-10 | 538 | 2.765625 | 3 | [] | no_license | /*Vamos a hacer un programa que dibuje un cuadrado del tamao que desee el usuario*/
#include<iostream>
int main(){
//Definicion de variables
char salir;
int lado, col, fil;
std::cout<< "Cual el lado del cuadrado? ";
std::cin>>lado; //nested
for(col=1;col<=lado;col++){
for(fil=1;fil<=lado;fil++){
std::cout<< '*';
}
std::cout<<"\n";
}
std::cin>>salir;
}
| true |
156689b772d7a85b01e52732a2ef8b7204b9b23c | C++ | autonomobil/SDCND-P8_Particle-Filter | /src/particle_filter.cpp | UTF-8 | 7,605 | 2.640625 | 3 | [
"MIT"
] | permissive | /*
* particle_filter.cpp
*
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*/
#include <random>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <math.h>
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>
#include "particle_filter.h"
using namespace std;
// http://www.cplusplus.com/reference/random/default_random_engine/
static default_random_engine gen;
void ParticleFilter::init(double x, double y, double theta, double std[]) {
// Set the number of particles. Initialize all particles to first position (based on estimates of
// x, y, theta and their uncertainties from GPS) and all weights to 1.
// Add random Gaussian noise to each particle.
num_particles = 123;
// Resize vectors
particles.resize(num_particles);
weights.resize(num_particles);
// set weight init
double w_init = 1.0/num_particles;
//Create normal distributions for x, y and theta
normal_distribution<double> dist_x(x, std[0]);
normal_distribution<double> dist_y(y, std[1]);
normal_distribution<double> dist_theta(theta, std[2]);
// Initializes particles vector with Gaussian
for (int i = 0; i < num_particles; ++i) {
particles[i].id = i;
particles[i].x = dist_x(gen);
particles[i].y = dist_y(gen);
particles[i].theta = dist_theta(gen);
particles[i].weight = w_init;
}
is_initialized = true;
}
void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) {
// Add measurements to each particle and add random Gaussian noise.
normal_distribution<double> dist_x(0, std_pos[0]);
normal_distribution<double> dist_y(0, std_pos[1]);
normal_distribution<double> dist_theta(0, std_pos[2]);
// Calculate x y and yaw for each particle
for (int i = 0; i < num_particles; i++){
if(fabs(yaw_rate)<= 0.0001){ //ignore yaw-rate
double vel_dt = velocity * delta_t;
particles[i].x += vel_dt * cos(particles[i].theta) ;
particles[i].y += vel_dt * sin(particles[i].theta) ;
}
else{ //consider yaw-rate
double vel_dt = velocity / yaw_rate;
double theta_rate = particles[i].theta + yaw_rate * delta_t;
particles[i].x += vel_dt * ( sin(theta_rate) - sin(particles[i].theta));
particles[i].y += vel_dt * (-cos(theta_rate) + cos(particles[i].theta));
particles[i].theta = theta_rate;
}
// Add Gaussian noise
particles[i].x += dist_x(gen);
particles[i].y += dist_y(gen);
particles[i].theta += dist_theta(gen);
}
}
void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) {
// Find the predicted measurement that is closest to each observed measurement and assign the
// observed measurement to this particular landmark.
// this method will NOT be called by the grading code. But you will probably find it useful to
// implement this method and use it as a helper during the updateWeights phase.
}
void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
const std::vector<LandmarkObs> &observations, const Map &map_landmarks) {
// Update the weights of each particle using a mult-variate Gaussian distribution.
double sig_x = std_landmark[0];
double sig_y = std_landmark[1];
double gauss_norm = 1 / (2 * M_PI * sig_x * sig_y);
// clears weight vector
weights.clear();
for (int i = 0; i < num_particles; i++){
// init weights
particles[i].weight = 1.0;
double x_p = particles[i].x;
double y_p = particles[i].y;
double sin_the = sin(particles[i].theta);
double cos_the = cos(particles[i].theta);
/////////// init & set predicted as a vector LandmarkObs
vector<LandmarkObs> predicted;
for (unsigned int j = 0; j < map_landmarks.landmark_list.size(); j++) {
// get x,y coordinates from landmarks
float x_land = map_landmarks.landmark_list[j].x_f;
float y_land = map_landmarks.landmark_list[j].y_f;
// check if in range, if not -> ignore
if (fabs(dist(x_p, y_p, x_land, y_land)) <= sensor_range) {
// add prediction to vector
predicted.push_back(LandmarkObs{map_landmarks.landmark_list[j].id_i, x_land, y_land });
}
}
/////////// init & set observations_trans as vector LandmarkObs
vector<LandmarkObs> observations_trans;
for (unsigned int j = 0; j < observations.size(); j++) {
// get x,y coordinates (Particle/car based)
float x_obs = observations[j].x;
float y_obs = observations[j].y;
// transform to map
double x_trans = x_p + cos_the * x_obs - sin_the * y_obs;
double y_trans = y_p + sin_the * x_obs + cos_the * y_obs;
// add transform to vector
observations_trans.push_back(LandmarkObs{observations[j].id, x_trans, y_trans});
}
/////////// Association and getting x,y values for weight calculation
for (unsigned int j = 0; j < observations_trans.size(); j++) {
// init x,y values for weight calculation
double x_obs, y_obs, x_pre, y_pre;
// init min_distance to largest number
double min_distance = numeric_limits<double>::max();
for (unsigned int p = 0; p < predicted.size(); p++) {
double distance = dist(observations_trans[j].x, observations_trans[j].y, predicted[p].x, predicted[p].y);
// search for min distance
if (distance < min_distance) {
x_obs = observations_trans[j].x;
y_obs = observations_trans[j].y;
x_pre = predicted[p].x;
y_pre = predicted[p].y;
min_distance = distance;
}
}
// calculate exponent
float exponent = (pow(x_obs - x_pre, 2) / (2 * sig_x * sig_x)) + (pow(y_obs - y_pre, 2) / (2 * sig_y * sig_y));
// calculate weight
particles[i].weight *= gauss_norm * exp(-exponent);
}
weights.push_back(particles[i].weight);
}
}
void ParticleFilter::resample() {
// http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
discrete_distribution<> particle_dist(weights.begin(), weights.end());
vector<Particle> particles_resamp;
particles_resamp.resize(num_particles);
for (int i = 0; i < num_particles; i++) {
particles_resamp[i] = particles[particle_dist(gen)];
}
particles = particles_resamp;
}
Particle ParticleFilter::SetAssociations(Particle& particle, const std::vector<int>& associations,
const std::vector<double>& sense_x, const std::vector<double>& sense_y)
{
//particle: the particle to assign each listed association, and association's (x,y) world coordinates mapping to
// associations: The landmark id that goes along with each listed association
// sense_x: the associations x mapping already converted to world coordinates
// sense_y: the associations y mapping already converted to world coordinates
particle.associations= associations;
particle.sense_x = sense_x;
particle.sense_y = sense_y;
}
string ParticleFilter::getAssociations(Particle best)
{
vector<int> v = best.associations;
stringstream ss;
copy( v.begin(), v.end(), ostream_iterator<int>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
string ParticleFilter::getSenseX(Particle best)
{
vector<double> v = best.sense_x;
stringstream ss;
copy( v.begin(), v.end(), ostream_iterator<float>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
string ParticleFilter::getSenseY(Particle best)
{
vector<double> v = best.sense_y;
stringstream ss;
copy( v.begin(), v.end(), ostream_iterator<float>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
| true |
04a9fdbbad98007d3687c72e8825eabd7091453d | C++ | burakbayramli/books | /GPU-Gems-Book-Source-Code/GPU-Gems-3-CD-Content/content/08/demo/RenderableTexture2D.hpp | UTF-8 | 1,966 | 2.796875 | 3 | [] | no_license | #pragma once
//--------------------------------------------------------------------------------------
// Simple class to encapsulate a Texture2D, a render target view and a shader resource
// view. Used to simplify the creation and management of the fairly common single
// render target/shader resource view per texture case.
class RenderableTexture2D
{
public:
// Create a new 2D texture using the given information
RenderableTexture2D(ID3D10Device* d3dDevice, unsigned int Width, unsigned int Height,
unsigned int MipLevels, DXGI_FORMAT Format,
const DXGI_SAMPLE_DESC* SampleDesc = 0);
// Create a render target and shader resource for the associated slice of the given
// 2D texture array.
RenderableTexture2D(ID3D10Device* d3dDevice, ID3D10Texture2D* TextureArray,
unsigned int Index);
~RenderableTexture2D();
unsigned int GetWidth() const { return m_Width; }
unsigned int GetHeight() const { return m_Height; }
unsigned int GetMipLevels() const { return m_MipLevels; }
DXGI_FORMAT GetFormat() const { return m_Format; }
bool IsArray() const { return m_Array; }
unsigned int GetArrayIndex() const { return m_ArrayIndex; }
ID3D10Texture2D * GetTexture() { return m_Texture; }
ID3D10RenderTargetView * GetRenderTarget() { return m_RenderTarget; }
ID3D10ShaderResourceView * GetShaderResource() { return m_ShaderResource; }
private:
// Not implemented
RenderableTexture2D(const RenderableTexture2D &);
unsigned int m_Width;
unsigned int m_Height;
unsigned int m_MipLevels;
DXGI_FORMAT m_Format;
bool m_Array;
unsigned int m_ArrayIndex;
ID3D10Texture2D* m_Texture;
ID3D10RenderTargetView* m_RenderTarget;
ID3D10ShaderResourceView* m_ShaderResource;
}; | true |
c2a52138777ef317c2cad028b70bfc6cfbde9984 | C++ | rootonchair/CV_Lab1 | /Converter.h | UTF-8 | 7,426 | 3.34375 | 3 | [] | no_license | #pragma once
#define R 2
#define G 1
#define B 0
#define H 0
#define S 1
#define V 2
#include "opencv2/opencv.hpp"
#include <math.h>
#include "opencv2/highgui.hpp"
using namespace std;
double max(double a, double b)
{
if (a > b)
return a;
return b;
}
double min(double a, double b)
{
if (a < b)
return a;
return b;
}
void SetValuePixel(cv::Mat& img, int row, int col, int color, int data)
{
img.data[row * img.channels() * img.cols + col * img.channels() + color] = data;
}
int GetPixelValue(cv::Mat img, int row, int col, int color)
{
return img.data[row * img.channels() * img.cols + col*img.channels() + color];
}
class Converter
{
public:
/*
Hàm chuyển đổi không gian màu của ảnh từ RGB sang GrayScale
sourceImage: ảnh input
destinationImage: ảnh output
Hàm trả về
0: nếu chuyển thành công
1: nếu chuyển thất bại (không đọc được ảnh input,...)
*/
int RGB2GrayScale(const cv::Mat& sourceImage, cv::Mat& destinationImage)
{
if (sourceImage.channels() != 3)
return 1;
destinationImage = cv::Mat(sourceImage.rows, sourceImage.cols, CV_8UC1);
//(*dstPixel) = 0.299*currentPixel[R] + 0.587*currentPixel[G] + 0.114*currentPixel[B];
for (int row= 0; row < sourceImage.rows; row++)
for (int col = 0; col < sourceImage.cols; col++)
{
int grayColor = 0.299 * GetPixelValue(sourceImage, row, col, R) + 0.558 * GetPixelValue(sourceImage, row, col, G) + 0.114 * GetPixelValue(sourceImage, row, col, B);
SetValuePixel(destinationImage, row, col, 0, grayColor);
}
return 0;
}
/*
Hàm chuyển đổi không gian màu của ảnh từ GrayScale sang RGB
sourceImage: ảnh input
destinationImage: ảnh output
Hàm trả về
0: nếu chuyển thành công
1: nếu chuyển thất bại (không đọc được ảnh input,...)
*/
int GrayScale2RGB(const cv::Mat& sourceImage, cv::Mat& destinationImage)
{
if (sourceImage.channels() != 1)
return 1;
destinationImage = cv::Mat(sourceImage.rows, sourceImage.cols, CV_8UC3);
for (int row = 0; row < sourceImage.rows; row++)
{
for (int col = 0; col < sourceImage.cols; col++)
{
uchar currentPixel = GetPixelValue(sourceImage, row, col, 0);
SetValuePixel(destinationImage, row, col, R, currentPixel);
SetValuePixel(destinationImage, row, col, G, currentPixel);
SetValuePixel(destinationImage, row, col, B, currentPixel);
}
}
return 0;
}
double findMax(double r, double g, double b)
{
double firstMax = (r > g ? r : g);
return (firstMax > b ? firstMax : b);
}
double findMin(double r, double g, double b)
{
double firstMin = (r > g ? g : r);
return (firstMin > b ? b : firstMin);
}
/*
Hàm chuyển đổi không gian màu của ảnh từ RGB sang HSV
sourceImage: ảnh input
destinationImage: ảnh output
Hàm trả về
0: nếu chuyển thành công
1: nếu chuyển thất bại (không đọc được ảnh input,...)
*/
int RGB2HSV(const cv::Mat& sourceImage, cv::Mat& destinationImage)
{
if (sourceImage.channels() != 3)
return 1;
destinationImage = cv::Mat(sourceImage.rows, sourceImage.cols, CV_8UC3);
for (int row = 0; row < sourceImage.rows; row++)
{
for (int col = 0; col < sourceImage.cols; col++)
{
cv::Vec3b currentPixel = sourceImage.at<cv::Vec3b>(row, col);
double h, s, v;
double r_scaled = currentPixel[R] / 255.0;
double g_scaled = currentPixel[G] / 255.0;
double b_scaled = currentPixel[B] / 255.0;
double val_max = findMax(r_scaled, g_scaled, b_scaled);
double val_min = findMin(r_scaled, g_scaled, b_scaled);
double delta = val_max - val_min;
v = val_max * 255;
if (delta < 0.00001)
{
h = 0.0;
s = NAN;
}
else if (val_max <= 0.0)
{
s = 0.0;
h = NAN;
}
else
{
s = delta / val_max;
if (r_scaled >= val_max) {
h = (g_scaled - b_scaled) / delta;
}
else if (g_scaled >= val_max) {
h = 2.0 + (b_scaled - r_scaled) / delta;
}
else {
h = 4.0 + (r_scaled - g_scaled) / delta;
}
h *= 60.0;
if (h < 0.0)
h += 360;
//Turn to OpenCV style
s *= 255.0;
h /= 2.0;
}
//destinationImage.at<cv::Vec3b>(row, col)[H] = (uchar)h;
SetValuePixel(destinationImage, row, col, H, h);
SetValuePixel(destinationImage, row, col, S, s);
SetValuePixel(destinationImage, row, col, V, v);
//cout << h << " " << s << " " << v << endl;
///destinationImage.at<cv::Vec3b>(row, col)[S] = (uchar)s;
//destinationImage.at<cv::Vec3b>(row, col)[V] = (uchar)v;
}
}
return 0;
}
/*
Hàm chuyển đổi không gian màu của ảnh từ HSV sang RGB
sourceImage: ảnh input
destinationImage: ảnh output
Hàm trả về
0: nếu chuyển thành công
1: nếu chuyển thất bại (không đọc được ảnh input,...)
*/
int HSV2RGB(const cv::Mat& sourceImage, cv::Mat& destinationImage)
{
if (sourceImage.channels() != 3)
return 1;
destinationImage = cv::Mat(sourceImage.rows, sourceImage.cols, CV_8UC3);
for (int row = 0; row < sourceImage.rows; row++)
for (int col = 0; col < sourceImage.cols; col++)
{
double r, g, b;
double h, s, v;
h = max(0, min(255, GetPixelValue(sourceImage, row, col, H))) * 2.0;
s = max(0, min(255, GetPixelValue(sourceImage, row, col, S))) / 255.0;
v = max(0, min(255, GetPixelValue(sourceImage, row, col, V))) / 255.0;
//cout << h << " " << s << " " << v << endl;
int hi = int(h / 60) % 6;
double f = h / 60 - hi;
double p = v * (1 - s);
double q = v * (1 - f * s);
double t = v * (1 - s + s * f);
switch (hi)
{
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = q;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
default:
r = v;
g = p;
b = q;
break;
}
SetValuePixel(destinationImage, row, col, R, int(r / 2)) ;
SetValuePixel(destinationImage, row, col, G, int(g*255));
SetValuePixel(destinationImage, row, col, B, int(b*255));
}
return 0;
}
public:
/*
Hàm chuyển đổi không gian màu của ảnh
sourceImage: ảnh input
destinationImage: ảnh output cùng kích thước, cùng loại với ảnh input
type: loại chuyển đổi
0,1: chuyển từ RGB sang GrayScale và ngược lại
2,3: chuyển từ RGB sang HSV và ngược lại
Hàm trả về
0: nếu chuyển thành công
1: nếu chuyển thất bại (không đọc được ảnh input hay type không chính xác,...)
*/
int Convert(cv::Mat& sourceImage, cv::Mat& destinationImage, int type)
{
if (sourceImage.data == NULL)
return 1;
switch (type)
{
case 0:
return RGB2GrayScale(sourceImage, destinationImage);
case 1:
return GrayScale2RGB(sourceImage, destinationImage);
case 2:
return RGB2HSV(sourceImage, destinationImage);
case 3:
return HSV2RGB(sourceImage, destinationImage);
default:
return 1;
}
}
int Convert(IplImage* sourceImage, IplImage* destinationImage, int type)
{
cv::Mat org = cv::cvarrToMat(sourceImage);
cv::Mat dst = cv::cvarrToMat(destinationImage);
return Convert(org, dst, type);
}
Converter()
{
}
~Converter()
{
}
};
| true |
acb9d50dc20749405be345a2ab6230bbda1be565 | C++ | Toebin/Lab-Advanced-Programming---Final | /Lab Advanced Programming - Final/Source.cpp | UTF-8 | 1,891 | 3.828125 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Ship
{
public:
Ship(string n, int sp, int pDmg, int sDmg)
{
name = n;
structuralPoints = sp;
primaryDmg = pDmg;
secondaryDmg = sDmg;
}
void takeDamage(int amount) { structuralPoints -= amount; }
int getPrimaryAttack() const { return primaryDmg; }
int getSecondaryAttack() const { return secondaryDmg; }
string getShipInfo()
{
stringstream s;
s << "Ship name: " << name << "\t Structural Points: " << structuralPoints << endl;
return s.str();
}
private:
string name;
int structuralPoints;
int primaryDmg;
int secondaryDmg;
};
class Carrier
{
public:
Carrier(string name, int maxShips) {
this->name = name;
this->maxShips = maxShips;
numShips = 0;
shipList = new Ship * [maxShips];
}
bool addShip(string name, int sp, int pDmg, int sDmg)
{
if (numShips < maxShips)
{
Ship* newShip = new Ship(name, sp, pDmg, sDmg);
shipList[numShips] = newShip;
numShips++;
return true;
}
return false;
}
Ship* launchShip(int pos)
{
if (pos >= numShips)
{
return NULL;
}
Ship* temp = shipList[pos];
shipList[pos] = shipList[numShips - 1];
numShips--;
return temp;
}
string getCarrierInfo()
{
stringstream s;
s << "Carrier Name: " << name << "\n";
s << "Ships Carried: \n";
for (int x = 0; x < numShips; x++) {
s << shipList[x]->getShipInfo() << endl;
}
return s.str();
}
int getNumShips() const
{
return numShips;
}
string getName() const
{
return name;
}
private:
string name;
int numShips;
int maxShips;
Ship** shipList;
};
int main()
{
Carrier c1("The Carry 5000", 10);
c1.addShip("X-Wing", 350, 25, 180);
c1.addShip("A-wing", 200, 20, 60);
c1.addShip("Y-wing", 500, 15, 400);
cout << c1.getCarrierInfo();
return 0;
/*Ship s1("X-Wing", 250, 30, 180);
cout << s1.getShipInfo();*/
} | true |
1a47b1322881dbc92b19f02f8fa497e6079b0bd2 | C++ | mamunhpath/leet-code | /string-to-integer-atoi-2.cpp | UTF-8 | 763 | 3.28125 | 3 | [] | no_license | // https://leetcode.com/problems/string-to-integer-atoi/description/
class Solution {
public:
int myAtoi(string s) {
bool sign = false;
int i = 0, n = s.length();
int ans = 0;
while(i < n && (s[i] == ' '))
i++;
if (s[i] == '+' || s[i] == '-')
sign = s[i++] == '-';
while('0' <= s[i] && s[i] <= '9' && i < n){
int c = s[i++] - '0';
// check if addition of number will cause an overflow
if (INT_MAX / 10 < ans || (INT_MAX / 10 == ans && INT_MAX % 10 < c))
return sign ? INT_MIN : INT_MAX;
ans = ans * 10 + c;
}
return sign ? -ans : ans;
}
};
| true |
c111cabd8e9757ad78405f6479b74d1063ffc3c8 | C++ | lewicki-pk/one_program_a_day | /by_month/02-luty/lut05.cpp | UTF-8 | 1,759 | 3.6875 | 4 | [] | no_license | /*
* lut05.cpp
*
* Created on: Feb 5, 2016
* Author: lewiatan
*/
#include <algorithm>
#include <vector>
#include <list>
#include <iostream>
using namespace std;
template <typename T>
void DisplayContents (const T& Input)
{
for (auto iElement = Input.cbegin();
iElement != Input.cend();
++iElement) {
cout << *iElement << ' ';
}
cout << endl;
}
int main()
{
vector<int> vecIntegers;
for (int n = -9; n < 10; ++n) {
vecIntegers.push_back(n);
}
vecIntegers.push_back(9);
vecIntegers.push_back(9);
list<int> listIntegers;
for (int n = -4; n < 5; ++n) {
listIntegers.push_back(n);
}
cout << "The contents of the sample vector are: " << endl;
DisplayContents(vecIntegers);
cout << "The contents of the sample list are: " << endl;
DisplayContents(listIntegers);
cout << "search() for the contents of list in vector: " << endl;
auto iRange = search(vecIntegers.cbegin(),
vecIntegers.cend(),
listIntegers.cbegin(),
listIntegers.cend());
if (iRange != vecIntegers.cend()) {
cout << "Sequence in list found in vector at position "
<< distance(vecIntegers.cbegin(), iRange) << endl;
}
cout << "Searching {9,9,9} in vector using search_n(): " << endl;
auto iPartialRange = search_n(vecIntegers.cbegin(),
vecIntegers.cend(),
3,
9);
if (iPartialRange != vecIntegers.end()) {
cout << "Sequence {9,9,9} found in vector at position: "
<< distance(vecIntegers.cbegin(), iPartialRange);
}
return 0;
}
| true |
5e949729bead5ed01c82964d6d31c851c8de9f1b | C++ | su519/test | /week5.cpp | UTF-8 | 320 | 3.1875 | 3 | [] | no_license | #include <iostream>
using namespace std;
float product(float a, float b){
return a*b;
}
float _negate(float x){
return -x;
}
float negated_product(float a, float b){
return -(a*b);
}
int main(){
float x, y;
cin >> x >> y;
float neg_xy = negated_product(x,y);
cout << neg_xy;
}
float a = product(x,y);
| true |
acaaa1130bcfacfc4a2e4b7e59f23ae9603faffb | C++ | CarolineZhu/Leetcode | /leetcode105.cpp | UTF-8 | 829 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespaces std;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if (preorder.size() == 0) return NULL;
TreeNode* root = new TreeNode(preorder[0]);
if (preorder.size() == 1) return root;
int i;
for (i = 0; i < inorder.size(); i++) {
if (inorder[i] == preorder[0]) break;
}
vector<int> inLeftTree, inRightTree, preLeftTree, preRightTree;
inLeftTree.assign(inorder.begin(), inorder.begin() + i);
inRightTree.assign(inorder.begin() + i + 1, inorder.end());
preLeftTree.assign(preorder.begin() + 1, preorder.begin() + i + 1);
preRightTree.assign(preorder.begin() + i + 1, preorder.end());
root -> left = buildTree(preLeftTree, inLeftTree);
root -> right = buildTree(preRightTree, inRightTree);
return root;
} | true |
8eed6b1b9076ecfe2bf9b19b595dea304f3b9dff | C++ | Zilleplus/cpp_templates | /chapter19/elementtype.cpp | UTF-8 | 375 | 2.984375 | 3 | [] | no_license | #include"elementtype.hpp"
#include<vector>
#include<iostream>
#include<typeinfo>
template<typename T>
void printElementType (T const& c)
{
std::cout << "Container of "
<< typeid(typename ElementT<T>::Type).name()
<< " elements. \n";
}
int main()
{
std::vector<bool> s;
printElementType(s);
int arr[42];
printElementType(arr);
}
| true |
c539d2674cbdc39658425e0be0bf8e9f0b58a070 | C++ | yvomenezes/cpp_polytech | /td3/testComplexe.cpp | UTF-8 | 929 | 2.59375 | 3 | [] | no_license | #include "complexe.hpp"
#include <iostream>
int main(int argc, char const *argv[]) {
// Complexe c1(2.1,-6.7);
// Complexe c2;
// Complexe c1 = Complexe();
// Complexe c2 = Complexe(4.5);
// Complexe c3 = Complexe(3.2, 8.9);
Complexe c1;
Complexe c2(4, 5);
Complexe c3(3, 10);
Complexe c4(3,10);
// c1 = 3*Complexe::i;
bool b1,b2;
c1 = 4 + constComplexes::i*3;
c1.ecrireComplexe();
// c1 = c2.rho();
// c1 = Complexe::polComplexe(c3.rho(), c3.theta());
// std::cout << "Reelle: " << c3.getPreelle() << " Img: " << c3.getPimg() << std::endl;
// std::cout << "Reelle: " << c1.getPreelle() << " Img: " << c1.getPimg() << std::endl;
// std::cout << "Rho: " << c3.rho() << " Theta: " << c3.theta() << std::endl;
//c1.ecrireComplexe();
// b1 = c1.egal(c2);
// b2 = c3==c4;
// std::cout << b1 <<std::endl;
// std::cout << b2 << std::endl;
// Complexe::i.ecrireComplexe();
return 0;
}
| true |
8a58f7e173250fa8c38a022130feff2f15b06ae2 | C++ | haved/DafCompiler | /Old/OldCpp/Compiler/src/parsing/ast/Type.cpp | UTF-8 | 3,847 | 2.625 | 3 | [] | no_license | #include "parsing/ast/Type.hpp"
#include "parsing/semantic/ConcreteType.hpp"
#include "parsing/ast/FunctionSignature.hpp" //To get FunctionType
#include "parsing/lexing/Token.hpp"
#include "parsing/semantic/NamespaceStack.hpp"
#include "parsing/ast/Definition.hpp"
#include "parsing/ast/Expression.hpp"
#include "parsing/semantic/ConcretableHelp.hpp"
#include "DafLogger.hpp"
#include "CodegenLLVM.hpp"
#include <iostream>
#include <map>
#include <algorithm>
Type::Type(const TextRange& range) : m_range(range) {}
const TextRange& Type::getRange() {
return m_range;
}
ConcretableState Type::retryMakeConcreteInternal(DependencyMap& depMap) {
(void) depMap;
return ConcretableState::CONCRETE;
}
TypeReference::TypeReference() : m_type() {}
TypeReference::TypeReference(unique_ptr<Type>&& type) : m_type(std::move(type)) {}
void TypeReference::printSignature() const {
if(m_type) {
m_type->printSignature();
} else {
std::cout << "NULL_TYPE";
}
}
ConcreteType* TypeReference::getConcreteType() {
assert(m_type);
return m_type->getConcreteType();
}
AliasForType::AliasForType(std::string&& name, const TextRange& range) : Type(range), m_name(std::move(name)), m_target(nullptr) {}
void AliasForType::printSignature() {
std::cout << "type{\"" << m_name << "\"}";
}
ConcretableState AliasForType::makeConcreteInternal(NamespaceStack& ns_stack, DependencyMap& depMap) {
Definition* definition = ns_stack.getDefinitionFromName(m_name, getRange()); //Errors if not present
if(!definition)
return ConcretableState::LOST_CAUSE;
DefinitionKind kind = definition->getDefinitionKind();
if(kind != DefinitionKind::TYPEDEF) {
auto& out = logDaf(getRange(), ERROR) << "expected typedef; " << m_name << " is a ";
printDefinitionKindName(kind, out) << std::endl;
return ConcretableState::LOST_CAUSE;
}
m_target = static_cast<TypedefDefinition*>(definition);
ConcretableState state = m_target->getConcretableState();
if(allConcrete() << state)
return retryMakeConcreteInternal(depMap);
if(anyLost() << state)
return ConcretableState::LOST_CAUSE;
depMap.makeFirstDependentOnSecond(this, m_target);
return ConcretableState::TRY_LATER;
}
ConcreteType* AliasForType::getConcreteType() {
return m_target->getConcreteType();
}
PointerType::PointerType(bool mut, TypeReference&& targetType, const TextRange& range) : Type(range), m_mut(mut), m_targetType(std::move(targetType)), m_concreteType() {
assert(m_targetType);
}
void PointerType::printSignature() {
auto& out = std::cout << "&";
if(m_mut)
out << "mut";
out << " ";
m_targetType.printSignature();
}
ConcretableState PointerType::makeConcreteInternal(NamespaceStack& ns_stack, DependencyMap& depMap) {
ConcretableState state = m_targetType.getType()->makeConcrete(ns_stack, depMap);
if(allConcrete() << state)
return retryMakeConcreteInternal(depMap);
if(anyLost() << state)
return ConcretableState::LOST_CAUSE;
depMap.makeFirstDependentOnSecond(this, m_targetType.getType());
return ConcretableState::TRY_LATER;
}
ConcretableState PointerType::retryMakeConcreteInternal(DependencyMap& depMap) {
(void) depMap;
ConcreteType* concreteTarget = m_targetType.getConcreteType();
assert(concreteTarget);
m_concreteType = ConcretePointerType::toConcreteType(m_mut, concreteTarget);
return ConcretableState::CONCRETE;
}
ConcreteType* PointerType::getConcreteType() {
return m_concreteType;
}
ConcreteTypeUse::ConcreteTypeUse(ConcreteType* type, const TextRange& range) : Type(range), m_type(type) {
assert(m_type);
}
void ConcreteTypeUse::printSignature() {
m_type->printSignature();
}
ConcretableState ConcreteTypeUse::makeConcreteInternal(NamespaceStack& ns_stack, DependencyMap& depMap) {
(void) ns_stack, (void) depMap;
return ConcretableState::CONCRETE;
}
ConcreteType* ConcreteTypeUse::getConcreteType() {
return m_type;
}
| true |
caf18d755e2ee52cc518e45328db8b30873fdb13 | C++ | deadelus/Chess | /include/Echiquier.h | UTF-8 | 915 | 2.71875 | 3 | [
"Unlicense"
] | permissive | #ifndef ECHIQUIER_H
#define ECHIQUIER_H
#include <vector>
#include "Pieces.h"
//#include <memory>
//#include <array>
class Echiquier
{
public:
Echiquier();
virtual ~Echiquier();
void placerPiece(Piece *p);
bool deplacerPiece(Piece *p, int oldX, int oldY);
void addPiece(Piece *p);//AJOUTE UNE PIECE SUR L'ECHIQUIER
void delPiece(Piece *p);//ENLEVE UNE PIECE DE L'ECHIQUIER
bool coordIsValid(int x, int y);
bool coordIsFreeToKing(int x, int y);
bool coordIsFree(int x, int y);
bool comparerPiece(Piece &p, int x, int y);
Piece* getPieces();
Piece* getPiece(int x, int y);
void toString();
protected:
private:
//std::array<std::array<std::unique_ptr<Piece>,8>,8> echiquier;
//std::array<std::array<Piece*,8>,8> echiquier;
Piece *echiquier[8][8];
};
#endif // ECHIQUIER_H
| true |
51397071ef20f16f7869866347111905d92fb922 | C++ | positoy/study-cpp | /cpp/chap04.cpp.reference와const.cpp | UTF-8 | 5,496 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include "include/util.hpp"
class MousePoint {
private:
int x,y;
public:
void setx(int x) { this->x=x; }
void sety(int y) { this->y=y; }
int getx() { return x; }
int gety() { return y; }
void setxy(int x, int y) { this->x=x, this->y=y; }
void print();
void nothing() const {}
MousePoint(int x, int y) { setxy(x,y); }
MousePoint(){}
};
void MousePoint::print() {
std::cout << x << ", " << y << std::endl;
}
class Rect {
private:
MousePoint rectPoint[2];
public:
Rect(MousePoint p1, MousePoint p2) { this->rectPoint[0] = p1, this->rectPoint[1] = p2; }
void print();
};
void Rect::print() {
std::cout << "p1: " << this->rectPoint[0].getx() << ", " << this->rectPoint[0].gety() << std::endl;
std::cout << "p2: " << this->rectPoint[1].getx() << ", " << this->rectPoint[1].gety() << std::endl;
}
void setZeroPointToMousePointByValue(MousePoint mp) {
mp.setxy(0,0);
}
void setZeroPointToMousePointByReference(MousePoint &mp) {
mp.setxy(0,0);
}
MousePoint& setMousePointWithAnother(MousePoint& mp1, MousePoint mp2) {
mp1 = mp2;
return mp1;
}
class ClassForConstKeyword {
private:
int x,y;
public:
ClassForConstKeyword() : x(100), y(200) {}
void setMemberVariablesZero();
// void setMemberVariablesZero() const;
void printMemberVariables() const;
};
void ClassForConstKeyword::setMemberVariablesZero() {
this->x=0, this->y=0;
}
void ClassForConstKeyword::printMemberVariables() const {
std::cout << "x: " << this->x << std::endl
<< "y: " << this->y << std::endl;
}
int main()
{
// 객체배열 생성과 초기화
MousePoint mpArr[3] = { MousePoint(10,20), MousePoint(100,200), MousePoint(1000,2000) };
for (int a=0; a<3; a++) mpArr[a].print();
// 객체포인터
MousePoint *mpPtr = &mpArr[0];
mpPtr->print();
MousePoint *mpPtr2 = new MousePoint(1,2);
mpPtr2->print();
// this 포인터
// 객체는 멤버변수의 블록은 별도로 갖고 멤버함수의 메모리 블록은 공유한다
// 멤버함수의 입장에서 내부적으로 멤버변수를 사용하면 어느 객체의 멤버변수인지 알 수 없기 때문에
// this 포인터로 멤버변수를 호출한 객체가 특정되어야 한다.
// 그런데, 정말? 나는 각 객체가 static 으로 선언 된 멤버함수만 공유하는 건 줄 알았는데?
// 아니네. print 내부의 static count 변수가 각 객체에서 호출할 때마다 차례로 증가함
for (int a=0; a<3; a++) mpArr[a].print();
Util::setBigTitle("SET BY VALUE vs SET BY REFERENCE");
// 전달인자가 개체인 함수
// ** 기본 자료형의 값 전달
// mpPtr->setxy(a,b); - a,b는 실매개변수
// MousePoint::setxy(int na, int nb) { ... } - na,nb는 형식매개변수
// 실매개변수와 형식매개변수는 각자의 메모리에 존재한다
// 객체에 대한 값 전달 방식
// ** MousePoint에 기본생성자가 없으면 아래 객체 생성은 오류가 발생한다.
MousePoint mp1(10,10), mp2(20,20);
Rect r2(mp1, mp2);
r2.print();
// ** MousePoint에 기본생성자가 없으면 아래 객체 생성은 오류가 발생한다.
Rect r(MousePoint(10,10), MousePoint(20,20));
r.print();
// 값에 의한 전달
setZeroPointToMousePointByValue(mp1);
mp1.print();
// 레퍼런스 전달
setZeroPointToMousePointByReference(mp1);
mp1.print();
// 객체복사 레퍼런스 사용!!!
// 객체간의 복사 (멤버변수가 복사 된다)
mp1.setxy(123,123);
mp2.setxy(456,456);
mp1 = mp2;
mp1.print();
// 객체간의 복사 함수
// by reference 를 사용하지 않으면 복사되지 않는다
mp1.setxy(123,123);
mp2.setxy(456,456);
setMousePointWithAnother(mp1, mp2); // MousePoint &mp1 = mp1, MousePoint &mp2 = mp2;
// reference는 변수 명은 두개지만 결국 같은 메모리주소를 공유한다
// 프로토타입이 setMousePointWithAnother(MousePoint mp1, MousePoint mp2) 라면 정상 복사되지 않는다
mp1.print();
mp1 = setMousePointWithAnother(mp1 ,mp2); // 리턴타입 MousePoint - 리턴할 때 새로운 메모리 생성
mp2 = setMousePointWithAnother(mp1, mp2); // 리턴타입 MousePoint& - 기존의 메모리 공간 반환하므로 공간,시간 절약
Util::setBigTitle("const Member Function and const Object");
// 1. const 멤버함수
// 멤버함수에 const 키워드를 사용해서 명시적으로 동작의 영향범위를 보여줄 수 있고 컴파일 단계에서 실수를 방지 할 수 있다.
// constructor, destructor 는 언제나 멤버변수에 접근하므로 const 를 사용할 수 없다
ClassForConstKeyword cfck;
cfck.setMemberVariablesZero();
cfck.printMemberVariables();
// const 객체
const MousePoint pt1(100,200);
MousePoint pt2(1000,2000);
// pt1 = pt2; 컴파일에러발생
// pt1.setxy(1,2); 컴파일에러발생
// const 객체는 '명시적인' const 멤버함수만 사용할 수 있다.
// pt1.print(); print 함수가 멤버변수를 조작하지 않음에도 불구하고 컴파일에러 발생
// const 함수를 선언했는데 그 함수에 const 멤버함수가 없으면 무용지물이 된다.
pt1.nothing();
}
| true |
911078330f94abf31897b6b11a256b3a677f5bc9 | C++ | rajulrs13/SPOJ | /EDIST_6219.cpp | UTF-8 | 1,134 | 3.078125 | 3 | [] | no_license | // Rajul Saxena
// rajulrs13@gmail.com
#include <string.h>
#include <iostream>
using namespace std;
char from[2001];
char to[2001];
int dp_mat[2001][2001];
int main() {
int t;
cin >> t;
while (t) {
cin >> from;
cin >> to;
int i, j;
int n = strlen(from);
int m = strlen(to);
// Initial setting of matrix
for (i = 0; i <= n; i++) {
dp_mat[i][0] = i;
}
for (j = 1; j <= m; j++) {
dp_mat[0][j] = j;
}
// DP Matrix Filling
int q1, q2, q3;
for (i = 1; i <= n; i++) {
for (j = 1; j <= m; j++) {
// Adding 1 only when replacement
q1 = ((from[i - 1] == to[j - 1]) ? 0 : 1) + dp_mat[i - 1][j - 1];
// Adding 1 only when inssertion
q2 = dp_mat[i][j - 1] + 1;
// Adding 1 only when deletion
q3 = dp_mat[i - 1][j] + 1;
// Minimum function implementation
int val = 0;
if (q1 < q2 && q1 < q3)
val = q1;
else {
if (q2 < q3)
val = q2;
else
val = q3;
}
dp_mat[i][j] = val;
}
}
cout << dp_mat[n][m] << endl;
t--;
}
} | true |
5875a47ea80ca206b252f1880b8920347bdf8219 | C++ | CESARIUX2596/cpp-crash-course | /Tetris/tetris.cpp | UTF-8 | 2,730 | 2.90625 | 3 | [] | no_license | /*
Tutorial From:
javidx9
https://www.youtube.com/watch?v=8OK8_tHeCIA
*/
#include <iostream>
#include <thread>
#include <vector>
using namespace std;
#include <stdio.h>
wstring tetromino[7];
int nFieldWidth = 12;
int nFieldHeigh = 18;
unsigned char *pField = nullptr;
int nScreenWidth = 80; // Console Size X (Col)
int nScreenHeigh = 30; // Console Size Y (Row)
int Rotate(int px, int py, int r)
{
switch (r % 4)
{
case 0:
return py * 4 + px; // 0 degrees
case 1:
return 12 + py - (px * 4); // 90 degrees
case 2:
return 15 - (py * 4) - px; // 180 degrees
case 3:
return 3 - py + (px * 4); // 270 degrees
}
return 0;
}
int main()
{
// Creating assets
tetromino[0].append(L"..X.");
tetromino[0].append(L"..X.");
tetromino[0].append(L"..X.");
tetromino[0].append(L"..X.");
tetromino[1].append(L"..X.");
tetromino[1].append(L".XX.");
tetromino[1].append(L".X..");
tetromino[1].append(L"....");
tetromino[2].append(L".X..");
tetromino[2].append(L".XX.");
tetromino[2].append(L"..X.");
tetromino[2].append(L"....");
tetromino[3].append(L"....");
tetromino[3].append(L".XX.");
tetromino[3].append(L".XX.");
tetromino[3].append(L"....");
tetromino[4].append(L"..x.");
tetromino[4].append(L".XX.");
tetromino[4].append(L"..X.");
tetromino[4].append(L"....");
tetromino[5].append(L"....");
tetromino[5].append(L".XX.");
tetromino[5].append(L"..X.");
tetromino[5].append(L"..X.");
tetromino[6].append(L"....");
tetromino[6].append(L".XX.");
tetromino[6].append(L".X..");
tetromino[6].append(L".X..");
pField = new unsigned char[nFieldWidth * nFieldHeigh];
for (int x = 0; x < nFieldWidth; x++)
for (int y = 0; y < nFieldHeigh; y++)
pField[y * nFieldWidth + x] = (x == 0 || x == nFieldWidth - 1 || y == nFieldHeigh - 1) ? 9 : 0;
wchar_t *screen = new wchar_t[nScreenWidth * nScreenHeigh];
for (int i = 0; i < nScreenWidth * nScreenHeigh; i++)
screen[i] = L' ';
HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
SetConsoleActiveScreenBuffer(hConsole);
DWORD dwBytesWritten = 0;
bool bGameOver = false;
while (!bGameOver)
{
// Draw Field
for (int x = 0; x < nFieldWidth; x++)
for (int y = 0; y < nFieldHeigh; y++)
screen[(y + 2) * nScreenWidth + (x + 2)] = L" ABCDEFG=#"[pField[y * nFieldWidth + x]];
// Display Frame
WriteConsoleOutputCharacter(hConsole, screen, nScreenWidth * nScreenHeigh, {0, 0}, &dwBytesWritten);
}
return 0;
}
| true |
7415713bb4391dde706590967502b9eb99c2d49c | C++ | ewanbarr/peasoup | /include/transforms/peakfinder.hpp | UTF-8 | 2,827 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <iostream>
#include "data_types/candidates.hpp"
#include "data_types/fourierseries.hpp"
#include "kernels/kernels.h"
#include <thrust/device_vector.h>
#include "utils/utils.hpp"
#include <cmath>
#include <algorithm>
class PeakFinder {
private:
float threshold; //Sigma threshold
float min_freq;
float max_freq;
int min_gap; //The minimum gap between adjacent peaks such that the are considered unique
unsigned int max_cands; //This value is hardcoded (could cause segfault)
std::vector<int> idxs;
std::vector<float> snrs;
std::vector<int> peakidxs;
std::vector<float> peaksnrs;
std::vector<float> peakfreqs;
thrust::device_vector<int> d_idxs;
thrust::device_vector<float> d_snrs;
cached_allocator allocator;
int identify_unique_peaks(unsigned int count)
{
int ii;
float cpeak;
int cpeakidx;
int lastidx= -1 * min_gap;
int npeaks=0;
ii=0;
while (ii<count){
cpeak=snrs[ii];
cpeakidx=idxs[ii];
lastidx=idxs[ii];
ii++;
while (ii<count && (idxs[ii]-lastidx) < min_gap){
if (snrs[ii]>cpeak)
{
cpeak=snrs[ii];
cpeakidx=idxs[ii];
lastidx=idxs[ii];
}
ii++;
}
peakidxs[npeaks]=cpeakidx;
peaksnrs[npeaks]=cpeak;
npeaks++;
}
return npeaks;
}
public:
PeakFinder(float threshold, float min_freq, float max_freq, unsigned int size, int min_gap=30)
:threshold(threshold), min_freq(min_freq),
max_freq(max_freq),min_gap(min_gap),max_cands(100000)
{
idxs.resize(max_cands);
snrs.resize(max_cands);
peakidxs.resize(max_cands);
peaksnrs.resize(max_cands);
peakfreqs.resize(max_cands);
d_idxs.resize(size);
d_snrs.resize(size);
}
void find_candidates(HarmonicSums<float>& sums, SpectrumCandidates& cands){
for (int ii=0;ii<sums.size();ii++)
find_candidates(*sums[ii],cands);
}
void find_candidates(DevicePowerSpectrum<float>& pspec, SpectrumCandidates& cands){
int size = pspec.get_nbins();
float nyquist = pspec.get_bin_width()*size;
int orig_size = 2.0*(size-1.0);
int nh = pspec.get_nh();
int max_bin = (int)((max_freq/pspec.get_bin_width())*pow(2.0,nh));
int start_idx = (int)(orig_size*(min_freq/nyquist)*pow(2.0,nh));
int count = device_find_peaks(std::min(size,max_bin),
start_idx, pspec.get_data(),
threshold, &idxs[0], &snrs[0],
d_idxs,d_snrs,allocator);
int npeaks = identify_unique_peaks(count);
float factor = 1.0/size*nyquist/pow(2.0,(float)nh);
for (int ii=0;ii<npeaks;ii++){
peakfreqs[ii] = peakidxs[ii]*factor;
}
cands.append(&peaksnrs[0],&peakfreqs[0],nh,npeaks);
}
};
| true |
68d8367d2a4c619373179c92a1b8fb2cf0a05a2b | C++ | smileszhang/674datastructure | /674homework2/674homework2/Data.h | UTF-8 | 286 | 2.625 | 3 | [] | no_license | #pragma once
#include<iostream>
#include<vector>
using namespace std;
class Data
{
public:
int key;
int value;
void swap(vector<Data> v, int i, int j);
int leftChild(int i);
int rightChild(int i);
int parent(int i);
bool comp(vector<Data> v, int i, int j);
}; | true |
4d47005061a8bd1e1c1083166ff99d1779cb591f | C++ | MD-Mahbub-Ul-Haque/NSU_CSE_250 | /stacktype08/main.cpp | UTF-8 | 2,550 | 3.515625 | 4 | [] | no_license | #include <bits/stdc++.h>
#include "stacktype.cpp"
using namespace std;
bool IsOperator(char c){
if(c == '+' || c == '-' || c == '*' || c == '/')
return 1;
else
return 0;
}
int prefarance(char ope){
int val = 0;
if(ope == '+' || ope == '-')
val = 1;
if (ope == '*' || ope == '/')
val = 2;
return val;
}
bool check_prefarance(char op1, char op2){
int r = prefarance(op1);
int q = prefarance(op2);
if(r>q || r==q)
return 1;
else
return 0;
}
string convert(string infix){
StackType <char> S;
string postfix ="";
char ch;
S.Push('(');
infix += ')';
for(int i = 0; i<infix.length(); i++){
ch = infix[i];
if(ch==' ')
continue;
else if(ch == '(')
S.Push(ch);
else if(isdigit(infix[i])){
postfix += ch;
int j=i;
if(j < infix.length()){
if(!isdigit(infix[j+1]))
postfix += " ";
}
}
else if(IsOperator(ch)){
while(!S.IsEmpty() && check_prefarance(S.Top(), ch)){
postfix += S.Top();
S.Pop();
}
S.Push(ch);
postfix += " ";
}
else if(ch == ')'){
while(!S.IsEmpty() && S.Top() != '('){
postfix += S.Top();
S.Pop();
}
S.Pop();
}
}
return postfix;
}
int main()
{
string str, str1;
double ans;
cin>>str;
str1 = convert(str);
StackType <double> st;
for(int i=0; i<str1.length(); i++){
double num=0;
if(str1[i]==' ')
continue;
else if(isdigit(str1[i])){
while(str1[i] != ' ' && isdigit(str1[i])){
num *= 10;
num += (double)(str1[i++]-'0');
}
st.Push(num);
}
else if(IsOperator(str1[i])){
int a = st.Top();
st.Pop();
int b = st.Top();
st.Pop();
char ch = str1[i];
double n;
if(ch=='+')
n = a+b;
else if(ch=='-')
n = b-a;
else if(ch=='*')
n = a*b*1;
else if(ch=='/')
n = b/a*1;
st.Push(n);
}
}
ans = st.Top();
st.Pop();
if(st.IsEmpty())
printf("%.2f\n",ans);
else
cout<<"Invalid Expression"<<endl;
return 0;
}
| true |
0f3c81ef6f4ebaf5351db0ede75e6b709e7ff844 | C++ | menegais1/VulkanRenderer | /src/Refactoring/CreateInfoHelpers.h | UTF-8 | 46,768 | 2.546875 | 3 | [] | no_license | //
// Created by menegais on 16/01/2021.
//
#ifndef VULKANBASE_CREATEINFOHELPERS_H
#define VULKANBASE_CREATEINFOHELPERS_H
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <vector>
#include <iostream>
namespace vk {
inline VkBufferCreateInfo bufferCreateInfo(VkDeviceSize size, const std::vector<uint32_t> &queueFamilyIndices,
VkBufferUsageFlags usage, VkSharingMode sharingMode, VkBufferCreateFlags flags) {
VkBufferCreateInfo vkBufferCreateInfo{};
vkBufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
vkBufferCreateInfo.size = size;
vkBufferCreateInfo.pQueueFamilyIndices = queueFamilyIndices.data();
vkBufferCreateInfo.queueFamilyIndexCount = queueFamilyIndices.size();
vkBufferCreateInfo.usage = usage;
vkBufferCreateInfo.sharingMode = sharingMode;
vkBufferCreateInfo.flags = flags;
return vkBufferCreateInfo;
}
inline VkMemoryAllocateInfo memoryAllocateInfo(VkDeviceSize allocationSize, uint32_t memoryTypeIndex) {
VkMemoryAllocateInfo vkMemoryAllocateInfo{};
vkMemoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
vkMemoryAllocateInfo.allocationSize = allocationSize;
vkMemoryAllocateInfo.memoryTypeIndex = memoryTypeIndex;
return vkMemoryAllocateInfo;
}
inline VkMappedMemoryRange mappedMemoryRange(VkDeviceMemory memory, VkDeviceSize offset, VkDeviceSize size) {
VkMappedMemoryRange vkMappedMemoryRange{};
vkMappedMemoryRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
vkMappedMemoryRange.memory = memory;
vkMappedMemoryRange.offset = offset;
vkMappedMemoryRange.size = size;
return vkMappedMemoryRange;
}
inline VkInstanceCreateInfo instanceCreateInfo(const std::vector<const char *> &extensions, const std::vector<const char *> &layers, VkApplicationInfo *applicationInfo) {
VkInstanceCreateInfo vkInstanceCreateInfo{};
vkInstanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
vkInstanceCreateInfo.enabledExtensionCount = extensions.size();
vkInstanceCreateInfo.ppEnabledExtensionNames = extensions.data();
vkInstanceCreateInfo.enabledLayerCount = layers.size();
vkInstanceCreateInfo.ppEnabledLayerNames = layers.data();
vkInstanceCreateInfo.pApplicationInfo = applicationInfo;
vkInstanceCreateInfo.flags = 0;
return vkInstanceCreateInfo;
}
inline VkApplicationInfo applicationInfo(uint32_t apiVersion, uint32_t engineVersion, uint32_t applicationVersion, const char *engineName, const char *applicationName) {
VkApplicationInfo vkApplicationInfo{};
vkApplicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
vkApplicationInfo.apiVersion = apiVersion;
vkApplicationInfo.pApplicationName = applicationName;
vkApplicationInfo.pEngineName = engineName;
vkApplicationInfo.applicationVersion = applicationVersion;
vkApplicationInfo.engineVersion = engineVersion;
return vkApplicationInfo;
}
inline VkDeviceCreateInfo
deviceCreateInfo(const std::vector<const char *> &extensions, const std::vector<const char *> &layers,
const std::vector<VkPhysicalDeviceFeatures> &features, const std::vector<VkDeviceQueueCreateInfo> &queuesCreateInfo) {
VkDeviceCreateInfo vkDeviceCreateInfo{};
vkDeviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
vkDeviceCreateInfo.enabledExtensionCount = extensions.size();
vkDeviceCreateInfo.ppEnabledExtensionNames = extensions.data();
vkDeviceCreateInfo.enabledLayerCount = layers.size();
vkDeviceCreateInfo.ppEnabledLayerNames = layers.data();
vkDeviceCreateInfo.pEnabledFeatures = features.data();
vkDeviceCreateInfo.queueCreateInfoCount = queuesCreateInfo.size();
vkDeviceCreateInfo.pQueueCreateInfos = queuesCreateInfo.data();
return vkDeviceCreateInfo;
}
inline VkDeviceQueueCreateInfo queueCreateInfo(uint32_t queueFamilyIndex, uint32_t queueCount, const float *queuePriorites) {
VkDeviceQueueCreateInfo vkDeviceQueueCreateInfo{};
vkDeviceQueueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
vkDeviceQueueCreateInfo.queueFamilyIndex = queueFamilyIndex;
vkDeviceQueueCreateInfo.queueCount = queueCount;
vkDeviceQueueCreateInfo.pQueuePriorities = queuePriorites;
return vkDeviceQueueCreateInfo;
}
inline VkSwapchainCreateInfoKHR swapchainCreateInfoKhr(VkSurfaceKHR surface, VkPresentModeKHR presentMode,
VkFormat imageFormat, VkColorSpaceKHR imageColorSpace,
uint32_t minImageCount, VkExtent2D imageExtent, const std::vector<uint32_t> &queueFamilyIndices) {
VkSwapchainCreateInfoKHR vkSwapchainCreateInfoKhr{};
vkSwapchainCreateInfoKhr.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
vkSwapchainCreateInfoKhr.oldSwapchain = VK_NULL_HANDLE;
vkSwapchainCreateInfoKhr.surface = surface;
vkSwapchainCreateInfoKhr.presentMode = presentMode;
vkSwapchainCreateInfoKhr.imageFormat = imageFormat;
vkSwapchainCreateInfoKhr.imageColorSpace = imageColorSpace;
vkSwapchainCreateInfoKhr.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
vkSwapchainCreateInfoKhr.minImageCount = minImageCount;
vkSwapchainCreateInfoKhr.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
vkSwapchainCreateInfoKhr.imageArrayLayers = 1;
vkSwapchainCreateInfoKhr.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
vkSwapchainCreateInfoKhr.clipped = VK_TRUE;
vkSwapchainCreateInfoKhr.imageExtent = imageExtent;
vkSwapchainCreateInfoKhr.queueFamilyIndexCount = queueFamilyIndices.size();
vkSwapchainCreateInfoKhr.pQueueFamilyIndices = queueFamilyIndices.data();
vkSwapchainCreateInfoKhr.imageSharingMode = queueFamilyIndices.size() == 1 ? VK_SHARING_MODE_EXCLUSIVE : VK_SHARING_MODE_CONCURRENT;
return vkSwapchainCreateInfoKhr;
}
inline VkSemaphoreCreateInfo semaphoreCreateInfo() {
VkSemaphoreCreateInfo vkSemaphoreCreateInfo{};
vkSemaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
return vkSemaphoreCreateInfo;
}
inline VkFenceCreateInfo fenceCreateInfo(VkFenceCreateFlags flags) {
VkFenceCreateInfo vkFenceCreateInfo{};
vkFenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
vkFenceCreateInfo.flags = flags;
return vkFenceCreateInfo;
}
inline VkVertexInputBindingDescription vertexInputBindingDescription(uint32_t binding, uint32_t stride, VkVertexInputRate inputRate) {
VkVertexInputBindingDescription vkVertexInputBindingDescription{};
vkVertexInputBindingDescription.binding = binding;
vkVertexInputBindingDescription.stride = stride;
vkVertexInputBindingDescription.inputRate = inputRate;
return vkVertexInputBindingDescription;
}
inline VkVertexInputAttributeDescription vertexInputAttributeDescription(uint32_t binding, VkFormat format, uint32_t location, uint32_t offset) {
VkVertexInputAttributeDescription vkVertexInputAttributeDescription{};
vkVertexInputAttributeDescription.binding = binding;
vkVertexInputAttributeDescription.format = format;
vkVertexInputAttributeDescription.location = location;
vkVertexInputAttributeDescription.offset = offset;
return vkVertexInputAttributeDescription;
}
inline VkPipelineInputAssemblyStateCreateInfo pipelineInputAssemblyStateCreateInfo(VkPrimitiveTopology topology, VkBool32 primitiveRestartEnable) {
VkPipelineInputAssemblyStateCreateInfo vkPipelineInputAssemblyStateCreateInfo{};
vkPipelineInputAssemblyStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
vkPipelineInputAssemblyStateCreateInfo.topology = topology;
vkPipelineInputAssemblyStateCreateInfo.primitiveRestartEnable = primitiveRestartEnable;
return vkPipelineInputAssemblyStateCreateInfo;
}
inline VkPipelineVertexInputStateCreateInfo
pipelineVertexInputStateCreateInfo(const std::vector<VkVertexInputBindingDescription> &vertexAttributeBindingDescriptions, const std::vector<VkVertexInputAttributeDescription> &vertexAttributeDescriptions) {
VkPipelineVertexInputStateCreateInfo vkPipelineVertexInputStateCreateInfo{};
vkPipelineVertexInputStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vkPipelineVertexInputStateCreateInfo.vertexBindingDescriptionCount = vertexAttributeBindingDescriptions.size();
vkPipelineVertexInputStateCreateInfo.pVertexAttributeDescriptions = vertexAttributeDescriptions.data();
vkPipelineVertexInputStateCreateInfo.vertexAttributeDescriptionCount = vertexAttributeDescriptions.size();
vkPipelineVertexInputStateCreateInfo.pVertexBindingDescriptions = vertexAttributeBindingDescriptions.data();
return vkPipelineVertexInputStateCreateInfo;
}
inline VkPipelineTessellationStateCreateInfo pipelineTessellationStateCreateInfo(uint32_t patchControlPoints) {
VkPipelineTessellationStateCreateInfo vkPipelineTessellationStateCreateInfo{};
vkPipelineTessellationStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO;
vkPipelineTessellationStateCreateInfo.patchControlPoints = patchControlPoints;
return vkPipelineTessellationStateCreateInfo;
}
inline VkViewport viewport(float x, float y, float width, float height, float minDepth, float maxDepth) {
VkViewport vkViewport{};
vkViewport.x = x;
vkViewport.y = y;
vkViewport.width = width;
vkViewport.height = height;
vkViewport.minDepth = minDepth;
vkViewport.maxDepth = maxDepth;
return vkViewport;
}
inline VkRect2D rect2D(VkExtent2D extent, VkOffset2D offset) {
VkRect2D vkRect2D{};
vkRect2D.extent = extent;
vkRect2D.offset = offset;
return vkRect2D;
}
inline VkExtent2D extent2D(uint32_t width, uint32_t height) {
VkExtent2D vkExtent2D{};
vkExtent2D.width = width;
vkExtent2D.height = height;
return vkExtent2D;
}
inline VkExtent3D extent3D(uint32_t width, uint32_t height, uint32_t depth) {
VkExtent3D vkExtent3D{};
vkExtent3D.width = width;
vkExtent3D.height = height;
vkExtent3D.depth = depth;
return vkExtent3D;
}
inline VkOffset2D offset2D(int32_t x, int32_t y) {
VkOffset2D vkOffset2D{};
vkOffset2D.x = x;
vkOffset2D.y = y;
return vkOffset2D;
}
inline VkOffset3D offset3D(int32_t x, int32_t y, int32_t z) {
VkOffset3D vkOffset3D{};
vkOffset3D.x = x;
vkOffset3D.y = y;
vkOffset3D.z = z;
return vkOffset3D;
}
inline VkPipelineViewportStateCreateInfo pipelineViewportStateCreateInfo(const std::vector<VkViewport> &viewports, const std::vector<VkRect2D> &scissors) {
VkPipelineViewportStateCreateInfo vkPipelineViewportStateCreateInfo{};
vkPipelineViewportStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
vkPipelineViewportStateCreateInfo.scissorCount = scissors.size();
vkPipelineViewportStateCreateInfo.pScissors = scissors.data();
vkPipelineViewportStateCreateInfo.viewportCount = viewports.size();
vkPipelineViewportStateCreateInfo.pViewports = viewports.data();
return vkPipelineViewportStateCreateInfo;
}
inline VkPipelineRasterizationStateCreateInfo pipelineRasterizationStateCreateInfo(VkPolygonMode polygonMode, VkCullModeFlags cullMode, VkFrontFace frontFace, float lineWidth) {
VkPipelineRasterizationStateCreateInfo vkPipelineRasterizationStateCreateInfo{};
vkPipelineRasterizationStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
vkPipelineRasterizationStateCreateInfo.depthClampEnable = VK_FALSE;
vkPipelineRasterizationStateCreateInfo.rasterizerDiscardEnable = VK_FALSE;
vkPipelineRasterizationStateCreateInfo.depthBiasEnable = VK_FALSE;
vkPipelineRasterizationStateCreateInfo.depthBiasClamp = 0;
vkPipelineRasterizationStateCreateInfo.depthBiasConstantFactor = 0;
vkPipelineRasterizationStateCreateInfo.depthBiasSlopeFactor = 0;
vkPipelineRasterizationStateCreateInfo.frontFace = frontFace;
vkPipelineRasterizationStateCreateInfo.cullMode = cullMode;
vkPipelineRasterizationStateCreateInfo.polygonMode = polygonMode;
vkPipelineRasterizationStateCreateInfo.lineWidth = lineWidth;
return vkPipelineRasterizationStateCreateInfo;
}
inline VkPipelineMultisampleStateCreateInfo pipelineMultisampleStateCreateInfo(VkSampleCountFlagBits rasterizationSamples, VkBool32 sampleShadingEnable,
float minSampleShading, const VkSampleMask *pSampleMask,
VkBool32 alphaToCoverageEnable, VkBool32 alphaToOneEnable) {
VkPipelineMultisampleStateCreateInfo vkPipelineMultisampleStateCreateInfo{};
vkPipelineMultisampleStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
vkPipelineMultisampleStateCreateInfo.sampleShadingEnable = sampleShadingEnable;
vkPipelineMultisampleStateCreateInfo.rasterizationSamples = rasterizationSamples;
vkPipelineMultisampleStateCreateInfo.minSampleShading = minSampleShading;
vkPipelineMultisampleStateCreateInfo.pSampleMask = pSampleMask;
vkPipelineMultisampleStateCreateInfo.alphaToCoverageEnable = alphaToCoverageEnable;
vkPipelineMultisampleStateCreateInfo.alphaToOneEnable = alphaToOneEnable;
return vkPipelineMultisampleStateCreateInfo;
}
inline VkPipelineMultisampleStateCreateInfo pipelineMultisampleStateCreateInfo() {
VkPipelineMultisampleStateCreateInfo vkPipelineMultisampleStateCreateInfo{};
vkPipelineMultisampleStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
return vkPipelineMultisampleStateCreateInfo;
}
inline VkPipelineColorBlendStateCreateInfo pipelineColorBlendStateCreateInfo(const std::vector<VkPipelineColorBlendAttachmentState> &attachments, float blendConstants[4],
VkBool32 logicOpEnable, VkLogicOp logicOp) {
VkPipelineColorBlendStateCreateInfo vkPipelineColorBlendStateCreateInfo{};
vkPipelineColorBlendStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
vkPipelineColorBlendStateCreateInfo.attachmentCount = attachments.size();
vkPipelineColorBlendStateCreateInfo.pAttachments = attachments.data();
vkPipelineColorBlendStateCreateInfo.blendConstants[0] = blendConstants[0];
vkPipelineColorBlendStateCreateInfo.blendConstants[1] = blendConstants[1];
vkPipelineColorBlendStateCreateInfo.blendConstants[2] = blendConstants[2];
vkPipelineColorBlendStateCreateInfo.blendConstants[3] = blendConstants[3];
vkPipelineColorBlendStateCreateInfo.logicOpEnable = logicOpEnable;
vkPipelineColorBlendStateCreateInfo.logicOp = logicOp;
return vkPipelineColorBlendStateCreateInfo;
}
inline VkPipelineColorBlendAttachmentState pipelineColorBlendAttachmentState(VkBool32 blendEnable, VkBlendFactor srcColorBlendFactor, VkBlendFactor dstColorBlendFactor,
VkBlendOp colorBlendOp, VkBlendFactor srcAlphaBlendFactor,
VkBlendFactor dstAlphaBlendFactor,
VkBlendOp alphaBlendOp,
VkColorComponentFlags colorWriteMask) {
VkPipelineColorBlendAttachmentState vkPipelineColorBlendAttachmentState{};
vkPipelineColorBlendAttachmentState.blendEnable = blendEnable;
vkPipelineColorBlendAttachmentState.alphaBlendOp = alphaBlendOp;
vkPipelineColorBlendAttachmentState.colorBlendOp = colorBlendOp;
vkPipelineColorBlendAttachmentState.colorWriteMask = colorWriteMask;
vkPipelineColorBlendAttachmentState.dstAlphaBlendFactor = dstAlphaBlendFactor;
vkPipelineColorBlendAttachmentState.srcAlphaBlendFactor = srcAlphaBlendFactor;
vkPipelineColorBlendAttachmentState.dstColorBlendFactor = dstColorBlendFactor;
vkPipelineColorBlendAttachmentState.srcColorBlendFactor = srcColorBlendFactor;
return vkPipelineColorBlendAttachmentState;
}
inline VkPipelineColorBlendAttachmentState pipelineColorBlendAttachmentState() {
VkPipelineColorBlendAttachmentState vkPipelineColorBlendAttachmentState{};
return vkPipelineColorBlendAttachmentState;
}
inline VkPipelineDepthStencilStateCreateInfo pipelineDepthStencilStateCreateInfo(VkBool32 depthTestEnable, VkBool32 depthTestWriteEnable, VkCompareOp depthCompareOp) {
VkPipelineDepthStencilStateCreateInfo vkPipelineDepthStencilStateCreateInfo{};
vkPipelineDepthStencilStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
vkPipelineDepthStencilStateCreateInfo.depthTestEnable = depthTestEnable;
vkPipelineDepthStencilStateCreateInfo.depthWriteEnable = depthTestWriteEnable;
vkPipelineDepthStencilStateCreateInfo.depthCompareOp = depthCompareOp;
return vkPipelineDepthStencilStateCreateInfo;
}
inline VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo(const std::vector<VkDescriptorSetLayout> &setLayouts, const std::vector<VkPushConstantRange> &pushConstantRanges) {
VkPipelineLayoutCreateInfo vkPipelineLayoutCreateInfo{};
vkPipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
vkPipelineLayoutCreateInfo.setLayoutCount = setLayouts.size();
vkPipelineLayoutCreateInfo.pSetLayouts = setLayouts.data();
vkPipelineLayoutCreateInfo.pushConstantRangeCount = pushConstantRanges.size();
vkPipelineLayoutCreateInfo.pPushConstantRanges = pushConstantRanges.data();
return vkPipelineLayoutCreateInfo;
}
inline VkPipelineShaderStageCreateInfo pipelineShaderStageCreateInfo(VkShaderModule module, char *name, VkShaderStageFlagBits stage) {
VkPipelineShaderStageCreateInfo vkPipelineShaderStageCreateInfo{};
vkPipelineShaderStageCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
vkPipelineShaderStageCreateInfo.module = module;
vkPipelineShaderStageCreateInfo.pName = name;
vkPipelineShaderStageCreateInfo.stage = stage;
return vkPipelineShaderStageCreateInfo;
}
inline VkGraphicsPipelineCreateInfo graphicsPipelineCreateInfo(const std::vector<VkPipelineShaderStageCreateInfo> &stages, const VkPipelineVertexInputStateCreateInfo *vertexInputState,
const VkPipelineInputAssemblyStateCreateInfo *inputAssemblyState, const VkPipelineTessellationStateCreateInfo *tessellationState,
const VkPipelineViewportStateCreateInfo *viewportState, const VkPipelineRasterizationStateCreateInfo *rasterizationState,
const VkPipelineMultisampleStateCreateInfo *multisampleState, const VkPipelineDepthStencilStateCreateInfo *depthStencilState,
const VkPipelineColorBlendStateCreateInfo *colorBlendState, const VkPipelineDynamicStateCreateInfo *dynamicState,
VkPipelineLayout layout, VkRenderPass renderPass, uint32_t subpass) {
VkGraphicsPipelineCreateInfo vkGraphicsPipelineCreateInfo{};
vkGraphicsPipelineCreateInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
vkGraphicsPipelineCreateInfo.renderPass = renderPass;
vkGraphicsPipelineCreateInfo.subpass = subpass;
vkGraphicsPipelineCreateInfo.stageCount = stages.size();
vkGraphicsPipelineCreateInfo.pStages = stages.data();
vkGraphicsPipelineCreateInfo.pColorBlendState = colorBlendState;
vkGraphicsPipelineCreateInfo.pVertexInputState = vertexInputState;
vkGraphicsPipelineCreateInfo.pInputAssemblyState = inputAssemblyState;
vkGraphicsPipelineCreateInfo.pMultisampleState = multisampleState;
vkGraphicsPipelineCreateInfo.pViewportState = viewportState;
vkGraphicsPipelineCreateInfo.pRasterizationState = rasterizationState;
vkGraphicsPipelineCreateInfo.pTessellationState = tessellationState;
vkGraphicsPipelineCreateInfo.pDepthStencilState = depthStencilState;
vkGraphicsPipelineCreateInfo.pDynamicState = dynamicState;
vkGraphicsPipelineCreateInfo.layout = layout;
return vkGraphicsPipelineCreateInfo;
}
inline VkDescriptorSetAllocateInfo descriptorSetAllocateInfo(VkDescriptorPool descriptorPool, const std::vector<VkDescriptorSetLayout> &setLayouts) {
VkDescriptorSetAllocateInfo vkDescriptorSetAllocateInfo{};
vkDescriptorSetAllocateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
vkDescriptorSetAllocateInfo.descriptorPool = descriptorPool;
vkDescriptorSetAllocateInfo.descriptorSetCount = setLayouts.size();
vkDescriptorSetAllocateInfo.pSetLayouts = setLayouts.data();
return vkDescriptorSetAllocateInfo;
}
inline VkDescriptorPoolSize descriptorPoolSize(VkDescriptorType type, uint32_t descriptorCount) {
VkDescriptorPoolSize vkDescriptorPoolSize{};
vkDescriptorPoolSize.type = type;
vkDescriptorPoolSize.descriptorCount = descriptorCount;
return vkDescriptorPoolSize;
}
inline VkDescriptorPoolCreateInfo descriptorPoolCreateInfo(const std::vector<VkDescriptorPoolSize> &poolSizes, uint32_t maxSets) {
VkDescriptorPoolCreateInfo vkDescriptorPoolCreateInfo{};
vkDescriptorPoolCreateInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
vkDescriptorPoolCreateInfo.poolSizeCount = poolSizes.size();
vkDescriptorPoolCreateInfo.pPoolSizes = poolSizes.data();
vkDescriptorPoolCreateInfo.maxSets = maxSets;
return vkDescriptorPoolCreateInfo;
}
inline VkDescriptorSetLayoutBinding descriptorSetLayoutBinding(uint32_t binding, VkDescriptorType descriptorType, uint32_t descriptorCount, VkShaderStageFlags stageFlags) {
VkDescriptorSetLayoutBinding vkDescriptorSetLayoutBinding{};
vkDescriptorSetLayoutBinding.binding = binding;
vkDescriptorSetLayoutBinding.descriptorCount = descriptorCount;
vkDescriptorSetLayoutBinding.descriptorType = descriptorType;
vkDescriptorSetLayoutBinding.stageFlags = stageFlags;
return vkDescriptorSetLayoutBinding;
}
inline VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCreateInfo(const std::vector<VkDescriptorSetLayoutBinding> &bindings) {
VkDescriptorSetLayoutCreateInfo vkDescriptorSetLayoutInfo{};
vkDescriptorSetLayoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
vkDescriptorSetLayoutInfo.bindingCount = bindings.size();
vkDescriptorSetLayoutInfo.pBindings = bindings.data();
return vkDescriptorSetLayoutInfo;
}
inline VkWriteDescriptorSet writeDescriptorSet(const std::vector<VkDescriptorBufferInfo> &bufferInfo, VkDescriptorType descriptorType, VkDescriptorSet descriptorSet,
uint32_t dstBinding, uint32_t dstArrayElement) {
VkWriteDescriptorSet vkWriteDescriptorSet{};
vkWriteDescriptorSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
vkWriteDescriptorSet.descriptorCount = bufferInfo.size();
vkWriteDescriptorSet.descriptorType = descriptorType;
vkWriteDescriptorSet.dstSet = descriptorSet;
vkWriteDescriptorSet.dstBinding = dstBinding;
vkWriteDescriptorSet.dstArrayElement = dstArrayElement;
vkWriteDescriptorSet.pBufferInfo = bufferInfo.data();
return vkWriteDescriptorSet;
}
inline VkWriteDescriptorSet writeDescriptorSet(VkDescriptorImageInfo* imageInfo, VkDescriptorType descriptorType, VkDescriptorSet descriptorSet,
uint32_t dstBinding, uint32_t dstArrayElement) {
VkWriteDescriptorSet vkWriteDescriptorSet{};
vkWriteDescriptorSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
vkWriteDescriptorSet.descriptorCount = 1;
vkWriteDescriptorSet.descriptorType = descriptorType;
vkWriteDescriptorSet.dstSet = descriptorSet;
vkWriteDescriptorSet.dstBinding = dstBinding;
vkWriteDescriptorSet.dstArrayElement = dstArrayElement;
vkWriteDescriptorSet.pImageInfo = imageInfo;
return vkWriteDescriptorSet;
}
inline VkWriteDescriptorSet writeDescriptorSet(const std::vector<VkDescriptorImageInfo> &imageInfo, VkDescriptorType descriptorType, VkDescriptorSet descriptorSet,
uint32_t dstBinding, uint32_t dstArrayElement) {
VkWriteDescriptorSet vkWriteDescriptorSet{};
vkWriteDescriptorSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
vkWriteDescriptorSet.descriptorCount = imageInfo.size();
vkWriteDescriptorSet.descriptorType = descriptorType;
vkWriteDescriptorSet.dstSet = descriptorSet;
vkWriteDescriptorSet.dstBinding = dstBinding;
vkWriteDescriptorSet.dstArrayElement = dstArrayElement;
vkWriteDescriptorSet.pImageInfo = imageInfo.data();
return vkWriteDescriptorSet;
}
inline VkWriteDescriptorSet writeDescriptorSet(const std::vector<VkBufferView> &texelBufferView, VkDescriptorType descriptorType, VkDescriptorSet descriptorSet,
uint32_t dstBinding, uint32_t dstArrayElement) {
VkWriteDescriptorSet vkWriteDescriptorSet{};
vkWriteDescriptorSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
vkWriteDescriptorSet.descriptorCount = texelBufferView.size();
vkWriteDescriptorSet.descriptorType = descriptorType;
vkWriteDescriptorSet.dstSet = descriptorSet;
vkWriteDescriptorSet.dstBinding = dstBinding;
vkWriteDescriptorSet.dstArrayElement = dstArrayElement;
vkWriteDescriptorSet.pTexelBufferView = texelBufferView.data();
return vkWriteDescriptorSet;
}
inline VkCommandPoolCreateInfo commandPoolCreateInfo(uint32_t queueFamilyIndex, VkCommandPoolCreateFlags flags) {
VkCommandPoolCreateInfo vkCommandPoolCreateInfo{};
vkCommandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
vkCommandPoolCreateInfo.queueFamilyIndex = queueFamilyIndex;
vkCommandPoolCreateInfo.flags = flags;
return vkCommandPoolCreateInfo;
}
inline VkCommandBufferAllocateInfo commandBufferAllocateInfo(VkCommandPool vkCommandPool, uint32_t commandBufferCount, VkCommandBufferLevel level) {
VkCommandBufferAllocateInfo vkCommandBufferAllocateInfo{};
vkCommandBufferAllocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
vkCommandBufferAllocateInfo.commandPool = vkCommandPool;
vkCommandBufferAllocateInfo.commandBufferCount = commandBufferCount;
vkCommandBufferAllocateInfo.level = level;
return vkCommandBufferAllocateInfo;
}
inline VkSubmitInfo submitInfo(const std::vector<VkCommandBuffer> &commandBuffers, const std::vector<VkSemaphore> &waitSemaphores,
const std::vector<VkSemaphore> &signalSemaphores, VkPipelineStageFlags *pWaitDstStageMask = nullptr) {
VkSubmitInfo vkSubmitInfo{};
vkSubmitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
vkSubmitInfo.commandBufferCount = commandBuffers.size();
vkSubmitInfo.pCommandBuffers = commandBuffers.data();
vkSubmitInfo.waitSemaphoreCount = waitSemaphores.size();
vkSubmitInfo.signalSemaphoreCount = signalSemaphores.size();
vkSubmitInfo.pSignalSemaphores = signalSemaphores.data();
vkSubmitInfo.pWaitSemaphores = waitSemaphores.data();
vkSubmitInfo.pWaitDstStageMask = pWaitDstStageMask;
return vkSubmitInfo;
}
inline VkAttachmentDescription attachmentDescription(VkFormat format, VkSampleCountFlagBits samples,
VkAttachmentLoadOp loadOp, VkAttachmentStoreOp storeOp,
VkImageLayout initialLayout, VkImageLayout finalLayout,
VkAttachmentLoadOp stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VkAttachmentStoreOp stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE) {
VkAttachmentDescription attachmentDescription{};
attachmentDescription.samples = samples;
attachmentDescription.format = format;
attachmentDescription.initialLayout = initialLayout;
attachmentDescription.finalLayout = finalLayout;
attachmentDescription.loadOp = loadOp;
attachmentDescription.storeOp = storeOp;
attachmentDescription.stencilLoadOp = stencilLoadOp;
attachmentDescription.stencilStoreOp = stencilStoreOp;
return attachmentDescription;
}
inline VkAttachmentReference attachmentReference(uint32_t attachment, VkImageLayout layout) {
VkAttachmentReference attachmentReference{};
attachmentReference.attachment = attachment;
attachmentReference.layout = layout;
return attachmentReference;
}
inline VkSubpassDescription subpassDescription(VkPipelineBindPoint pipelineBindPoint,
const std::vector<VkAttachmentReference> &colorAttachments, const std::vector<VkAttachmentReference> &inputAttachments,
const std::vector<VkAttachmentReference> &resolveAttachments, const std::vector<VkAttachmentReference> &depthStencilAttachments,
const std::vector<uint32_t> &preserveAttachments) {
VkSubpassDescription vkSubpassDescription{};
vkSubpassDescription.pipelineBindPoint = pipelineBindPoint;
vkSubpassDescription.inputAttachmentCount = inputAttachments.size();
vkSubpassDescription.pInputAttachments = inputAttachments.data();
vkSubpassDescription.colorAttachmentCount = colorAttachments.size();
vkSubpassDescription.pColorAttachments = colorAttachments.data();
vkSubpassDescription.pResolveAttachments = resolveAttachments.data();
vkSubpassDescription.pDepthStencilAttachment = depthStencilAttachments.data();
vkSubpassDescription.preserveAttachmentCount = preserveAttachments.size();
vkSubpassDescription.pPreserveAttachments = preserveAttachments.data();
return vkSubpassDescription;
}
inline VkSubpassDependency subpassDependency(uint32_t srcSubpass, uint32_t dstSubpass,
VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
VkAccessFlags srcAccessMask, VkAccessFlags dstAccessMask,
VkDependencyFlags dependencyFlags) {
VkSubpassDependency vkSubpassDependency{};
vkSubpassDependency.srcSubpass = srcSubpass;
vkSubpassDependency.dstSubpass = dstSubpass;
vkSubpassDependency.srcStageMask = srcStageMask;
vkSubpassDependency.dstStageMask = dstStageMask;
vkSubpassDependency.srcAccessMask = srcAccessMask;
vkSubpassDependency.dstAccessMask = dstAccessMask;
vkSubpassDependency.dependencyFlags = dependencyFlags;
return vkSubpassDependency;
}
inline VkRenderPassCreateInfo renderPassCreateInfo(const std::vector<VkAttachmentDescription> &attachments,
const std::vector<VkSubpassDependency> &dependencies,
const std::vector<VkSubpassDescription> &subpasses) {
VkRenderPassCreateInfo vkRenderPassCreateInfo{};
vkRenderPassCreateInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
vkRenderPassCreateInfo.attachmentCount = attachments.size();
vkRenderPassCreateInfo.pAttachments = attachments.data();
vkRenderPassCreateInfo.dependencyCount = dependencies.size();
vkRenderPassCreateInfo.pDependencies = dependencies.data();
vkRenderPassCreateInfo.subpassCount = subpasses.size();
vkRenderPassCreateInfo.pSubpasses = subpasses.data();
return vkRenderPassCreateInfo;
}
inline VkShaderModuleCreateInfo shaderModuleCreateInfo(const std::vector<char> &shaderBytes) {
VkShaderModuleCreateInfo vkShaderModuleCreateInfo{};
vkShaderModuleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
vkShaderModuleCreateInfo.codeSize = shaderBytes.size();
vkShaderModuleCreateInfo.pCode = reinterpret_cast<const uint32_t *>(shaderBytes.data());
return vkShaderModuleCreateInfo;
}
inline VkImageViewCreateInfo imageViewCreateInfo(VkImage image, VkImageViewType viewType,
VkFormat format, VkComponentMapping components,
VkImageSubresourceRange subresourceRange) {
VkImageViewCreateInfo vkImageViewCreateInfo{};
vkImageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
vkImageViewCreateInfo.image = image;
vkImageViewCreateInfo.viewType = viewType;
vkImageViewCreateInfo.format = format;
vkImageViewCreateInfo.components = components;
vkImageViewCreateInfo.subresourceRange = subresourceRange;
return vkImageViewCreateInfo;
}
inline VkImageSubresourceRange imageSubresourceRange(VkImageAspectFlags aspectMask,
uint32_t baseMipLevel, uint32_t levelCount,
uint32_t baseArrayLayer, uint32_t layerCount) {
VkImageSubresourceRange vkImageSubresourceRange{};
vkImageSubresourceRange.aspectMask = aspectMask;
vkImageSubresourceRange.baseMipLevel = baseMipLevel;
vkImageSubresourceRange.levelCount = levelCount;
vkImageSubresourceRange.baseArrayLayer = baseArrayLayer;
vkImageSubresourceRange.layerCount = layerCount;
return vkImageSubresourceRange;
};
inline VkFramebufferCreateInfo framebufferCreateInfo(VkFramebufferCreateFlags flags,
VkRenderPass renderPass, const std::vector<VkImageView> &attachments,
uint32_t width, uint32_t height, uint32_t layers) {
VkFramebufferCreateInfo vkFramebufferCreateInfo{};
vkFramebufferCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
vkFramebufferCreateInfo.flags = flags;
vkFramebufferCreateInfo.renderPass = renderPass;
vkFramebufferCreateInfo.attachmentCount = attachments.size();
vkFramebufferCreateInfo.pAttachments = attachments.data();
vkFramebufferCreateInfo.width = width;
vkFramebufferCreateInfo.height = height;
vkFramebufferCreateInfo.layers = layers;
return vkFramebufferCreateInfo;
}
inline VkRenderPassBeginInfo renderPassBeginInfo(VkRenderPass renderPass, VkFramebuffer framebuffer,
VkRect2D renderArea, const std::vector<VkClearValue> &clearValues) {
VkRenderPassBeginInfo vkRenderPassBeginInfo{};
vkRenderPassBeginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
vkRenderPassBeginInfo.renderPass = renderPass;
vkRenderPassBeginInfo.framebuffer = framebuffer;
vkRenderPassBeginInfo.renderArea = renderArea;
vkRenderPassBeginInfo.clearValueCount = clearValues.size();
vkRenderPassBeginInfo.pClearValues = clearValues.data();
return vkRenderPassBeginInfo;
}
inline VkPresentInfoKHR presentInfoKHR(const std::vector<VkSemaphore> &waitSemaphores,
const std::vector<VkSwapchainKHR> &swapchains,
const uint32_t *imageIndices,
VkResult *pResults) {
VkPresentInfoKHR vkPresentInfoKHR{};
vkPresentInfoKHR.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
vkPresentInfoKHR.waitSemaphoreCount = waitSemaphores.size();
vkPresentInfoKHR.pWaitSemaphores = waitSemaphores.data();
vkPresentInfoKHR.swapchainCount = swapchains.size();
vkPresentInfoKHR.pSwapchains = swapchains.data();
vkPresentInfoKHR.pImageIndices = imageIndices;
vkPresentInfoKHR.pResults = pResults;
return vkPresentInfoKHR;
}
inline VkBufferCopy bufferCopy(VkDeviceSize size, VkDeviceSize srcOffset, VkDeviceSize dstOffset) {
VkBufferCopy vkBufferCopy{};
vkBufferCopy.size = size;
vkBufferCopy.srcOffset = srcOffset;
vkBufferCopy.dstOffset = dstOffset;
return vkBufferCopy;
}
inline VkBufferMemoryBarrier bufferMemoryBarrier(VkAccessFlags srcAccessMask, VkAccessFlags dstAccessMask,
uint32_t srcQueueFamilyIndex, uint32_t dstQueueFamilyIndex,
VkBuffer buffer, VkDeviceSize offset, VkDeviceSize size) {
VkBufferMemoryBarrier vkBufferMemoryBarrier{};
vkBufferMemoryBarrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
vkBufferMemoryBarrier.buffer = buffer;
vkBufferMemoryBarrier.size = size;
vkBufferMemoryBarrier.offset = offset;
vkBufferMemoryBarrier.srcAccessMask = srcAccessMask;
vkBufferMemoryBarrier.dstAccessMask = dstAccessMask;
vkBufferMemoryBarrier.srcQueueFamilyIndex = srcQueueFamilyIndex;
vkBufferMemoryBarrier.dstQueueFamilyIndex = dstQueueFamilyIndex;
return vkBufferMemoryBarrier;
}
inline VkImageMemoryBarrier imageMemoryBarrier(VkAccessFlags srcAccessMask, VkAccessFlags dstAccessMask,
VkImageLayout oldLayout, VkImageLayout newLayout,
uint32_t srcQueueFamilyIndex, uint32_t dstQueueFamilyIndex,
VkImage image, VkImageSubresourceRange subresourceRange) {
VkImageMemoryBarrier vkImageMemoryBarrier{};
vkImageMemoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
vkImageMemoryBarrier.srcAccessMask = srcAccessMask;
vkImageMemoryBarrier.dstAccessMask = dstAccessMask;
vkImageMemoryBarrier.oldLayout = oldLayout;
vkImageMemoryBarrier.newLayout = newLayout;
vkImageMemoryBarrier.srcQueueFamilyIndex = srcQueueFamilyIndex;
vkImageMemoryBarrier.dstQueueFamilyIndex = dstQueueFamilyIndex;
vkImageMemoryBarrier.image = image;
vkImageMemoryBarrier.subresourceRange = subresourceRange;
return vkImageMemoryBarrier;
}
inline VkBufferImageCopy bufferImageCopy(VkDeviceSize bufferOffset, uint32_t bufferRowLength, uint32_t bufferImageHeight,
VkImageSubresourceLayers imageSubresource, VkOffset3D imageOffset, VkExtent3D imageExtent) {
VkBufferImageCopy vkBufferImageCopy{};
vkBufferImageCopy.bufferOffset = bufferOffset;
vkBufferImageCopy.bufferRowLength = bufferRowLength;
vkBufferImageCopy.bufferImageHeight = bufferImageHeight;
vkBufferImageCopy.imageSubresource = imageSubresource;
vkBufferImageCopy.imageOffset = imageOffset;
vkBufferImageCopy.imageExtent = imageExtent;
return vkBufferImageCopy;
}
inline VkImageSubresourceLayers imageSubresourceLayers(VkImageAspectFlags aspectMask,
uint32_t mipLevel,
uint32_t baseArrayLayer,
uint32_t layerCount) {
VkImageSubresourceLayers vkImageSubresourceLayers{};
vkImageSubresourceLayers.aspectMask = aspectMask;
vkImageSubresourceLayers.mipLevel = mipLevel;
vkImageSubresourceLayers.baseArrayLayer = baseArrayLayer;
vkImageSubresourceLayers.layerCount = layerCount;
return vkImageSubresourceLayers;
}
inline VkImageCreateInfo imageCreateInfo(VkImageCreateFlags flags, VkImageType imageType,
VkFormat format, VkExtent3D extent,
uint32_t mipLevels, uint32_t arrayLayers,
VkSampleCountFlagBits samples, VkImageTiling tiling,
VkImageUsageFlags usage, VkSharingMode sharingMode,
const std::vector<uint32_t> &queueFamilyIndices, VkImageLayout initialLayout) {
VkImageCreateInfo vkImageCreateInfo{};
vkImageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
vkImageCreateInfo.flags = flags;
vkImageCreateInfo.imageType = imageType;
vkImageCreateInfo.format = format;
vkImageCreateInfo.extent = extent;
vkImageCreateInfo.mipLevels = mipLevels;
vkImageCreateInfo.arrayLayers = arrayLayers;
vkImageCreateInfo.samples = samples;
vkImageCreateInfo.tiling = tiling;
vkImageCreateInfo.usage = usage;
vkImageCreateInfo.sharingMode = sharingMode;
vkImageCreateInfo.queueFamilyIndexCount = queueFamilyIndices.size();
vkImageCreateInfo.pQueueFamilyIndices = queueFamilyIndices.data();
vkImageCreateInfo.initialLayout = initialLayout;
return vkImageCreateInfo;
}
inline VkImageViewCreateInfo imageCreateInfo(VkImageViewCreateFlags flags,
VkImage image, VkImageViewType viewType,
VkFormat format, VkComponentMapping components,
VkImageSubresourceRange subresourceRange) {
VkImageViewCreateInfo vkImageCreateInfo{};
vkImageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
vkImageCreateInfo.flags = flags;
vkImageCreateInfo.image = image;
vkImageCreateInfo.viewType = viewType;
vkImageCreateInfo.format = format;
vkImageCreateInfo.components = components;
vkImageCreateInfo.subresourceRange = subresourceRange;
return vkImageCreateInfo;
}
inline VkSamplerCreateInfo samplerCreateInfo(VkSamplerCreateFlags flags,
VkFilter magFilter, VkFilter minFilter,
VkSamplerMipmapMode mipmapMode, VkSamplerAddressMode addressModeU,
VkSamplerAddressMode addressModeV, VkSamplerAddressMode addressModeW,
float mipLodBias, VkBool32 anisotropyEnable,
float maxAnisotropy, VkBool32 compareEnable,
VkCompareOp compareOp, float minLod, float maxLod,
VkBorderColor borderColor, VkBool32 unnormalizedCoordinates) {
VkSamplerCreateInfo vkSamplerCreateInfo{};
vkSamplerCreateInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
vkSamplerCreateInfo.flags = flags;
vkSamplerCreateInfo.magFilter = magFilter;
vkSamplerCreateInfo.minFilter = minFilter;
vkSamplerCreateInfo.mipmapMode = mipmapMode;
vkSamplerCreateInfo.addressModeU = addressModeU;
vkSamplerCreateInfo.addressModeV = addressModeV;
vkSamplerCreateInfo.addressModeW = addressModeW;
vkSamplerCreateInfo.mipLodBias = mipLodBias;
vkSamplerCreateInfo.anisotropyEnable = anisotropyEnable;
vkSamplerCreateInfo.maxAnisotropy = maxAnisotropy;
vkSamplerCreateInfo.compareEnable = compareEnable;
vkSamplerCreateInfo.compareOp = compareOp;
vkSamplerCreateInfo.minLod = minLod;
vkSamplerCreateInfo.maxLod = maxLod;
vkSamplerCreateInfo.borderColor = borderColor;
vkSamplerCreateInfo.unnormalizedCoordinates = unnormalizedCoordinates;
return vkSamplerCreateInfo;
}
inline VkSamplerCreateInfo samplerCreateInfo() {
VkSamplerCreateInfo vkSamplerCreateInfo{};
vkSamplerCreateInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
return vkSamplerCreateInfo;
}
inline VkDescriptorImageInfo descriptorImageInfo(VkSampler sampler, VkImageView imageView, VkImageLayout imageLayout) {
VkDescriptorImageInfo vkDescriptorImageInfo;
vkDescriptorImageInfo.sampler = sampler;
vkDescriptorImageInfo.imageView = imageView;
vkDescriptorImageInfo.imageLayout = imageLayout;
return vkDescriptorImageInfo;
}
inline VkDescriptorBufferInfo descriptorBufferInfo(const VkBuffer& buffer, const VkDeviceSize& offset, const VkDeviceSize& range)
{
VkDescriptorBufferInfo vkDescriptorImageInfo;
vkDescriptorImageInfo.buffer = buffer;
vkDescriptorImageInfo.offset = offset;
vkDescriptorImageInfo.range = range;
return vkDescriptorImageInfo;
}
}
#endif//VULKANBASE_CREATEINFOHELPERS_H
| true |
cc678e1eff867d706cd7da75f8695ff05ff9f705 | C++ | wangyileipku/ACM | /Google Code Jam/2012round2_D.cpp | UTF-8 | 3,145 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <utility>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <list>
#include <time.h>
#include <stdio.h>
#define FORST(X,S,T) for(int X=S; X<=T; X++)
#define RFORST(X,S,T) for(int X=S; X>=T; X--)
#define FOR(X,XB) for(int X=0; X<XB; X++)
#define RFOR(X,XB) for(int X=XB-1; X>=0; X--)
#define FORSTL(X,C) for(X=C.begin();X!=C.end();X++)
#define SQR(X) ((X)*(X))
#define MID(X,Y) ((X+Y)/2)
#define FILL(X,V) memset(X,V,sizeof(X))
#define FILE_R(X) freopen(X, "r", stdin)
#define FILE_W(X) freopen(X, "w", stdout)
#define ERREQ(X,Y) fabs(X-Y)<EPS
const double PI = acos(-1.0);
const double EPS = 1E-9;
const int INF = (int)1E9;
using namespace std;
struct Point{
double x, y;
Point(){}
Point(double _x, double _y){ x=_x; y=_y; }
double dist(Point &p){
return sqrt(SQR(x-p.x)+SQR(y-p.y));
}
};
struct Circle{
double x, y, r;
Circle(){}
Circle(double _x, double _y, double _r) { x=_x; y=_y; r=_r; }
double dist(Circle &c){
return Point(x,y).dist(Point(c.x,c.y));
}
double dist(Point &p){
return Point(x,y).dist(p);
}
};
int N;
Circle plant[50];
Point sprinkler[2500];
int cnt;
bool check(double r){
cnt = 0;
FOR(i, N) sprinkler[cnt++] = Point(plant[i].x, plant[i].y);
FOR(i, N) FORST(j, i+1, N-1){
double r1 = r-plant[i].r;
double r2 = r-plant[j].r;
double dist = plant[i].dist(plant[j]);
if(dist>r1+r2+EPS) continue;
double x1 = plant[i].x, x2 = plant[j].x, y1 = plant[i].y, y2 = plant[j].y;
double a = 2.0*(x2-x1), b=2.0*(y2-y1), c=SQR(x1)-SQR(x2)+SQR(y1)-SQR(y2)+SQR(r2)-SQR(r1);
double X1, Y1, X2, Y2;
if(fabs(x1-x2)>fabs(y1-y2)){
double A = SQR(a)+SQR(b);
double B = 2.0*(b*c+a*b*x1-y1*SQR(a));
double C = SQR(c)+2.0*a*x1*c+SQR(a)*(SQR(x1)+SQR(y1)-SQR(r1));
double Delta = SQR(B)-4.0*A*C;
if(Delta>0+EPS){
Y1 = (-B+sqrt(Delta))/2.0/A;
X1 = (-b*Y1-c)/a;
Y2 = (-B-sqrt(Delta))/2.0/A;
X2 = (-b*Y2-c)/a;
sprinkler[cnt++] = Point(X1, Y1);
sprinkler[cnt++] = Point(X2, Y2);
}
}else{
double A = SQR(a)+SQR(b);
double B = 2.0*(a*c+a*b*y1-x1*SQR(b));
double C = SQR(c)+2.0*b*y1*c+SQR(b)*(SQR(x1)+SQR(y1)-SQR(r1));
double Delta = SQR(B)-4.0*A*C;
if(Delta>0+EPS){
X1 = (-B+sqrt(Delta))/2.0/A;
Y1 = (-a*X1-c)/b;
X2 = (-B-sqrt(Delta))/2.0/A;
Y2 = (-a*X2-c)/b;
sprinkler[cnt++] = Point(X1, Y1);
sprinkler[cnt++] = Point(X2, Y2);
}
}
}
FOR(i, cnt) FORST(j, i+1, cnt-1){
bool ok = 1;
FOR(k, N){
double d1 = plant[k].dist(sprinkler[i]);
double d2 = plant[k].dist(sprinkler[j]);
if(d1+plant[k].r>r+EPS && d2+plant[k].r>r+EPS){
ok = 0;
break;
}
}
if(ok) return true;
}
return false;
}
int main(){
int cs;
double lr, rr, mr;
//FILE_W("output");
cin>>cs;
for(int csn=1;csn<=cs;csn++){
printf("Case #%d: ", csn);
cin>>N;
FOR(i, N){
double x, y, r;
cin >> x >> y >> r;
plant[i] = Circle(x,y,r);
}
lr = 0; rr = 10000;
while(lr<rr-EPS){
mr = MID(lr, rr);
if(check(mr))
rr = mr;
else
lr = mr;
}
printf("%.8lf\n", lr);
}
return 0;
} | true |
6f1c02abc488bf2975833c19276bfdb4370feaf9 | C++ | farmerboy95/CompetitiveProgramming | /SPOJ/SPOJ LASTDIG.cpp | UTF-8 | 594 | 3.0625 | 3 | [] | no_license | /*
Author: Nguyen Tan Bao
Status: AC
Idea: Simply (a^b) % 10
*/
#include <bits/stdc++.h>
#define FOR(i,a,b) for (int i = (a); i <= (b); i++)
using namespace std;
using ll = long long;
ll binPowMod(ll a, ll b, ll m) {
a %= m;
ll res = 1;
while (b > 0) {
if (b & 1LL) res = res * a % m;
a = a * a % m;
b >>= 1LL;
}
return res;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
int a, b;
cin >> a >> b;
cout << binPowMod(a, b, 10) << "\n";
}
return 0;
}
| true |
aa9fba41f6ea5ffe69c8384ba1506a0c800bf29a | C++ | cf-zhang/design_patterns | /MultipleDispatchingByVisit/multiple_dispatching_by_visit.cpp | UTF-8 | 2,106 | 2.875 | 3 | [] | no_license | #include "mainwindow.h"
#include "temperature.h"
#include <boost/algorithm/string.hpp>
#include <QDebug>
#include <QApplication>
#include <iostream>
#include <typeinfo>
using namespace std;
class Gladiolus;
class Renuculus;
class Chrysanthemum;
class Visitor{
public:
virtual void visit(Gladiolus *f) = 0;
virtual void visit(Renuculus *f) = 0;
virtual void visit(Chrysanthemum *f) = 0;
virtual ~Visitor(){}
};
class Flower{
public:
virtual void accept(Visitor &) = 0;
virtual ~Flower(){}
};
class Gladiolus : public Flower{
public:
virtual void accept(Visitor &v){
v.visit(this);
}
};
class Renuculus : public Flower{
public:
virtual void accept(Visitor &v){
v.visit(this);
}
};
class Chrysanthemum : public Flower
{
public:
virtual void accept(Visitor &v){
v.visit(this);
}
};
class StringVal : public Visitor{
string s;
public:
operator const string &() { return s;}
virtual void visit(Gladiolus*){
s = "Gladious";
}
virtual void visit(Renuculus*){
s = "Renuculus";
}
virtual void visit(Chrysanthemum*){
s = "Chrysanthemum";
}
};
class Bee : public Visitor{
public:
virtual void visit(Gladiolus*){
cout << "Bee and Gladiolus" << endl;
}
virtual void visit(Renuculus*){
cout << "Bee and Renuculus" << endl;
}
virtual void visit(Chrysanthemum *){
cout << "Bee and Chrysanthemum" << endl;
}
};
struct FlowerGen
{
Flower *operator()(){
switch (rand() % 3) {
default:
case 0: return new Gladiolus;
case 1: return new Renuculus;
case 2: return new Chrysanthemum;
}
}
};
int main(int argc, char *argv[])
{
srand(time(0));
vector<Flower*> v(10);
generate(v.begin(), v.end(), FlowerGen());
vector<Flower*>::iterator it;
StringVal sval;
for(it = v.begin(); it != v.end(); it++){
(*it)->accept(sval);
cout <<string(sval) << endl;
}
Bee bee;
for(it = v.begin(); it != v.end(); it++){
(*it)->accept(bee);
}
}
| true |
5509e96748cdbbbcdaaf4e07b82e1bc4717da5d7 | C++ | jakesauter/acm | /sorting.cpp | UTF-8 | 468 | 3.75 | 4 | [] | no_license | #include <iostream>
#include <array>//size
#include <algorithm>
using namespace std;
int main()
{
/*sorting an array*/
int a_size = 10;
int a[a_size] = {4,3,2,9,1,7,6,5,4,4};
sort(a,a+a_size);
for(int i=0;i<a_size;i++)
{
cout << a[i] << " ";
}
cout << endl;
/*sorting a vector*/
vector<int> v = {1,2,3,4,5,5,6,7,8,9};
sort(v.begin(), v.end());
for(int i=0;i<v.size();i++)
{
cout << v[i] << " ";
}
cout << endl;
return 0;
}
| true |
4acc507f580d2d0261b88944b064e2c251d3c925 | C++ | ericgu/ESP8266Animation | /RGBColorFade.h | UTF-8 | 993 | 2.546875 | 3 | [] | no_license | class RGBColorFade: public Animation
{
private:
Adafruit_NeoPixel* _pStrip;
Mapper* _pMapper;
Chunk* _pChunk;
Chunk* _pColors;
int _currentColor;
Pixel _pixel;
public:
RGBColorFade(Adafruit_NeoPixel* pStrip, String rgbValues)
{
_pStrip = pStrip;
_pColors = new Chunk(rgbValues);
_currentColor = _pColors->numPixels();
_pixel = Pixel(RGBColor(0, 0, 0));
_pChunk = new Chunk(1);
_pChunk->setPixel(0, _pixel);
_pMapper = new Mapper(_pStrip);
}
~RGBColorFade()
{
delete _pColors;
delete _pMapper;
}
virtual void update()
{
_pixel.update();
if (_pixel.isDone())
{
Serial.println("u");
_currentColor = (_currentColor + 1) % _pColors->numPixels();
RGBColor color = _pColors->getPixel(_currentColor)->getColor();
Serial.println(color.toString());
_pixel.animateToNewColor(color, 1000);
}
_pMapper->renderAndShow(_pChunk);
}
};
| true |
2fae4d2173ca63f2ffcc7176a47e59045382520e | C++ | fanqo/CppPrimer | /Ch11/ex11.16.cpp | UTF-8 | 454 | 3.15625 | 3 | [] | no_license | #include <iostream>
using std::cout;
using std::endl;
#include <map>
using std::map;
#include <utility>
using std::pair;
int main()
{
map<int, int> mii {pair<int, int> {3, 1}};
for (auto index : mii)
cout << index.first << ", "
<< index.second << endl;
auto beg = mii.begin();
beg->second = 2;
for (auto index : mii)
cout << index.first << ", "
<< index.second << endl;
return 0;
}
| true |
b8ef998fd1b1e49971f5ef299a3e490df9a5c367 | C++ | quanghuy0497/Competitive-Programing | /Friends_10608_UVA.cpp | UTF-8 | 1,003 | 2.828125 | 3 | [] | no_license | //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1549
#include <iostream>
#include <algorithm>
using namespace std;
#define MAX 500000
int parent[MAX], friends[MAX];
//=============================================================
int findSet(int u)
{
while (u != parent[u])
u = parent[u];
return u;
}
//=============================================================
void unionSet(int u, int v)
{
int up = findSet(u);
int vp = findSet(v);
if (up != vp)
friends[up] += friends[vp];
parent[vp] = up;
}
//=============================================================
int main()
{
int k;
cin >>k;
while (k--)
{
int n,m;
cin >>m >>n;
for (int i = 1; i <= m; i++)
{
parent[i] = i;
friends[i] = 1;
}
for (int i = 0; i < n; i++)
{
int a,b;
cin >>a >>b;
unionSet(a, b);
}
int max_friends = 0;
for (int i = 1; i <= m; i++)
max_friends = max(max_friends, friends[i]);
cout<< max_friends <<endl;
}
return 0;
}
| true |
f7957bf761d26179e4f26883097bbb3f1edbe361 | C++ | Kaustic/KLib | /Include/KLib/String.hpp | UTF-8 | 2,777 | 2.9375 | 3 | [
"MIT"
] | permissive | #pragma once
//TODO: Create a universal String class like sf::String
//TODO: UTF-8 support
#include <algorithm> // std::transform
#include <sstream> // stringstream
#include <stdlib.h> // atoi, atol, atof
#include <string>
#include <KLib/Config.hpp>
#include <KLib/ArrayList.hpp>
#include <KLib/Number.hpp>
namespace klib
{
typedef std::string String;
//#include <SFML/System/String.hpp>
//typedef sf::String StringSuper;
namespace string
{
inline API_EXPORT ArrayList<String> Split(const String& str, char delim)
{
ArrayList<String> elems;
std::stringstream ss(str);
String item;
while (std::getline(ss, item, delim))
{
elems.push_back(item);
}
return elems;
}
inline API_EXPORT String Lower(const String& in)
{
String str(in);
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
return str;
}
inline API_EXPORT String Upper(const String& in)
{
String str(in);
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
return str;
}
} // string
// klib...
// Templates have to be in headers :'<
// ToString
template<typename T>
String API_EXPORT ToString(const T& generic)
{
std::ostringstream convert;
convert << generic;
return convert.str();
}
template<>
String API_EXPORT ToString<bool>(const bool& boolean);
template<>
inline API_EXPORT String ToString<bool>(const bool& boolean)
{
return boolean ? "true" : "false";
}
// FromString
template<typename T>
T API_EXPORT FromString(const String& in);
template<>
inline API_EXPORT Int FromString<Int>(const String& in)
{
return atoi(in.c_str());
}
template<>
inline API_EXPORT Long FromString<Long>(const String& in)
{
return atol(in.c_str());
}
template<>
inline API_EXPORT Float FromString<Float>(const String& in)
{
return atof(in.c_str());
}
template<>
inline API_EXPORT Double FromString<Double>(const String& in)
{
return atof(in.c_str());
}
template<>
inline API_EXPORT bool FromString<bool>(const String& in)
{
return ( string::Lower(in) == "true" ) ? true : false;
}
// To/FromArray
template<typename T>
inline API_EXPORT String ToStringArray(const ArrayList<T>& array)
{
std::ostringstream ts;
for (int i = 0; i < array.size(); i++)
{
ts << ToString<T>(array[i]);
if (i + 1 != array.size())
ts << ",";
}
return ts.str();
}
template<typename T>
inline API_EXPORT ArrayList<T> FromStringArray(const String& in)
{
ArrayList<T> elems;
ArrayList<String> split = string::Split(in, ','); // split string at commas
for (String elem : split)
elems.push_back(FromString<T>(elem)); // FromString every separated 'string'
return elems;
}
// ToHexString
template<typename T>
inline API_EXPORT String ToHexString(const T& generic)
{
std::ostringstream convert;
convert << "0x" << std::hex << generic;
return convert.str();
}
} // klib | true |