blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a73b86b5185874707496b910cedd69953385675f
|
74ceaf043c44651c7ee4ff9232ec65282d8b367e
|
/frameworks/cocos2d-x/cocos/scripting/lua-bindings/manual/dhspine/DHDictionary.h
|
6557af2b40b6783f0f91db78c8d07813bf9cb23b
|
[] |
no_license
|
PenpenLi/TF2016-NEW
|
e182bdf15d3d4d4b29b6fac15ab9f847ae678402
|
85b88b83d2f1cf32c1a99583199baf69586482cf
|
refs/heads/master
| 2021-06-06T08:47:50.479822
| 2016-09-01T10:30:29
| 2016-09-01T10:30:29
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,200
|
h
|
DHDictionary.h
|
//
// DHDictionary.h
// dhspine
//
// Created by youbin on 13-10-10.
//
//
#ifndef __dhspine__DHDictionary__
#define __dhspine__DHDictionary__
#include "cocos2d.h"
#include "base/uthash.h"
NS_CC_BEGIN
#define DH_MAX_KEY_LEN 256
struct DHDictElement {
DHDictElement(const char* srcKey, Ref* srcValue);
char key[DH_MAX_KEY_LEN];
Ref* value;
UT_hash_handle hh;
private:
DHDictElement();
};
class DHDictionary {
public:
DHDictionary();
~DHDictionary();
int getCount() const ;
void insert(const char* key, Ref* value);
void insertUnSafe(const char* key, Ref* value);
Ref* find(const char* key);
DHDictElement* getRandomElement();
void remove(const char* key);
void removeForElememt(DHDictElement* element);
void removeAll();
DHDictElement* getHashHead() const {
return m_elements;
}
private:
DHDictElement* m_elements;
};
#define DH_DICT_FOREACH(__dict__, __el__) \
DHDictElement* temp = NULL; \
if (__dict__) \
HASH_ITER(hh, (__dict__)->getHashHead(), __el__, temp)
NS_CC_END
#endif /* defined(__dhspine__DHDictionary__) */
|
86f6e2881ff9853ed4f2e1ce92479c785f13990b
|
8fd925c25e846d6554ca4305a968e9a2e2af0a71
|
/src/main/cpp/Recursividad/Fibonacci.cpp
|
3fb73dcb021097da412e6e43733210d43ff9fa3c
|
[] |
no_license
|
meschoyez/PEF-tp2
|
404d55a0165060eef44625f4ea58321e3fcd5337
|
2849e4118f6dc06e678f9f67423f274b747d3eee
|
refs/heads/master
| 2023-08-26T20:10:07.778946
| 2021-11-03T17:48:29
| 2021-11-03T17:48:29
| 421,962,370
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 476
|
cpp
|
Fibonacci.cpp
|
#include <iostream>
#include <cstdlib>
using namespace std;
int Fibonacci (int n);
int main (int argc, char* argv[]) {
int n = 0, f = 0;
if (argc != 2) {
cout << "Uso: " << argv[0] << " valor" << endl;
return 1;
}
n = atoi(argv[1]);
f = Fibonacci(n);
cout << "F(" << n << ") = " << f << endl;
return 0;
}
int Fibonacci (int n) {
int f = 1;
if (n < 0)
f = -1;
else if (n > 2)
f = Fibonacci(n - 2) + Fibonacci(n - 1);
return f;
}
|
f71d8dde8b1371cc256108a98dcccd0cbf5a648c
|
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
|
/Codes/AC/2142.cpp
|
af1575f9232700ab8ba44494a74fa835554b2bb2
|
[] |
no_license
|
thegamer1907/Code_Analysis
|
0a2bb97a9fb5faf01d983c223d9715eb419b7519
|
48079e399321b585efc8a2c6a84c25e2e7a22a61
|
refs/heads/master
| 2020-05-27T01:20:55.921937
| 2019-11-20T11:15:11
| 2019-11-20T11:15:11
| 188,403,594
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 727
|
cpp
|
2142.cpp
|
#include <iostream>
#include <vector>
#include <set>
#include <fstream>
#include <algorithm>
#include <map>
#include <cmath>
using namespace std;
#define ll long long
int main() {
ios_base::sync_with_stdio(false);
int n;
cin >> n;
vector<ll> a(n);
for (int i = 0; i < n; ++i) cin >> a[i];
int i1 = -1;
int i2 = n;
ll sum1 = 0;
ll sum2 = 0;
ll ans = 0;
while (i1 < i2) {
if (sum1 < sum2) sum1 += a[++i1];
else if (sum1 > sum2) sum2 += a[--i2];
else {
ans = sum1;
sum1 += a[++i1];
sum2 += a[--i2];
}
}
cout << ans << endl;
return 0;
}
|
7136f4fd17c624ee557f80e85b559d80ea0d2735
|
2b721d0e6d9ada23668d02ee14e83219a1ee0f48
|
/source/libguiex_core/guiperfmonitor.h
|
cf2e417d5231f63232f04be276f0c39ec5a8e912
|
[] |
no_license
|
lougithub/libguiex
|
fef2165e06f3adb66295aac2cf5f0be24dd47d46
|
30cf061a40a4c113b58765dc3aeacddc4521a034
|
refs/heads/master
| 2016-09-10T10:20:48.122440
| 2014-06-11T14:17:56
| 2014-06-11T14:17:56
| 2,423,027
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,714
|
h
|
guiperfmonitor.h
|
/**
* @file PerfMonitor.h
* @brief thanks for yu jian rong
* @author ken
* @date 2004-10-28
*/
/*******************************************
* PerfMon
* Performance monitor
*******************************************/
#ifndef _KEN_PERFMONITOR_28102004_H_
#define _KEN_PERFMONITOR_28102004_H_
//====================================================================================//
// include
//====================================================================================//
#include "guibase.h"
//====================================================================================//
// define
//====================================================================================//
#if GUI_PERFORMANCE_ON
# define PERFMON_INIT( nFrameCnt, nSectionNum ) CPerfMonitor::Init(nFrameCnt, nSectionNum)
# define PERFMON_EXIT( ) CPerfMonitor::Exit( )
# define PERFMON_BEGIN( nSection, name ) CPerfMonitor::GetIt()->BeginSection( nSection, name )
# define PERFMON_END( nSection ) CPerfMonitor::GetIt()->EndSection( nSection )
# define PERFMON_SCOPE( nSection, name ) CPerfMonObject gPerfMon_##nSection(nSection, name)
#else //GUI_PERFORMANCE_ON
# define PERFMON_INIT( nFrameCnt, nSectionNum )
# define PERFMON_EXIT( )
# define PERFMON_BEGIN( nSection, name )
# define PERFMON_END( nSection )
# define PERFMON_SCOPE( nSection, name )
#endif //GUI_PERFORMANCE_ON
#if GUI_PERFORMANCE_ON
//====================================================================================//
// declare
//====================================================================================//
namespace guiex
{
class CPerfMon_impl;
}
//====================================================================================//
// class
//====================================================================================//
namespace guiex
{
class GUIEXPORT CPerfMonitor
{
public:
~CPerfMonitor();
static void Init( int32 nFrameCnt, int32 nSectionNum);
static void Exit( );
static CPerfMonitor* GetIt();
/**
* @brief calls this each frame!
*/
void FrameUpdate();
/**
* @brief is frame updated this frame
*/
bool IsUpdated();
/**
* @brief get frame numbers per second
*/
real GetFPS();
/**
* @brief call this in the begin of the section.
*/
void BeginSection(int32 nSectionNo, const char* pName);
/**
* @brief call this in the end of the section
*/
void EndSection(int32 nSectionNo);
/**
* @brief get the rate of this section.
*/
real GetRate(int32 nSectionNo);
/**
* @brief get the millionsecond of the section.
*/
unsigned GetMillionsec(int32 nSectionNo);
/**
* @brief get the run timers of the section.
*/
unsigned GetTimes(int32 nSectionNo);
/**
* @brief get the name of the section.
*/
const char* GetName(int32 nSectionNo) const;
/**
* @brief get number of the section.
*/
const int32 GetSectionNum() const;
protected:
CPerfMonitor();
void Initialize( int32 nFrameCnt, int32 nSectionNum );
void Release();
static CPerfMonitor* ms_perfMon;
private:
CPerfMon_impl* m_impl;
};
/**
* @brief object of the performance monitor.
* for scope monitor.
*/
class CPerfMonObject
{
public:
CPerfMonObject(int32 nSectionNo, const char* pName)
:m_nSectionNo(nSectionNo)
{
CPerfMonitor::GetIt()->BeginSection( nSectionNo, pName );
}
~CPerfMonObject()
{
CPerfMonitor::GetIt()->EndSection( m_nSectionNo );
}
protected:
int32 m_nSectionNo;
};
}//namespace guiex
#endif //GUI_PERFORMANCE_ON
#endif //_KEN_PERFMONITOR_28102004_H_
|
459041fc891078ef496df62c027f21b78ea1cb04
|
a0bdedcc814dfcbf6f1742c398b64a31619af4df
|
/ideccmbd/CrdIdecNav/DlgIdecNavLoaini.h
|
3c3dd024b3654bd77c3ac7e75ce400030538e8bd
|
[
"BSD-2-Clause"
] |
permissive
|
mpsitech/idec_public
|
ec7231939b8987fd66482d99276609e16d4ad3f7
|
a74cf1c7095e08ee61b237fddc1642f83dbb852d
|
refs/heads/master
| 2021-05-13T20:43:55.046131
| 2018-06-09T16:11:30
| 2018-06-09T16:11:30
| 116,916,593
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,158
|
h
|
DlgIdecNavLoaini.h
|
/**
* \file DlgIdecNavLoaini.h
* job handler for job DlgIdecNavLoaini (declarations)
* \author Alexander Wirthmueller
* \date created: 30 Dec 2017
* \date modified: 30 Dec 2017
*/
#ifndef DLGIDECNAVLOAINI_H
#define DLGIDECNAVLOAINI_H
// IP custInclude --- IBEGIN
#include <sys/types.h>
#include <dirent.h>
// IP custInclude --- IEND
#include "IexIdecIni.h"
#define VecVDlgIdecNavLoainiDit DlgIdecNavLoaini::VecVDit
#define VecVDlgIdecNavLoainiDo DlgIdecNavLoaini::VecVDo
#define VecVDlgIdecNavLoainiDoImp DlgIdecNavLoaini::VecVDoImp
#define VecVDlgIdecNavLoainiSge DlgIdecNavLoaini::VecVSge
#define ContIacDlgIdecNavLoaini DlgIdecNavLoaini::ContIac
#define ContInfDlgIdecNavLoaini DlgIdecNavLoaini::ContInf
#define ContInfDlgIdecNavLoainiImp DlgIdecNavLoaini::ContInfImp
#define StatAppDlgIdecNavLoaini DlgIdecNavLoaini::StatApp
#define StatShrDlgIdecNavLoaini DlgIdecNavLoaini::StatShr
#define StatShrDlgIdecNavLoainiAcv DlgIdecNavLoaini::StatShrAcv
#define StatShrDlgIdecNavLoainiIfi DlgIdecNavLoaini::StatShrIfi
#define StatShrDlgIdecNavLoainiImp DlgIdecNavLoaini::StatShrImp
#define StatShrDlgIdecNavLoainiLfi DlgIdecNavLoaini::StatShrLfi
#define TagDlgIdecNavLoaini DlgIdecNavLoaini::Tag
#define TagDlgIdecNavLoainiAcv DlgIdecNavLoaini::TagAcv
#define TagDlgIdecNavLoainiIfi DlgIdecNavLoaini::TagIfi
#define TagDlgIdecNavLoainiImp DlgIdecNavLoaini::TagImp
#define TagDlgIdecNavLoainiLfi DlgIdecNavLoaini::TagLfi
#define DpchAppDlgIdecNavLoainiData DlgIdecNavLoaini::DpchAppData
#define DpchAppDlgIdecNavLoainiDo DlgIdecNavLoaini::DpchAppDo
#define DpchEngDlgIdecNavLoainiData DlgIdecNavLoaini::DpchEngData
/**
* DlgIdecNavLoaini
*/
class DlgIdecNavLoaini : public JobIdec {
public:
/**
* VecVDit (full: VecVDlgIdecNavLoainiDit)
*/
class VecVDit {
public:
static const uint IFI = 1;
static const uint IMP = 2;
static const uint ACV = 3;
static const uint LFI = 4;
static uint getIx(const string& sref);
static string getSref(const uint ix);
static string getTitle(const uint ix, const uint ixIdecVLocale);
static void fillFeed(const uint ixIdecVLocale, Feed& feed);
};
/**
* VecVDo (full: VecVDlgIdecNavLoainiDo)
*/
class VecVDo {
public:
static const uint BUTDNECLICK = 1;
static uint getIx(const string& sref);
static string getSref(const uint ix);
};
/**
* VecVDoImp (full: VecVDlgIdecNavLoainiDoImp)
*/
class VecVDoImp {
public:
static const uint BUTRUNCLICK = 1;
static const uint BUTSTOCLICK = 2;
static uint getIx(const string& sref);
static string getSref(const uint ix);
};
/**
* VecVSge (full: VecVDlgIdecNavLoainiSge)
*/
class VecVSge {
public:
static const uint IDLE = 1;
static const uint PRSIDLE = 2;
static const uint PARSE = 3;
static const uint ALRIDECPER = 4;
static const uint PRSDONE = 5;
static const uint IMPIDLE = 6;
static const uint IMPORT = 7;
static const uint IMPDONE = 8;
static const uint UPKIDLE = 9;
static const uint UNPACK = 10;
static const uint DONE = 11;
static uint getIx(const string& sref);
static string getSref(const uint ix);
static void fillFeed(Feed& feed);
};
/**
* ContIac (full: ContIacDlgIdecNavLoaini)
*/
class ContIac : public Block {
public:
static const uint NUMFDSE = 1;
public:
ContIac(const uint numFDse = 1);
public:
uint numFDse;
public:
bool readXML(xmlXPathContext* docctx, string basexpath = "", bool addbasetag = false);
void writeXML(xmlTextWriter* wr, string difftag = "", bool shorttags = true);
set<uint> comm(const ContIac* comp);
set<uint> diff(const ContIac* comp);
};
/**
* ContInf (full: ContInfDlgIdecNavLoaini)
*/
class ContInf : public Block {
public:
static const uint NUMFSGE = 1;
public:
ContInf(const uint numFSge = 1);
public:
uint numFSge;
public:
void writeXML(xmlTextWriter* wr, string difftag = "", bool shorttags = true);
set<uint> comm(const ContInf* comp);
set<uint> diff(const ContInf* comp);
};
/**
* ContInfImp (full: ContInfDlgIdecNavLoainiImp)
*/
class ContInfImp : public Block {
public:
static const uint TXTPRG = 1;
public:
ContInfImp(const string& TxtPrg = "");
public:
string TxtPrg;
public:
void writeXML(xmlTextWriter* wr, string difftag = "", bool shorttags = true);
set<uint> comm(const ContInfImp* comp);
set<uint> diff(const ContInfImp* comp);
};
/**
* StatApp (full: StatAppDlgIdecNavLoaini)
*/
class StatApp {
public:
static void writeXML(xmlTextWriter* wr, string difftag = "", bool shorttags = true, const bool initdone = false, const string& shortMenu = "");
};
/**
* StatShr (full: StatShrDlgIdecNavLoaini)
*/
class StatShr : public Block {
public:
static const uint BUTDNEACTIVE = 1;
public:
StatShr(const bool ButDneActive = true);
public:
bool ButDneActive;
public:
void writeXML(xmlTextWriter* wr, string difftag = "", bool shorttags = true);
set<uint> comm(const StatShr* comp);
set<uint> diff(const StatShr* comp);
};
/**
* StatShrAcv (full: StatShrDlgIdecNavLoainiAcv)
*/
class StatShrAcv : public Block {
public:
static const uint ULDACTIVE = 1;
public:
StatShrAcv(const bool UldActive = true);
public:
bool UldActive;
public:
void writeXML(xmlTextWriter* wr, string difftag = "", bool shorttags = true);
set<uint> comm(const StatShrAcv* comp);
set<uint> diff(const StatShrAcv* comp);
};
/**
* StatShrIfi (full: StatShrDlgIdecNavLoainiIfi)
*/
class StatShrIfi : public Block {
public:
static const uint ULDACTIVE = 1;
public:
StatShrIfi(const bool UldActive = true);
public:
bool UldActive;
public:
void writeXML(xmlTextWriter* wr, string difftag = "", bool shorttags = true);
set<uint> comm(const StatShrIfi* comp);
set<uint> diff(const StatShrIfi* comp);
};
/**
* StatShrImp (full: StatShrDlgIdecNavLoainiImp)
*/
class StatShrImp : public Block {
public:
static const uint BUTRUNACTIVE = 1;
static const uint BUTSTOACTIVE = 2;
public:
StatShrImp(const bool ButRunActive = true, const bool ButStoActive = true);
public:
bool ButRunActive;
bool ButStoActive;
public:
void writeXML(xmlTextWriter* wr, string difftag = "", bool shorttags = true);
set<uint> comm(const StatShrImp* comp);
set<uint> diff(const StatShrImp* comp);
};
/**
* StatShrLfi (full: StatShrDlgIdecNavLoainiLfi)
*/
class StatShrLfi : public Block {
public:
static const uint DLDACTIVE = 1;
public:
StatShrLfi(const bool DldActive = true);
public:
bool DldActive;
public:
void writeXML(xmlTextWriter* wr, string difftag = "", bool shorttags = true);
set<uint> comm(const StatShrLfi* comp);
set<uint> diff(const StatShrLfi* comp);
};
/**
* Tag (full: TagDlgIdecNavLoaini)
*/
class Tag {
public:
static void writeXML(const uint ixIdecVLocale, xmlTextWriter* wr, string difftag = "", bool shorttags = true);
};
/**
* TagAcv (full: TagDlgIdecNavLoainiAcv)
*/
class TagAcv {
public:
static void writeXML(const uint ixIdecVLocale, xmlTextWriter* wr, string difftag = "", bool shorttags = true);
};
/**
* TagIfi (full: TagDlgIdecNavLoainiIfi)
*/
class TagIfi {
public:
static void writeXML(const uint ixIdecVLocale, xmlTextWriter* wr, string difftag = "", bool shorttags = true);
};
/**
* TagImp (full: TagDlgIdecNavLoainiImp)
*/
class TagImp {
public:
static void writeXML(const uint ixIdecVLocale, xmlTextWriter* wr, string difftag = "", bool shorttags = true);
};
/**
* TagLfi (full: TagDlgIdecNavLoainiLfi)
*/
class TagLfi {
public:
static void writeXML(const uint ixIdecVLocale, xmlTextWriter* wr, string difftag = "", bool shorttags = true);
};
/**
* DpchAppData (full: DpchAppDlgIdecNavLoainiData)
*/
class DpchAppData : public DpchAppIdec {
public:
static const uint JREF = 1;
static const uint CONTIAC = 2;
public:
DpchAppData();
public:
ContIac contiac;
public:
string getSrefsMask();
void readXML(pthread_mutex_t* mScr, map<string,ubigint>& descr, xmlXPathContext* docctx, string basexpath = "", bool addbasetag = false);
};
/**
* DpchAppDo (full: DpchAppDlgIdecNavLoainiDo)
*/
class DpchAppDo : public DpchAppIdec {
public:
static const uint JREF = 1;
static const uint IXVDO = 2;
static const uint IXVDOIMP = 3;
public:
DpchAppDo();
public:
uint ixVDo;
uint ixVDoImp;
public:
string getSrefsMask();
void readXML(pthread_mutex_t* mScr, map<string,ubigint>& descr, xmlXPathContext* docctx, string basexpath = "", bool addbasetag = false);
};
/**
* DpchEngData (full: DpchEngDlgIdecNavLoainiData)
*/
class DpchEngData : public DpchEngIdec {
public:
static const uint JREF = 1;
static const uint CONTIAC = 2;
static const uint CONTINF = 3;
static const uint CONTINFIMP = 4;
static const uint FEEDFDSE = 5;
static const uint FEEDFSGE = 6;
static const uint STATAPP = 7;
static const uint STATSHR = 8;
static const uint STATSHRACV = 9;
static const uint STATSHRIFI = 10;
static const uint STATSHRIMP = 11;
static const uint STATSHRLFI = 12;
static const uint TAG = 13;
static const uint TAGACV = 14;
static const uint TAGIFI = 15;
static const uint TAGIMP = 16;
static const uint TAGLFI = 17;
static const uint ALL = 18;
public:
DpchEngData(const ubigint jref = 0, ContIac* contiac = NULL, ContInf* continf = NULL, ContInfImp* continfimp = NULL, Feed* feedFDse = NULL, Feed* feedFSge = NULL, StatShr* statshr = NULL, StatShrAcv* statshracv = NULL, StatShrIfi* statshrifi = NULL, StatShrImp* statshrimp = NULL, StatShrLfi* statshrlfi = NULL, const set<uint>& mask = {NONE});
public:
ContIac contiac;
ContInf continf;
ContInfImp continfimp;
Feed feedFDse;
Feed feedFSge;
StatShr statshr;
StatShrAcv statshracv;
StatShrIfi statshrifi;
StatShrImp statshrimp;
StatShrLfi statshrlfi;
public:
string getSrefsMask();
void merge(DpchEngIdec* dpcheng);
void writeXML(const uint ixIdecVLocale, pthread_mutex_t* mScr, map<ubigint,string>& scr, map<string,ubigint>& descr, xmlTextWriter* wr);
};
bool evalIfiUldActive(DbsIdec* dbsidec);
bool evalImpButRunActive(DbsIdec* dbsidec);
bool evalImpButStoActive(DbsIdec* dbsidec);
bool evalAcvUldActive(DbsIdec* dbsidec);
bool evalLfiDldActive(DbsIdec* dbsidec);
bool evalButDneActive(DbsIdec* dbsidec);
public:
DlgIdecNavLoaini(XchgIdec* xchg, DbsIdec* dbsidec, const ubigint jrefSup, const uint ixIdecVLocale);
~DlgIdecNavLoaini();
public:
ContIac contiac;
ContInf continf;
ContInfImp continfimp;
StatShr statshr;
StatShrAcv statshracv;
StatShrIfi statshrifi;
StatShrImp statshrimp;
StatShrLfi statshrlfi;
Feed feedFMcbAlert;
Feed feedFDse;
Feed feedFSge;
IexIdecIni* iex;
uint ixVDit;
// IP custVar --- IBEGIN
string infilename;
// IP custVar --- IEND
public:
// IP cust --- INSERT
public:
DpchEngIdec* getNewDpchEng(set<uint> items);
void refreshIfi(DbsIdec* dbsidec, set<uint>& moditems);
void refreshImp(DbsIdec* dbsidec, set<uint>& moditems);
void refreshAcv(DbsIdec* dbsidec, set<uint>& moditems);
void refreshLfi(DbsIdec* dbsidec, set<uint>& moditems);
void refresh(DbsIdec* dbsidec, set<uint>& moditems);
public:
void changeStage(DbsIdec* dbsidec, uint _ixVSge, DpchEngIdec** dpcheng = NULL);
uint enterSgeIdle(DbsIdec* dbsidec, const bool reenter);
void leaveSgeIdle(DbsIdec* dbsidec);
uint enterSgePrsidle(DbsIdec* dbsidec, const bool reenter);
void leaveSgePrsidle(DbsIdec* dbsidec);
uint enterSgeParse(DbsIdec* dbsidec, const bool reenter);
void leaveSgeParse(DbsIdec* dbsidec);
uint enterSgeAlridecper(DbsIdec* dbsidec, const bool reenter);
void leaveSgeAlridecper(DbsIdec* dbsidec);
uint enterSgePrsdone(DbsIdec* dbsidec, const bool reenter);
void leaveSgePrsdone(DbsIdec* dbsidec);
uint enterSgeImpidle(DbsIdec* dbsidec, const bool reenter);
void leaveSgeImpidle(DbsIdec* dbsidec);
uint enterSgeImport(DbsIdec* dbsidec, const bool reenter);
void leaveSgeImport(DbsIdec* dbsidec);
uint enterSgeImpdone(DbsIdec* dbsidec, const bool reenter);
void leaveSgeImpdone(DbsIdec* dbsidec);
uint enterSgeUpkidle(DbsIdec* dbsidec, const bool reenter);
void leaveSgeUpkidle(DbsIdec* dbsidec);
uint enterSgeUnpack(DbsIdec* dbsidec, const bool reenter);
void leaveSgeUnpack(DbsIdec* dbsidec);
uint enterSgeDone(DbsIdec* dbsidec, const bool reenter);
void leaveSgeDone(DbsIdec* dbsidec);
string getSquawk(DbsIdec* dbsidec);
void handleRequest(DbsIdec* dbsidec, ReqIdec* req);
void handleDpchAppIdecInit(DbsIdec* dbsidec, DpchAppIdecInit* dpchappidecinit, DpchEngIdec** dpcheng);
void handleDpchAppDataContiac(DbsIdec* dbsidec, ContIac* _contiac, DpchEngIdec** dpcheng);
void handleDpchAppDoButDneClick(DbsIdec* dbsidec, DpchEngIdec** dpcheng);
void handleDpchAppDoImpButRunClick(DbsIdec* dbsidec, DpchEngIdec** dpcheng);
void handleDpchAppDoImpButStoClick(DbsIdec* dbsidec, DpchEngIdec** dpcheng);
void handleDpchAppIdecAlert(DbsIdec* dbsidec, DpchAppIdecAlert* dpchappidecalert, DpchEngIdec** dpcheng);
void handleUpload(DbsIdec* dbsidec, const string& filename);
string handleDownload(DbsIdec* dbsidec);
void handleTimer(DbsIdec* dbsidec, const string& sref);
};
#endif
|
22537505523dd5d11a5d072f8ad20e28f28c5960
|
3d81463f488da3c36efdc601762f6dc4ed0fd0dc
|
/HelloWorld/HelloOpenGL/src/GL5Uniforms/UniformBuffer.h
|
c309b79ffd1d07b274c797484d6a85c0a6c35e88
|
[] |
no_license
|
ugreg/opengl-playground
|
40b1d05ffb92270abf60f64cf259480c34771bf8
|
7ef4abcadb6901cc6d152fc183a285f3a38b6483
|
refs/heads/master
| 2022-05-14T14:55:35.452725
| 2020-02-15T22:51:31
| 2020-02-15T22:51:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 311
|
h
|
UniformBuffer.h
|
#include <iostream>
#include "UniformShader.h"
#include "GL\glew.h"
#include "GLFW\glfw3.h"
class UniformBuffer
{
public:
UniformBuffer();
int run();
void createBuffer(unsigned int& buffer, unsigned int& index_buffer);
void bindVertex(unsigned int index_to_bind, unsigned int num_floats_per_vertex);
};
|
0925368a128f779c7e7ef96a4b4361a80c91d2aa
|
f6c0270b00ae78607c91a1b393510144f0f595b3
|
/TestAppSTM32+88E6352/drivers/mpu.cpp
|
c7b61fac90ba5366944dce5856b5d1dfb1f9a987
|
[
"Apache-2.0"
] |
permissive
|
yacoub-automation/mstp-lib
|
3d9bea7d93308aa9e7a80b427a8a7ccb6d4a1ab5
|
57089f9b7826a65fdd8d391a31d0598476c3488c
|
refs/heads/master
| 2023-04-26T05:28:04.951248
| 2021-05-04T08:30:24
| 2021-05-04T08:30:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,233
|
cpp
|
mpu.cpp
|
#include "mpu.h"
#include <stm32f769xx.h>
void mpu_disable()
{
// Make sure outstanding transfers are done.
__DMB();
// Disable fault exceptions
SCB->SHCSR &= ~SCB_SHCSR_MEMFAULTENA_Msk;
// Disable the MPU and clear the control register
MPU->CTRL = 0;
}
void mpu_enable (uint32_t control)
{
// Enable the MPU
MPU->CTRL = control | MPU_CTRL_ENABLE_Msk;
// Enable fault exceptions
SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk;
// Ensure MPU setting take effects
__DSB();
__ISB();
}
void mpu_config_region (MPU_Region_InitTypeDef *MPU_Init)
{
// Check the parameters
//assert_param(IS_MPU_REGION_NUMBER(MPU_Init->Number));
// assert_param(IS_MPU_REGION_ENABLE(MPU_Init->Enable));
// Set the Region number
MPU->RNR = MPU_Init->Number;
if (MPU_Init->Enable)
{
// Check the parameters
//assert_param(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec));
//assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission));
//assert_param(IS_MPU_TEX_LEVEL(MPU_Init->TypeExtField));
//assert_param(IS_MPU_ACCESS_SHAREABLE(MPU_Init->IsShareable));
//assert_param(IS_MPU_ACCESS_CACHEABLE(MPU_Init->IsCacheable));
//assert_param(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable));
//assert_param(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable));
//assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size));
MPU->RBAR = MPU_Init->BaseAddress;
MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) |
((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) |
((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) |
((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) |
((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) |
((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) |
((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) |
((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) |
((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos);
}
else
{
MPU->RBAR = 0x00;
MPU->RASR = 0x00;
}
}
|
f345c636c41ac83fdff87c8ac295755e750aeb00
|
b7d9f2ad27e52592d8f029336d1551cf26415eaa
|
/RegistroPilha.h
|
51c8f7d7c20b77d229f7abafe13b351368ae897f
|
[] |
no_license
|
enio-martinelli/TAD-Pilha---Aloca-o-Encadeada-e-Din-mica
|
1619791256e9e0d010232595fce6037dfc7169c8
|
34ccfbef7a46664ac7e8c7aa91545acc8f632e5d
|
refs/heads/main
| 2023-08-13T04:52:01.472006
| 2021-09-16T18:47:15
| 2021-09-16T18:47:15
| 407,277,258
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 494
|
h
|
RegistroPilha.h
|
#ifndef REGISTROPILHA_H
#define REGISTROPILHA_H
#include <iostream>
//Definição do tipo Node
struct Node{
char info; //local onde será armazenado a informção do elemento
struct Node *next; //Ponteiro que apontará para o próximo elemento da pilha
};
//Definindo um ponteiro do tipo Node como NodePtr
typedef struct Node *NodePtr;
//Definição do tipo Pilha
struct Pilha{
NodePtr topo; //Ponteiro que apontará para o elemento do tipo Node que está no topo da Pilha
};
#endif
|
d8ca0e520c0d65a2854f54a7f0bef08656c1f1c0
|
a7d7cdbe03c60567129cd790047aaae3c2d08daf
|
/geometry/Noise.h
|
3db2400a3031a220dcb7c62041adc9a34aa7a1f2
|
[] |
no_license
|
m-hogue/JHU-Graphics
|
c23b8d18ca589ac08ba277917a51ce462d9b4d94
|
547a62c23cc997cb154c13b4e0ef94756d89702e
|
refs/heads/master
| 2021-01-25T00:46:36.040604
| 2014-12-09T03:51:59
| 2014-12-09T03:51:59
| 27,748,191
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,227
|
h
|
Noise.h
|
//============================================================================
// Johns Hopkins University Engineering for Professionals
// 605.467 Computer Graphics and 605.767 Applied Computer Graphics
// Instructor: David W. Nesbitt
//
// Author: David W. Nesbitt
// File: Noise.h
// Purpose: Noise generation methods.
//============================================================================
#ifndef __NOISE_H__
#define __NOISE_H__
#include <math.h>
// NOTE - not required until 605.767!
/**
* Noise generation methods
*/
class Noise
{
public:
/**
* Constructor
*/
Noise()
{
}
/**
* Finds the noise at a specific 3D position. Linearly interpolates
* lattice noise.
* @param p Position
* @param scale Scale
* @return Returns linearly interpolated noise value.
*/
float noise(const Point3& p, const float scale)
{
return 1.0f;
}
/**
* Find turbelence value.
* @param scale Scale
* @param p Position
* @return Returns a turbulence value
*/
float turbulence(float scale, const Point3& p)
{
return 1.0f;
}
private:
};
#endif
|
aed9e64b822be7705e6bb864518af14fd53d9027
|
a3a12224ce1742689598066bcfd039c9ce10e446
|
/codeforces/200b.cpp
|
998cf67b2c044c76174125e5df40bd5aa8af32be
|
[] |
no_license
|
sasankrajeev/Codeforces
|
6c6e72f48fffb74f1bcc2ddf21eecd02c35e394e
|
ebb0a5e2f968cb3a74319a05d3381004d7e46cc2
|
refs/heads/master
| 2020-03-23T12:45:08.159911
| 2018-09-06T18:09:14
| 2018-09-06T18:09:14
| 141,579,485
| 0
| 0
| null | 2018-07-19T13:16:18
| 2018-07-19T12:55:19
|
C++
|
UTF-8
|
C++
| false
| false
| 216
|
cpp
|
200b.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main() {
float a,i,b,c=0;
vector <float>d;
cin>>a;
for(i=0;i<a;i++){
cin>>b;
d.push_back(b);
c=c+d[i];
}
cout<<fixed<<setprecision(6)<<c/a;
return 0;
}
|
712c4244bfb0a5cc262a010ea42379298529e3a1
|
2f78e134c5b55c816fa8ee939f54bde4918696a5
|
/code_ps3/gfx/irradiance_ps3.h
|
2eea8e29068e2502dc99f57b1ea2ef0c066d168b
|
[] |
no_license
|
narayanr7/HeavenlySword
|
b53afa6a7a6c344e9a139279fbbd74bfbe70350c
|
a255b26020933e2336f024558fefcdddb48038b2
|
refs/heads/master
| 2022-08-23T01:32:46.029376
| 2020-05-26T04:45:56
| 2020-05-26T04:45:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,189
|
h
|
irradiance_ps3.h
|
//--------------------------------------------------
//!
//! \file irradiance_ps3.h
//! This is a dummy holding a few doxygen comments.
//!
//--------------------------------------------------
#ifndef GFX_IRRADIANCE_H
#define GFX_IRRADIANCE_H
#ifndef GFX_RENDERTARGET_H
#include "gfx/rendertarget.h"
#endif
#ifndef GFX_SPHERICAL_HARMONICS_H
#include "gfx/sphericalharmonics.h"
#endif
#ifndef GFX_SHADER_H
#include "gfx/shader.h"
#endif
//--------------------------------------------------------------------------------------------------------
//!
//! Irradiance Cache Manager
//! It generates a cube map per view per frame which stores
//!
//--------------------------------------------------------------------------------------------------------
class IrradianceManager
{
public:
IrradianceManager( void );
void GenerateIrradianceCubeMap( const Texture::Ptr pCubeMap, const SHChannelMatrices& SHCoeffs );
private:
SHChannelMatrices m_cachedSHCoeffs;
DebugShader* m_pIrradianceVertexShader;
DebugShader* m_pIrradiancePixelShader;
DebugShader* m_pDownsampleVertexShader;
DebugShader* m_pDownsamplePixelShader;
VBHandle m_hSimpleQuadData[7];
};
#endif // GFX_IRRADIANCE_H
|
ea721994f74ebfc480a3e1714139ed9cf66a4890
|
43a3f10d283605abab26790e68258b8351a4e856
|
/Image.h
|
ee630fff40426cc809a905a4e3b9727dce6f3aa0
|
[] |
no_license
|
shoval6/cppEX8
|
82fd9c50c9ffbdd9ddbabfc79b1ff6dfbd97b577
|
430328cd1e034dff47e0f0ef36320ba0e559afa9
|
refs/heads/master
| 2020-03-19T02:17:03.676011
| 2018-06-05T09:51:13
| 2018-06-05T09:51:13
| 135,615,213
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 546
|
h
|
Image.h
|
//#include <iostream>
#include <fstream>
#include "Board.h"
using namespace std;
struct RGB {
uint8_t red, green, blue;
public:
RGB() : red(255) , green(255) , blue(255) {}
RGB(uint8_t red, uint8_t green, uint8_t blue): red(red), green(green), blue(blue) {}
};
class Image{
private:
RGB* image;
int dim;
void drawTable(int cell);
void drawX(int row , int col , int cell);
void drawO(int row , int col , int cell);
public:
Image(int dim);
~Image();
string createPPM(Pair** pr , uint size);
};
|
d22372ada84e2c2d14f0fe2f4d76abc2f141015f
|
726df6fc883aa216b81f8e0682ec427febdbf89d
|
/VINew/vihwclass.h
|
00da406b00c3760ba05d4d0268d821fac1f6969e
|
[] |
no_license
|
Qmax/QUTE
|
48ac34384885558ea4f6310f122b2e4f6450853d
|
09d65671d4280d6cd9b9f97243846708d7968cff
|
refs/heads/master
| 2021-01-01T05:33:53.379760
| 2014-12-04T11:38:05
| 2014-12-04T11:38:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,721
|
h
|
vihwclass.h
|
#ifndef VIHWCLASS_H
#define VIHWCLASS_H
#include <BackPlaneInterface.h>
#include <PTEventInterfaces.h>
#include <CalibrationInterfaces.h>
#include <IPSOCCommunication.h>
#include "ApplicationCardInterface.h"
#include <QPluginLoader>
#include <vimodelview.h>
#include "PTSPIMemoryInterface.h"
#include "ad5318components.h"
#include "ad5293.h"
#include <math.h>
#include <unistd.h>
class VIHWClass
{
public:
VIHWClass();
~VIHWClass()
{
qDebug()<<"HWClass Destructor";
IPsoc->closeSerial();
IBackPlane->closeObject();
}
void initializeHWLibraries();
unsigned short checkProbeStatus();
void initializeInterruptSequeces();
bool checkMUXDetection();
void switchExternalMux(short int,short int);
bool readMUXStatus();
void readTestandRefChannel();
bool checkSPIMemoryCodeID();
unsigned int readPSOCID();
unsigned int switchTestMuxChannel(short int pTestPinChannel);
unsigned int switchRefMuxChannel(short int pRefPinChannel);
void switchVoltageRegister(unsigned int);
void setVoltageConstant(double pVolt);
void setVoltageGain(double pGain);
void switchFrequencyRegister(unsigned int);
void switchPROBE(PROBESELECTION m_eSelection);
void switchImpedanceRegister(unsigned int);
void driveRAM(unsigned short int *pData);
void driveDDS();
void calculateDDSFrequency(unsigned int);
void performDrive();
void performReceive();
void peformDriveConfiguration();
void setDriveCount(unsigned short pSamples,unsigned short pPrePostCount);
unsigned int getDriveCount();
void writeSPIMemory(unsigned int,unsigned int,short unsigned int *);
short unsigned int* ReadSPIData(unsigned int,unsigned int);
void setPSOCDelay();
void enableInterrupt();
void disableInterrupt();
void clearInterrupt();
unsigned int readEmbKeyValue();
unsigned int readAPPCardInterruptValue();
void writeReceiveRAM();
void writePSOC(unsigned int);
void onGNDRelay(bool);
void resetPSOC();//added by ravivarman 31st july
unsigned int readPSOC();
void resetDAC();
void updateDAC(double pVolt);
void stopDrive();
void checkforDriveDoneBit();
void changePSOCBaudRate(unsigned int);
protected:
IApplicationCardInterface *IAppCard;
ISPIMemoryInterface *ISPIMemory;
IntefaceBackPlane *IBackPlane;
IPSOCCOMMUNICATION *IPsoc;
PTEventInterface *IPTKeyEvent;
AD5318Components *m_objAD5318Component;
AD5293 *m_objAD5293Component;
unsigned short int *m_nReceiveData;
AD5318_DACSELECT m_eSelect;
double m_nVGain,m_nVConst;
unsigned int m_nInterruptValue;
private:
unsigned int m_nDriveCount;
};
#endif // VIHWCLASS_H
|
47f4439c8f5d5f35f62a3c74bfd5b8b1cebd6942
|
6d34fa23c708320b2e42d120d107f187106302e3
|
/orca/gporca/libnaucrates/include/naucrates/md/CSystemId.h
|
b32d6366b13a7b7c3b8927c0fecd8409c144da9d
|
[
"Apache-2.0"
] |
permissive
|
joe2hpimn/dg16.oss
|
a38ca233ba5c9f803f9caa99016a4c7560da9f08
|
2c4275c832b3e4b715b7475726db6757b127030c
|
refs/heads/master
| 2021-08-23T19:11:49.831210
| 2017-12-06T05:23:22
| 2017-12-06T05:23:22
| 113,322,478
| 2
| 1
| null | 2017-12-06T13:50:44
| 2017-12-06T13:50:44
| null |
UTF-8
|
C++
| false
| false
| 1,573
|
h
|
CSystemId.h
|
//---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2012 EMC Corp.
//
// @filename:
// CSystemId.h
//
// @doc:
// Class for representing the system id of a metadata provider
//
// @owner:
//
//
// @test:
//
//
//---------------------------------------------------------------------------
#ifndef GPMD_CSystemId_H
#define GPMD_CSystemId_H
#include "gpos/base.h"
#include "naucrates/md/IMDId.h"
#define GPDXL_SYSID_LENGTH 10
namespace gpmd
{
using namespace gpos;
//---------------------------------------------------------------------------
// @class:
// CSystemId
//
// @doc:
// Class for representing the system id of a metadata provider
//
//---------------------------------------------------------------------------
class CSystemId
{
private:
// system id type
IMDId::EMDIdType m_emdidt;
// system id
WCHAR m_wsz[GPDXL_SYSID_LENGTH + 1];
public:
// ctor
CSystemId(IMDId::EMDIdType emdidt, const WCHAR *wsz, ULONG ulLength = GPDXL_SYSID_LENGTH);
// copy ctor
CSystemId(const CSystemId &);
// type of system id
IMDId::EMDIdType Emdidt() const
{
return m_emdidt;
}
// system id string
const WCHAR *Wsz() const
{
return m_wsz;
}
// equality
BOOL FEquals(const CSystemId &sysid) const;
// hash function
ULONG UlHash() const;
};
// dynamic arrays over md system id elements
typedef CDynamicPtrArray<CSystemId, CleanupDelete> DrgPsysid;
}
#endif // !GPMD_CSystemId_H
// EOF
|
55e9c6453d3c7711cc149e8975226b5f8ffca7ea
|
464d6cb42fb8981595cbf7260069cd1e6a67fe2f
|
/HashMap/Standard IMportant/Word Pattern.cpp
|
7131b829c7c9a476e9b13f89541359068e88076f
|
[] |
no_license
|
rahul799/leetcode_problems
|
fd42276f85dc881b869072b74654f5811c6618ea
|
cc7f086eb9ac9bbd20ea004c46d89aa84df10d36
|
refs/heads/main
| 2023-04-14T05:09:31.016878
| 2021-04-20T19:46:52
| 2021-04-20T19:46:52
| 359,933,382
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,764
|
cpp
|
Word Pattern.cpp
| ERROR: type should be string, got "\n\nhttps://leetcode.com/problems/word-pattern/\n\n\n\n290. Word Pattern\nEasy\n\n1688\n\n208\n\nAdd to List\n\nShare\nGiven a pattern and a string s, find if s follows the same pattern.\n\nHere follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.\n\n \n\nExample 1:\n\nInput: pattern = \"abba\", s = \"dog cat cat dog\"\nOutput: true\nExample 2:\n\nInput: pattern = \"abba\", s = \"dog cat cat fish\"\nOutput: false\nExample 3:\n\nInput: pattern = \"aaaa\", s = \"dog cat cat dog\"\nOutput: false\nExample 4:\n\nInput: pattern = \"abba\", s = \"dog dog dog dog\"\nOutput: false\n \n\nConstraints:\n\n1 <= pattern.length <= 300\npattern contains only lower-case English letters.\n1 <= s.length <= 3000\ns contains only lower-case English letters and spaces ' '.\ns does not contain any leading or trailing spaces.\nAll the words in s are separated by a single space.\n\n\n\n\n\n\n\n\n\nclass Solution {\npublic:\n bool wordPattern(string pattern, string s) {\n // goal\n // given a pattern of char\n // return true/false if string s follows the same pattern\n \n \n // questions/info\n // pattern length -> 1 and 300\n // s length -> 1 and 3000\n // s substrings are separated by a space\n // s does not contain any trailing or leading spaces\n \n // process\n // 1st map -> for char map -> unordered_map<char, int>\n // 2nd map -> for string map -> unordered_map<string, int>\n // loop over our string, make sure number of substring == size of pattern\n // time complexity -> o(n), size of pattern/number of substrings in s \n // space complexity -> o(n), size of ordered_maps based on size of pattern/number substring of s \n \n \n unordered_map<char, string> char_map;\n unordered_map<string, char> string_map;\n \n stringstream ss (s);\n string holder;\n int i = 0; \n int num_substring = 0;\n \n while (ss >> holder) { \n if (char_map.count(pattern[i]) == 0 && string_map.count(holder) == 0) { \n char_map[pattern[i]] = holder;\n string_map[holder] = pattern[i]; \n } else if (char_map.count(pattern[i]) == 1 && string_map.count(holder) == 1) { \n if (char_map[pattern[i]] != holder || string_map[holder] != pattern[i]) {\n return false;\n } \n } else {\n return false; \n } \n i++;\n num_substring++;\n }\n return num_substring == pattern.size() ? true : false; \n }\n};\n"
|
12f8c04729155010a86816dc8dd7feefdf4c098c
|
ee70238bbfc121e4bf6fcc7631e68a5e48ebf3da
|
/include/PhysicsManager.h
|
cc23a8e37a1bbcc3a6582cfe1655bd5d48c2d995
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
callumW/ECSTest
|
cc263a1e1dfb3d0d4c9e4e911a4f5dd1503ac852
|
0ac38c42af550e561ebe31412f3531cdbb3059ef
|
refs/heads/master
| 2023-01-12T02:52:12.815295
| 2020-11-07T22:34:54
| 2020-11-07T22:34:54
| 258,451,436
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 666
|
h
|
PhysicsManager.h
|
#ifndef PHYSICS_MANAGER_H
#define PHYSICS_MANAGER_H
#include <array>
#include <unordered_map>
#include <vector>
#include "ComponentManager.h"
#include "Entity.h"
#include "PhysicsComponent.h"
class PhysicsManager : public ComponentManager<physics_component_t> {
public:
static PhysicsManager& get();
void simulate(float delta);
b2Body* create_body(b2BodyDef const& body_def) { return world.CreateBody(&body_def); }
b2World& World() { return world; }
private:
PhysicsManager() : world(GRAVITY){};
virtual void pre_remove(physics_component_t* component) override;
b2Vec2 const GRAVITY = {0.0f, -10.0f};
b2World world;
};
#endif
|
7eacae3a818c97c143b5e4ed548d73db81e8bf9e
|
bf9b2a5b68b6f97af49fd8542a99a95542404557
|
/tools/streamingServer/rpiCamera.h
|
40e2a653d213b603f3056dd5229756221ad48545
|
[] |
no_license
|
viv92/video-analytics
|
7d6f2b4bddac7d981fe9cbbf8aae9cdba11d8e62
|
c0d1b431ceb42c6734460ae4933f7df96f0666f9
|
refs/heads/master
| 2020-07-10T12:34:41.344895
| 2019-08-25T07:56:58
| 2019-08-25T07:56:58
| 204,263,798
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 364
|
h
|
rpiCamera.h
|
//
// Created by aitoe on 12/09/2017
//
#ifndef RPICAMERA_H
#define RPICAMERA_H
#include <cv.h>
#include <opencv2/highgui.hpp>
#include <unistd.h>
#include <iostream>
class rpiCamera {
public:
rpiCamera();
void getFrame();
std::vector<uchar>* getEncodedFrame();
private:
cv::VideoCapture* camera;
cv::Mat frame;
};
#endif // RPICAMERA_H
|
3df542abb95d87b6f0c57ec30ade43ab3a93876c
|
d440825440b2582c9bf39e627a8f3acd3124875a
|
/Project/EventManager.cpp
|
135ffc45a23a6624f3068ecb48ef26565e24c414
|
[] |
no_license
|
wnchen1/Otto1
|
f107abb3f7d58e21a8ba3669d8f9c2330e87a5ef
|
e358dda8cb03f81174dc885e5a465f2e205bd12a
|
refs/heads/master
| 2023-07-09T05:42:07.058444
| 2021-08-17T06:36:00
| 2021-08-17T06:36:00
| 390,887,170
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,802
|
cpp
|
EventManager.cpp
|
#include "EventManager.h"
#include "Game.h"
#include <cstring>
#include <iostream>
void EventManager::Init()
{
s_currentKeyState = SDL_GetKeyboardState(&s_numKeys);
s_lastKeyState = new Uint8[s_numKeys];
std::memcpy(s_lastKeyState, s_currentKeyState, s_numKeys);
s_currentMouseState = SDL_GetMouseState(&s_mousePos.x, &s_mousePos.y);
s_lastMouseState = s_currentMouseState;
std::cout << "EventManager init done!" << std::endl;
}
void EventManager::HandleEvents()
{
SDL_Event event;
std::memcpy(s_lastKeyState, s_currentKeyState, s_numKeys);
s_lastMouseState = s_currentMouseState;
s_lastKeyDown = -1;
s_lastKeyUp = -1;
while (SDL_PollEvent(&event)) // Pump events invoked.
{
switch (event.type) // Parse some global events.
{
case SDL_QUIT: // User pressed window's 'x' button.
Game::GetInstance().Quit();
break;
case SDL_KEYDOWN:
s_lastKeyDown = event.key.keysym.sym;
break;
case SDL_KEYUP:
s_lastKeyUp = event.key.keysym.sym;
if (event.key.keysym.sym == SDLK_ESCAPE)
Game::GetInstance().Quit();
break;
}
}
s_currentKeyState = SDL_GetKeyboardState(&s_numKeys);
s_currentMouseState = SDL_GetMouseState(&s_mousePos.x, &s_mousePos.y);
}
bool EventManager::KeyHeld(const SDL_Scancode key)
{
if (s_currentKeyState)
{
return s_currentKeyState[key] == 1;
}
return false;
}
bool EventManager::KeyPressed(const SDL_Scancode key)
{
return (s_currentKeyState[key] > s_lastKeyState[key]);
}
bool EventManager::KeyReleased(const SDL_Scancode key)
{
return (s_currentKeyState[key] < s_lastKeyState[key]);
}
int EventManager::LastKeyDown()
{
return s_lastKeyDown;
}
int EventManager::LastKeyUp()
{
return s_lastKeyUp;
}
bool EventManager::MouseHeld(const int button)
{
if (button >= 1 && button <= 3)
return (s_currentMouseState & SDL_BUTTON(button));
else
return false;
}
bool EventManager::MousePressed(const int button)
{
return ((s_currentMouseState & SDL_BUTTON(button)) > (s_lastMouseState & SDL_BUTTON(button)));
}
bool EventManager::MouseReleased(const int button)
{
return ((s_currentMouseState & SDL_BUTTON(button)) < (s_lastMouseState & SDL_BUTTON(button)));
}
SDL_Point& EventManager::GetMousePos()
{
return s_mousePos;
}
void EventManager::SetCursor(const SDL_SystemCursor& cursor)
{
SDL_FreeCursor(s_cursor);
s_cursor = SDL_CreateSystemCursor(cursor);
SDL_SetCursor(s_cursor);
}
void EventManager::Quit()
{
delete s_lastKeyState;
SDL_FreeCursor(s_cursor);
}
const Uint8* EventManager::s_currentKeyState = nullptr;
Uint8* EventManager::s_lastKeyState;
int EventManager::s_numKeys;
int EventManager::s_lastKeyDown;
int EventManager::s_lastKeyUp;
SDL_Point EventManager::s_mousePos = { 0,0 };
Uint32 EventManager::s_currentMouseState;
Uint32 EventManager::s_lastMouseState;
SDL_Cursor* EventManager::s_cursor;
|
cb727eb1e414d82545aaf6ca0c941a58e6ff7048
|
edd2c827b36f3082bde9ec0a58ed5703e94e1167
|
/Test/RegularPolygonTest.h
|
94fe5903d40b3363fc8ed700e3cc8d37be7cb18f
|
[] |
no_license
|
gloomyRuby/task31
|
d5ab6d96a8204fc63a73cc5cabf700c7b30945dc
|
230b42755a5a8c2deb0d95ced070da02b7a4da74
|
refs/heads/master
| 2021-05-12T00:59:51.078434
| 2018-02-04T18:45:54
| 2018-02-04T18:45:54
| 117,547,823
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 119
|
h
|
RegularPolygonTest.h
|
//
// Created by Oysha on 28/01/2018.
//
#pragma once
class RegularPolygonTest
{
public:
void test() const;
};
|
43551a1069679dcfdeb06d74f9ab504c6a57ecc7
|
5ee0eb940cfad30f7a3b41762eb4abd9cd052f38
|
/Case_save/case2/900/nut
|
b3e5516f50249086e9a8b4aa0849b3a2e2d0a368
|
[] |
no_license
|
mamitsu2/aircond5_play4
|
052d2ff593661912b53379e74af1f7cee20bf24d
|
c5800df67e4eba5415c0e877bdeff06154d51ba6
|
refs/heads/master
| 2020-05-25T02:11:13.406899
| 2019-05-20T04:56:10
| 2019-05-20T04:56:10
| 187,570,146
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,975
|
nut
|
/*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "900";
object nut;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 2 -1 0 0 0 0];
internalField nonuniform List<scalar>
459
(
0.0010604
0.00115471
0.00117202
0.00122784
0.00127941
0.00132724
0.00137331
0.00142027
0.00145862
0.00148147
0.00148346
0.0014603
0.00141129
0.0013427
0.00126692
0.000473716
0.000582541
0.000637004
0.000616756
0.00058652
0.000553541
0.000518715
0.000486053
0.000456712
0.000430622
0.000407423
0.000386755
0.000368298
0.000351549
0.00033595
0.000320733
0.000304746
0.000296095
0.000273148
0.0014638
0.00348217
0.00330476
0.00385271
0.0043748
0.00490347
0.00539372
0.00577443
0.00610416
0.00638282
0.00656892
0.00660562
0.00640421
0.00576856
0.00412627
0.00128929
0.000831422
0.000531122
0.00100738
0.00132318
0.00152395
0.00160595
0.00158176
0.00133632
0.0011777
0.00105873
0.000964528
0.000887588
0.000822501
0.000763825
0.000708878
0.000656102
0.000610327
0.000565365
0.000678889
0.000375007
0.00180294
0.0047766
0.00406088
0.00522667
0.00579805
0.00622103
0.00654694
0.00679797
0.00704502
0.00730527
0.00755194
0.00773805
0.00780098
0.00766608
0.00716245
0.0057424
0.00125122
0.00109123
0.00145891
0.00174663
0.00196823
0.00209292
0.00201058
0.000732849
0.000651369
0.000585831
0.00053275
0.000489306
0.000453357
0.000423353
0.00039827
0.000377584
0.000402557
0.000453858
0.000764773
0.000443359
0.00213201
0.00621105
0.00405884
0.00557236
0.00617404
0.0063962
0.00650301
0.00659963
0.00676411
0.0070067
0.00730077
0.00759697
0.00782759
0.00794023
0.00785696
0.00735461
0.005666
0.00146771
0.00183794
0.00229372
0.00263964
0.00285239
0.00294918
0.00274298
0.000815918
0.000746876
0.000698825
0.00066314
0.000632875
0.000604074
0.000576435
0.000547191
0.000512677
0.000480612
0.000482389
0.000905639
0.000494054
0.00246892
0.00806719
0.00455728
0.00531125
0.00616175
0.00633158
0.0062958
0.00624947
0.00638576
0.00662663
0.00695467
0.00731408
0.00761182
0.00777471
0.00774718
0.00747593
0.00681596
0.00551396
0.00496186
0.00465058
0.00442269
0.00424904
0.00411802
0.00395223
0.00341068
0.00316685
0.0030323
0.00292458
0.00280014
0.00260878
0.00232949
0.00198159
0.001591
0.00118827
0.00086823
0.000883294
0.000636955
0.000629996
0.00075237
0.000839144
0.00282522
0.0100754
0.0064831
0.00527986
0.00581539
0.00618176
0.00615048
0.00613225
0.00625999
0.00648174
0.00680604
0.00718806
0.00752516
0.0077036
0.00764818
0.00735357
0.00688057
0.00632246
0.00588966
0.00553021
0.0052101
0.00494877
0.00474511
0.00456238
0.00433602
0.00414706
0.00398028
0.00381626
0.00364428
0.00345494
0.00319107
0.00283669
0.00239204
0.00188137
0.00141313
0.00101342
0.000828162
0.000751523
0.00110632
0.000875675
0.00314894
0.0114898
0.00925138
0.0070464
0.00654189
0.00657922
0.00648894
0.00637732
0.00637469
0.00654468
0.00688188
0.00730337
0.0076707
0.00784041
0.0077262
0.007343
0.00682277
0.00634864
0.00600173
0.00569458
0.00537263
0.00504674
0.0047307
0.00444933
0.0042158
0.00403172
0.00387069
0.00371826
0.00357213
0.00343649
0.00331053
0.00308161
0.00272563
0.00227702
0.00185104
0.00143511
0.00118988
0.00112852
0.00116129
0.000972216
0.00320974
0.010251
0.00914447
0.00852469
0.00803737
0.00746148
0.00687098
0.00651046
0.00647026
0.00672937
0.00718676
0.00768947
0.00806116
0.00814969
0.00789135
0.00734189
0.00669913
0.0061996
0.00585757
0.00543902
0.00495374
0.00448175
0.00409347
0.00381464
0.00362313
0.00348182
0.00336458
0.00326459
0.00318594
0.00313737
0.00312778
0.00312803
0.00292463
0.00260989
0.00234296
0.00222272
0.00234092
0.00276404
0.00365742
0.00151079
0.0031223
0.0036998
0.00412864
0.00427075
0.00438344
0.0045784
0.00494942
0.00555221
0.00633559
0.0071775
0.00793515
0.00847604
0.00867824
0.00846325
0.00787426
0.00707564
0.00636219
0.00576981
0.00519669
0.00457156
0.00399158
0.00355095
0.00325539
0.00306167
0.00292481
0.00281488
0.00271685
0.00262478
0.0025358
0.00244744
0.00235798
0.00226881
0.00219674
0.00215118
0.00215374
0.0021963
0.00221666
0.00215427
0.002015
0.00140747
0.0015752
0.00356668
0.00538424
0.006792
0.00796348
0.00885931
0.00943326
0.0096883
0.00966896
0.00940991
0.00888809
0.00813361
0.0071884
0.0062833
0.00551254
0.00477946
0.00407275
0.00347606
0.00304596
0.00276932
0.00259009
0.00246507
0.00237021
0.00229365
0.00223012
0.00217794
0.00213772
0.00211215
0.002106
0.00212378
0.00215585
0.00220354
0.00226493
0.0023233
0.00235301
0.00234681
0.00209556
0.00116181
0.00217238
0.00586509
0.00835847
0.00891883
0.00928325
0.00943095
0.00922887
0.00874478
0.00807248
0.00730362
0.00651547
0.00578942
0.00510926
0.00447112
0.00384631
0.00327592
0.00282859
0.00250899
0.00227816
0.00211966
0.0020098
0.00193463
0.00188798
0.00186709
0.00186986
0.00189333
0.00193287
0.00198143
0.00204664
0.00212666
0.0022196
0.00232176
0.00242316
0.00251016
0.00258363
0.00263426
0.00182789
0.00119752
0.00193031
0.0020477
0.00213214
0.0022929
0.00221774
0.00211349
0.00202819
0.00192125
0.00178791
0.00163903
0.00147832
0.00131193
0.00114759
0.000995538
0.000868942
0.000774077
0.00070862
0.000666843
0.000642748
0.000631493
0.000630082
0.00063433
0.000643191
0.000656124
0.000672864
0.000693316
0.000717523
0.000745732
0.000778522
0.000817057
0.000860963
0.000910525
0.000966084
0.00102811
0.00109665
0.00117483
0.00119951
0.00109119
0.00102301
0.0011697
)
;
boundaryField
{
floor
{
type nutkWallFunction;
Cmu 0.09;
kappa 0.41;
E 9.8;
value nonuniform List<scalar>
29
(
0.000151681
5.6343e-05
7.01601e-05
7.69521e-05
7.44349e-05
7.06577e-05
6.65107e-05
6.20983e-05
5.79268e-05
5.41496e-05
5.07653e-05
4.77341e-05
4.50152e-05
4.25713e-05
4.03399e-05
3.82493e-05
3.61977e-05
3.40283e-05
3.28485e-05
2.96958e-05
2.96957e-05
4.34624e-05
5.24225e-05
5.89545e-05
0.000151681
5.6343e-05
6.36764e-05
0.000131394
0.000174482
)
;
}
ceiling
{
type nutkWallFunction;
Cmu 0.09;
kappa 0.41;
E 9.8;
value nonuniform List<scalar>
43
(
0.000225605
0.00023838
0.000247522
0.000264957
0.000256928
0.000245693
0.000236447
0.000224788
0.000210149
0.00019366
0.000175675
0.000156823
0.00013794
0.000120193
0.000105178
9.376e-05
8.57853e-05
8.06497e-05
7.76705e-05
7.62742e-05
7.60989e-05
7.66262e-05
7.77249e-05
7.93253e-05
8.13916e-05
8.39076e-05
8.68742e-05
9.03164e-05
9.42983e-05
9.89527e-05
0.000104225
0.000110138
0.000116724
0.000124024
0.000132032
0.000141099
0.000143947
0.000131397
0.000123427
0.000140509
0.000352838
0.000412378
0.000251685
)
;
}
sWall
{
type nutkWallFunction;
Cmu 0.09;
kappa 0.41;
E 9.8;
value uniform 0.000225669;
}
nWall
{
type nutkWallFunction;
Cmu 0.09;
kappa 0.41;
E 9.8;
value nonuniform List<scalar> 6(0.00010161 0.000105986 0.000117451 0.000139605 0.000143729 0.000140519);
}
sideWalls
{
type empty;
}
glass1
{
type nutkWallFunction;
Cmu 0.09;
kappa 0.41;
E 9.8;
value nonuniform List<scalar> 9(0.000127901 0.000174276 0.000212141 0.000248142 0.000284385 0.00032215 0.000356034 0.000362368 0.00035329);
}
glass2
{
type nutkWallFunction;
Cmu 0.09;
kappa 0.41;
E 9.8;
value nonuniform List<scalar> 2(0.000179426 0.000167768);
}
sun
{
type nutkWallFunction;
Cmu 0.09;
kappa 0.41;
E 9.8;
value nonuniform List<scalar>
14
(
0.000127801
0.000138764
0.000140765
0.000147197
0.000153111
0.000158571
0.00016381
0.000169129
0.00017346
0.000176034
0.000176258
0.000173649
0.000168114
0.000160332
)
;
}
heatsource1
{
type nutkWallFunction;
Cmu 0.09;
kappa 0.41;
E 9.8;
value nonuniform List<scalar> 3(7.60889e-05 9.11239e-05 0.000101608);
}
heatsource2
{
type nutkWallFunction;
Cmu 0.09;
kappa 0.41;
E 9.8;
value nonuniform List<scalar> 4(0.000154235 0.000100678 0.000100678 0.000149875);
}
Table_master
{
type nutkWallFunction;
Cmu 0.09;
kappa 0.41;
E 9.8;
value nonuniform List<scalar> 9(8.87404e-05 7.87335e-05 7.05752e-05 6.38864e-05 5.83509e-05 5.37242e-05 4.98275e-05 4.65432e-05 4.38149e-05);
}
Table_slave
{
type nutkWallFunction;
Cmu 0.09;
kappa 0.41;
E 9.8;
value nonuniform List<scalar> 9(9.88074e-05 9.04497e-05 8.45796e-05 8.01892e-05 7.64433e-05 7.28584e-05 6.93986e-05 6.57157e-05 6.13376e-05);
}
inlet
{
type calculated;
value uniform 0.000100623;
}
outlet
{
type calculated;
value nonuniform List<scalar> 2(0.00193031 0.0020477);
}
}
// ************************************************************************* //
|
|
3ff5d5473af7afbeecfb017de04b212034fc60ff
|
6e28b96a7b9a516ee8f851a2de081a422313b47b
|
/HVT_WithoutD2D.cc
|
26cdd7135979424804afb9ad76b0a2a72a2bffe1
|
[] |
no_license
|
lvwf1/ECE6110D2D
|
e334afd2ea4922cdbc44a0f0a078c070c0ebae8c
|
825ba1ee26f73f3f17daa577c56c77c75ec91556
|
refs/heads/master
| 2021-05-08T19:20:09.499608
| 2018-01-30T16:55:27
| 2018-01-30T16:55:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,814
|
cc
|
HVT_WithoutD2D.cc
|
#include <iostream>
#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/netanim-module.h"
#include "ns3/flow-monitor-module.h"
#include "ns3/mobility-module.h"
#include "ns3/lte-module.h"
#include <ns3/buildings-helper.h>
using namespace ns3;
int main(int argc, char *argv[]) {
uint16_t port = 8080;
double delay = 2.0;
double interval = 0.05;
double simTime = 10.0;
uint64_t dataRate = 50000000;
CommandLine cmd;
cmd.AddValue("delay", "Link latency in miliseconds", delay);
cmd.AddValue("dataRate", "Data rate in bps", dataRate);
cmd.AddValue("interval", "UDP client packet interval", interval);
cmd.Parse(argc, argv);
// Create 5 nodes, 1 for base station, 4 for user mobiles.
NodeContainer baseNode;
NodeContainer userNodes;
baseNode.Create(1);
userNodes.Create(4);
Ptr<LteHelper> LTEHelper = CreateObject<LteHelper>();
// Set the nodes position
Ptr<ListPositionAllocator> userPosition = CreateObject<ListPositionAllocator>();
userPosition->Add(Vector(10, 10, 0));
userPosition->Add(Vector(0, 10, 0));
userPosition->Add(Vector(20, 10, 0));
userPosition->Add(Vector(-10, 10, 0));
Ptr<ListPositionAllocator> basePosition = CreateObject<ListPositionAllocator>();
basePosition->Add(Vector(5, -20, 0));
MobilityHelper mobilityHelper;
mobilityHelper.SetMobilityModel("ns3::ConstantPositionMobilityModel");
// Install userNodes to Mobility Model
mobilityHelper.SetPositionAllocator(userPosition);
mobilityHelper.Install(userNodes);
BuildingsHelper::Install(userNodes);
// Install baseNode to Mobility Model
mobilityHelper.SetPositionAllocator(basePosition);
mobilityHelper.Install(baseNode);
BuildingsHelper::Install(baseNode);
// Create Device and install them on nodes.
NetDeviceContainer baseDev = LTEHelper->InstallEnbDevice(baseNode);
NetDeviceContainer userDev1 = LTEHelper->InstallUeDevice(userNodes.Get(0));
NetDeviceContainer userDev2 = LTEHelper->InstallUeDevice(userNodes.Get(1));
NetDeviceContainer userDev3 = LTEHelper->InstallUeDevice(userNodes.Get(2));
NetDeviceContainer userDev4 = LTEHelper->InstallUeDevice(userNodes.Get(3));
// Attach the user mobile to base Station.
LTEHelper->Attach(userDev1, baseDev.Get(0));
LTEHelper->Attach(userDev2, baseDev.Get(0));
LTEHelper->Attach(userDev3, baseDev.Get(0));
LTEHelper->Attach(userDev4, baseDev.Get(0));
// Create the topology.
PointToPointHelper pointHelper;
// Create channels between user mobiles and base station.
pointHelper.SetChannelAttribute("Delay", TimeValue(MilliSeconds(delay)));
pointHelper.SetDeviceAttribute("DataRate", DataRateValue(DataRate(dataRate)));
NetDeviceContainer dev1 = pointHelper.Install(userNodes.Get(0), baseNode.Get(0));
NetDeviceContainer dev2 = pointHelper.Install(userNodes.Get(1), baseNode.Get(0));
NetDeviceContainer dev3 = pointHelper.Install(userNodes.Get(2), baseNode.Get(0));
NetDeviceContainer dev4 = pointHelper.Install(userNodes.Get(3), baseNode.Get(0));
// Install nodes to internet stack
InternetStackHelper stackHelper;
stackHelper.Install(userNodes);
stackHelper.Install(baseNode);
// Add IP address to devices
Ipv4AddressHelper ipv4AddressHelper;
ipv4AddressHelper.SetBase("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer ip1 = ipv4AddressHelper.Assign(dev1);
ipv4AddressHelper.SetBase("10.1.2.0", "255.255.255.0");
Ipv4InterfaceContainer ip2 = ipv4AddressHelper.Assign(dev2);
ipv4AddressHelper.SetBase("10.1.3.0", "255.255.255.0");
Ipv4InterfaceContainer ip3 = ipv4AddressHelper.Assign(dev3);
ipv4AddressHelper.SetBase("10.1.4.0", "255.255.255.0");
Ipv4InterfaceContainer ip4 = ipv4AddressHelper.Assign(dev4);
Ipv4GlobalRoutingHelper::PopulateRoutingTables();
// Create UDP Server application on base station node
UdpServerHelper server(port);
ApplicationContainer serverApp = server.Install(baseNode.Get(0));
// Set up the applications start and stop time
serverApp.Start(Seconds(1.0));
serverApp.Stop(Seconds(simTime));
// Create UDP client application to set up direct connection between
// user node 1 and user node 0
uint32_t maxPacketSize = 512;
uint32_t maxPacketCount = 10000;
UdpClientHelper client1(ip2.GetAddress(0), port);
client1.SetAttribute("MaxPackets", UintegerValue(maxPacketCount));
client1.SetAttribute("Interval", TimeValue(Seconds(interval)));
client1.SetAttribute("PacketSize", UintegerValue(maxPacketSize));
ApplicationContainer app1 = client1.Install(userNodes.Get(0));
app1.Start(Seconds(2.0));
app1.Stop(Seconds(simTime));
// Create UDP client application to transfer packets between user node 0
// and other nodes
UdpClientHelper client2(ip2.GetAddress(0), port);
client2.SetAttribute("MaxPackets", UintegerValue(maxPacketCount));
client2.SetAttribute("Interval", TimeValue(Seconds(interval)));
client2.SetAttribute("PacketSize", UintegerValue(maxPacketSize));
ApplicationContainer app2 = client2.Install(userNodes.Get(2));
app2.Start(Seconds(2.0));
app2.Stop(Seconds(simTime));
UdpClientHelper client3(ip2.GetAddress(0), port);
client3.SetAttribute("MaxPackets", UintegerValue(maxPacketCount));
client3.SetAttribute("Interval", TimeValue(Seconds(interval)));
client3.SetAttribute("PacketSize", UintegerValue(maxPacketSize));
ApplicationContainer app3 = client2.Install(userNodes.Get(3));
app3.Start(Seconds(2.0));
app3.Stop(Seconds(simTime));
FlowMonitorHelper flowmon;
Ptr<FlowMonitor> moniter = flowmon.InstallAll();
Simulator::Stop(Seconds(simTime));
Simulator::Run();
Ptr<Ipv4FlowClassifier> classifier = DynamicCast<Ipv4FlowClassifier>(flowmon.GetClassifier());
std::map<FlowId, FlowMonitor::FlowStats> stats = moniter->GetFlowStats();
for (std::map<FlowId, FlowMonitor::FlowStats>::const_iterator i = stats.begin(); i != stats.end(); ++i) {
Ipv4FlowClassifier::FiveTuple t = classifier->FindFlow(i->first);
std::cout << "Flow " << i->first << " (" << t.sourceAddress << " -> " << t.destinationAddress << ")\n";
std::cout << "Tx Bytes: " << i->second.txBytes << "\n";
std::cout << "Rx Bytes: " << i->second.rxBytes << "\n";
std::cout << "Throughput: "
<< i->second.rxBytes * 8.0 / (i->second.timeLastRxPacket.GetSeconds() -
i->second.timeFirstTxPacket.GetSeconds()) / 1024 / 1024
<< " Mbps\n";
}
Simulator::Destroy();
return 0;
}
|
2755c9bedbe03d5e1b931f6d9706a90d506c919c
|
814392727ee54fcbf3fc1fb8ab74aaec73b2f5a2
|
/respo/Data_Structure/Binary_Tree/Binary_Tree/tttcpp.cpp
|
af28020e4320e5bd82bdc17590452b45bdf38800
|
[] |
no_license
|
Mrhs121/NEEP
|
9298b86685c339e5b0167b74cbd428f9bccd9586
|
960c2aeac277ea809799fd85a04a12b2d6efb936
|
refs/heads/master
| 2021-06-10T03:15:31.236296
| 2021-04-02T13:29:58
| 2021-04-02T13:29:58
| 153,987,706
| 3
| 1
| null | null | null | null |
GB18030
|
C++
| false
| false
| 2,463
|
cpp
|
tttcpp.cpp
|
#include "stdafx.h"
#include <stdlib.h>
#include<iostream>
using namespace std;
enum Tag { link, thread }; //这里定义一个枚举类型,link(0)表示指向孩子,thread(1)表示指向前驱后继的线索
//定义节点结构
typedef struct BiThreadNode
{
char data;
struct BiThreadNode *lchild, *rchild;
Tag ltag, rtag;
}BiThreadNode, *BiThreadTree;
//定义一个全局变量,始终指向刚刚访问过的节点
BiThreadTree pre;
//前序遍历创建二叉树
void createBtTree(BiThreadTree &T)
{
char c;
cout << "input (# mean null) : ";
cin >> c;
if (c == '#')
{
T = NULL;
}
else
{
T = new BiThreadNode;
T->data = c;
T->ltag = T->rtag = link;
cout << c << " l child" << endl;
createBtTree(T->lchild);
cout << c << " r child" << endl;
createBtTree(T->rchild);
}
}
//中序遍历二叉线索树并且对节点进行处理.
void midOrderThread(BiThreadTree &T)
{
if (T)
{
midOrderThread(T->lchild);
//对节点进行处理,即把判断为线索的指针域修改为thread。注意修改前驱后继时分别对pre和T两个指针指向的节点进行处理。
if (!T->lchild)
{
T->ltag = thread;
T->lchild = pre; //当发现左孩子为空时另ltag=thread,同时让lchild指针(本来为空)指向前驱节点pre
}
if (!pre->rchild)
{
T->rtag = thread; //当发现pre节点的右孩子为空时,另其rtag=thread,同时让他的rchild指向其后继节点T
pre->rchild = T;
}
pre = T;
midOrderThread(T->rchild);
}
}
//由于以上只是处理了动态的过程的代码,初始化时会因为pre指针没有赋值从而出错,需要在建立个函数解决此问题
//建立头结点,并中序线索二叉树
void inOrderThread(BiThreadTree &p, BiThreadTree &t)
{
p = new BiThreadNode;
p->ltag = link;
p->rtag = thread;
p->rchild = p;
if (!t)
{
p->lchild = p;
p->ltag = link;
}
else
{
p->lchild = t;
pre = p;
midOrderThread(t);
pre->rchild = p;
pre->rtag = thread;
p->rchild = pre;
}
}
//非递归方式遍历二叉树并输出
void inOrderVisit(BiThreadTree p)
{
BiThreadTree T;
T = p->lchild ;
while (T != p)
{
while (T->ltag == link)
{
T = T->lchild;
}
cout << T->data;
while (T->rtag == thread && T->rchild != p)
{
T = T->rchild;
cout << T->data;
}
T = T->rchild;
}
}
int main()
{
BiThreadTree Tree, p;
createBtTree(Tree);
inOrderThread(p, Tree);
inOrderVisit(p);
system("pause");
}
|
9b5f73556ff77e3cc1fc4c9e064423e669b63ccf
|
9997cb296b19a9ae3149484caa2290c26c1f030a
|
/boj/03032/03032.cpp14.cpp
|
40dbc83480f1be55bb469bd681acb633c0d14cbf
|
[] |
no_license
|
pukuba/Algorithm
|
0eca36297a5a278e666cb2d851bd0a4c99e11357
|
ea71d0e21534a2a54626fc89da58e58ea8eb1791
|
refs/heads/master
| 2023-06-03T05:54:43.564074
| 2021-06-23T02:26:06
| 2021-06-23T02:26:06
| 317,562,256
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 636
|
cpp
|
03032.cpp14.cpp
|
#include <bits/stdc++.h>
using namespace std;
int d[104][104],arr[104],n,x,sum,ans;
int f(int s,int e,int r){
if(r == n-1) return 0;
if(d[s][e] != -1) return d[s][e];
int ns = s==1 ? n : s-1,ne = e==n ? 1 : e+1;
if(r&1) return d[s][e] = max(f(s,ne,r+1)+arr[ne],f(ns,e,r+1)+arr[ns]);
return d[s][e] = min(f(s,ne,r+1),f(ns,e,r+1));
}
int main(){
ios_base::sync_with_stdio(0);cin.tie(nullptr);
memset(d,-1,sizeof(d));
cin>>n;
for(int i=1; i<=n; i++){
cin>>x;
if(x&1) arr[i]++,sum++;
}
for(int i=1; i<=n; i++) ans += f(i,i,0)+arr[i] > sum/2;
cout<<ans;
}
|
29f9d824fce217ae20c6ad978a9d37120978e865
|
40172ef126338b72ee2eff03056c0fced996c957
|
/day7/day7.cpp
|
878a4fa6b71050aa23f302f3d5bf8a89701b1969
|
[
"MIT"
] |
permissive
|
cristicretu/advent_of_code_2020
|
70413e0cfc2adc39cd475331bbb6955986d44cce
|
456969f98bd6df56800301a006fbd6971957914e
|
refs/heads/main
| 2023-02-03T18:47:17.615332
| 2020-12-23T19:21:56
| 2020-12-23T19:21:56
| 322,234,135
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 394
|
cpp
|
day7.cpp
|
/**
* author: etohirse
* created: 20.12.2020 20:54:52
**/
#include <algorithm>
#include <fstream>
#include <map>
#include <string>
#include <vector>
using rule = std::map<std::string, int>;
std::ifstream fin("input.in");
std::ofstream fout("input.out");
int main() {
std::map<std::string, rule> rules;
std::string line;
while (geline(line)) {
line.erase
}
return 0;
}
|
d95f7605b77570f6bc1d347bef442f087f336130
|
5c364c06003ec3d6b9b2a8b91eaab6d0293ff907
|
/牛客/牛牛找工作_二分/main.cpp
|
b2ee35f2841b0ab17216532c9bd615533be97232
|
[] |
no_license
|
majiaoliya/acm
|
aa3d4b9679ac8f7ace28c2f4b5a21dc2d6421b71
|
c0aa06b08547e6d75ea5a4b7db3cfe5e7f9bed83
|
refs/heads/master
| 2020-09-17T01:51:16.950731
| 2020-04-29T15:02:05
| 2020-04-29T15:02:05
| 223,952,294
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,386
|
cpp
|
main.cpp
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#define MAXN 300005
#include <map>
#define ll long long int
#define max(x, y) ( x > y ? x : y )
using namespace std;
ll n, m;
struct Node {
ll hard, val;
} arr[MAXN];
map<ll, ll> mp;
int cmp(Node& x, Node& y) { return x.hard < y.hard; }
// 这个二分有很大的问题
ll binsearch(ll val) {
ll mid = -1, lef = 0, rig = n-1;
while(lef < rig) {
mid = (lef + rig + 1) >> 1;
if(arr[mid].hard <= val) lef = mid;
else rig = mid - 1;
}
if(arr[lef].hard > val) return -1;
printf("%lld %lld", val, arr[lef].hard);
return arr[lef].hard;
}
int main() {
freopen("test", "r", stdin);
while(~scanf("%lld %lld", &n, &m)) {
mp.clear();
ll tmax = 0;
for(int i=0; i<n; i++) {
scanf("%lld %lld", &arr[i].hard, &arr[i].val);
}
sort(arr, arr+n, cmp);
tmax = arr[0].val;
mp[arr[0].hard] = tmax;
for(int i=1; i<n; i++) {
tmax = max(tmax, arr[i].val);
mp[arr[i].hard] = tmax;
}
ll x;
while(m--) {
scanf("%lld", &x);
map<ll, ll>::iterator it = mp.lower_bound(x);
if(it == mp.end()) it --;
else if(it->first > x) it --;
printf("%lld\n", it->second);
// printf("x:%lld idx:%lld\n", x, idx);
}
}
/**
int temp[] = {
1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 9, 9, 9
};
for(int i=0; i<=12; i++)
printf("[%d %lld] ", i, binsearch(i, temp, 13));
*/
return 0;
}
|
491497acc1d1a7c23c2011d0b070acb4ae58243f
|
68572da614e34b418daab726a4075fd62eea2375
|
/practice/5/try_this/uncaught_exception.cpp
|
dc8416521afa1bdfc619d4bec2e0d16eddb48d3d
|
[] |
no_license
|
samkots/ppp2e
|
25ff5e7d2562476f670b439d75bde3564a66e3b7
|
b84cfa056600415b8136d773427f11f104e32c5e
|
refs/heads/master
| 2022-01-24T04:16:55.444701
| 2019-08-06T16:36:56
| 2019-08-06T16:36:56
| 113,661,884
| 1
| 0
| null | 2017-12-31T16:15:44
| 2017-12-09T10:44:22
|
C++
|
UTF-8
|
C++
| false
| false
| 85
|
cpp
|
uncaught_exception.cpp
|
#include "std_lib_facilities.h"
int main()
{
error("The uncaught exception!");
}
|
e63ce7bdf45a5fe2c43a1c44efd5540250f2ee02
|
245bf13493619d3c58bc7591fe7c2022adb91914
|
/PAT/PAT-Basic Level/CPP/1024.cpp
|
ba180e1302ef25ff9a494b2d7bd02d13a6b5176d
|
[] |
no_license
|
huixiongyu/Algorithms
|
98ff3b5011101b7e34ae71b30c8f2bec0bd67165
|
2cd0620cead3a2db5e306c4083208c422f4822db
|
refs/heads/master
| 2021-06-02T13:59:11.747665
| 2021-01-25T23:25:56
| 2021-01-25T23:25:56
| 98,390,111
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 677
|
cpp
|
1024.cpp
|
#include<iostream>
#include<string>
using namespace std;
int main(){
string s,num;
int ex,t=0;
cin>>s;
for(int i=0;i<s.length();i++)
if(s[i] == 'E') t=i;
num = s.substr(1,t-1);
ex = stoi(s.substr(t+1));
// cout<<num<<" "<<s.substr(t+1);
if(s[0] == '-') cout<< "-";
if(ex < 0){
cout<<"0.";
for(int i=0;i<abs(ex)-1;i++) cout<<'0';
for(int i=0;i<num.length();i++)
if(num[i] != '.') cout<<num[i];
}else{
cout<<num[0];
int j,tmp;
for(int j=2,tmp=0;j<num.length()&&tmp<ex;j++,tmp++) cout<<num[j];
if(j == num.length()){
for(int i=0;i<ex-tmp;i++) cout<<'0';
}else{
cout<<'.';
for(int i=j;i<num.length();i++) cout<<num[i];
}
}
return 0;
}
|
ffd7902e1aa0ccf17bacbd0fd2faaa5acdd123b6
|
75a93b5c33e732c294ba8b19a1690b1e7c199a0e
|
/net/Inc/fastmq/server.hpp
|
3df8553f41d5942131dec48b6a284307e5532b1f
|
[] |
no_license
|
sherzodv/mobi
|
642a2bbf93dabe3aeea15623d6a5e10575fe3d1b
|
eaffad5dc378ec22a8ef447b1ea01dbc0a34743f
|
refs/heads/master
| 2021-03-24T14:02:42.599805
| 2014-03-03T07:20:19
| 2014-03-03T07:20:19
| 14,749,502
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,140
|
hpp
|
server.hpp
|
#ifndef fastmq_server_base_hpp
#define fastmq_server_base_hpp
#include <stack>
#include <vector>
#include <functional>
#include <fastmq/peer.hpp>
#include <fastmq/node.hpp>
#include <fastmq/pool.hpp>
namespace fastmq {
namespace ba = boost::asio;
namespace bs = boost::system;
template <class ProtoT, class LogT>
class server_base: node_base {
protected:
typedef LogT log_t;
typedef ProtoT proto_t;
typedef ba::basic_stream_socket<proto_t> sock_t;
typedef peer<server_base<proto_t, log_t>> peer_t;
typedef ba::basic_socket_acceptor<proto_t> acpt_t;
friend peer_t;
public:
typedef typename proto_t::endpoint endpoint_t;
server_base(ba::io_service & io
, message_pool_base & pool
, const endpoint_t & ep
, log_t l)
: m_sock(io), m_acpt(io, ep)
, L(std::move(l)), P(pool)
{
m_book.reserve(30);
}
virtual ~server_base() {
for (peer_t * p: m_book) {
/* No need to call unregister_terminal here
* since node_base implementation is already
* destructed by this moment, and actually
* did all cleanup itself.
*
* Morover since it's a virtual member function
* it is impossible to call it here. */
if (p)
destroy(p);
}
}
void listen() {
ltrace(L) << "server_base::listen: Listening...";
m_acpt.async_accept(m_sock, boost::bind(&server_base::on_accept
, this, ba::placeholders::error));
}
protected:
sock_t m_sock;
acpt_t m_acpt;
log_t L;
message_pool_base & P;
void on_accept(const bs::error_code & ec) {
if (!ec) {
linfo(L) << "server_base::on_accept: New incoming connection";
peer_t * p = create(m_sock, *this);
p->recv_identity();
listen();
} else {
lerror(L) << ec.message();
}
}
void on_recv_error(terminal_base * p) {
/* Default implementation:
* unregister and destroy */
unregister_terminal(p);
destroy(static_cast<peer_t *>(p));
}
void on_send_error(terminal_base * p, msgu * msg) {
(void)(msg);
/* Default implementation:
* unregister and destroy */
unregister_terminal(p);
destroy(static_cast<peer_t *>(p));
}
void on_recv_identity(peer_t * p) {
if(register_terminal(p)) {
ltrace(L)
<< "server_base::on_recv_identity: terminal registered: "
<< "(" << p->id() << ":" << p->type() << ")";
p->send_greeting();
} else {
lerror(L)
<< "server_base::on_recv_identity: terminal rejected: "
<< "(" << p->id() << ":" << p->type() << ")";
destroy(p);
}
}
void on_send_greeting(peer_t * p) {
p->produce_message();
}
void on_recv_identity_error(peer_t * p) {
/* TODO: notify implementation */
destroy(p);
}
void on_send_greeting_error(peer_t * p) {
/* TODO: notify implementation */
unregister_terminal(p);
destroy(p);
}
/* Used only in client_base */
void on_recv_greeting(peer_t * p) {
(void)(p);
lerror(L) << "Call to on_recv_greeting in server";
}
void on_send_identity(peer_t * p) {
(void)(p);
lerror(L) << "Call to on_send_identity in server";
}
void on_send_identity_error(peer_t * p) {
(void)(p);
lerror(L) << "Call to on_send_identity_error in server";
}
void on_recv_greeting_error(peer_t * p) {
(void)(p);
lerror(L) << "Call to on_recv_greeting_error in server";
}
void on_connect_error() {
lerror(L) << "Call to on_connect_error in server";
}
private:
std::stack<std::size_t> m_hole;
std::vector<peer_t *> m_book;
template<typename ... Args>
peer_t * create(Args & ... args) {
peer_t * p;
std::size_t idx;
if (!m_hole.empty()) {
idx = m_hole.top();
p = new peer_t(idx, args ...);
m_hole.pop();
m_book[idx] = p;
} else {
idx = m_book.size();
p = new peer_t(idx, args ...);
m_book.push_back(p);
}
return p;
}
void destroy(peer_t * p) {
m_book.at(p->index()) = nullptr;
m_hole.push(p->index());
delete p;
}
};
template <class LogT>
using unix_domain_server_base
= server_base<boost::asio::local::stream_protocol, LogT>;
template <class LogT>
using tcp_server_base
= server_base<boost::asio::ip::tcp, LogT>;
}
#endif
|
d8638daf270b110a0b08046b97de3054a091a0a2
|
d3e1f9a07e09953ac689c74ad1f7f1ada982dd77
|
/SDK/GA_Cat_parameters.h
|
47a83ed0313b8c68769a4395c9b5f307c3167398
|
[] |
no_license
|
xnf4o/HSH_SURVIVE_SDK
|
5857159731ceda7c06e158711003fbaf22021842
|
2f49c97a5f14b4eadf7dc3387b55c09bc968da66
|
refs/heads/main
| 2023-04-12T06:52:47.854249
| 2021-04-27T03:13:24
| 2021-04-27T03:13:24
| 361,965,544
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,951
|
h
|
GA_Cat_parameters.h
|
#pragma once
// Name: hsh, Version: 2
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function GA_Cat.GA_Cat_C.GetSpawnTransfrom
struct UGA_Cat_C_GetSpawnTransfrom_Params
{
struct FTransform ReturnValue; // (Parm, OutParm, ReturnParm, IsPlainOldData, NoDestructor)
};
// Function GA_Cat.GA_Cat_C.UpdateItem
struct UGA_Cat_C_UpdateItem_Params
{
};
// Function GA_Cat.GA_Cat_C.EventReceived_F0DCE78043A14E77EEF97BB37FB5325E
struct UGA_Cat_C_EventReceived_F0DCE78043A14E77EEF97BB37FB5325E_Params
{
struct FGameplayTag EventTag; // (BlueprintVisible, BlueprintReadOnly, Parm, NoDestructor, HasGetValueTypeHash)
struct FGameplayEventData EventData; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function GA_Cat.GA_Cat_C.OnCancelled_F0DCE78043A14E77EEF97BB37FB5325E
struct UGA_Cat_C_OnCancelled_F0DCE78043A14E77EEF97BB37FB5325E_Params
{
struct FGameplayTag EventTag; // (BlueprintVisible, BlueprintReadOnly, Parm, NoDestructor, HasGetValueTypeHash)
struct FGameplayEventData EventData; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function GA_Cat.GA_Cat_C.OnInterrupted_F0DCE78043A14E77EEF97BB37FB5325E
struct UGA_Cat_C_OnInterrupted_F0DCE78043A14E77EEF97BB37FB5325E_Params
{
struct FGameplayTag EventTag; // (BlueprintVisible, BlueprintReadOnly, Parm, NoDestructor, HasGetValueTypeHash)
struct FGameplayEventData EventData; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function GA_Cat.GA_Cat_C.OnBlendOut_F0DCE78043A14E77EEF97BB37FB5325E
struct UGA_Cat_C_OnBlendOut_F0DCE78043A14E77EEF97BB37FB5325E_Params
{
struct FGameplayTag EventTag; // (BlueprintVisible, BlueprintReadOnly, Parm, NoDestructor, HasGetValueTypeHash)
struct FGameplayEventData EventData; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function GA_Cat.GA_Cat_C.OnCompleted_F0DCE78043A14E77EEF97BB37FB5325E
struct UGA_Cat_C_OnCompleted_F0DCE78043A14E77EEF97BB37FB5325E_Params
{
struct FGameplayTag EventTag; // (BlueprintVisible, BlueprintReadOnly, Parm, NoDestructor, HasGetValueTypeHash)
struct FGameplayEventData EventData; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
// Function GA_Cat.GA_Cat_C.K2_ActivateAbility
struct UGA_Cat_C_K2_ActivateAbility_Params
{
};
// Function GA_Cat.GA_Cat_C.K2_OnEndAbility
struct UGA_Cat_C_K2_OnEndAbility_Params
{
bool bWasCancelled; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
// Function GA_Cat.GA_Cat_C.ExecuteUbergraph_GA_Cat
struct UGA_Cat_C_ExecuteUbergraph_GA_Cat_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
7cddbd5854b700dec9f41268b985ee3669b25964
|
2053f511bad670807dfc441b1c4b355206a6cdf1
|
/tp2/src/Jugador.cpp
|
790c5d76b36eb7f6a63efd617d2033f22170d717
|
[] |
no_license
|
mgaido/TallerProgramacion2016-2
|
d451caf1602a06be61112e0952da065f60f263eb
|
f687a1dbbe74cdf273971c988ed59e378f2ad3d9
|
refs/heads/master
| 2021-03-27T13:50:45.567981
| 2016-12-14T21:27:45
| 2016-12-14T21:27:45
| 66,484,798
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,575
|
cpp
|
Jugador.cpp
|
/*
* Jugador.cpp
*
* Created on: 2 oct. 2016
* Author: rodrigo
*/
#include "Jugador.h"
Jugador::Jugador(int id, std::string nombre, Config& _configuracion) : Objeto(id), configuracion(_configuracion) {
this->nombre = nombre;
velocCaminar = 0, velocSaltoX = 0, velocSaltoY = 0;
tiempoCaminando=0;
tiempoSalto=0;
killAll = false;
estado = Estado::Desconectado;
tipo = Tipo::Jugador;
cambios = false;
}
Jugador::~Jugador() {
}
std::string Jugador::getNombre() {
return nombre;
}
void Jugador::caminar(Direccion direccion) {
std::unique_lock<std::mutex> lock(mutex);
if (direccion == Direccion::IZQUIERDA)
velocCaminar = - configuracion.getVelocidadX();
else
velocCaminar = configuracion.getVelocidadX();
if (tiempoSalto == 0)
tiempoCaminando = tiempo();
}
void Jugador::detenerse() {
std::unique_lock<std::mutex> lock(mutex);
actualizar();
velocCaminar = 0;
tiempoCaminando = 0;
}
void Jugador::saltar() {
std::unique_lock<std::mutex> lock(mutex);
if (tiempoSalto == 0) {
velocSaltoY=configuracion.getVelocidadY();
velocSaltoX = velocCaminar;
tiempoSalto = tiempo();
}
}
bool Jugador::tieneCambios() {
std::unique_lock<std::mutex> lock(mutex);
return actualizar();
}
void Jugador::setConectado(bool conectado) {
if (estado == Estado::Desconectado && conectado) {
estado = Estado::Quieto;
frame = 0;
cambios = true;
}
if (estado != Estado::Desconectado && ! conectado) {
estado = Estado::Desconectado;
frame = 0;
cambios = true;
}
}
bool Jugador::actualizar() {
if (estado != Estado::Desconectado) {
micros t=0;
double vx = 0;
if (tiempoSalto > 0) {
vx = velocSaltoX;
t = tiempo() - tiempoSalto;
velocSaltoY -= t*configuracion.getGravedad();
tiempoSalto += t;
} else if (tiempoCaminando > 0) {
vx = velocCaminar;
t = tiempo() - tiempoCaminando;
tiempoCaminando += t;
}
cambios |= t != 0;
if (vx != 0)
orientacion = vx < 0;
pos.x += (int) round(vx*t);
pos.y += (int) round(velocSaltoY*t);
if (tiempoSalto > 0 && velocSaltoY < 0 && pos.y <= 0) {
pos.y = 0;
velocSaltoX = 0;
velocSaltoY = 0;
if (velocCaminar != 0)
tiempoCaminando = tiempoSalto;
tiempoSalto = 0;
}
if (t > 0 && pos.x < 0)
pos.x = 0;
Estado estado;
if (tiempoSalto > 0)
estado = Estado::Saltando;
else if (tiempoCaminando > 0)
estado = Estado::Caminando;
else
estado = Estado::Quieto;
if (estado != this->estado) {
this->estado = estado;
cambios = true;
frame = 0;
}
}
bool rv = cambios;
cambios = false;
return rv;
}
|
ca930d8f9b5d9e1ee2043ab73e47977815d52e09
|
dd58ad1707abfc82a0f723f0f11c2bbf438471ee
|
/Random/mutex.cpp
|
754c288bf3b9bcd575839cab6eb2b3eaf4f00fe5
|
[] |
no_license
|
khandelwalankit/BasicAlgorithms
|
e844bf572349e92704671e6a907019ec11322c83
|
718840f56f48b8b4a59f59db62649bd68854a35d
|
refs/heads/master
| 2021-01-20T10:46:07.586264
| 2014-10-17T19:55:21
| 2014-10-17T19:55:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 402
|
cpp
|
mutex.cpp
|
#include<iostream>
#include<cstdlib>
#include<thread>
#include<mutex>
using namespace std;
std::mutex mtx;
void print_block(int n, char c)
{
//mtx.lock();
for(int i =0 ;i <n;i++)
{
cout<<c;
}
cout<<"\n";
//mtx.unlock();
}
int main()
{
std::thread th1 (print_block,50,'*');
std::thread th2 (print_block,50,'$');
th1.join();
th2.join();
return 0;
}
|
56a4437522c33f7da86e10884d5fb4b814967a35
|
ba163a6b6ecf4a7ba0ecc9ec24ef6da6f6712668
|
/assembler/test_ctor_copy.cpp
|
79433de9e7907043db1c45860727849bdc8171a5
|
[] |
no_license
|
Jeremy-Martin4794/CS2-projects
|
3eacf0874e597a5789537da67cf080f404e762d2
|
bd9850898b97c26d852efabbc1bb6b6db59af657
|
refs/heads/main
| 2023-08-31T23:54:47.122847
| 2021-09-26T19:46:52
| 2021-09-26T19:46:52
| 410,633,054
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,977
|
cpp
|
test_ctor_copy.cpp
|
// Jeremy Martin
// testing copy constructor
#include "stack.hpp"
#include <cassert>
#include <iostream>
#include "string.hpp"
//===========================================================================
int main()
{
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<int> x;
stack<int> y(x);
// VERIFY
assert(y.empty());
assert(x == y);
}
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<int> x;
x.push(10);
stack<int> y(x);
// VERIFY
assert(y.empty() == false);
assert(y.top() == 10);
assert(x == y);
}
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<int> x;
x.push(10);
x.push(20);
x.push(30);
x.push(40);
stack<int> y(x);
// VERIFY
assert(y.empty() == false);
assert(y.top() == 40);
assert(x == y);
}
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<int> x;
x.push(10);
x.push(20);
x.pop();
stack<int> y(x);
// VERIFY
assert(y.empty() == false);
assert(y.top() == 10);
assert(x == y);
}
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<int> x;
x.push(10);
stack<int> y(x);
y.push(20);
stack<int> z(y);
// VERIFY
assert(z.empty() == false);
assert(z.top() == 20);
assert(y == z);
}
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<int> x;
x.push(10);
stack<int> y(x);
y.push(20);
y.pop();
// VERIFY
assert(y.empty() == false);
assert(y.top() == 10);
assert(x == y);
}
/////////////////////////////////////////////////////////
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<char> x;
stack<char> y(x);
// VERIFY
assert(y.empty());
assert(x == y);
}
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<char> x;
x.push('a');
stack<char> y(x);
// VERIFY
assert(y.empty() == false);
assert(y.top() == 'a');
assert(x == y);
}
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<char> x;
x.push('a');
x.push('b');
x.push('c');
x.push('d');
stack<char> y(x);
// VERIFY
assert(y.empty() == false);
assert(y.top() == 'd');
assert(x == y);
}
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<char> x;
x.push('a');
x.push('b');
x.pop();
stack<char> y(x);
// VERIFY
assert(y.empty() == false);
assert(y.top() == 'a');
assert(x == y);
}
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<char> x;
x.push('a');
stack<char> y(x);
y.push('b');
stack<char> z(y);
// VERIFY
assert(z.empty() == false);
assert(z.top() == 'b');
assert(y == z);
}
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<char> x;
x.push('a');
stack<char> y(x);
y.push('b');
y.pop();
// VERIFY
assert(y.empty() == false);
assert(y.top() == 'a');
assert(x == y);
}
/////////////////////////////////////////////////////////
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<String> x;
stack<String> y(x);
// VERIFY
assert(y.empty());
assert(x == y);
}
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<String> x;
x.push("hello");
stack<String> y(x);
// VERIFY
assert(y.empty() == false);
assert(y.top() == "hello");
assert(x == y);
}
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<String> x;
x.push("hello");
x.push("world");
x.push("this");
x.push("test");
stack<String> y(x);
// VERIFY
assert(y.empty() == false);
assert(y.top() == "test");
assert(x == y);
}
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<String> x;
x.push("hello");
x.push("world");
x.pop();
stack<String> y(x);
// VERIFY
assert(y.empty() == false);
assert(y.top() == "hello");
assert(x == y);
}
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<String> x;
x.push("hello");
stack<String> y(x);
y.push("world");
stack<String> z(y);
// VERIFY
assert(z.empty() == false);
assert(z.top() == "world");
assert(y == z);
}
{
//------------------------------------------------------
// SETUP FIXTURE
// TEST
stack<String> x;
x.push("hello");
stack<String> y(x);
y.push("world");
y.pop();
// VERIFY
assert(y.empty() == false);
assert(y.top() == "hello");
assert(x == y);
}
std::cout << "Done testing copy constructor" << std::endl;
}
|
942ba27c233145af4b1921ffd54e05aaa812cfa6
|
5ba2544f304e60e58fcb981a9e543cc526cb602a
|
/DisplayLetters/DisplayLetters/main.cpp
|
b25dfd422ad193cb80baa1973eaf0230e1add98e
|
[] |
no_license
|
air2310/cpp_rep
|
24747ab9d55c17a00693ff7226c272ddf459edbe
|
c3464f08ae6431e64ee48b1c2a4c0539cc886189
|
refs/heads/master
| 2021-01-12T15:42:46.056782
| 2016-12-06T12:25:00
| 2016-12-06T12:25:00
| 71,864,975
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,165
|
cpp
|
main.cpp
|
#pragma comment(lib, "sfml-graphics-d.lib")
#pragma comment(lib, "sfml-network-d.lib")
#pragma comment(lib, "sfml-system-d.lib")
#pragma comment(lib, "sfml-window-d.lib")
#include <SFML/Graphics.hpp>
#include <SFML/Graphics.hpp>
#include <iostream>
#include "network.h"
#include "settings.h"
#include "Draw.h"
int main() {
//open server
Server();
// open window
sf::RenderWindow window(sf::VideoMode(mon.width, mon.height), "some moving stuff", sf::Style::None);
window.setPosition(sf::Vector2i(0, 0));
window.setVerticalSyncEnabled(true);
window.setActive(false);
//open drawthread
sf::Thread* drawthread = 0;
drawthread = new sf::Thread(&drawLetters, &window);
drawthread->launch();
// start getting data from network
sf::Thread* thread = 0;
thread = new sf::Thread(&get_data);
thread->launch();
if (thread)
{
thread->wait();
delete thread;
}
//continue running the threads
if (drawthread)
{
drawthread->wait();
delete drawthread;
}
// handle events
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
}
return 0;
}
|
5e009f5bf702b46783716ffe51ec3015cad4c1ba
|
50d85ffcb55198884bbc9cbb4afa39e828de6001
|
/libs/vscore/source/libVRMLRenderer/VRMLRendererTraverser.cpp
|
47dee0d69bf1326e8c0c2e2e7b33b1d305042b1a
|
[] |
no_license
|
Calit2-UCI/EMMA-FINAL
|
60e772cec27f8718fabb4d1a948b3552e99afa57
|
8e48a7d592ff1fe5d69de6c7dbc4b0a2989da08a
|
refs/heads/master
| 2021-01-24T10:47:29.719351
| 2016-11-09T12:12:57
| 2016-11-09T12:12:57
| 70,107,807
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 36,237
|
cpp
|
VRMLRendererTraverser.cpp
|
// VRMLRendererTraverser.cpp: implementation of the VRMLRendererTraverser class.
//
//////////////////////////////////////////////////////////////////////
// Disable annyoing debug-compile error caused by STL.
// This is safe.
#pragma warning(disable : 4786)
#if _MSC_VER >= 1400
#define _CRT_SECURE_NO_DEPRECATE // shut up the vs2005 compiler
#define _CRT_NONSTDC_NO_DEPRECATE
#endif
//#include "SurfaceData.h"
#ifdef WIN32
#include <GL/glew.h>
#define GL_GLEXT_PROTOTYPES
#include <gl\glaux.h>
#include <gl/glext.h>
#include <direct.h>
#ifdef GLEW_VERSION_1_5_IS_NOT_SUPPORTED //address the standard extensions to glew ARB extensions
#define glGenBuffers GLEW_GET_FUN(__glewGenBuffersARB)
#define glBindBuffer GLEW_GET_FUN(__glewBindBufferARB)
#define glBufferData GLEW_GET_FUN(__glewBufferDataARB)
#define glBufferSubData GLEW_GET_FUN(__glewBufferSubDataARB)
#define glDeleteBuffers GLEW_GET_FUN(__glewDeleteBuffersARB)
#define glGetBufferParameteriv GLEW_GET_FUN(__glewGetBufferParameterivARB)
#define glGetBufferPointerv GLEW_GET_FUN(__glewGetBufferPointervARB)
#define glGetBufferSubData GLEW_GET_FUN(__glewGetBufferSubDataARB)
#define glIsBuffer GLEW_GET_FUN(__glewIsBufferARB)
#define glMapBuffer GLEW_GET_FUN(__glewMapBufferARB)
#define glUnmapBuffer GLEW_GET_FUN(__glewUnmapBufferARB)
#endif
#elif defined(LINUX)
#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glx.h>
#include <GL/glext.h>
//#include <GL/glut.h>
//#include <GL/freeglut_ext.h>
#include <unistd.h>
#elif defined(MAC)
#include <OpenGL/gl.h>
#include <GLUT/glut.h>
#include <OpenGL/glext.h>
#include <unistd.h>
#elif defined(IPHONE)
#include <OpenGLES/ES1/gl.h>
#include <OpenGLES/ES1/glext.h>
#import <UIKit/UIKit.h>
// #include "glues.h"
#include <unistd.h>
#endif
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <cstring>
#include <iostream>
#include <cmath>
#include "VRMLRendererTraverser.h"
#include "GLVertexBuffer.hpp"
// Added by KStankovic
/* In case your <GL/gl.h> does not advertise EXT_texture_cube_map... */
#ifndef GL_EXT_texture_cube_map
# define GL_NORMAL_MAP_EXT 0x8511
# define GL_REFLECTION_MAP_EXT 0x8512
# define GL_TEXTURE_CUBE_MAP_EXT 0x8513
# define GL_TEXTURE_BINDING_CUBE_MAP_EXT 0x8514
# define GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT 0x8515
# define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT 0x8516
# define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT 0x8517
# define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT 0x8518
# define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT 0x8519
# define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT 0x851A
# define GL_PROXY_TEXTURE_CUBE_MAP_EXT 0x851B
# define GL_MAX_CUBE_MAP_TEXTURE_SIZE_EXT 0x851C
#endif
//
// VC does not define M_PI
//#define M_PI 3.141592653589793238462643383279502884197196
namespace VisageSDK
{
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
VRMLRendererTraverser::VRMLRendererTraverser()
{
mRenderPart = false;
isStaticDataInBuffer = false;
nBuffersCreated = 0;
nWorkingBuffer = 0;
mLipsSurface = NULL;
nLoadedTextures = 0;
mFlashingPointSize = 6.0f;
}
VRMLRendererTraverser::~VRMLRendererTraverser()
{
// Unload textures
// for(map<string, GLuint>::iterator theIt = mLoadedTextures.begin(); theIt != mLoadedTextures.end(); theIt++)
// glDeleteTextures(1, &(*theIt).second);
int i;
for(i = 0; i<nLoadedTextures;i++)
{
glDeleteTextures(1, &(loadedTexture[i]));
free(loadedTextureName[i]);
std::cout << "delete texture" << std::endl;
}
for(i = 0; i<nBuffersCreated; i++)
{
glDeleteBuffers(1, &(meshBuffer[i]));
std::cout << "delete mesh" << std::endl;
}
}
void VRMLRendererTraverser::SetRenderingIndex(int index)
{
mRenderShape = index;
mRenderPart = true;
}
// Changed by KStankovic
int VRMLRendererTraverser::LoadTextures(char *fullPath, char *folderPath, GLenum target)
//
{
// Texture varible, return
GLuint texture[1];
#ifndef IPHONE
// Returns a texture-index if successfully loaded, returns -1 if
// there was some error.
char curPath[200];
// change to the folder where the model file is, so the textures can be loaded
if(folderPath[0])
{
#ifdef WIN32
_getcwd(curPath,200); // remember current folder
_chdir(folderPath);
#else
getcwd(curPath,200); // remember current folder
chdir(folderPath);
#endif
}
FILE *File=NULL;
File=fopen(fullPath,"r");
if(!File)
{
return -1;
}
fclose(File);
// Changed by KStankovic
if (target == GL_TEXTURE_2D)
{
glGenTextures(1, &texture[0]); // Create The Texture
// Typical Texture Generation Using Data From The Bitmap
//by KaiK
glActiveTexture( GL_TEXTURE0 );
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[0]);
}
else if (target == GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT)
{
glGenTextures(1, &texture[0]); // Create The Texture
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_CUBE_MAP_EXT, texture[0]);
}
//
Image* my_image = new Image();
my_image->read_image(fullPath);
// Load texture into GL.
int maxSize = 0;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxSize);
// Create a texture of nearest power 2
int xPowSize = 1;
int yPowSize = 1;
while((my_image->get_size_x() / xPowSize) > 0) xPowSize <<= 1;
while((my_image->get_size_y() / yPowSize) > 0) yPowSize <<= 1;
// Size to nearest lower power of 2 for speed
xPowSize >>= 1;
yPowSize >>= 1;
// So we're not overriding gfx-cards capabilitys
if(xPowSize > maxSize) xPowSize = maxSize;
if(yPowSize > maxSize) yPowSize = maxSize;
// Allocate memory to the scaled image.
GLubyte* tempScaleImage = new GLubyte[yPowSize * (xPowSize * my_image->get_n_channels())];
// Scale original image to nearest lower power of 2.
switch(my_image->get_n_channels())
{
cout << "N channels per image: " << my_image->get_n_channels() << endl;
case 3:
{
gluScaleImage(GL_RGB, my_image->get_size_x(), my_image->get_size_y(), GL_UNSIGNED_BYTE, my_image->get_data(), xPowSize, yPowSize, GL_UNSIGNED_BYTE, tempScaleImage);
// Changed by KStankovic
glTexImage2D(target, 0, 3, xPowSize, yPowSize, 0, GL_RGB, GL_UNSIGNED_BYTE, tempScaleImage);
//
}
break;
case 4:
{
cout << "4 channels" << endl;
gluScaleImage(GL_RGBA, my_image->get_size_x(), my_image->get_size_y(), GL_UNSIGNED_BYTE, my_image->get_data(), xPowSize, yPowSize, GL_UNSIGNED_BYTE, tempScaleImage);
// Changed by KStankovic
glTexImage2D(target, 0, 4, xPowSize, yPowSize, 0, GL_RGBA, GL_UNSIGNED_BYTE, tempScaleImage);
//
}
break;
// Safety stuff.
default:
cout << "incorrect number of channels: "<< my_image->get_n_channels() << endl;
return -1;
break;
}
// Clean up
delete [] tempScaleImage;
delete my_image;
// Changed by KStankovic
if (target == GL_TEXTURE_2D)
{
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); // Linear Filtering
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering
} else if (target == GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT)
{
#ifdef IPHONE
glTexParameteri(GL_TEXTURE_CUBE_MAP_EXT,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP_EXT,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
#else
glTexParameteri(GL_TEXTURE_CUBE_MAP_EXT,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP_EXT,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP_EXT,GL_TEXTURE_WRAP_S,GL_CLAMP);
glTexParameteri(GL_TEXTURE_CUBE_MAP_EXT,GL_TEXTURE_WRAP_T,GL_CLAMP);
#endif
}
//
// return to the current folder if necessary
if(folderPath[0])
{
#ifdef WIN32
_chdir(curPath);
#else
chdir(curPath);
#endif
}
#else
//IPHONE SPECIFIC CODE TO LOAD TEXTURES
CGImageRef textureImage;
CGContextRef textureContext;
char buffer[2048];
NSString* readPath = [[NSBundle mainBundle] resourcePath];
[readPath getCString:buffer maxLength:2048 encoding:NSUTF8StringEncoding];
strcat(buffer, "/");
strcat( buffer, fullPath );
NSString *path = [NSString stringWithUTF8String:buffer];
UIImage *uiImage = [UIImage imageWithContentsOfFile:path];
if( uiImage ) {
textureImage = uiImage.CGImage;
int width = CGImageGetWidth(textureImage);
int height = CGImageGetHeight(textureImage);
GLubyte *textureData;
if(textureImage) {
/* if(width%256!=0)
{
textureData = (GLubyte *) malloc(512 * 512 * 4);
textureContext = CGBitmapContextCreate(textureData, 512, 512, 8, width * 4, CGImageGetColorSpace(textureImage), kCGImageAlphaPremultipliedLast);
CGContextTranslateCTM (textureContext, 0, 512);
CGContextScaleCTM (textureContext, 1.0, -1.0);
CGContextScaleCTM(textureContext, 512/width, 512/height);
CGContextDrawImage(textureContext, CGRectMake(0.0, 0.0, (float)512, (float)512), textureImage);
width = 512;
height = 512;
}
else
{
*/ textureData = (GLubyte *) malloc(width * height * 4);
textureContext = CGBitmapContextCreate(textureData, width, height, 8, width * 4, CGImageGetColorSpace(textureImage), kCGImageAlphaPremultipliedLast);
CGContextTranslateCTM (textureContext, 0, height);
CGContextScaleCTM (textureContext, 1.0, -1.0);
CGContextDrawImage(textureContext, CGRectMake(0.0, 0.0, (float)width, (float)height), textureImage);
// }
}
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &texture[0]);
glBindTexture(GL_TEXTURE_2D, texture[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//ONLY FOR IPHONE VERSION >= 2
glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE );
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData);
//ONLY FOR IPHONE VERSION >= 2
glGenerateMipmap( GL_TEXTURE_2D );
if(glGetError())
{
printf("glTexImage2D failed. ");
//return 0;
}
free(textureData);
CGContextRelease(textureContext);
}
else {
cout << "cannot load image" << endl;
}
#endif
// Successfully return the loaded image.
return texture[0];
}
int VRMLRendererTraverser::traverseTransform(VRMLModel *model, // pointer to the traversed model
VRMLNode *thisNode, // the node currently being traversed
int index, // index of the transform within the face model
float *c, // Center of rotation expressed as translation (x,y,z)
float *negc, // Negative translation of the center of rotation
float *r, // Rotation expressed as axis and angle in radians (x,y,z,angle)
float *rq, // Rotation expressed as quaternion (x,y,z,w)
float *s, // Scale (x,y,z)
float *so, // Scale orientation (acis and angle)
float *soq, // Scale orientation (quaternion)
float *negso, // Inverse of scale orientation (axis and angle)
float *negsoq, // Inverse of scale orientation (quaternion)
float *t, // Translation (x,y,z)
myMatrix m) // Complete transformation matrix
{
// Save off old matrix
glPushMatrix();
glMultMatrixf((GLfloat *) m);
return 0;
}
void VRMLRendererTraverser::traverseTransformEnd(VRMLModel *model, VRMLNode *thisNode,int index)
{
// Get back old GL_MODELVIEW matrix.
glPopMatrix();
}
void VRMLRendererTraverser::traverseMesh(VRMLModel *model, // pointer to the traversed model
VRMLNode *thisNode, // the node currently being traversed
int index, // index of the polygon mesh within the face model
VRMLMaterial *mat, // material for this shape
float *coord, // vertex coordinates
float *origCoord, // original vertex coordinates
int coordLength, // length of the vertex coordinates array (number of vertices * 3)
int *coordInd, // vertex indices for triangles
int coordIndLength, // length of coordInd array
float *norm, // normals
int normLength, // length of norm array
int *normInd, // normal indices, per vertex
int normIndLength, // length of normInd array
int NPV, // Normal Per Vertex: 1 if on, 0 if off (i.e. normal per face)
int normalsCalculated,// If 1, normals are calculated by VRMLModel; if 0, normals were read from the file
float creaseAngle, // VRML creaseAngle (default 0.0; 1.2 is good value to smooth)
int solid, // VRML solid (default 1)
int ccw, // VRML counter-clockwise (default 1)
int convex, // VRML convex (default 1)
float *tcoord, // texture coordinates, if any (else zero)
int tcoordLength,
int *tcoordInd,
int tcoordIndLength,
float *cpv, // colors per vertex, if any (else zero)
int cpvLength,
int *cpvInd,
int cpvIndLength,
int CPV, // color per vertex (1) or per face (1)
VRMLMeshMT *mt, // pointer to the list of morph targets for this mesh
VRMLMeshBones *bones) // color per vertex (1) or per face (0)
{
if(mRenderPart)
if(index != mRenderShape) return;
if(nBuffersCreated < model->nCoordLists)
{
GLVertexBuffer my_VBO_data = GLVertexBuffer(
mat, // material for this shape
coord, // vertex coordinates
coordLength, // length of the vertex coordinates array (number of vertices * 3)
coordInd, // vertex indices for triangles
coordIndLength, // length of coordInd array
norm, // normals
normLength, // length of norm array
normInd, // normal indices, per vertex
normIndLength, // length of normInd array
tcoord, // texture coordinates, if any (else zero)
tcoordLength,
tcoordInd,
tcoordIndLength,
cpv, // colors per vertex, if any (else zero)
cpvLength,
cpvInd,
cpvIndLength,
NPV, // Normal Per Vertex: 1 if on, 0 if off (i.e. normal per face)
CPV);
//generates a VBO
glGenBuffers(1, &meshBuffer[nBuffersCreated]);
//link the specified buffer
glBindBuffer(GL_ARRAY_BUFFER, meshBuffer[nBuffersCreated]);
glBufferData(GL_ARRAY_BUFFER, my_VBO_data.get_VBO_buffer_size(), 0, GL_DYNAMIC_DRAW);
//unlink buffer
glBindBuffer(GL_ARRAY_BUFFER, 0);
std::cout << "generated buffer number: " << nBuffersCreated << std::endl;
nBuffersCreated++;
}
else if(nWorkingBuffer == nBuffersCreated)
{
nWorkingBuffer = 0;
//first time when nWorkingBuffer = nBuffersCreated, all static data (colors, tex_coord) has been loaded into buffer
if(!isStaticDataInBuffer)
isStaticDataInBuffer = true;
}
// changed by Ratty
// don't crash here, use default material instead
// assert(mat);
bool destroy_mat = false;
if( !mat )
{
destroy_mat = true;
mat = new VRMLMaterial();
}
assert(coord);
assert(coordInd);
assert(norm);
assert(normInd);
//added by Ratty
if( coordInd == 0 || normInd == 0 )
return;
//
bool is_rgba_texture = false;
// Traverse the shape and convert VMRL to openGL calls.
// First set the material.
// Ambient component
GLfloat ambient[4] = { mat->ambientIntensity, mat->ambientIntensity, mat->ambientIntensity, 1.0f };
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient);
// Diffuse component
GLfloat diffuseColor[4] = { mat->diffuseColor[0], mat->diffuseColor[1], mat->diffuseColor[2], 1.0f };
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuseColor);
// Emissive component
GLfloat emissiveColor[4] = { mat->emissiveColor[0], mat->emissiveColor[1], mat->emissiveColor[2], 1.0f };
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emissiveColor);
// Material shininess
GLfloat shininess[4] = { mat->shininess, mat->shininess, mat->shininess, 1.0f };
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, shininess);
// Specular component
GLfloat specularColor[4] = { mat->specularColor[0], mat->specularColor[1], mat->specularColor[2], 1.0f };
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specularColor);
// If there is a texture, load it and set up
GLuint texture[1];
texture[0] = 0;
if(tcoord)
{
// Added by KStankovic
bool isCubemap = false;
if (mat->cubemapNames[0] != NULL) isCubemap = true;
//
// Changed by KStankovic
char *textureURL;
if (isCubemap) textureURL = mat->cubemapNames[0];
else textureURL = mat->textureName;
int i; //CHANGED BY I.K. declared iterator outside of loop
for(i =0; i< nLoadedTextures; i++) //identifica la textura que hay que cargar
{
if(!strcmp(textureURL,loadedTextureName[i]))
break;
}
//
if(i == nLoadedTextures)
{
if (isCubemap)
{
cout << "CUBEMAP TEXTURE" << endl;
texture[0] = LoadTextures(mat->cubemapNames[0],((VRMLModel*)model)->filePath,
GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT);
int j;
for (j = 1; j < 6; j++)
LoadTextures(mat->cubemapNames[j],((VRMLModel*)model)->filePath,
GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT + j);
}
else
{
cout << "NOT CUBEMAP TEXTURE" << endl;
texture[0] = LoadTextures(mat->textureName,((VRMLModel*)model)->filePath,
GL_TEXTURE_2D);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[0]); // Select Our Texture
}
loadedTexture[nLoadedTextures] = texture[0];
loadedTextureName[nLoadedTextures] = (char*)malloc((strlen(textureURL)+1) * sizeof(char));
strcpy(loadedTextureName[nLoadedTextures],textureURL);
nLoadedTextures++;
if (isCubemap)
glBindTexture(GL_TEXTURE_CUBE_MAP_EXT, texture[0]); // Select Our Texture
else
{
glBindTexture(GL_TEXTURE_2D, texture[0]); // Select Our Texture
}
//
}
else
{
// Was the texture properly loaded?
if(i<nLoadedTextures)
{
texture[0] = loadedTexture[i];
// Changed by KStankovic
if (isCubemap)
{
glBindTexture(GL_TEXTURE_CUBE_MAP_EXT, texture[0]); // Select Our Texture
}
else
{
//by KaiK
glActiveTexture( GL_TEXTURE0 );
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[0]); // Select Our Texture
}
//
}
}
// Changed by KStankovic
#ifndef IPHONE//solo para comprobar si tiene 4 canales!!
// figure out if this texture contains an alpha channel or not
GLint params;
if (isCubemap)
glGetTexLevelParameteriv(GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT, 0, GL_TEXTURE_COMPONENTS, ¶ms);
else
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_COMPONENTS, ¶ms);
//
if (params == 4)
is_rgba_texture = true;
#endif
// Added by KStankovic
if (isCubemap)
{
glDisable(GL_TEXTURE_2D);
glEnable(GL_TEXTURE_CUBE_MAP_EXT);
}
//
}
else
{
//glBindTexture(GL_TEXTURE_2D, 0);
}
// Then start feeding coordinates and normals.
if(coordIndLength != normIndLength) assert(NULL);
if(ccw)
glFrontFace(GL_CCW);
else
glFrontFace(GL_CW);
if (is_rgba_texture)
{
//glEnable(GL_CULL_FACE); // Remove Back Face
glAlphaFunc(GL_GREATER,0.5f); // Set Alpha Testing (disable blending)
glEnable(GL_ALPHA_TEST); // Enable Alpha Testing (disable blending)
RenderMesh(
mat, coord, origCoord, coordLength, coordInd, coordIndLength, norm, normLength, normInd, normIndLength,
NPV, normalsCalculated, creaseAngle, solid, ccw, convex, tcoord, tcoordLength, tcoordInd, tcoordIndLength,
cpv, cpvLength, cpvInd, cpvIndLength, CPV);
glDisable(GL_ALPHA_TEST),
glDisable(GL_CULL_FACE); // Remove Back Face
glPushMatrix();
// glScalef(1.01, 1.01, 1.01); // avoid z-fighting
// Enable Alpha Blending (disable alpha testing)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND); // Enable Blending (disable alpha testing)
glDepthMask(GL_FALSE);
RenderMesh(
mat, coord, origCoord, coordLength, coordInd, coordIndLength, norm, normLength, normInd, normIndLength,
NPV, normalsCalculated, creaseAngle, solid, ccw, convex, tcoord, tcoordLength, tcoordInd, tcoordIndLength,
cpv, cpvLength, cpvInd, cpvIndLength, CPV);
}
glDepthMask(GL_TRUE);
RenderMesh(
mat, coord, origCoord, coordLength, coordInd, coordIndLength, norm, normLength, normInd, normIndLength,
NPV, normalsCalculated, creaseAngle, solid, ccw, convex, tcoord, tcoordLength, tcoordInd, tcoordIndLength,
cpv, cpvLength, cpvInd, cpvIndLength, CPV);
if (is_rgba_texture)
{
glEnable(GL_DEPTH_TEST);
#ifndef IPHONE
glDisable (GL_POLYGON_STIPPLE);
#endif
glDepthMask(GL_TRUE);
glDisable(GL_CULL_FACE); // Remove Back Face
glDisable(GL_ALPHA_TEST); // Enable Alpha Testing (disable blending)
glDisable(GL_BLEND);
glPopMatrix();
}
// Changed by KStankovic
if(tcoord)
{
glBindTexture(GL_TEXTURE_2D, 0);
if (mat->cubemapNames[0] != NULL)
{
glDisable(GL_TEXTURE_CUBE_MAP_EXT);
glEnable(GL_TEXTURE_2D);
}
}
//
// added by Ratty
if( destroy_mat )
delete mat;
nWorkingBuffer++;
//TEST by KaiK !!!!!!!!
//nBuffersCreated = 0;
//nWorkingBuffer = 0;
//isStaticDataInBuffer = false;
//glDeleteBuffers(1, &meshBuffer[nBuffersCreated]);
}
/*
void VRMLRendererTraverser::traverseMesh(VRMLModel *model, // pointer to the traversed model
VRMLNode *thisNode, // the node currently being traversed
int index, // index of the polygon mesh within the face model
VRMLMaterial *mat, // material for this shape
float *coord, // vertex coordinates
float *origCoord, // original vertex coordinates
int coordLength, // length of the vertex coordinates array (number of vertices * 3)
int *coordInd, // vertex indices for triangles
int coordIndLength, // length of coordInd array
float *norm, // normals
int normLength, // length of norm array
int *normInd, // normal indices, per vertex
int normIndLength, // length of normInd array
int NPV, // Normal Per Vertex: 1 if on, 0 if off (i.e. normal per face)
int normalsCalculated,// If 1, normals are calculated by VRMLModel; if 0, normals were read from the file
float creaseAngle, // VRML creaseAngle (default 0.0; 1.2 is good value to smooth)
int solid, // VRML solid (default 1)
int ccw, // VRML counter-clockwise (default 1)
int convex, // VRML convex (default 1)
float *tcoord, // texture coordinates, if any (else zero)
int tcoordLength,
int *tcoordInd,
int tcoordIndLength,
float *cpv, // colors per vertex, if any (else zero)
int cpvLength,
int *cpvInd,
int cpvIndLength,
int CPV, // color per vertex (1) or per face (1)
VRMLMeshMT *mt, // pointer to the list of morph targets for this mesh
VRMLMeshBones *bones) // color per vertex (1) or per face (0)
{
if(mRenderPart)
if(index != mRenderShape) return;
bool destroy_mat = false;
if( !mat )
{
destroy_mat = true;
mat = new VRMLMaterial();
}
if( coordInd == 0 || normInd == 0 )
return;
// Ambient component
GLfloat ambient[4] = { mat->ambientIntensity, mat->ambientIntensity, mat->ambientIntensity, 1.0f };
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient);
// Diffuse component
GLfloat diffuseColor[4] = { mat->diffuseColor[0], mat->diffuseColor[1], mat->diffuseColor[2], 1.0f };
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuseColor);
// Emissive component
GLfloat emissiveColor[4] = { mat->emissiveColor[0], mat->emissiveColor[1], mat->emissiveColor[2], 1.0f };
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emissiveColor);
// Material shininess
GLfloat shininess[4] = { mat->shininess, mat->shininess, mat->shininess, 1.0f };
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, shininess);
// Specular component
GLfloat specularColor[4] = { mat->specularColor[0], mat->specularColor[1], mat->specularColor[2], 1.0f };
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specularColor);
// If there is a texture, load it and set up
GLuint texture[1];
texture[0] = 0;
if(tcoord)
{
char *textureURL;
textureURL = mat->textureName;
int i;
for(i =0; (i< nLoadedTextures); i++) //identifica la textura que hay que cargar
{
if(!strcmp(textureURL,loadedTextureName[i]))
break;
}
if((i == nLoadedTextures)) //if texture is loaded for first time
{
texture[0] = LoadTextures(mat->textureName,((VRMLModel*)model)->filePath, GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE0);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[0]); // Select Our Texture
loadedTexture[nLoadedTextures] = texture[0];
loadedTextureName[nLoadedTextures] = (char*)malloc((strlen(textureURL)+1) * sizeof(char));
strcpy(loadedTextureName[nLoadedTextures],textureURL);
nLoadedTextures++;
}
else //if texture has been loaded previously
{
if(i<nLoadedTextures)
{
texture[0] = loadedTexture[i];
glActiveTexture( GL_TEXTURE0 );
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture[0]); // Select Our Texture
}
}
}
else //if there is no texture
{
//by KaiK
// glBindTexture(GL_TEXTURE_2D, 0);
}
if(coordIndLength != normIndLength) assert(NULL);
if(ccw)
glFrontFace(GL_CCW);
else
glFrontFace(GL_CW);
//by Kaik
//glDepthMask(GL_FALSE); // esto provoca que se vea el interior en vez de el exterior
glDepthMask(GL_TRUE);
RenderMesh(
mat, coord, origCoord, coordLength, coordInd, coordIndLength, norm, normLength, normInd, normIndLength,
NPV, normalsCalculated, creaseAngle, solid, ccw, convex, tcoord, tcoordLength, tcoordInd, tcoordIndLength,
cpv, cpvLength, cpvInd, cpvIndLength, CPV);
// Changed by KStankovic
if(tcoord)
{
glBindTexture(GL_TEXTURE_2D, 0);
}
//
// added by Ratty
// if( destroy_mat )
// delete mat;
}
*/
void VRMLRendererTraverser::RenderMesh( VRMLMaterial *mat, // material for this shape
float *coord, // vertex coordinates
float *origCoord, // original vertex coordinates
int coordLength, // length of the vertex coordinates array (number of vertices * 3)
int *coordInd, // vertex indices for triangles
int coordIndLength, // length of coordInd array
float *norm, // normals
int normLength, // length of norm array
int *normInd, // normal indices, per vertex
int normIndLength, // length of normInd array
int NPV, // Normal Per Vertex: 1 if on, 0 if off (i.e. normal per face)
int normalsCalculated,// If 1, normals are calculated by VRMLModel; if 0, normals were read from the file
float creaseAngle, // VRML creaseAngle (default 0.0; 1.2 is good value to smooth)
int solid, // VRML solid (default 1)
int ccw, // VRML counter-clockwise (default 1)
int convex, // VRML convex (default 1)
float *tcoord, // texture coordinates, if any (else zero)
int tcoordLength,
int *tcoordInd,
int tcoordIndLength,
float *cpv, // colors per vertex, if any (else zero)
int cpvLength,
int *cpvInd,
int cpvIndLength,
int CPV // color per vertex (1) or per face (1)
)
{
#ifdef MSVC
// Local pointers are much faster than stackvalues, therfore use locals.
int *tempNormInd = normInd;
float *tempNorm = norm;
int *tempCpvInd = cpvInd;
float *tempCpv = cpv;
// int tempCPV = CPV;
int *tempCoordInd = coordInd;
int tempCoordIndLength = coordIndLength;
float *tempCoord = coord;
int coordIndex = 0;
int normalIndex = 0;
int colorIndex = 0;
//int notCPVcntr = 0;
int textureIndex = 0;
glBegin(GL_TRIANGLES);
for(int i=0; i<tempCoordIndLength; i++)
{
// Input normal and if any color first
int actualNormal = tempNormInd[normalIndex] * 3;
assert(actualNormal <= normLength);
glNormal3fv(&tempNorm[actualNormal]);
// Normal per vertex or per face?
if(NPV)
normalIndex++;
else
if(((coordIndex + 1) % 3) == 0) normalIndex++;
assert(normalIndex <= normIndLength);
// Input color, if any
if(tempCpv)
{
int actualColor = tempCpvInd[colorIndex] * 3;
assert(actualColor <= cpvLength);
// Is node lit (does there exist material?)
if(mat)
{
// !! TODO !! Set alpha straight
cout << "using diffuse color material per vertex" << endl;
GLfloat diffuseColor[4] = { tempCpv[actualColor], tempCpv[actualColor + 1], tempCpv[actualColor + 2], 1.0f };
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuseColor);
}
else
glColor3fv(&tempCpv[actualColor]);
// Is there a color per vertex?
if(CPV)
colorIndex++;
else
if(((coordIndex + 1) % 3) == 0) colorIndex++;
assert(colorIndex <= cpvIndLength);
}
// Changed by KStankovic
// Input texture, if any
if(tcoord)
{
if (mat->cubemapNames[0] != NULL)
{
int actualTexture = tcoordInd[textureIndex] * 3;
assert(actualTexture <= tcoordLength);
glTexCoord3f(tcoord[actualTexture], tcoord[actualTexture + 1],tcoord[actualTexture + 2]);
textureIndex++;
assert(textureIndex <= tcoordIndLength);
}
else
{
int actualTexture = tcoordInd[textureIndex] * 2;
assert(actualTexture <= tcoordLength);
glTexCoord2f(tcoord[actualTexture], tcoord[actualTexture + 1]);
textureIndex++;
assert(textureIndex <= tcoordIndLength);
}
}
//
// Get actual coord
int actualCoordinate = tempCoordInd[coordIndex] * 3;
assert(actualCoordinate <= coordLength);
glVertex3fv(&tempCoord[actualCoordinate]);
coordIndex++;
assert(coordIndex <= coordIndLength);
}
glEnd();
#else
GLVertexBuffer my_VBO_data = GLVertexBuffer(
mat, // material for this shape
coord, // vertex coordinates
coordLength, // length of the vertex coordinates array (number of vertices * 3)
coordInd, // vertex indices for triangles
coordIndLength, // length of coordInd array
norm, // normals
normLength, // length of norm array
normInd, // normal indices, per vertex
normIndLength, // length of normInd array
tcoord, // texture coordinates, if any (else zero)
tcoordLength,
tcoordInd,
tcoordIndLength,
cpv, // colors per vertex, if any (else zero)
cpvLength,
cpvInd,
cpvIndLength,
NPV, // Normal Per Vertex: 1 if on, 0 if off (i.e. normal per face)
CPV);
//BAD OPTION, BECAUSE SPENT TOO MUCH TIME CREATING VBO EVERY ITERATION
// GLuint dynamicVBO;
// glGenBuffers(1, &dynamicVBO);
// glBindBuffer(GL_ARRAY_BUFFER, dynamicVBO);
// glBufferData(GL_ARRAY_BUFFER, my_VBO_data.get_VBO_buffer_size(), 0, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, meshBuffer[nWorkingBuffer]);
GLchar* vbo_buffer=0;
#ifdef IPHONE
vbo_buffer= (GLchar*)glMapBufferOES(GL_ARRAY_BUFFER, GL_WRITE_ONLY_OES);
#else
vbo_buffer = (GLchar*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
#endif
while(my_VBO_data.has_next())
{
if(!isStaticDataInBuffer)
{
memcpy(vbo_buffer, my_VBO_data.get_coord(), my_VBO_data.get_coord_size());
vbo_buffer += my_VBO_data.get_coord_size();
memcpy(vbo_buffer, my_VBO_data.get_normal(), my_VBO_data.get_normal_size());
vbo_buffer += my_VBO_data.get_normal_size();
if(my_VBO_data.check_colors())
{
memcpy(vbo_buffer, my_VBO_data.get_cpv(), my_VBO_data.get_cpv_size());
vbo_buffer += my_VBO_data.get_cpv_size();
}
if(my_VBO_data.check_texCoord())
{
memcpy(vbo_buffer, my_VBO_data.get_texCoord(), my_VBO_data.get_texCoord_size());
vbo_buffer += my_VBO_data.get_texCoord_size();
}
}
else
{
memcpy(vbo_buffer, my_VBO_data.get_coord(), my_VBO_data.get_coord_size());
vbo_buffer += my_VBO_data.get_coord_size();
memcpy(vbo_buffer, my_VBO_data.get_normal(), my_VBO_data.get_normal_size());
vbo_buffer += my_VBO_data.get_normal_size();
if(my_VBO_data.check_colors())
{
vbo_buffer += my_VBO_data.get_cpv_size();
}
if(my_VBO_data.check_texCoord())
{
vbo_buffer += my_VBO_data.get_texCoord_size();
}
}
}
if(my_VBO_data.check_colors() && !isStaticDataInBuffer)
std::cout << "setting colors for:" << nWorkingBuffer << std::endl;
if(my_VBO_data.check_texCoord()&& !isStaticDataInBuffer)
std::cout << "setting tex_coords for:" << nWorkingBuffer << std::endl;
#ifdef IPHONE
glUnmapBufferOES(GL_ARRAY_BUFFER);
#else
glUnmapBuffer(GL_ARRAY_BUFFER);
#endif
//---End data transfers---//
//DEFINE ACTIVE ATTRIBUTES
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(my_VBO_data.get_coord_comp(), GL_FLOAT, my_VBO_data.get_vertex_size(), my_VBO_data.get_coord_offset());
glEnableClientState(GL_NORMAL_ARRAY);
glNormalPointer(GL_FLOAT, my_VBO_data.get_vertex_size(), my_VBO_data.get_normal_offset());
if(my_VBO_data.check_colors())
{
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(my_VBO_data.get_cpv_comp(), GL_FLOAT, my_VBO_data.get_vertex_size(), my_VBO_data.get_cpv_offset());
}
if(my_VBO_data.check_texCoord())
{
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(my_VBO_data.get_texCoord_comp(), GL_FLOAT, my_VBO_data.get_vertex_size(), my_VBO_data.get_texCoord_offset());
}
glColor4f(1.0, 1.0, 1.0, 1.0);
//DRAW!!!! This is the actual draw command
glDrawArrays(GL_TRIANGLES, 0, my_VBO_data.get_num_of_vertex());
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
if(my_VBO_data.check_colors())
glDisableClientState(GL_COLOR_ARRAY);
if(my_VBO_data.check_texCoord())
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);
#endif
}
void VRMLRendererTraverser::EnterLipEditingMode(SurfaceData *lipsSurface)
{
mLipsSurface = lipsSurface;
}
}
|
58608a767bfa24385f20b3bf2d0192aca8b47f67
|
0a785520716487af3b8ae5a975fbb47ffe5fa3a7
|
/Versão Anterior/teapot/rectangle.cpp
|
e80c2d963d6ccaf21235fdb2319d3d017472da08
|
[
"MIT"
] |
permissive
|
iagoesp/UFBA2017_IC
|
8ab985475d726c18bad8640629316f0bfd3ae699
|
65917a6a2e129e745d5553bbff8e69ad62b3ba1d
|
refs/heads/master
| 2018-10-20T10:52:26.257922
| 2018-09-27T15:08:26
| 2018-09-27T15:08:26
| 110,012,663
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,506
|
cpp
|
rectangle.cpp
|
#include "Rectangle.h"
#include <glm/glm.hpp>
#include <glfw/glfw3.h>
#include "mat.h"
#include "Teapot.h"
namespace byhj
{
void Rectangle::Init()
{
init_buffer();
init_vertexArray();
init_shader();
}
void Rectangle::Render(GLfloat aspect)
{
//Bind the vao, which manage status we when to render
glUseProgram(program);
glBindVertexArray(vao);
mat4 projection = Perspective(60.0, aspect, 5, 10);
// mat4 projection = Frustum( -3, 3, -3, 3, 5, 10 );
glUniformMatrix4fv(glGetUniformLocation(program, "P"), 1, GL_TRUE, projection);
float t = glfwGetTime();
mat4 modelview = Translate(-0.2625f, -1.575f, -1.0f);
modelview *= Translate(0.0f, 0.0f, -7.5f);
glUniformMatrix4fv(glGetUniformLocation(program, "MV"), 1, GL_TRUE, modelview);
glPatchParameteri(GL_PATCH_VERTICES, NumTeapotVerticesPerPatch);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDrawElements(GL_PATCHES, NumTeapotVertices, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glUseProgram(0);
}
void Rectangle::Shutdown()
{
glDeleteProgram(program);
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
}
void Rectangle::init_shader()
{
RectangleShader.init();
RectangleShader.attach(GL_VERTEX_SHADER, "teapot.vert");
RectangleShader.attach(GL_TESS_CONTROL_SHADER, "teapot.tcs");
RectangleShader.attach(GL_TESS_EVALUATION_SHADER, "teapot.tes");
RectangleShader.attach(GL_FRAGMENT_SHADER, "teapot.frag");
RectangleShader.link();
RectangleShader.use();
RectangleShader.info();
program = RectangleShader.GetProgram();
Inner_loc = glGetUniformLocation(program, "Inner");
Outer_loc = glGetUniformLocation(program, "Outer");
glUniform1f(Inner_loc, Inner);
glUniform1f(Outer_loc, Outer);
}
void Rectangle::init_buffer()
{
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(TeapotVertices), TeapotVertices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(TeapotIndices), TeapotIndices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
void Rectangle::init_vertexArray()
{
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_DOUBLE, GL_FALSE, 0, 0);
glBindVertexArray(0);
}
}
|
db5dba277a9cc430c0394a9ca9f65748f0468c42
|
872ee143626405cc285aa99066f968aae1cd551f
|
/野田 悠介/ソース/SRC/Scene/GameScene/gameScene.h
|
4406f5633f7b6cb3bf9aecc318b1510ee850c7f0
|
[] |
no_license
|
NodaYusuke/-
|
67bc9b21c4333ea3a7689028c69a437187f98d3c
|
bc75c124f534306f42c671a6bc6d77459624ff46
|
refs/heads/master
| 2022-10-15T15:49:26.521881
| 2020-06-12T03:18:31
| 2020-06-12T03:18:31
| 271,691,539
| 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 3,157
|
h
|
gameScene.h
|
#pragma once
#include"../SceneBace/sceneBase.h"
#include"../../Chara/chara.h"
#include"../../Stage/stage.h"
#include"../../MeshLei/meshLei.h"
#include"../../Camera/camera.h"
#include"../../Sound/BGM/BGM_Game/BGM_game.h"
//ゲームシーン//sceneBaseの派生クラス
//AttackHitAng関数は攻撃が当たるかどうか調べる
//SetCharaElement関数は構造体に変数をセットする
//GetTargetVecAng関数はターゲットまでの角度を調べる
//AttackGuard関数は攻撃が防御されたかどうか調べる
//HitAttack関数は相手が攻撃をくらう状態か調べる
//charaDamageInvincibleTime関数はキャラが攻撃を受けた後の無敵時間を管理する
class C_Game :public C_SceneBase
{
public:
C_Game();
~C_Game();
bool Update();
void Render3D();
void Render2D();
void SetCamera();
bool AttackHitAng(float TargetAng, float Len);
void SetCharaElement(charaElement* chraElement,const D3DXMATRIX *duelMat, const HitElement *duelElement, bool AttackHitFlg, const float* Len, float* ToAng,bool* danmageFlg,D3DXVECTOR3* camPos);
float GetTargetVecAng(const D3DXMATRIX* charaMat, D3DXVECTOR3 targetVec);
bool AttackGuard(int NowState, int NowPosition, int duelNowPosition, int* damageCnt);
bool HitAttack(HitAttackElement charaHitAttackElement);
void charaDamageInvincibleTime(bool* damageFlg, int* damageCnt);
bool StartTexCntSetCamea(C_Camera & camera ,int &battleStartTexCnt,const D3DXMATRIX &playerMat, const D3DXMATRIX& enemyMat,const D3DXVECTOR3 & pos );
private:
D3DLIGHT9 Light; //照明
C_Stage stage; //ステージのクラス
C_MeshLei meshLei; //メッシュレイのクラス
C_Camera camera; //カメラのクラス
std::vector<C_Chara*>chara;//キャラクターのクラス
//カメラのテスト用変数
D3DXVECTOR3 TestPos; //テスト用座標
D3DXVECTOR3 cameraVec;//テスト用ベクトル
//player関連----------------------------------
bool playerFlg; /*playerが生きてるかどうか*/
bool playerDamageFlg=false;/*攻撃を受けたかどうか*/
bool playerAttackHitFlg;
//--------------------------------------------
//enemy関連------------------------------------
bool enemyFlg; /*敵が生きているかどうか*/
bool enemyDamageFlg=false;/*攻撃を受けたかどうか*/
bool enemyAttackHitFlg;
//---------------------------------------------
int damageCnt[2]; /*色が変わる時間*/
float Target;/*敵との距離 -1はあったていない*/
//text表示用
LPDIRECT3DTEXTURE9 winBattleEndTex[3];
D3DXMATRIX winBattleEndTexMat[3];
LPDIRECT3DTEXTURE9 loseBattleEndTex[3];
D3DXMATRIX loseBattleEndTexMat[3];
D3DXMATRIX BattleEndTexTransMat[2];
D3DXMATRIX BattleEndTexScaleMat[2];
float scaleSize[2];
//戦いが続いている
/*trueで継続 falseで終了*/
bool battleContinuedFlg;
//戦闘開始時に表示される画像の変数
LPDIRECT3DTEXTURE9 battleStartTex[2];
D3DXMATRIX battleStartTexMat;
int battleStartTexCnt;/*表示される時間*/
LPDIRECT3DTEXTURE9 timeTex;
D3DXMATRIX timeTexMat[3];
int timeCnt;
C_BGM_Game* bgm;
D3DXVECTOR3 camPos;
};
|
108087affa36581eb69bd53c1dfa844a7910edf4
|
6e0a6ae015c23b2a30a912f9c0a83df1e29c2152
|
/Pr05.Ej04/main.cpp
|
491326be178809f6a0da39cd44422cbc06e8466e
|
[] |
no_license
|
aritzugazaga/programacionIV-workspace
|
1e17d4c9d1cf2d1c52682de2de7cdd669ada2ed3
|
cb8189219ae4ac55f87b52658b1487268c27d87a
|
refs/heads/master
| 2022-09-28T10:55:24.064201
| 2020-06-07T11:31:38
| 2020-06-07T11:31:38
| 242,957,511
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 692
|
cpp
|
main.cpp
|
/*
* main.cpp
*
* Created on: 23 abr. 2020
* Author: Aritz
*/
#include "Point.h"
#include <iostream>
using namespace std;
int main()
{
Point p1(2, 3);
Point *p2 = new Point(1,2);
p1.setX(3); //llamada a metodo no-const sobre objeto no-const
cout << "El valor de X es: " << p1.getX() << endl; //llamada a metodo const sobre objeto no-const
p2->sumar(p1);
cout << "El valor de X es: " << p2->getX() << endl; //llamada a metodo const sobre objeto no-const
const Point &pConst = p1;
cout << "El valor de X es: " << pConst.getX() << endl; //llamada a metodo const sobre objeto const
//pConst.setX(5); //Error. No podemos llamar un metodo no-const sobre un objeto const
}
|
cab10e0df18e6d2e43e0e6dbcc85328830ea8c1c
|
1f1691b2921cfbfd299ae817d29cd10e0e62455a
|
/src/helics/apps/appMain.cpp
|
0324295dc550d7ea9bc68743417cd55f6bd2573f
|
[
"BSD-3-Clause",
"LGPL-2.0-or-later"
] |
permissive
|
manoj1511/HELICS
|
d8b63a6cdaf201d763d22133d0d18100c67ec287
|
5b085bb4331f943d3fa98eb40056c3e10a1b882d
|
refs/heads/master
| 2020-08-05T03:34:01.500844
| 2019-09-27T20:52:55
| 2019-09-27T20:52:55
| 212,377,676
| 0
| 0
|
BSD-3-Clause
| 2019-10-02T15:34:43
| 2019-10-02T15:34:42
| null |
UTF-8
|
C++
| false
| false
| 4,223
|
cpp
|
appMain.cpp
|
/*
Copyright (c) 2017-2019,
Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See
the top-level NOTICE for additional details. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
*/
#include "../common/loggerCore.hpp"
#include "../core/BrokerFactory.hpp"
#include "../core/core-exceptions.hpp"
#include "../core/helicsCLI11.hpp"
#include "BrokerApp.hpp"
#include "Clone.hpp"
#include "Echo.hpp"
#include "Player.hpp"
#include "Recorder.hpp"
#include "Source.hpp"
#include "Tracer.hpp"
#include <iostream>
static const std::vector<std::string> helpArgs{"-?"};
int main (int argc, char *argv[])
{
helics::helicsCLI11App app ("simple execution for all the different HELICS apps", "helics_app");
app.ignore_case ()->prefix_command ();
app.add_subcommand ("player", "Helics Player App")
->callback ([&app] () {
helics::apps::Player player (app.remaining_for_passthrough (true));
std::cout << "player subcommand\n";
if (player.isActive ())
{
player.run ();
}
})
->footer ([] {
helics::apps::Player player ({"-?"});
return std::string{};
});
app.add_subcommand ("recorder", "Helics Recorder App")
->callback ([&app] () {
helics::apps::Recorder recorder (app.remaining_for_passthrough (true));
std::cout << "recorder subcommand\n";
if (recorder.isActive ())
{
recorder.run ();
}
})
->footer ([] {
helics::apps::Recorder rec ({"-?"});
return std::string{};
});
app.add_subcommand ("clone", "Helics Clone App")
->callback ([&app] () {
helics::apps::Clone cloner (app.remaining_for_passthrough (true));
std::cout << "clone subcommand\n";
if (cloner.isActive ())
{
cloner.run ();
}
})
->footer ([] {
helics::apps::Clone rec ({"-?"});
return std::string{};
});
app.add_subcommand ("echo", "Helics Echo App")
->callback ([&app] () {
std::cout << "echo subcommand\n";
helics::apps::Echo echo (app.remaining_for_passthrough (true));
if (echo.isActive ())
{
echo.run ();
}
})
->footer ([] {
helics::apps::Echo echo ({"-?"});
return std::string{};
});
app.add_subcommand ("source", "Helics Source App")
->callback ([&app] () {
std::cout << "source subcommand\n";
helics::apps::Source source (app.remaining_for_passthrough (true));
if (source.isActive ())
{
source.run ();
}
})
->footer ([] {
helics::apps::Source src ({"-?"});
return std::string{};
});
app.add_subcommand ("tracer", "Helics Tracer App")
->callback ([&app] () {
std::cout << "tracer subcommand\n";
helics::apps::Tracer tracer (app.remaining_for_passthrough (true));
if (tracer.isActive ())
{
tracer.run ();
}
})
->footer ([] {
helics::apps::Tracer trac ({"-?"});
return std::string{};
});
app.add_subcommand ("broker", "Helics Broker App")
->callback ([&app] () {
std::cout << "broker subcommand\n";
helics::apps::BrokerApp broker (app.remaining_for_passthrough (true));
})
->footer ([=] {
helics::apps::BrokerApp broker (argc, argv);
return std::string{};
});
app.footer ("helics_app [SUBCOMMAND] --help will display the options for a particular subcommand");
auto ret = app.helics_parse (argc, argv);
helics::LoggerManager::getLoggerCore ()->addMessage ("!!>flush");
helics::cleanupHelicsLibrary ();
switch (ret)
{
case helics::helicsCLI11App::parse_output::help_call:
case helics::helicsCLI11App::parse_output::help_all_call:
case helics::helicsCLI11App::parse_output::version_call:
case helics::helicsCLI11App::parse_output::ok:
return 0;
default:
return static_cast<int> (ret);
}
}
|
dedc8b11f1f7734bc1925882c2d61990506ce4f6
|
6186c188cdbacf49fca5dd3835a5ab2187d245b9
|
/glwidget.h
|
5c6982bdd8b048f4042d2472ba6fab82e4d2dd45
|
[] |
no_license
|
walkerka/MyImage
|
e85e2d531786b8d59cea0067d7696d0a76dd24aa
|
dddcd76bd67d066bc6155360acd45a01a319cc8a
|
refs/heads/master
| 2021-07-23T04:30:24.319924
| 2020-07-19T03:14:42
| 2020-07-19T03:14:42
| 199,115,020
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,079
|
h
|
glwidget.h
|
#ifndef GLWIDGET_H
#define GLWIDGET_H
#include <QOpenGLWidget>
#include <QOpenGLContext>
#include <QOffscreenSurface>
#include <QOpenGLFunctions>
#include <QOpenGLFramebufferObject>
#include <QOpenGLShaderProgram>
#include <QThread>
class RenderThread: public QThread, QOpenGLFunctions
{
Q_OBJECT
public:
RenderThread(QOpenGLContext* ctx, QSurface* surface);
~RenderThread();
void run();
void stop();
int GetTextureId() { return mTextureId; }
private:
QOpenGLContext* mContext;
QSurface* mSurface;
bool mDone;
int mTextureId;
};
class GLWidget : public QOpenGLWidget, QOpenGLFunctions
{
Q_OBJECT
public:
explicit GLWidget(QWidget *parent = 0);
~GLWidget();
void createRenderThread();
void Load(int w, int h, void* data);
signals:
public slots:
protected:
void initializeGL();
void resizeGL(int w, int h);
void paintGL();
private:
QOffscreenSurface* mSurface;
RenderThread* mThread;
QOpenGLShaderProgram* m_program;
int m_posAttr;
int m_matrixUniform;
};
#endif // GLWIDGET_H
|
76eda4c8fde2d13fa8d9d6a9e1b93e794011dc23
|
4606a221b70dc7e53729dccf6026916f6ff4c58f
|
/native/services/surfaceflinger/ExLayer.cpp
|
07e087ca78e7a382765657a745184229afa4f904
|
[] |
no_license
|
maxwen/vendor_qcom_opensource_display-frameworks
|
25fad7049edb718f2d91decf3648427134b22716
|
3cbe55e5591b4b0c304bf10113e2eb63f900563a
|
refs/heads/mm6.0-staging
| 2021-01-22T21:00:32.049242
| 2015-10-11T02:50:13
| 2015-10-12T20:06:20
| 44,710,143
| 1
| 3
| null | 2015-10-21T23:25:38
| 2015-10-21T23:25:37
| null |
UTF-8
|
C++
| false
| false
| 6,220
|
cpp
|
ExLayer.cpp
|
/* Copyright (c) 2015, The Linux Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of The Linux Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include <stdint.h>
#include <sys/types.h>
#include <utils/Errors.h>
#include <utils/Log.h>
#include <ui/GraphicBuffer.h>
#include <gralloc_priv.h>
#include "ExLayer.h"
namespace android {
/* Calculates the aspect ratio for external display based on the video w/h */
static Rect getAspectRatio(const sp<const DisplayDevice>& hw,
const int& srcWidth, const int& srcHeight) {
Rect outRect;
int fbWidth = hw->getWidth();
int fbHeight = hw->getHeight();
int x , y = 0;
int w = fbWidth, h = fbHeight;
if (srcWidth * fbHeight > fbWidth * srcHeight) {
h = fbWidth * srcHeight / srcWidth;
w = fbWidth;
} else if (srcWidth * fbHeight < fbWidth * srcHeight) {
w = fbHeight * srcWidth / srcHeight;
h = fbHeight;
}
x = (fbWidth - w) / 2;
y = (fbHeight - h) / 2;
outRect.left = x;
outRect.top = y;
outRect.right = x + w;
outRect.bottom = y + h;
return outRect;
}
ExLayer::ExLayer(SurfaceFlinger* flinger, const sp<Client>& client,
const String8& name, uint32_t w, uint32_t h, uint32_t flags)
: Layer(flinger, client, name, w, h, flags) {
char property[PROPERTY_VALUE_MAX] = {0};
mDebugLogs = false;
if((property_get("persist.debug.qdframework.logs", property, NULL) > 0) &&
(!strncmp(property, "1", PROPERTY_VALUE_MAX ) ||
(!strncasecmp(property,"true", PROPERTY_VALUE_MAX )))) {
mDebugLogs = true;
}
ALOGD_IF(isDebug(),"Creating custom Layer %s",__FUNCTION__);
}
ExLayer::~ExLayer() {
}
bool ExLayer::isExtOnly() const {
const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
if (activeBuffer != 0) {
ANativeWindowBuffer* buffer = activeBuffer->getNativeBuffer();
if(buffer) {
private_handle_t* hnd = static_cast<private_handle_t*>
(const_cast<native_handle_t*>(buffer->handle));
/* return true if layer is EXT_ONLY */
return (hnd && (hnd->flags & private_handle_t::PRIV_FLAGS_EXTERNAL_ONLY));
}
}
return false;
}
bool ExLayer::isIntOnly() const {
const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
if (activeBuffer != 0) {
ANativeWindowBuffer* buffer = activeBuffer->getNativeBuffer();
if(buffer) {
// TODO: uncomment this after adding PRIV_FLAG_INTERNAL_ONLY in gralloc
/* private_handle_t* hnd = static_cast<private_handle_t*>
(const_cast<native_handle_t*>(buffer->handle)); */
/* return true if layer is INT_ONLY */
/* return (hnd && (hnd->flags & private_handle_t::PRIV_FLAGS_EXTERNAL_ONLY));*/
return false;
}
}
return false;
}
bool ExLayer::isSecureDisplay() const {
const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
if (activeBuffer != 0) {
ANativeWindowBuffer* buffer = activeBuffer->getNativeBuffer();
if(buffer) {
private_handle_t* hnd = static_cast<private_handle_t*>
(const_cast<native_handle_t*>(buffer->handle));
/* return true if layer is SECURE_DISPLAY */
return (hnd && (hnd->flags & private_handle_t::PRIV_FLAGS_SECURE_DISPLAY));
}
}
return false;
}
bool ExLayer::isYuvLayer() const {
const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
if(activeBuffer != 0) {
ANativeWindowBuffer* buffer = activeBuffer->getNativeBuffer();
if(buffer) {
private_handle_t* hnd = static_cast<private_handle_t*>
(const_cast<native_handle_t*>(buffer->handle));
/* return true if layer is YUV */
return (hnd && (hnd->bufferType == BUFFER_TYPE_VIDEO));
}
}
return false;
}
void ExLayer::setPosition(const sp<const DisplayDevice>& hw,
HWComposer::HWCLayerInterface& layer, const State& state) {
/* Set dest_rect to display width and height, if external_only flag
* for the layer is enabled or if its yuvLayer in extended mode.
*/
uint32_t w = hw->getWidth();
uint32_t h = hw->getHeight();
bool extendedMode = ExSurfaceFlinger::isExtendedMode();
if(isExtOnly()) {
/* Position: fullscreen for ext_only */
Rect r(0, 0, w, h);
layer.setFrame(r);
} else if(hw->getDisplayType() > 0 && (extendedMode && isYuvLayer())) {
/* Need to position the video full screen on external with aspect ratio */
Rect r = getAspectRatio(hw, state.active.w, state.active.h);
layer.setFrame(r);
}
return;
}
}; // namespace android
|
4782e9ef34d55eaeaaab55cf63ba369653ff1503
|
f49af15675a8528de1f7d929e16ded0463cb88e6
|
/C++/C++ Advanced/TestProjects/10ExcersieRuleOfThreeInheritancePoly/02IndexedSet/IndexedSet.h
|
4e66534c05def529f039320402f1bb04e665dc66
|
[] |
no_license
|
genadi1980/SoftUni
|
0a5e207e0038fb7855fed7cddc088adbf4cec301
|
6562f7e6194c53d1e24b14830f637fea31375286
|
refs/heads/master
| 2021-01-11T18:57:36.163116
| 2019-05-18T13:37:19
| 2019-05-18T13:37:19
| 79,638,550
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 467
|
h
|
IndexedSet.h
|
#ifndef INDEXED_MAP_H
#include <cstdlib>
#include <set>
typedef int Value;
class IndexedSet {
std::set<Value> valuesSet;
Value * valuesArray;
public:
IndexedSet();
IndexedSet(const IndexedSet& other);
void add(const Value& v);
size_t size() const;
const Value& operator[](size_t index);
IndexedSet& operator=(const IndexedSet& other);
~IndexedSet();
private:
void buildIndex();
void clearIndex();
};
#define INDEXED_MAP_H
#endif // !INDEXED_MAP_H
|
8b0595be8eaa6baad6c2657b55798c2cb56f6ec5
|
3d47b90d4222d69df873d3dace722c7e39dc6e17
|
/BAPS/include/BAPPartitioner.h
|
a28ee071a355cf8f41e1e876e4e8fd714bb107c3
|
[] |
no_license
|
harishl/bap
|
063af9b5c330e2e59198310d2f985de9aca10e12
|
d09be55487ca1c58a429ecda1a1dc83eaf5aed0c
|
refs/heads/master
| 2016-09-05T21:56:34.764603
| 2012-11-18T15:06:17
| 2012-11-18T15:06:17
| 6,371,064
| 6
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,307
|
h
|
BAPPartitioner.h
|
/******************************************************************
*
* Filename : BAPPartitioner.h
* Author : David Ong Tat-Wee
*
* Version : 1.01b
* Date : 29 May 98
*
* Description : Interface file for the abstract BAP Partitioning class
* Be sure to inherit a non-abstract class from this class
* and call it with the BAPSolver.
*
* Reference : nil
*
* Notes : This class should not be modified without proper
* authorization.
*
* Changes : nil
*
* Copyright : Copyright (c) 1998
* All rights reserved by
* Resource Allocation and Scheduling Group
* Department of Information Systems and Computer Science
* National University of Singapore
*
******************************************************************/
#ifndef __BAP_PARTITIONER__
#define __BAP_PARTITIONER__
#include "def.h"
#include "BAPPackage.h"
class BAPPartitioner : public BAPBase
{
public:
BAPPartitioner(BAPPackage& aPackage);
~BAPPartitioner();
void Print(int aWidth = 1, int aDetail = 0) const;
virtual void Solve() = 0; // Abstract member function
protected:
BAPPackage& mPackage;
};
#endif
|
f36f4d5b7448217acaae937bc41d63f9c90bead3
|
53a910dfc6d58d0e1c1c9601fb3fa1452dd49d86
|
/C++/examples/DataStructures/Classes/AbstractBase/ExtensionOfCoupledClasses/Containee.h
|
a195f9306c36ddf715235e6360d75f5f8de2e871
|
[] |
no_license
|
mrodozov/Homeworks
|
342510c1154d21f730d5080d379b555d08da9a6e
|
77aaf9219819f2e9dd1accc4b8d26cd428ba0031
|
refs/heads/master
| 2021-01-22T04:57:05.907980
| 2016-08-19T04:57:42
| 2016-08-19T04:57:42
| 32,219,484
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,167
|
h
|
Containee.h
|
class AbstractBaseDetail {
public:
virtual void printType()=0;
AbstractBaseDetail();
virtual ~AbstractBaseDetail();
};
class AbstractBaseContainer {
protected:
AbstractBaseDetail * containeeInstance;
public:
virtual void setDetail(AbstractBaseDetail * cc)=0;
virtual AbstractBaseDetail * getDetail()=0;
AbstractBaseContainer();
virtual ~AbstractBaseContainer();
};
////
class Detail : public AbstractBaseDetail {
public:
virtual void printType();
Detail();
~Detail();
};
class DetailTwo : public Detail{
public:
virtual void printType();
void extensionMethod ();
DetailTwo();
~DetailTwo();
};
class Container : public AbstractBaseContainer {
public:
virtual void setDetail(AbstractBaseDetail * c){this->containeeInstance = c;}
virtual Detail * getDetail() {return dynamic_cast<Detail*>( this->containeeInstance);}
Container();
~Container();
};
class ContainerTwo : public Container{
public:
virtual DetailTwo * getDetail (){ return dynamic_cast<DetailTwo*>( this->containeeInstance); }
void extensionMethodInContainer ();
ContainerTwo();
~ContainerTwo();
};
|
b1aaa06208c8bca33cbf536c020d31b728ef3240
|
b4c0d854ac6b4b8820d49bafc2b81f276de8d25b
|
/v11/analyze.cpp
|
3937a8b7c041999b58acc9988674a2a7233d6a90
|
[] |
no_license
|
ikoljanin/Analza_HEP
|
1dd82b0491477448179044e0d94aca4ac22ce7ee
|
d2c9f7ac48957530215ceb034985fa114700e23d
|
refs/heads/master
| 2023-02-17T12:54:11.402738
| 2021-01-20T12:12:50
| 2021-01-20T12:12:50
| 302,001,414
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 386
|
cpp
|
analyze.cpp
|
#include "Analyzer.h"
using namespace std;
int main()
{
Analyzer *A;
int x;
//gornji i donji limit za primjer s predavanja
//A->upper_limit_cp(1,4,0.6827);
//A->lower_limit_cp(1,4,0.6827);
//A->CP_for10(10,0.6827);//10 događaja conf- interval
A->dice_throw(0.6827);
//cout<<"Input r for display"<<endl;
//cin>>x;
//A->Draw_cp_zone(x,10,0.6827);
return 0;
}
|
341b5786d5be7d9c5535434ac1865148d98b31d8
|
547290c8cf579680e574769a95806b500b9ef8ea
|
/Unit.cpp
|
6d266d47a659cd62bed8b87ca01e97697cec3d32
|
[] |
no_license
|
matitr/Roguelike-Game
|
84a59532d2eb60b39758c456d03dffffab5f05b1
|
2eddf52781d9a771eb529de093ecf1e7d84b0a32
|
refs/heads/master
| 2021-10-09T17:29:32.239422
| 2019-01-01T20:49:40
| 2019-01-01T20:49:40
| 123,633,468
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,240
|
cpp
|
Unit.cpp
|
#include "Unit.h"
#include "Game.h"
#include "UnitAction.h"
#include "Attacks.h"
#include "Player.h"
#include "PassivesManager.h"
#include "BuffsManager.h"
#include "Passive.h"
#include "HealthBar.h"
#include "CombatTextManager.h"
#include <math.h>
bool Unit::update(std::list <AttackType*>& monsterAttacks, Map* map) {
attackPos.x = (int)closestEnemy->getPositionX();
attackPos.y = (int)closestEnemy->getPositionY();
if (staticPassives[StaticPassiveName::hp] <= 0) {
passivesManager->activatePassives(PassiveActivateOn::Death, monsterAttacks);
}
if (staticPassives[StaticPassiveName::hp] <= 0) {
isAlive = false;
return actionsManager.updateDeathAction(this, monsterAttacks, &attackPos);
}
actionsManager.updateMove();
actionsManager.onClosestObj(map, closestEnemy, closestEnemyDist, position);
actionsManager.updateAction(velocity);
passivesManager->activatePassives(PassiveActivateOn::Passive, monsterAttacks);
passivesManager->updateAllPassives(this);
speed = staticPassives[StaticPassiveName::unitSpeed];
actionsManager.makeAttack(this, monsterAttacks, &attackPos);
actionsManager.makeMove(this);
unitDetectedCollisionUnit = false;
unitDetectedCollisionWall = false;
makeMove();
maxSpeed = -1;
return true;
}
void Unit::makeMove() {
if (!(!velocity.y && !velocity.x)) {
double dir = atan2(velocity.y, velocity.x);
if (maxSpeed == -1 || (speed * (1 + staticPassives[StaticPassiveName::unitSpeedMult])) <= maxSpeed) {
position.x += cos(dir) * speed * (1 + staticPassives[StaticPassiveName::unitSpeedMult]);
position.y += sin(dir) * speed * (1 + staticPassives[StaticPassiveName::unitSpeedMult]);
}
else {
position.x += cos(dir) * maxSpeed;
position.y += sin(dir) * maxSpeed;
}
}
}
void Unit::draw(SDL_Point* startRender) {
dstRect.x = int(position.x - startRender->x) - positionShiftX;
dstRect.y = int((position.y - startRender->y) * HEIGHT_SCALE) - positionShiftY;
SDL_RenderCopy(Game::renderer, texture, &srcRect, &dstRect);
healthBar->draw();
// Draw hitbox
SDL_Rect r;
r.h = 4;
r.w = radius * 2;
r.x = (int)position.x - positionShiftX - startRender->x;
r.y = (int)position.y - startRender->y;
SDL_SetRenderDrawColor(Game::renderer, rand() % 225, 0, 102, 255);
renderCircle((int)position.x - startRender->x, ((int)position.y - startRender->y) * HEIGHT_SCALE, radius);
}
void Unit::setClosestEnemy(Unit* u, double dist) {
closestEnemy = u;
closestEnemyDist = dist;
}
void Unit::takeDamage(float& damage, DamageType damageType) {
passivesManager->takeDamage(damage, damageType);
if (damage < 0)
damageType = DamageType::Heal;
CombatTextManager::get().addDamage(damage, damageType, this);
}
Unit::Unit(TextureInfo& txtInfo, UnitType uType)
: GameObject(txtInfo, Dynamic, Circle), actionsManager(srcRect, staticPassives[StaticPassiveName::unitSpeedMult], staticPassives[StaticPassiveName::attackSpeedMult], this), unitType(uType) {
passivesManager = new PassivesManager(staticPassives);
healthBar = new HealthBar(dstRect, staticPassives[StaticPassiveName::hp], staticPassives[StaticPassiveName::hpMax], unitType);
healthBar->draw();
passivesManager->setStartingStat(StaticPassiveName::damage, 1);
passivesManager->setStartingStat(StaticPassiveName::hp, 100);
passivesManager->setStartingStat(StaticPassiveName::hpMax, 100);
passivesManager->setStartingStat(StaticPassiveName::unitSpeed, 3);
velocity.x = 0;
velocity.y = 0;
}
Unit::~Unit() {
delete passivesManager;
delete healthBar;
}
void Unit::renderCircle(int _x, int _y, int radius) {
int x = radius - 1;
int y = 0;
int tx = 1;
int ty = 1;
int err = tx - (radius << 1);
while (x >= y) {
SDL_RenderDrawPoint(Game::renderer, _x + x, _y - y);
SDL_RenderDrawPoint(Game::renderer, _x + x, _y + y);
SDL_RenderDrawPoint(Game::renderer, _x - x, _y - y);
SDL_RenderDrawPoint(Game::renderer, _x - x, _y + y);
SDL_RenderDrawPoint(Game::renderer, _x + y, _y - x);
SDL_RenderDrawPoint(Game::renderer, _x + y, _y + x);
SDL_RenderDrawPoint(Game::renderer, _x - y, _y - x);
SDL_RenderDrawPoint(Game::renderer, _x - y, _y + x);
if (err <= 0){
y++;
err += ty;
ty += 2;
}
else if (err > 0) {
x--;
tx += 2;
err += tx - (radius << 1);
}
}
}
|
ba6bd96a705f1c6446eaa896eb33d74d60d43642
|
5c2e9f04a1fbc4177db5ce1a448c7236284ab6d6
|
/Server/Server.cpp
|
520131cc0989d25edb0614dd06a3fc896116cb28
|
[] |
no_license
|
kien6034/Networking---Winsock-programming
|
30146efe4eaba4c6395c6ff32a54faad0955bc72
|
278d9d9cb95113c22b21b621c74d960e97423d07
|
refs/heads/master
| 2022-11-06T10:47:11.801798
| 2020-06-18T12:08:47
| 2020-06-18T12:08:47
| 273,227,508
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,152
|
cpp
|
Server.cpp
|
// Server.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32")
#pragma warning(disable:4996)
DWORD WINAPI ClientThread(LPVOID);
int main()
{
WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
SOCKADDR_IN addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(9000);
SOCKET listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bind(listener, (SOCKADDR*)& addr, sizeof(addr));
listen(listener, 5);
while (1)
{
printf("Waiting for new client...\n");
SOCKET client = accept(listener, NULL, NULL);
printf("New client accepted: %d\n", client);
CreateThread(0, 0, ClientThread, &client, 0, 0);
const char* okMsg = "Press R to record, press S to stop \n";
send(client, okMsg, strlen(okMsg), 0);
}
}
DWORD WINAPI ClientThread(LPVOID lpParam)
{
SOCKET client = *(SOCKET*)lpParam;
char buf[256];
int ret;
while (1) {
ret = recv(client, buf, sizeof(buf), 0);
if (ret <= 0)
{
closesocket(client);
return 0;
}
buf[ret] = 0;
printf("Received: %s\n", buf);
}
}
|
338d4cd7f351b8d6fac3acda8f2f04d8a56a720b
|
fa50fd913aca4da3a10b0198480012a8ce80515f
|
/AlgorithmStudy/Array.h
|
584b22ab8af5c08f5a91eeb956749e198e7d37c9
|
[] |
no_license
|
wuningjian/AlgorithmStudy
|
0ad3a28795a788181cdd0c5304caad48ab0945be
|
b991fa2bf8221e3a00b1e1d4a217297886fc94f5
|
refs/heads/master
| 2020-05-07T10:05:05.527985
| 2019-05-19T15:11:19
| 2019-05-19T15:11:19
| 180,404,366
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 823
|
h
|
Array.h
|
#ifndef Array_hpp
#define Array_hpp
#pragma once
template <class T>//类模板详细介绍 https://www.cnblogs.com/msymm/p/9750787.html
class Array
{
private:
T *base;//数组首地址
int length;//数组元素个数
int size;//数组总大小
public:
Array();
~Array();
//初始化内存,分配内存
bool init();
//检查内存是否够用,不够就增加
bool ensureCapcity();
//添加元素到数组最后
bool add(T item);
//插入元素到数组具体位置,位置从1开始
bool insert(T item, int idx);
//删除指定位置元素并返回,位置从1开始
T deleteItem(int idx);
//返回指定位置元素 从1开始计算
T getItemByIndex(int idx);
//打印数组所有元素
void pringArray();
};
//参考 https://www.cnblogs.com/jiy-for-you/p/6892358.html
#endif // !Array_hpp
|
591ad31f536aa74cbe30bd12c22a09ef65ffa08b
|
e9c2ebc2dbe98208e8a0a28a5dad5ffca4dff1fd
|
/sherpas/src/query.cpp
|
becdb4b40fcf9b3a36bb6e7374afaea094e9bdcc
|
[
"MIT"
] |
permissive
|
wangdi2014/sherpas
|
cc0c8311e631332c66390159f5830bbc53085681
|
f9b63a0ab3d8635528d9c8ace09a057fceb1cc28
|
refs/heads/master
| 2022-11-24T10:04:32.961022
| 2020-06-24T07:39:13
| 2020-06-24T07:39:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,772
|
cpp
|
query.cpp
|
/*
* query.cpp
*
* Created on: 23 oct. 2018
* Author: scholz
*/
#include<iostream>
#include<fstream>
#include<vector>
#include <cstring>
#include<cmath>
#include "query.h"
using namespace std;
//the main algorithm
std::vector<rappas::io::fasta> gapRm(std::vector<rappas::io::fasta> *sequences)
{
//gap-remover; useful to remove gaps (now that was unexpected)
int s=(*sequences).size();
std::vector<rappas::io::fasta> res;
for(int i=0; i<s; i++)
{
(res).emplace_back(move((((*sequences)[i]).header()).data()), move(rappas::io::clean_sequence((((*sequences)[i]).sequence()).data())));
}
return res;
}
void make_circu(std::string res, std::string rep, int p)
{
// adds p bases of the end to the beginning of the sequence, and p bases of the beginning to the end. p should be (ws+k-1)/2 for queries.
// creates a new file. To be used until circularity is considered in the core for db building and queries reading (if that happens).
ofstream write(rep);
std::vector<rappas::io::fasta> seq= rappas::io::read_fasta(res);
std::string prefix = "";
std::string suffix = "";
for(int i=0; i<seq.size(); i++)
{
prefix = (seq[i].sequence()).substr(0, p);
suffix = (seq[i].sequence()).substr((seq[i].sequence()).length()-p);
write << ">" << seq[i].header() << endl;
write << suffix << seq[i].sequence() << prefix << endl;
}
}
void windInit(std::vector<std::vector<Arc*>> *wind)
{
//empties windows vector
int s=(*wind).size();
for(int i=0; i<s; i++)
{
(*wind).pop_back();
}
}
int nucl(char c)
//tests whether a character is a nucleotide (1) or a gap/uncertain state (0).
{
int res=0;
if(c=='A'||c=='C'||c=='T'||c=='G')
{
res=1;
}
return res;
}
std::vector<std::vector<core::phylo_kmer_db::key_type>> encode_ambiguous_string(std::string_view long_read, const size_t kmer_size)
{
//reads the query as a list of kmers, then translated into a list of multi-codes. kmers with one ambiguity get codes for each possibility, kmers with more than one ambiguity are skipped.
size_t position = 0;
std::vector<std::vector<core::phylo_kmer_db::key_type>> res(0);
std::vector<core::phylo_kmer_db::key_type> nope (0);
nope.push_back(-1);
for (const auto& [kmer, codes] : core::to_kmers<core::one_ambiguity_policy>(long_read, kmer_size))
{
{
res.push_back(codes);
}
++position;
}
if(res.size() != long_read.size()-kmer_size+1)
{
res=fixCcodes(res, long_read, kmer_size);
}
return res;
}
std::vector<std::vector<core::phylo_kmer_db::key_type>> fixCcodes(std::vector<std::vector<core::phylo_kmer_db::key_type>> ccodes, std::string_view long_read, const size_t kmer_size)
{
// assigns empty code string to kmers with more than one ambiguity
std::vector<std::vector<core::phylo_kmer_db::key_type>> res(0);
std::vector<core::phylo_kmer_db::key_type> nope (0);
nope.push_back(-1);
int check=0;
int pos=0;
for(int i=0; i<kmer_size; i++)
{
check=check+1-nucl(long_read[i]);
}
if(check>1)
{
res.push_back(nope);
}
else
{
res.push_back(ccodes[pos]);
pos++;
}
for(int i=kmer_size; i<long_read.size(); i++)
{
check=check+nucl(long_read[i-kmer_size])-nucl(long_read[i]);
if(check>1)
{
res.push_back(nope);
}
else
{
res.push_back(ccodes[pos]);
pos++;
}
}
return res;
}
void readQuery(std::vector<std::vector<core::phylo_kmer_db::key_type>> codes, const core::phylo_kmer_db& db, std::vector<Arc>* branches, Htree *H)
{
//RAPPAS algorithm on a given query
//result stored in heap *H
std::vector<Arc*> res(0);
size_t k=db.kmer_size();
double thr = log10(core::score_threshold(db.omega(),k));
int q=codes.size();
std::vector<core::phylo_kmer_db::key_type> ka;
std::vector<double> Lamb((*branches).size());
int w=0;
double add=0;
for(int i=0; i<q; i++)
{
ka=codes[i];
if(ka.size() == 1)
{
if (auto entries = db.search(ka[0]) ; entries)
{
for (const auto& [branch, score] : *entries)
{
(*branches)[branch].updateScore(score,1);
if(((*branches)[branch]).getKmers()==1)
{
(res).push_back(&((*branches)[branch]));
}
}
}
}
else
{
w=ka.size();
Lamb.clear();
for(int p=0; p<w; p++)
{
if (auto entries = db.search(ka[p]) ; entries)
{
for (const auto& [branch, score] : *entries)
{
Lamb[branch]+=(pow(10,score)-pow(10,thr))/w;
}
}
}
for(int j=0; j<Lamb.size(); j++)
{
if(Lamb[j] !=0)
{
(*branches)[j].updateScore(Lamb[j],1);
if(((*branches)[j]).getKmers()==1)
{
(res).push_back(&((*branches)[j]));
}
}
}
}
}
int s=(res).size();
double up;
for(int i=0; i<s; i++)
{
up=(thr)*(q-(*(res)[i]).getKmers());
(*(res)[i]).updateScore(up,0);
(*H).push(res[i]);
}
}
void addKmer(std::vector<core::phylo_kmer_db::key_type> keys, Htree* H, const core::phylo_kmer_db& db, std::vector<Arc>* branches, double thr, int sw, int k, int move)
{
//updates scores when a kmer is added.
int w=keys.size();
double add=0;
if(w==1)
{
if (auto entries = db.search(keys[0]) ; entries)
{
for (const auto& [branch, score] : *entries)
{
(*branches)[branch].updateScore(score-thr,1);
if(((*branches)[branch]).getKmers()==1)
{
(*branches)[branch].updateScore(((sw-1)*thr),0);
(*H).push(&((*branches)[branch]));
}
else
{
(*H).heapUp(((*branches)[branch].ArcCheck()));
}
}
}
}
else if(w>1)
{
std::vector<double> Lamb((*branches).size());
for(int i=0; i<w; i++)
{
if (auto entries = db.search(keys[i]) ; entries)
{
for (const auto& [branch, score] : *entries)
{
Lamb[branch]+=(pow(10,score)-pow(10,thr))/w;
}
}
}
for(int j=0; j<Lamb.size(); j++)
{
if(Lamb[j] !=0)
{
add=log10(Lamb[j]+pow(10,thr))-thr;
(*branches)[j].updateScore(add,1);
if(((*branches)[j]).getKmers()==1)
{
(*branches)[j].updateScore(((sw-1)*thr),0);
(*H).push(&((*branches)[j]));
}
else
{
(*H).heapUp(((*branches)[j].ArcCheck()));
}
}
}
}
if(move==0)
{
for(int i=0; i<(*H).size(); i++)
{
if((*((*H).h(i))).getKmers()>0)
{
(*((*H).h(i))).updateScore(thr,0);
}
}
}
}
void rmKmer(std::vector<core::phylo_kmer_db::key_type> keys, Htree* H, const core::phylo_kmer_db& db, std::vector<Arc>* branches, double thr, int move)
{
//updates scores when a kmer is removed.
int w=keys.size();
double rem=0;
if(w==1)
{
if (auto entries = db.search(keys[0]) ; entries)
{
for (const auto& [branch, score] : *entries)
{
(*branches)[branch].updateScore(thr-score,-1);
if(((*branches)[branch]).getKmers()==0)
{
(*H).pop(((*branches)[branch]).ArcCheck());
}
else
{
(*H).heapDown(((*branches)[branch].ArcCheck()));
}
}
}
}
else if(w>1)
{
std::vector<double> Lamb((*branches).size());
for(int i=0; i<w; i++)
{
if (auto entries = db.search(keys[i]) ; entries)
{
for (const auto& [branch, score] : *entries)
{
Lamb[branch]+=(pow(10,score)-pow(10,thr))/w;
}
}
}
for(int j=0; j<Lamb.size(); j++)
{
if(Lamb[j] !=0)
{
rem=thr-log10(Lamb[j]+pow(10,thr));
(*branches)[j].updateScore(rem,-1);
if(((*branches)[j]).getKmers()==0)
{
(*H).pop(((*branches)[j]).ArcCheck());
}
else
{
(*H).heapDown(((*branches)[j].ArcCheck()));
}
}
}
}
if(move==0)
{
for(int i=0; i<(*H).size(); i++)
{
if((*((*H).h(i))).getKmers()>0)
{
(*((*H).h(i))).updateScore(-thr,0);
}
}
}
}
void slidingVarWindow(std::vector<std::vector<core::phylo_kmer_db::key_type>> codes, int wi, int sw, int m, const core::phylo_kmer_db& db, std::vector<Arc>* branches, std::vector<std::vector<Arc*>> *res, std::vector<double> *rat, char met)
{
//the main algorithm.
//basically a sliding window except the window size increases (from wi to sw) at the beginning of the query and decreases (from sw to wi) at the end.
//equivalent to a sliding window if wi=sw (case of circular queries).
//as the window size increases by 2 at each step, wi and ws should have same parity (I can't guarantee what happens otherwise, but this may induce a shift in positions somewhere).
//Arc *neutral=new Arc(-1,0);
std::vector<Arc*> rest(0);
Htree H(rest);
std::vector<Arc*> temp(m);
size_t k=db.kmer_size();
double thr = log10(core::score_threshold(db.omega(),k));
int q=codes.size();
std::vector<core::phylo_kmer_db::key_type> ka;
std::vector<core::phylo_kmer_db::key_type> kr;
if(sw>q || wi>sw)
{
cout << "Dimension problems: check windows size vs k-mer size and/or windows size vs query length" << endl;
cout << wi << "<" << sw << "<" << q << endl;
}
else
{
std::vector<std::vector<core::phylo_kmer_db::key_type>> firstw(codes.begin(),codes.begin()+wi-1);
readQuery(firstw, db, branches, &H);
H.getTop(m);
if(met=='R')
{
(*rat).push_back(H.lRatio(k));
}
else
{
(*rat).push_back(H.dRatio(k));
}
int s=H.size();
for(int i=0; i<m; i++)
{
if(s>i)
{
Arc *best=new Arc(*(H.h(i)));
temp[i]=best;
}
else
{
Arc *neutral=new Arc(-1,0);
temp[i]=neutral;
}
}
(*res).push_back(temp);
for(int j=wi; j<sw-1; j+=2)
{
ka=codes[j];
kr=codes[j+1];
addKmer(ka, &H, db, branches, thr, j+1, k, 0);
addKmer(kr, &H, db, branches, thr, j+1, k, 0);
H.getTop(m);
if(met=='R')
{
(*rat).push_back(H.lRatio(k));
}
else
{
(*rat).push_back(H.dRatio(k));
}
s=H.size();
for(int i=0; i<m; i++)
{
if(s>i)
{
Arc *best=new Arc(*(H.h(i)));
temp[i]=best;
}
else
{
Arc *neutral=new Arc(-1,0);
temp[i]=neutral;
}
}
(*res).push_back(temp);
}
for(int j=sw; j<q; j++)
{
ka=codes[j];
kr=codes[j-sw];
addKmer(ka, &H, db, branches, thr, j+1, k, 1);
rmKmer(kr, &H, db, branches, thr, 1);
H.getTop(m);
if(met=='R')
{
(*rat).push_back(H.lRatio(k));
}
else
{
(*rat).push_back(H.dRatio(k));
}
s=H.size();
for(int i=0; i<m; i++)
{
if(s>i)
{
Arc *best=new Arc(*(H.h(i)));
temp[i]=best;
}
else
{
Arc *neutral=new Arc(-1,0);
temp[i]=neutral;
}
}
(*res).push_back(temp);
}
for(int j=q-sw; j<q-wi-1; j+=2)
{
ka=codes[j];
kr=codes[j+1];
rmKmer(ka, &H, db, branches, thr, 0);
rmKmer(kr, &H, db, branches, thr, 0);
H.getTop(m);
if(met=='R')
{
(*rat).push_back(H.lRatio(k));
}
else
{
(*rat).push_back(H.dRatio(k));
}
s=H.size();
for(int i=0; i<m; i++)
{
if(s>i)
{
Arc *best=new Arc(*(H.h(i)));
temp[i]=best;
}
else
{
Arc *neutral=new Arc(-1,0);
temp[i]=neutral;
}
}
(*res).push_back(temp);
}
}
}
|
87d788feb8f5a4897f565661e7a5fe931ac6901c
|
adb23ab9c2db760afa93c09a1737687ae2431466
|
/DgEngine/AmbientLight.h
|
fb93245be89bafe52f6eb427ea1e298fe018920e
|
[] |
no_license
|
int-Frank/SoftwareRasterizer
|
cb5d3234dcd59f55e6384a7152e0bb81cabc0401
|
f62d5bf7e16b0cefe9dd46b255341ba0cea0893d
|
refs/heads/master
| 2021-09-08T04:16:39.613309
| 2014-09-12T23:13:23
| 2014-09-12T23:13:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,477
|
h
|
AmbientLight.h
|
/*!
* @file AmbientLight.h
*
* @author Frank Hart
* @date 7/01/2014
*
* Class header: AmbientLight
*/
#ifndef AMBIENTLIGHT_H
#define AMBIENTLIGHT_H
#include "Light.h"
struct Vertex;
struct Polygon;
class Mesh;
class VQS;
namespace pugi{ class xml_node; }
/*!
* @ingroup lights
*
* @class AmbientLight
*
* @brief An ambient light source represents a fixed-intensity and
* fixed-color light source that affects all objects in the scene equally
*
* @author Frank Hart
* @date 7/01/2014
*/
class AmbientLight : public Light
{
public:
//Constructor / destructor
AmbientLight(){}
~AmbientLight(){}
//Copy operations
AmbientLight(const AmbientLight& other): Light(other) {}
AmbientLight& operator= (const AmbientLight&);
/*!
* @brief Creates a deep copy of a derived object.
*
* @return Pointer to the newly created object.
*/
AmbientLight* clone() const {return new AmbientLight(*this);}
//! @brief Build light from pugi::xml_node.
friend pugi::xml_node& operator>>(pugi::xml_node&, AmbientLight& dest);
//! Adjusts intensity.
void Transform(const VQS&);
//! Adjusts intensity.
void TransformQuick(const VQS&);
//! Temporarily transform the light, then add to a Mesh.
void AddToMesh(Mesh&, const VQS&, const Materials&) const;
/*! Does the light touch the sphere?
*
* @return
* - 0: No collision
* - 1: Collision
*/
uint8 Test(const Sphere& r) const {return 1;}
protected:
//Data members
};
#endif
|
c277dc889dc10d38e5c41adb9cab459c32e712d5
|
e3ea7046b84288cad31d72b9c31172e7ab8c9f11
|
/lib/libriscv/cpu_inline.hpp
|
d54ea7657aefd2f1255e128aac93081fd8f587df
|
[] |
no_license
|
5l1v3r1/libriscv
|
a1561b2f2069f340ec8a098747a6b6adf5d3e795
|
8a5ea17359d7cf4a80ce19ca0d7bfdb677fae13c
|
refs/heads/master
| 2021-05-25T08:42:02.907603
| 2020-04-05T16:00:40
| 2020-04-05T16:14:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,404
|
hpp
|
cpu_inline.hpp
|
template <int W>
inline CPU<W>::CPU(Machine<W>& machine)
: m_machine { machine }
{
}
template <int W>
inline void CPU<W>::change_page(address_t this_page)
{
#ifdef RISCV_PAGE_CACHE
for (const auto& cache : m_page_cache) {
if (cache.address == this_page) {
m_current_page = cache;
return;
}
}
#endif
m_current_page.address = this_page;
m_current_page.page = &machine().memory.create_page(this_page >> Page::SHIFT);
#ifdef RISCV_PAGE_CACHE
// cache it
m_page_cache[m_cache_iterator] = m_current_page;
m_cache_iterator = (m_cache_iterator + 1) % m_page_cache.size();
#endif
// verify execute permission
if (UNLIKELY(!m_current_page.page->attr.exec)) {
this->trigger_exception(EXECUTION_SPACE_PROTECTION_FAULT);
}
}
template<int W> constexpr
inline void CPU<W>::jump(const address_t dst)
{
this->registers().pc = dst;
// it's possible to jump to a misaligned address
if constexpr (!compressed_enabled) {
if (UNLIKELY(this->registers().pc & 0x3)) {
this->trigger_exception(MISALIGNED_INSTRUCTION);
}
} else {
if (UNLIKELY(this->registers().pc & 0x1)) {
this->trigger_exception(MISALIGNED_INSTRUCTION);
}
}
}
#ifdef RISCV_DEBUG
template <int W>
inline void CPU<W>::breakpoint(address_t addr, breakpoint_t func) {
this->m_breakpoints[addr] = func;
}
template <int W>
inline void CPU<W>::default_pausepoint(CPU& cpu)
{
cpu.machine().print_and_pause();
}
#endif
|
758918d99cebbf74e20540b2688e41d34d63e1bc
|
5447a87c9fa3cd790453a8bf4a40761b4fbb099b
|
/leetcode2/Other/MyStack.h
|
d0a813a64387b79bbeb2aae60d04c4185532a4fa
|
[] |
no_license
|
necromaner/C-
|
ffb215520d3035a1e785147303c753a10a47619a
|
f7978b358f8246072c7f9627cee80e5df1994b25
|
refs/heads/master
| 2021-05-25T09:13:32.011117
| 2020-11-10T09:00:47
| 2020-11-10T09:00:47
| 126,946,399
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,116
|
h
|
MyStack.h
|
//
// Created by necromaner on 2020/9/14.
//
#ifndef LEETCODE2_MYSTACK_H
#define LEETCODE2_MYSTACK_H
#include <queue>
using namespace std;
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
/*
执行用时:0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗:7 MB, 在所有 C++ 提交中击败了43.77% 的用户
*/
class MyStack {//2) 栈(先进后出)
public:
MyStack();
void push(int x);
int pop();
int top();
bool empty();
private:
queue<int> queue1;//1) 堆(先进先出)
};
/*
执行用时:0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗:6.9 MB, 在所有 C++ 提交中击败了79.44% 的用户
*/
class MyStack1 {//单队列
public:
MyStack1(){}
void push(int x){queue1.push(x);}//顺序压入
int pop();
int top();
bool empty(){return queue1.empty();}
private:
queue<int> queue1;//1) 堆(先进先出)
};
#endif //LEETCODE2_MYSTACK_H
|
4431b39cb30314b190a38c93dfba4db04addddb8
|
e42ee3ca63e7ca509a26b88ee9868e09d2e5a8bb
|
/GeneratedFiles/ui_qg_cadtoolbarmain.h
|
4912746cacc6b2951b7e54aff324174af819a22b
|
[] |
no_license
|
15831944/Democad
|
fdee2b2a63de7a2791d6e2ac6a3f55a71cf7c985
|
88fd0fcafba9f28ab022790538d433c333ffa165
|
refs/heads/master
| 2021-06-09T07:19:49.861046
| 2016-11-25T01:42:07
| 2016-11-25T01:42:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,590
|
h
|
ui_qg_cadtoolbarmain.h
|
/********************************************************************************
** Form generated from reading UI file 'qg_cadtoolbarmain.ui'
**
** Created: Mon Sep 26 14:56:11 2016
** by: Qt User Interface Compiler version 4.8.4
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_QG_CADTOOLBARMAIN_H
#define UI_QG_CADTOOLBARMAIN_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QFrame>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QToolButton>
#include <QtGui/QWidget>
QT_BEGIN_NAMESPACE
class Ui_QG_CadToolBarMain
{
public:
QToolButton *bHidden;
QToolButton *bTrim;
QToolButton *bTrim2;
QToolButton *bScale;
QToolButton *bMove;
QToolButton *bRotate;
QToolButton *bMirror;
QFrame *line;
QFrame *line_2;
QToolButton *bCircle;
QToolButton *bNormal;
QToolButton *bRectangle;
QToolButton *bArc;
QFrame *line_3;
QToolButton *bDel;
QToolButton *bUnAll;
QToolButton *bAll;
QToolButton *bInvert;
QLabel *lCoord1;
QLabel *lCoord1b;
QLabel *lGridGap;
void setupUi(QWidget *QG_CadToolBarMain)
{
if (QG_CadToolBarMain->objectName().isEmpty())
QG_CadToolBarMain->setObjectName(QString::fromUtf8("QG_CadToolBarMain"));
QG_CadToolBarMain->resize(80, 307);
QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(QG_CadToolBarMain->sizePolicy().hasHeightForWidth());
QG_CadToolBarMain->setSizePolicy(sizePolicy);
QG_CadToolBarMain->setMinimumSize(QSize(0, 0));
QG_CadToolBarMain->setMaximumSize(QSize(80, 457));
bHidden = new QToolButton(QG_CadToolBarMain);
bHidden->setObjectName(QString::fromUtf8("bHidden"));
bHidden->setGeometry(QRect(2, 353, 0, 0));
bHidden->setMaximumSize(QSize(0, 0));
bHidden->setIconSize(QSize(0, 0));
bHidden->setCheckable(true);
bHidden->setAutoExclusive(true);
bTrim = new QToolButton(QG_CadToolBarMain);
bTrim->setObjectName(QString::fromUtf8("bTrim"));
bTrim->setEnabled(true);
bTrim->setGeometry(QRect(2, 70, 32, 32));
bTrim->setMaximumSize(QSize(32, 32));
QIcon icon;
icon.addFile(QString::fromUtf8(":/extui/modifytrim_OFF.png"), QSize(), QIcon::Active, QIcon::Off);
icon.addFile(QString::fromUtf8(":/extui/modifytrim_ON.png"), QSize(), QIcon::Active, QIcon::On);
bTrim->setIcon(icon);
bTrim->setIconSize(QSize(32, 32));
bTrim->setCheckable(true);
bTrim->setChecked(false);
bTrim->setAutoExclusive(false);
bTrim2 = new QToolButton(QG_CadToolBarMain);
bTrim2->setObjectName(QString::fromUtf8("bTrim2"));
bTrim2->setEnabled(true);
bTrim2->setGeometry(QRect(33, 70, 32, 32));
bTrim2->setMaximumSize(QSize(32, 32));
QIcon icon1;
icon1.addFile(QString::fromUtf8(":/extui/modifytrim2_OFF.png"), QSize(), QIcon::Active, QIcon::Off);
icon1.addFile(QString::fromUtf8(":/extui/modifytrim2_ON.png"), QSize(), QIcon::Active, QIcon::On);
bTrim2->setIcon(icon1);
bTrim2->setIconSize(QSize(32, 32));
bTrim2->setCheckable(true);
bTrim2->setChecked(false);
bTrim2->setAutoExclusive(false);
bScale = new QToolButton(QG_CadToolBarMain);
bScale->setObjectName(QString::fromUtf8("bScale"));
bScale->setEnabled(true);
bScale->setGeometry(QRect(2, 132, 32, 32));
bScale->setMaximumSize(QSize(32, 32));
QIcon icon2;
icon2.addFile(QString::fromUtf8(":/extui/dlgscale_OFF.png"), QSize(), QIcon::Active, QIcon::Off);
icon2.addFile(QString::fromUtf8(":/extui/dlgscale_ON.png"), QSize(), QIcon::Active, QIcon::On);
bScale->setIcon(icon2);
bScale->setIconSize(QSize(32, 32));
bScale->setCheckable(true);
bScale->setChecked(false);
bScale->setAutoExclusive(false);
bMove = new QToolButton(QG_CadToolBarMain);
bMove->setObjectName(QString::fromUtf8("bMove"));
bMove->setEnabled(true);
bMove->setGeometry(QRect(2, 101, 32, 32));
bMove->setMaximumSize(QSize(32, 32));
QIcon icon3;
icon3.addFile(QString::fromUtf8(":/extui/modifymove_OFF.png"), QSize(), QIcon::Active, QIcon::Off);
icon3.addFile(QString::fromUtf8(":/extui/modifymove_ON.png"), QSize(), QIcon::Active, QIcon::On);
bMove->setIcon(icon3);
bMove->setIconSize(QSize(32, 32));
bMove->setCheckable(true);
bMove->setChecked(false);
bMove->setAutoExclusive(false);
bRotate = new QToolButton(QG_CadToolBarMain);
bRotate->setObjectName(QString::fromUtf8("bRotate"));
bRotate->setEnabled(true);
bRotate->setGeometry(QRect(33, 101, 32, 32));
bRotate->setMaximumSize(QSize(32, 32));
QIcon icon4;
icon4.addFile(QString::fromUtf8(":/extui/modifyrotate_OFF.png"), QSize(), QIcon::Active, QIcon::Off);
icon4.addFile(QString::fromUtf8(":/extui/modifyrotate_ON.png"), QSize(), QIcon::Active, QIcon::On);
bRotate->setIcon(icon4);
bRotate->setIconSize(QSize(32, 32));
bRotate->setCheckable(true);
bRotate->setChecked(false);
bRotate->setAutoExclusive(false);
bMirror = new QToolButton(QG_CadToolBarMain);
bMirror->setObjectName(QString::fromUtf8("bMirror"));
bMirror->setEnabled(true);
bMirror->setGeometry(QRect(33, 132, 32, 32));
bMirror->setMaximumSize(QSize(32, 32));
QIcon icon5;
icon5.addFile(QString::fromUtf8(":/extui/modifymirror_OFF.png"), QSize(), QIcon::Active, QIcon::Off);
icon5.addFile(QString::fromUtf8(":/extui/modifymirror_ON.png"), QSize(), QIcon::Active, QIcon::On);
bMirror->setIcon(icon5);
bMirror->setIconSize(QSize(32, 32));
bMirror->setCheckable(true);
bMirror->setChecked(false);
bMirror->setAutoExclusive(false);
line = new QFrame(QG_CadToolBarMain);
line->setObjectName(QString::fromUtf8("line"));
line->setEnabled(true);
line->setGeometry(QRect(2, 60, 65, 16));
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
line_2 = new QFrame(QG_CadToolBarMain);
line_2->setObjectName(QString::fromUtf8("line_2"));
line_2->setEnabled(true);
line_2->setGeometry(QRect(2, 160, 65, 16));
line_2->setFrameShape(QFrame::HLine);
line_2->setFrameShadow(QFrame::Sunken);
bCircle = new QToolButton(QG_CadToolBarMain);
bCircle->setObjectName(QString::fromUtf8("bCircle"));
bCircle->setEnabled(true);
bCircle->setGeometry(QRect(33, 33, 32, 32));
bCircle->setMaximumSize(QSize(32, 32));
QIcon icon6;
icon6.addFile(QString::fromUtf8(":/extui/circles_OFF.png"), QSize(), QIcon::Active, QIcon::Off);
icon6.addFile(QString::fromUtf8(":/extui/circles_ON.png"), QSize(), QIcon::Active, QIcon::On);
bCircle->setIcon(icon6);
bCircle->setIconSize(QSize(32, 32));
bCircle->setCheckable(true);
bCircle->setChecked(false);
bCircle->setAutoExclusive(false);
bNormal = new QToolButton(QG_CadToolBarMain);
bNormal->setObjectName(QString::fromUtf8("bNormal"));
bNormal->setEnabled(true);
bNormal->setGeometry(QRect(2, 2, 32, 32));
bNormal->setMaximumSize(QSize(32, 32));
QIcon icon7;
icon7.addFile(QString::fromUtf8(":/extui/linesnormal_OFF.png"), QSize(), QIcon::Active, QIcon::Off);
icon7.addFile(QString::fromUtf8(":/extui/linesnormal_ON.png"), QSize(), QIcon::Active, QIcon::On);
bNormal->setIcon(icon7);
bNormal->setIconSize(QSize(32, 32));
bNormal->setCheckable(true);
bNormal->setChecked(false);
bNormal->setAutoExclusive(false);
bRectangle = new QToolButton(QG_CadToolBarMain);
bRectangle->setObjectName(QString::fromUtf8("bRectangle"));
bRectangle->setEnabled(true);
bRectangle->setGeometry(QRect(33, 2, 32, 32));
bRectangle->setMaximumSize(QSize(32, 32));
QIcon icon8;
icon8.addFile(QString::fromUtf8(":/extui/linesrect_OFF.png"), QSize(), QIcon::Active, QIcon::Off);
icon8.addFile(QString::fromUtf8(":/extui/linesrect_ON.png"), QSize(), QIcon::Active, QIcon::On);
bRectangle->setIcon(icon8);
bRectangle->setIconSize(QSize(32, 32));
bRectangle->setCheckable(true);
bRectangle->setChecked(false);
bRectangle->setAutoExclusive(false);
bArc = new QToolButton(QG_CadToolBarMain);
bArc->setObjectName(QString::fromUtf8("bArc"));
bArc->setEnabled(true);
bArc->setGeometry(QRect(2, 33, 32, 32));
bArc->setMaximumSize(QSize(32, 32));
QIcon icon9;
icon9.addFile(QString::fromUtf8(":/extui/arcscraa_OFF.png"), QSize(), QIcon::Active, QIcon::Off);
icon9.addFile(QString::fromUtf8(":/extui/arcscraa_ON.png"), QSize(), QIcon::Active, QIcon::On);
bArc->setIcon(icon9);
bArc->setIconSize(QSize(32, 32));
bArc->setCheckable(true);
bArc->setChecked(false);
bArc->setAutoExclusive(false);
line_3 = new QFrame(QG_CadToolBarMain);
line_3->setObjectName(QString::fromUtf8("line_3"));
line_3->setEnabled(true);
line_3->setGeometry(QRect(4, 230, 60, 16));
line_3->setFrameShape(QFrame::HLine);
line_3->setFrameShadow(QFrame::Sunken);
bDel = new QToolButton(QG_CadToolBarMain);
bDel->setObjectName(QString::fromUtf8("bDel"));
bDel->setEnabled(true);
bDel->setGeometry(QRect(33, 202, 32, 32));
bDel->setMaximumSize(QSize(32, 32));
QIcon icon10;
icon10.addFile(QString::fromUtf8(":/extui/delete.png"), QSize(), QIcon::Active, QIcon::Off);
icon10.addFile(QString::fromUtf8(":/extui/delete.png"), QSize(), QIcon::Active, QIcon::On);
bDel->setIcon(icon10);
bDel->setIconSize(QSize(32, 32));
bDel->setCheckable(true);
bDel->setAutoRepeat(false);
bDel->setAutoExclusive(false);
bDel->setAutoRepeatDelay(500);
bUnAll = new QToolButton(QG_CadToolBarMain);
bUnAll->setObjectName(QString::fromUtf8("bUnAll"));
bUnAll->setEnabled(true);
bUnAll->setGeometry(QRect(2, 171, 32, 32));
bUnAll->setMaximumSize(QSize(32, 32));
QIcon icon11;
icon11.addFile(QString::fromUtf8(":/extui/selectnothing_OFF.png"), QSize(), QIcon::Active, QIcon::Off);
icon11.addFile(QString::fromUtf8(":/extui/selectnothing_ON.png"), QSize(), QIcon::Active, QIcon::On);
bUnAll->setIcon(icon11);
bUnAll->setIconSize(QSize(32, 32));
bUnAll->setCheckable(true);
bUnAll->setAutoRepeat(false);
bUnAll->setAutoExclusive(false);
bAll = new QToolButton(QG_CadToolBarMain);
bAll->setObjectName(QString::fromUtf8("bAll"));
bAll->setEnabled(true);
bAll->setGeometry(QRect(33, 171, 32, 32));
bAll->setMaximumSize(QSize(32, 32));
QIcon icon12;
icon12.addFile(QString::fromUtf8(":/extui/selectall_OFF.png"), QSize(), QIcon::Active, QIcon::Off);
icon12.addFile(QString::fromUtf8(":/extui/selectall_ON.png"), QSize(), QIcon::Active, QIcon::On);
bAll->setIcon(icon12);
bAll->setIconSize(QSize(32, 32));
bAll->setCheckable(true);
bAll->setAutoRepeat(false);
bAll->setAutoExclusive(false);
bInvert = new QToolButton(QG_CadToolBarMain);
bInvert->setObjectName(QString::fromUtf8("bInvert"));
bInvert->setEnabled(true);
bInvert->setGeometry(QRect(2, 202, 32, 32));
bInvert->setMaximumSize(QSize(32, 32));
QIcon icon13;
icon13.addFile(QString::fromUtf8(":/extui/selectinvert_OFF.png"), QSize(), QIcon::Active, QIcon::Off);
icon13.addFile(QString::fromUtf8(":/extui/selectinvert_ON.png"), QSize(), QIcon::Active, QIcon::On);
bInvert->setIcon(icon13);
bInvert->setIconSize(QSize(32, 32));
bInvert->setCheckable(true);
bInvert->setAutoRepeat(false);
bInvert->setAutoExclusive(false);
lCoord1 = new QLabel(QG_CadToolBarMain);
lCoord1->setObjectName(QString::fromUtf8("lCoord1"));
lCoord1->setGeometry(QRect(3, 242, 60, 20));
QFont font;
font.setFamily(QString::fromUtf8("\345\256\213\344\275\223"));
font.setPointSize(9);
lCoord1->setFont(font);
lCoord1->setFrameShape(QFrame::NoFrame);
lCoord1->setFrameShadow(QFrame::Plain);
lCoord1->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
lCoord1->setWordWrap(false);
lCoord1b = new QLabel(QG_CadToolBarMain);
lCoord1b->setObjectName(QString::fromUtf8("lCoord1b"));
lCoord1b->setGeometry(QRect(3, 262, 60, 20));
lCoord1b->setFont(font);
lCoord1b->setFrameShape(QFrame::NoFrame);
lCoord1b->setFrameShadow(QFrame::Plain);
lCoord1b->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
lCoord1b->setWordWrap(false);
lGridGap = new QLabel(QG_CadToolBarMain);
lGridGap->setObjectName(QString::fromUtf8("lGridGap"));
lGridGap->setGeometry(QRect(3, 283, 60, 20));
lGridGap->setFont(font);
lGridGap->setFrameShape(QFrame::NoFrame);
lGridGap->setFrameShadow(QFrame::Plain);
lGridGap->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
lGridGap->setWordWrap(false);
retranslateUi(QG_CadToolBarMain);
QMetaObject::connectSlotsByName(QG_CadToolBarMain);
} // setupUi
void retranslateUi(QWidget *QG_CadToolBarMain)
{
QG_CadToolBarMain->setWindowTitle(QApplication::translate("QG_CadToolBarMain", "Main", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
bHidden->setToolTip(QString());
#endif // QT_NO_TOOLTIP
bHidden->setText(QString());
#ifndef QT_NO_TOOLTIP
bTrim->setToolTip(QApplication::translate("QG_CadToolBarMain", "\344\277\256\345\211\2521", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
bTrim->setText(QString());
#ifndef QT_NO_TOOLTIP
bTrim2->setToolTip(QApplication::translate("QG_CadToolBarMain", "\344\277\256\345\211\2522", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
bTrim2->setText(QString());
#ifndef QT_NO_TOOLTIP
bScale->setToolTip(QApplication::translate("QG_CadToolBarMain", "\347\274\251\346\224\276: \350\257\267\345\205\210\351\200\211\346\213\251\345\233\276\345\275\242\345\220\216\357\274\214\345\206\215\346\211\247\350\241\214\347\274\251\346\224\276\345\212\237\350\203\275!", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
bScale->setText(QString());
#ifndef QT_NO_TOOLTIP
bMove->setToolTip(QApplication::translate("QG_CadToolBarMain", "\345\271\263\347\247\273: \350\257\267\345\205\210\351\200\211\346\213\251\345\233\276\345\275\242\345\220\216\357\274\214\345\206\215\346\211\247\350\241\214\345\271\263\347\247\273\345\212\237\350\203\275!", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
bMove->setText(QString());
#ifndef QT_NO_TOOLTIP
bRotate->setToolTip(QApplication::translate("QG_CadToolBarMain", "\346\227\213\350\275\254: \350\257\267\345\205\210\351\200\211\346\213\251\345\233\276\345\275\242\345\220\216\357\274\214\345\206\215\346\211\247\350\241\214\346\227\213\350\275\254\345\212\237\350\203\275!", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
bRotate->setText(QString());
#ifndef QT_NO_TOOLTIP
bMirror->setToolTip(QApplication::translate("QG_CadToolBarMain", "\351\225\234\345\203\217: \350\257\267\345\205\210\351\200\211\346\213\251\345\233\276\345\275\242\345\220\216\357\274\214\345\206\215\346\211\247\350\241\214\351\225\234\345\203\217\345\212\237\350\203\275!", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
bMirror->setText(QString());
#ifndef QT_NO_TOOLTIP
bCircle->setToolTip(QApplication::translate("QG_CadToolBarMain", "\345\234\206", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
bCircle->setText(QString());
#ifndef QT_NO_TOOLTIP
bNormal->setToolTip(QApplication::translate("QG_CadToolBarMain", "\347\272\277\346\256\265", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
bNormal->setText(QString());
#ifndef QT_NO_TOOLTIP
bRectangle->setToolTip(QApplication::translate("QG_CadToolBarMain", "\347\237\251\345\275\242", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
bRectangle->setText(QString());
#ifndef QT_NO_TOOLTIP
bArc->setToolTip(QApplication::translate("QG_CadToolBarMain", "\345\234\206\345\274\247", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
bArc->setText(QString());
#ifndef QT_NO_TOOLTIP
bDel->setToolTip(QApplication::translate("QG_CadToolBarMain", "\345\210\240\351\231\244", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
bDel->setText(QString());
#ifndef QT_NO_TOOLTIP
bUnAll->setToolTip(QApplication::translate("QG_CadToolBarMain", "\346\224\276\345\274\203\351\200\211\346\213\251", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
bUnAll->setText(QString());
#ifndef QT_NO_TOOLTIP
bAll->setToolTip(QApplication::translate("QG_CadToolBarMain", "\345\205\250\351\200\211", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
bAll->setText(QString());
#ifndef QT_NO_TOOLTIP
bInvert->setToolTip(QApplication::translate("QG_CadToolBarMain", "\345\217\215\351\200\211", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
bInvert->setText(QString());
lCoord1->setText(QApplication::translate("QG_CadToolBarMain", "0.0000", 0, QApplication::UnicodeUTF8));
lCoord1b->setText(QApplication::translate("QG_CadToolBarMain", "0.0000", 0, QApplication::UnicodeUTF8));
lGridGap->setText(QApplication::translate("QG_CadToolBarMain", "10", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class QG_CadToolBarMain: public Ui_QG_CadToolBarMain {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_QG_CADTOOLBARMAIN_H
|
65d9a0ad9078755ee0e285e38f851964f82f6648
|
314f05a6ca48b39afb69d8a1208a2528fda1d349
|
/Algorithm.h
|
874142c6cb0a528f0f2f4cb8a940e85fa8a084ff
|
[] |
no_license
|
hatcherl/INFO450Encrypt
|
6e47cd12a4c13000e602b73e745101f9c180d5ac
|
18071abe1a7f080535bf05db9835eacb6d94e594
|
refs/heads/master
| 2020-09-28T04:20:37.084316
| 2019-12-08T15:17:36
| 2019-12-08T15:17:36
| 226,686,673
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 218
|
h
|
Algorithm.h
|
#pragma once
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Algorithm
{
private:
public:
Algorithm();
int encryptFile(string filename);
int decryptFile(string filename);
};
|
66bbec31702f6b1e818b29d88a4c140249a01597
|
9386acb33a6c522ebbb79c4447b61b191860a87b
|
/lib/sk/util/test/collection/AliasingProcessorTest.cc
|
1e1f08e3a6195e5ae880797c21ac7e64b872ea86
|
[
"MIT"
] |
permissive
|
stemkit-collection/stemkit-cpp
|
878fa2c74272127a8cf3ff9659ec9e39034bb4d8
|
dfa77d831f49916ba6d134f407a4dcd0983328f6
|
refs/heads/master
| 2020-04-19T08:58:17.402275
| 2019-02-04T20:16:47
| 2019-02-04T20:16:47
| 168,095,623
| 4
| 0
|
MIT
| 2019-01-30T04:49:32
| 2019-01-29T05:35:00
|
HTML
|
UTF-8
|
C++
| false
| false
| 1,266
|
cc
|
AliasingProcessorTest.cc
|
/* vim: set sw=2:
* Copyright (c) 2009, Gennady Bystritsky <bystr@mac.com>
*
* Distributed under the MIT Licence.
* This is free software. See 'LICENSE' for details.
* You must read and accept the license prior to use.
*
* Author: Gennady Bystritsky (gennady.bystritsky@quest.com)
*/
#include "AliasingProcessorTest.h"
#include <sk/util/ArrayList.cxx>
#include <sk/util/processor/Aliasing.hxx>
#include <sk/util/String.h>
CPPUNIT_TEST_SUITE_REGISTRATION(sk::util::test::AliasingProcessorTest);
sk::util::test::AliasingProcessorTest::
AliasingProcessorTest()
{
}
sk::util::test::AliasingProcessorTest::
~AliasingProcessorTest()
{
}
void
sk::util::test::AliasingProcessorTest::
setUp()
{
}
void
sk::util::test::AliasingProcessorTest::
tearDown()
{
}
void
sk::util::test::AliasingProcessorTest::
testAliasing()
{
sk::util::ArrayList<sk::util::String>::Copying source;
sk::util::ArrayList<sk::util::String> target;
source.add("aaa");
source.add("bbb");
source.add("ccc");
source.forEach(processor::Aliasing<sk::util::String>(target));
CPPUNIT_ASSERT_EQUAL(3, target.size());
CPPUNIT_ASSERT(&source.get(0) == &target.get(0));
CPPUNIT_ASSERT(&source.get(1) == &target.get(1));
CPPUNIT_ASSERT(&source.get(2) == &target.get(2));
}
|
bceb96f3fac02c3b51733a3de488e6e5a5fc7b12
|
8ee0c674afe7546aebb70582956b6a61d99bcfbb
|
/YYX_EXAM1_1/YYX_EXAM1_1/YYX_EXAM1_1.h
|
8dcc0abaf896ac6a0ced2935ada12fe37bb12c62
|
[] |
no_license
|
WashingtonYang/FuckMFC
|
dac2ccd1a58f0da2218559278cd09766d60efa27
|
e5ca806cc4e39deb67608c12e01a3f951b1c35b5
|
refs/heads/master
| 2020-09-04T08:11:44.355341
| 2020-08-20T03:55:51
| 2020-08-20T03:55:51
| 219,690,952
| 2
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 546
|
h
|
YYX_EXAM1_1.h
|
// YYX_EXAM1_1.h : YYX_EXAM1_1 应用程序的主头文件
//
#pragma once
#ifndef __AFXWIN_H__
#error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件"
#endif
#include "resource.h" // 主符号
// CYYX_EXAM1_1App:
// 有关此类的实现,请参阅 YYX_EXAM1_1.cpp
//
class CYYX_EXAM1_1App : public CWinApp
{
public:
CYYX_EXAM1_1App();
// 重写
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
// 实现
afx_msg void OnAppAbout();
DECLARE_MESSAGE_MAP()
};
extern CYYX_EXAM1_1App theApp;
|
cc0ed517cd9c317865c4a0f4bdc35bd1dba70e78
|
048963913f6667066eae6bea4a1d80a1670b3d5c
|
/Algorithms/isValidPalindrome.cpp
|
2686d7fe4f265b7e83162cf00452472c0e7f477c
|
[] |
no_license
|
Yu4n/LeetCode_in_cpp
|
7e1b3fb83ab2128844116bd2e7e15778999a95bf
|
bf1dcbdf9196dc29573fbe9e06fd778ee157a47c
|
refs/heads/master
| 2023-05-02T18:44:47.917069
| 2021-05-23T13:02:52
| 2021-05-23T13:02:52
| 308,310,356
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 403
|
cpp
|
isValidPalindrome.cpp
|
//
// Created by Yu4n on 2021-04-08.
//
bool isPalindrome(string s) {
int low = 0, high = s.size() - 1;
while (low < high){
while (!isalnum(s[low]) && low < high){
low++;
}
while (!isalnum(s[high]) && low < high){
high--;
}
if (tolower(s[low++]) != tolower(s[high--])){
return false;
}
}
return true;
}
|
3d938a84fa9e69ef6d0ce5955ba7c7d595b5e453
|
ffb568806e34199501c4ca6b61ac86ee9cc8de2e
|
/gflib2/gfx/source/WinDX11/gfl2_WinDX11GeometryShader.cpp
|
ea1b40a38f508d2d78065ecd930b8ba9e9f89643
|
[] |
no_license
|
Fumikage8/gen7-source
|
433fb475695b2d5ffada25a45999f98419b75b6b
|
f2f572b8355d043beb468004f5e293b490747953
|
refs/heads/main
| 2023-01-06T00:00:14.171807
| 2020-10-20T18:49:53
| 2020-10-20T18:49:53
| 305,500,113
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 771
|
cpp
|
gfl2_WinDX11GeometryShader.cpp
|
#include <gfx/include/WinDX11/gfl2_WinDx11Types.h>
#include <gfx/include/WinDX11/gfl2_WinDX11GeometryShader.h>
#include <gfx/include/gfl2_GFGL.h>
namespace gfl2 { namespace gfx { namespace windx11 {
WinDX11GeometryShader::WinDX11GeometryShader( const void* code, u32 size ) : Shader()
{
HRESULT hr;
hr = GFGL::GetDevice()->CreateGeometryShader( code, size, NULL, &m_pGeometryShader);
if (FAILED(hr))
assert(0);
D3DReflect( code, size, IID_ID3D11ShaderReflection, (void**)&m_pReflector );
}
WinDX11GeometryShader::~WinDX11GeometryShader()
{
m_pGeometryShader.reset();
m_pReflector.reset();
}
void WinDX11GeometryShader::Bind() const
{
GFGL::GetDeviceContext()->GSSetShader( m_pGeometryShader.get(), NULL, 0);
}
}}}
|
95bf160c549970cd87ff7f34e63f46fb217fde43
|
31b6ec7cf50a7d532179bbf30ace0b2d3d8c7dc0
|
/Segment_Tree/307.Range-Sum-Query-Mutable/307.Range-Sum-Query-Mutable_BIT.cpp
|
e738ea721c28b7101e8e46491a9c5ef0d3638565
|
[] |
no_license
|
Bourns-A/LeetCode
|
5223179bdec3b3d8d956b8ff45e75c1af732b888
|
ff9aeccbcbcabc637438821446c7c73270bd569b
|
refs/heads/master
| 2022-12-04T12:53:21.358288
| 2020-08-19T06:10:39
| 2020-08-19T06:10:39
| 289,118,643
| 3
| 0
| null | 2020-08-20T21:57:08
| 2020-08-20T21:57:07
| null |
UTF-8
|
C++
| false
| false
| 844
|
cpp
|
307.Range-Sum-Query-Mutable_BIT.cpp
|
class NumArray {
public:
vector<int>bitArr;
vector<int>nums;
NumArray(vector<int>& nums) {
this->nums = nums;
bitArr.resize(nums.size()+1);
for (int i=0; i<nums.size(); i++)
my_update(i, nums[i]);
cout<<"init done"<<endl;
}
void update(int i, int val){
my_update(i, val-nums[i]);
nums[i] = val;
}
void my_update(int i, int delta) {
int idx = i+1;
while (idx<bitArr.size())
{
bitArr[idx]+=delta;
idx+=idx&(-idx);
}
}
int my_query(int idx){
idx+=1;
int result = 0;
while (idx){
result += bitArr[idx];
idx-=idx&(-idx);
}
return result;
}
int sumRange(int i, int j) {
return my_query(j)-my_query(i-1);
}
};
|
2028db92fe47bdb33d50f02dffbbe8246258b50f
|
09eee6417b45466d1a780acaf52ac226c7383817
|
/Computer-Graphics--OpenGL-GLUT-master/Balloon_man_half_complete/Ballon_man.cpp
|
a3e49715a32ea0928ae0955529d9f7bc58dc3f8e
|
[
"MIT"
] |
permissive
|
Ihsan28/OpenGL
|
1adfe273e4476c3b896cbd84f7a27cd687dcbeb7
|
6ccb1816256fb94e15b65afb65db403259d19847
|
refs/heads/master
| 2023-04-28T02:57:10.554936
| 2021-05-16T18:12:17
| 2021-05-16T18:12:17
| 347,770,961
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,814
|
cpp
|
Ballon_man.cpp
|
/* Graphics Final Project(Boy With a Ballon)
Islam, Md. Najrul--13-24747-2
Rahman, Md. Hasibur--13-23141-1
Ahmed, Abu Syeed--12-21201-1
Hossain Shakawat--13--23372-1
*/
#include <stdio.h>
#include <stdlib.h>
#include <GL/glut.h>
#include <time.h>
float x=200, y=-60;
float x1 = 650, y1=20; //x2 = 750, y2 = 50, x3 = 950, y3 =-10, x4=1150, y4=-50, x5=1350, y5=-110;
int score, exit1 = 1;
void boy(float a, float b){
glBegin(GL_POLYGON);//head
glColor3f(1, 1, 1);
glVertex2f(20 + a, 230 + b);//head 1st co-ordinate(-x+y)
glVertex2f(20.3 + a, 231 + b);
glVertex2f(20.7+ a, 232 + b);
glVertex2f(21+ a, 233 + b);
glVertex2f(21.3 + a, 234 + b);
glVertex2f(21.7 + a, 235 + b);
glVertex2f(22.3+ a, 236 + b);
glVertex2f(22.7 + a, 236.5 + b);
glVertex2f(23 + a, 237 + b);
glVertex2f(23.5 + a, 237.3 + b);
glVertex2f(24 + a, 237.7 + b);
glVertex2f(24.5 + a, 238+ b);
glVertex2f(25 + a, 238.3 + b);
glVertex2f(26 + a, 238.7 + b);
glVertex2f(27 + a, 239 + b);
glVertex2f(28 + a, 239.3 + b);
glVertex2f(29 + a, 239.7 + b);
glVertex2f(30 + a, 240 + b);
glVertex2f(31 + a, 239.7 + b);//head 2nd co-ordinate(+x+y)
glVertex2f(32 + a, 239.5 + b);
glVertex2f(33 + a, 239.3 + b);
glVertex2f(33.5 + a, 239 + b);
glVertex2f(34 + a, 238.7 + b);
glVertex2f(34.5 + a, 238.3+ b);
glVertex2f(34.7 + a, 238 + b);
glVertex2f(34.9 + a, 237.7 + b);
glVertex2f(35 + a, 237.5 + b);
glVertex2f(35.2 + a, 237.4 + b);
glVertex2f(35.3 + a, 237.3 + b);
glVertex2f(35.5 + a, 237.1 + b);
glVertex2f(35.7 + a, 237 + b);
glVertex2f(35.9 + a, 236.9 + b);
glVertex2f(36 + a, 236.7 + b);
glVertex2f(36.3 + a, 236.3 + b);
glVertex2f(36.7+ a, 236 + b);
glVertex2f(37 + a, 235.7 + b);
glVertex2f(37.3 + a, 235.3+ b);
glVertex2f(37.7 + a, 235 + b);
glVertex2f(38 + a, 234.5 + b);
glVertex2f(38.3 + a, 234+ b);
glVertex2f(38.7 + a, 233.5 + b);
glVertex2f(39 + a, 233 + b);
glVertex2f(39.3 + a, 232+ b);
glVertex2f(39.7 + a, 231 + b);
glVertex2f(40 + a, 230+ b);
glVertex2f(39.7 + a, 229 + b);//head 3rd co-ordinate(+x-y)
glVertex2f(39.3 + a, 228 + b);
glVertex2f(39 + a, 227 + b);
glVertex2f(38.7 + a, 226.5 + b);
glVertex2f(38.3 + a, 226 + b);
glVertex2f(38 + a, 225.5 + b);
glVertex2f(37.7 + a, 225 + b);
glVertex2f(37.3 + a, 224.5 + b);
glVertex2f(37 + a, 224 + b);
glVertex2f(36.7 + a, 223.7 + b);
glVertex2f(36 + a, 223.3 + b);
glVertex2f(35.7 + a, 223 + b);
glVertex2f(35.3 + a, 222.7 + b);
glVertex2f(35 + a, 222.3 + b);
glVertex2f(34.5 + a, 222 + b);
glVertex2f(34 + a, 221.7 + b);
glVertex2f(33.5 + a, 221.3 + b);
glVertex2f(33 + a, 221 + b);
glVertex2f(32 + a, 220.7 + b);
glVertex2f(31 + a, 220.3 + b);
glVertex2f(30 + a, 220 + b);
glVertex2f(29 + a, 220.3 + b);//head 4th co-ordinate(-x-y)
glVertex2f(28 + a, 220.7 + b);
glVertex2f(27.5 + a, 221 + b);
glVertex2f(27 + a, 221.3 + b);
glVertex2f(26.5 + a, 221.7 + b);
glVertex2f(26 + a, 222 + b);
glVertex2f(25.5 + a, 222.3 + b);
glVertex2f(25 + a, 222.7 + b);
glVertex2f(24.5 + a, 223 + b);
glVertex2f(24 + a, 223.3 + b);
glVertex2f(23.7 + a, 223.5 + b);
glVertex2f(23.3 + a, 224 + b);
glVertex2f(23 + a, 224.5 + b);
glVertex2f(22.7 + a, 225 + b);
glVertex2f(22.3 + a, 225.5 + b);
glVertex2f(22 + a, 226 + b);
glVertex2f(21.7 + a, 226.5 + b);
glVertex2f(21.3 + a, 227 + b);
glVertex2f(21 + a, 227.5 + b);
glVertex2f(20.7 + a, 228 + b);
glVertex2f(20.3 + a, 229 + b);
glVertex2f(20 + a, 230 + b);
glEnd();
glBegin(GL_POLYGON);//left eye
glColor3f(0, 0, 0);
glVertex2f(25 + a, 228 + b);
glVertex2f(23 + a, 230 + b);
glVertex2f(25 + a, 232 + b);
glVertex2f(27 + a, 230 + b);
glEnd();
glBegin(GL_POLYGON);//right eye
glColor3f(0, 0, 0);
glVertex2f(35 + a, 228 + b);
glVertex2f(33 + a, 230 + b);
glVertex2f(35 + a, 232 + b);
glVertex2f(37 + a, 230 + b);
glEnd();
/*glBegin(GL_LINE_STRIP);//mouth
glColor3f(0, 0, 0);
glVertex2f(28 + a, 228 + b);
glVertex2f(30 + a, 225 + b);
glVertex2f(32 + a, 228 + b);
glEnd();*/
glBegin(GL_POLYGON);//body
glColor3f(.73, .36, .36);
glVertex2f(18 + a, 215 + b);
glVertex2f(25 + a, 220 + b);
glVertex2f(35 + a, 220 + b);
glVertex2f(42 + a, 215 + b);
glVertex2f(42 + a, 180 + b);
glVertex2f(18 + a, 180 + b);
glEnd();
glBegin(GL_POLYGON);//left leg
glColor3f(1, 1, 1);
glVertex2f(20 + a, 180 + b);
glVertex2f(25 + a, 180 + b);
glVertex2f(25 + a, 160 + b);
glVertex2f(20 + a, 160 + b);
glEnd();
glBegin(GL_POLYGON);//right leg
glColor3f(1, 1, 1);
glVertex2f(35 + a, 180 + b);
glVertex2f(40 + a, 180 + b);
glVertex2f(40 + a, 160 + b);
glVertex2f(35 + a, 160 + b);
glEnd();
glBegin(GL_LINES);//left hand
glColor3f(1, 1, 1);
glVertex2f(18 + a, 210 + b);
glVertex2f(12 + a, 205 + b);
glVertex2f(12 + a, 205 + b);
glVertex2f(12 + a, 195 + b);
glEnd();
glBegin(GL_LINES);//right hand
glColor3f(1, 1, 1);
glVertex2f(42 + a, 210 + b);
glVertex2f(50 + a, 200 + b);
glEnd();
glBegin(GL_LINES);//bellon stand
glColor3f(1, 1, 1);
glVertex2f(50 + a, 200 + b);
glVertex2f(50 + a, 250 + b);
glEnd();
}
void ballon(float a, float b)
{
glBegin(GL_POLYGON);//head
glColor3f(0.7,0.5,0.7);
glVertex2f(40 + a, 260 + b);//head 1st co-ordinate
glVertex2f(40.3 + a, 261 + b);
glVertex2f(40.7+ a, 262 + b);
glVertex2f(41+ a, 263 + b);
glVertex2f(41.3 + a, 264 + b);
glVertex2f(41.7 + a, 265 + b);
glVertex2f(42.3+ a, 266 + b);
glVertex2f(42.7 + a, 266.5 + b);
glVertex2f(43 + a, 267 + b);
glVertex2f(43.5 + a, 267.3 + b);
glVertex2f(44 + a, 267.7 + b);
glVertex2f(44.5 + a, 268+ b);
glVertex2f(45 + a, 268.3 + b);
glVertex2f(46 + a, 268.7 + b);
glVertex2f(47 + a, 269 + b);
glVertex2f(48 + a, 269.3 + b);
glVertex2f(49 + a, 269.7 + b);
glVertex2f(50 + a, 270 + b);
glVertex2f(51 + a, 269.7 + b);//head 2nd co-ordinate
glVertex2f(52 + a, 269.5 + b);
glVertex2f(53 + a, 269.3 + b);
glVertex2f(53.5 + a, 269 + b);
glVertex2f(54 + a, 268.7 + b);
glVertex2f(54.5 + a, 268.3+ b);
glVertex2f(54.7 + a, 268 + b);
glVertex2f(54.9 + a, 267.7 + b);
glVertex2f(55 + a, 267.5 + b);
glVertex2f(55.2 + a, 267.4 + b);
glVertex2f(55.3 + a, 267.3 + b);
glVertex2f(55.5 + a, 267.1 + b);
glVertex2f(55.7 + a, 267 + b);
glVertex2f(55.9 + a, 266.9 + b);
glVertex2f(56 + a, 266.7 + b);
glVertex2f(56.3 + a, 266.3 + b);
glVertex2f(56.7+ a, 266 + b);
glVertex2f(57 + a, 265.7 + b);
glVertex2f(57.3 + a, 265.3+ b);
glVertex2f(57.7 + a, 265 + b);
glVertex2f(58 + a, 264.5 + b);
glVertex2f(58.3 + a, 264+ b);
glVertex2f(58.7 + a, 263.5 + b);
glVertex2f(59 + a, 263 + b);
glVertex2f(59.3 + a, 262+ b);
glVertex2f(59.7 + a, 261 + b);
glVertex2f(60 + a, 260+ b);
glVertex2f(59.7 + a, 259 + b);//head 3rd co-ordinate
glVertex2f(59.3 + a, 258 + b);
glVertex2f(59 + a, 257 + b);
glVertex2f(58.7 + a, 256.5 + b);
glVertex2f(58.3 + a, 256 + b);
glVertex2f(58 + a, 255.5 + b);
glVertex2f(57.7 + a, 255 + b);
glVertex2f(57.3 + a, 254.5 + b);
glVertex2f(57 + a, 254 + b);
glVertex2f(56.7 + a, 253.7 + b);
glVertex2f(56 + a, 253.3 + b);
glVertex2f(55.7 + a, 253 + b);
glVertex2f(55.3 + a, 252.7 + b);
glVertex2f(55 + a, 252.3 + b);
glVertex2f(54.5 + a, 252 + b);
glVertex2f(54 + a, 251.7 + b);
glVertex2f(53.5 + a, 251.3 + b);
glVertex2f(53 + a, 251 + b);
glVertex2f(52 + a, 250.7 + b);
glVertex2f(51 + a, 250.3 + b);
glVertex2f(50 + a, 250 + b);
glVertex2f(49 + a, 250.3 + b);//head 4th co-ordinate
glVertex2f(48 + a, 250.7 + b);
glVertex2f(47.5 + a, 251 + b);
glVertex2f(47 + a, 251.3 + b);
glVertex2f(46.5 + a, 251.7 + b);
glVertex2f(46 + a, 252 + b);
glVertex2f(45.5 + a, 252.3 + b);
glVertex2f(45 + a, 252.7 + b);
glVertex2f(44.5 + a, 253 + b);
glVertex2f(44 + a, 253.3 + b);
glVertex2f(43.7 + a, 253.5 + b);
glVertex2f(43.3 + a, 254 + b);
glVertex2f(43 + a, 254.5 + b);
glVertex2f(42.7 + a, 255 + b);
glVertex2f(42.3 + a, 255.5 + b);
glVertex2f(42 + a, 256 + b);
glVertex2f(41.7 + a, 256.5 + b);
glVertex2f(41.3 + a, 257 + b);
glVertex2f(41 + a, 257.5 + b);
glVertex2f(40.7 + a, 258 + b);
glVertex2f(40.3 + a, 259 + b);
glVertex2f(40 + a, 260 + b);
glEnd();
}
void box(float a, float b){
glBegin(GL_QUADS);
glColor3f(1, 0, 0);//red box
glVertex2f(20 + a, 220 + b);
glVertex2f(70 + a, 220 + b);
glVertex2f(70 + a, 240 + b);
glVertex2f(20 + a, 240 + b);
glEnd();
}
void drawDisplay(void){
glClear(GL_COLOR_BUFFER_BIT);
//down road-side
glBegin(GL_POLYGON);
glColor3f(0.0, 0.0, 1.0);
glVertex2f(0, 0);
glVertex2f(0,120);
glVertex2f(650, 120);
glVertex2f(650, 0);
glEnd();
//road
glBegin(GL_POLYGON);
glColor3f(0.0, 0.0, 0.0);
glVertex2f(0, 120);
glVertex2f(650,120 );
glVertex2f(650, 380);
glVertex2f(0, 380);
glEnd();
//up road-side
glBegin(GL_POLYGON);
glColor3f(0.0, 0.0, 1.0);
glVertex2f(0, 550);
glVertex2f(650, 550);
glVertex2f(650, 380);
glVertex2f(0, 380);
glEnd();
}
void drawSc(int scor){
int i, j, k;
i = scor / 100;
j = scor / 10 - i * 10;
k = scor - j * 10 - i * 100;
glPushMatrix();
glColor3f(1.0, 0.0, 0.0);
glTranslated(480, 440, 0);
glScaled(.2, .2, 0);
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'S');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'c');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'o');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'r');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'e');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)':');
glColor3f(1.0, 0.0, 0.0);
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)i + 48);
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)j + 48);
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)k + 48);
glPopMatrix();
glPushMatrix();
glColor3f(0.0, 1.0, 0.0);
glTranslated(480, 50, 0);
glScaled(.06, .1, 0);
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'P');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'r');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'e');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'s');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'s');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)' ');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'s');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)' ');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'t');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'o');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)' ');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'S');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'t');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'a');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'r');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'t');
glPopMatrix();
glPushMatrix();
glColor3f(0.0, 1.0, 0.0);
glTranslated(480, 35, 0);
glScaled(.06, .1, 0);
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'P');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'r');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'e');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'s');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'s');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)' ');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'q');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)' ');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'t');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'o');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)' ');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'q');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'u');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'i');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'t');
glPopMatrix();
}
int random()
{
srand((int)time(0));//random generation
int c= rand() % 5 + 1;
if(c==1)
{
y1=110;
}
else if(c==2)
{
y1=50;
}
else if(c==3)
{
y1=-10;
}
else if(c==4)
{
y1=-50;
}
else if(c==4)
{
y1=-110;
}
return y1;
}
void myDisplay()
{
if (exit1 == 1)
{
/*if(y<-120 || y>120)
{
printf("Y\n");
printf("%f\n",x);
printf("%f\n",x1);
printf("%f\n",y);
exit1 = 1;
}*/
if(x1<=x+40 && x1>x+20 && y==y1-30)
{
printf("X1\n");
printf("%f\n",x);
printf("%f\n",x1);
printf("%f\n",y);
exit1 = 0;
}
if (score < 25)
{
x1 -= .5;
/*x2 -= .8;
x3 -= .9;
x4 -= 1;
x5 -= 1.1;*/
}
if (score >= 20 && score < 50)
{
x1 -= 2.1;
/*x2 -= 1.3;
x3 -= 1.4;
x4 -= 1.5;
x5 -= 1.6;*/
}
if (score >= 50)
{
x1 -= 2.3;
/*x2 -= 1.8;
x3 -= 1.9;
x4 -= 2;
x5 -= 2.1;*/
}
if (x1 < -500)
{
score += 1;
srand((int)time(0));//random generation
int c= rand() % 8 + 1;
if(c==1)
{
x1 = 600;
y1=130;
}
else if(c==2)
{
x1 = 590;
y1=110;
}
else if(c==3)
{
x1 = 610;
y1=90;
}
else if(c==4)
{
x1 = 620;
y1=70;
}
else if(c==5)
{
x1 = 590;
y1=50;
}
else if(c==6)
{
x1 = 620;
y1=30;
}
else if(c==7)
{
x1 = 580;
y1=10;
}
else if(c==8)
{
x1 = 610;
y1=-10;
}
}
glClear(GL_COLOR_BUFFER_BIT);
drawDisplay();
drawSc(score);
if(exit1==1)
{
ballon(x,y);
}
boy(x, y);
box(x1, y1);
//box(x2, y2);
//box(x3, y3);
//box(x4, y4);
//box(x5, y5);
glutSwapBuffers();
}
if(exit1==2)
{
glutPostRedisplay();
}
if (exit1==0)
{
glutPostRedisplay();
for(int i =0;i<900000000;i++)
{
}
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glColor3f(0.0, 0.0, 1.0);
glVertex2f(0, 550);
glVertex2f(650, 550);
glVertex2f(650, 0);
glVertex2f(0, 0);
glEnd();
drawSc(score);
glPushMatrix();
glColor3f(1, 0, 0);
glTranslated(200, 400, 0);
glScaled(.4, .4, 0);
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'G');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'A');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'M');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'E');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'O');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'V');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'E');
glutStrokeCharacter(GLUT_STROKE_ROMAN, (int)'R');
glEnd();
glPopMatrix();
glutSwapBuffers();
}
}
void myInit(void)
{
glClearColor(1.0, 1.0, 1.0, 0.0);
glColor3f(0.0f, 0.0f, 0.0f);
glPointSize(4.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
void keyboards(unsigned char keys, int x4, int y4)
{
//start key
if (keys == 's')
{
glutIdleFunc(myDisplay);
}
//stop key
if (keys == 'q')
{
exit(-1);
}
if(keys=='0')
{
exit1=2;
}
if(keys=='1')
{
exit1=1;
}
glutPostRedisplay();
}
void keyPressed( int keys, int x4, int y4)
{
if (keys == GLUT_KEY_LEFT)
x -= 20;
if (keys == GLUT_KEY_RIGHT)
x += 20;
if (keys == GLUT_KEY_UP)
y += 20;
if (keys == GLUT_KEY_DOWN)
y -= 20;
glutPostRedisplay();
}
void main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(1000, 600);
glutInitWindowPosition(150, 50);
glutCreateWindow("Boy With a Bellon");
glutDisplayFunc(myDisplay);
glutSpecialFunc(keyPressed);
glutKeyboardFunc(keyboards);
myInit();
glutMainLoop();
}
|
1164c9f7464ab5fa94f2913ddbae33ccbf8044f4
|
b3af5522d410b319b6e75219ca3cd7f58dc433a3
|
/DX11Game/EnemyTypes.h
|
2efd9552984e9688128e1bc509e565e9132690c5
|
[] |
no_license
|
CatFailure/DX11Game
|
5bc37a31d3fc234a0d02bd5e435b413a4dd48c1e
|
a2606c1d62843fe41c96eeaa857b54ef9b110b4f
|
refs/heads/master
| 2022-06-20T07:40:18.185908
| 2020-05-06T12:46:55
| 2020-05-06T12:46:55
| 256,351,711
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 505
|
h
|
EnemyTypes.h
|
#pragma once
#include "Enemy.h"
// Inherited enemy class for the red ship enemy type
class EnemyRedShip : public Enemy
{
public:
EnemyRedShip();
void Init() override;
void Update(float _deltaTime) override;
void Render(float _deltaTime, DirectX::SpriteBatch& _sprBatch) override;
private:
};
class EnemyGreenShip : public Enemy
{
public:
EnemyGreenShip();
void Init() override;
void Update(float _deltaTime) override;
void Render(float _deltaTime, DirectX::SpriteBatch& _sprBatch) override;
};
|
a48e217f66a3962121454b0f62226dd41a7ea6be
|
e595f0e5ac15d5ef9fc27135a0f71d068d742c88
|
/CFDtype/C++/CFDtype.cpp
|
70ba03d7ee8231520163586c1b8bd90862b5c1f4
|
[] |
no_license
|
mwang1991/PublicCFDriver
|
e0ebf267912a8f660d9340511fe3a60402f834cd
|
b9a9d090055808f23c2b72913a4a59ef6e8483c7
|
refs/heads/master
| 2022-05-31T05:20:16.650443
| 2022-03-23T21:37:15
| 2022-03-23T21:37:15
| 208,267,621
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,450
|
cpp
|
CFDtype.cpp
|
#include "CFDtype.h"
void CFDtype::init()
{
data = new char[datalen];
}
char* CFDtype::getData()
{
return data;
}
void CFDtype::Recv()
{
count = 0;
char *buffer = new char[datalen];
RecvData(buffer);
FromCFData(buffer);
delete buffer;
}
void CFDtype::Send()
{
count = 0;
ToCFData();
SendData(datalen, data);
}
//send an array of CFDtype
void CFDtype::SendArray(CFDtype _array[])
{
int size = sizeof(_array);
SendSize(size);
int _len = 0;
int _count = 0;
for (int i = 0; i < sizeof(_array); i++)
_len += _array[i].datalen;
char *_data = new char[_len];
for (int i = 0; i < sizeof(_array); i++)
{
_array[i].count = 0;
_array[i].ToCFData();
strcpy(_data + _count, _array[i].getData());
memcpy(_data + _count, _array[i].getData(), _array[i].datalen);
_count += _array[i].datalen;
}
SendData(_len, _data);
delete _data;
}
void CFDtype::RecvArray(std::vector<CFDtype*> _array) //generate array of the type from recieved data
{
//recieve data from server
char *_data = new char[sizeof(_array) * _array[0]->datalen];
RecvData(_data);
//generate array
int _count = 0;
for (int i = 0; i < sizeof(_array); i++)
{
_array[i]->FromCFData(_data + _count);
_count += _array[i]->datalen;
}
delete _data;
}
void CFDtype::Add(float _data)
{
float* _buff = &_data;
memcpy(data + count, _buff, 4);
count += 4;
}
void CFDtype::Add(double _data)
{
double* _buff = &_data;
memcpy(data + count, _buff, 8);
count += 8;
}
void CFDtype::Add(int _data)
{
int* _buff = &_data;
memcpy(data + count, _buff, 4);
count += 4;
}
int CFDtype::GetInt(char _data[])
{
int* _buff;
sscanf(_data + count, "%4s", _buff);
count += 4;
return *_buff;
}
float CFDtype::GetFloat(char _data[])
{
float* _buff;
sscanf(_data + count, "%4s", _buff);
count += 4;
return *_buff;
}
double CFDtype::GetDouble(char _data[])
{
double* _buff;
sscanf(_data + count, "%8s", _buff);
count += 8;
return *_buff;
}
const char* DllString(std::string s)
{
return s.c_str();
}
int initClient(std::string adress, int port = 8087)
{
return InitClient(adress.c_str(), port); //connect to server
}
void initServer(int port = 8087)
{
InitServer(port);
}
void sendCommand(char c)
{
SendCommand(c);
}
char recvCommand()
{
return RecvCommand();
}
void disconnect()
{
Disconnect();
}
|
fc43a1528cf696628c65ffdf32a6cee118b9b0f3
|
5d635f12542665e56f55662b832c2cabe5a4cca1
|
/2017/c++/19/one.cpp
|
1007e7baa2901de59d3e23c8ff4f4d82579cc4e7
|
[] |
no_license
|
ld86/adventofcode
|
ff24c47532dabaa333f1820c3cc76aadf244c919
|
f156dded396ea0cf14caabfc2e298f39419d34ef
|
refs/heads/master
| 2021-06-13T01:58:34.566300
| 2018-12-03T20:13:20
| 2018-12-03T20:13:20
| 47,494,445
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,416
|
cpp
|
one.cpp
|
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <unordered_map>
#include <stack>
#include <sstream>
#include <iomanip>
enum class TDirection {
DOWN,
UP,
RIGHT,
LEFT,
NONE
};
class TMap {
public:
TMap(const std::vector<std::string>& lines)
: Lines(lines)
, X(0)
, Y(0)
, PrevX(X)
, PrevY(Y)
, Direction(TDirection::DOWN)
{
FindStartingPosition();
}
unsigned char GetCurrent() const {
return Lines.at(Y).at(X);
}
TDirection GetDirection() const {
return Direction;
}
unsigned char GetNext() const {
switch (Direction) {
case TDirection::DOWN:
return Lines.at(Y + 1).at(X);
case TDirection::UP:
return Lines.at(Y - 1).at(X);
case TDirection::RIGHT:
return Lines.at(Y).at(X + 1);
case TDirection::LEFT:
return Lines.at(Y).at(X - 1);
case TDirection::NONE:
return Lines.at(Y).at(X);
}
}
void Move() {
switch (Direction) {
case TDirection::DOWN:
PrevX = X;
PrevY = Y;
Y++;
break;
case TDirection::UP:
PrevX = X;
PrevY = Y;
Y--;
break;
case TDirection::RIGHT:
PrevX = X;
PrevY = Y;
X++;
break;
case TDirection::LEFT:
PrevX = X;
PrevY = Y;
X--;
break;
case TDirection::NONE:
throw std::runtime_error("Nowhere to move");
}
}
bool Step() {
if (Direction == TDirection::NONE) {
return false;
}
if (GetNext() == '-' || GetNext() == '|') {
Move();
return true;
}
if (GetNext() == '+') {
Move();
Direction = FindNewDirection();
return true;
}
if (GetNext() >= 'A' && GetNext() <= 'Z') {
Letters << GetNext();
Move();
return true;
}
return false;
}
unsigned char GetByXY(int x, int y) {
return Lines.at(y).at(x);
}
int GetX() const {
return X;
}
int GetY() const {
return Y;
}
std::string GetLetters() const {
return Letters.str();
}
private:
TDirection FindNewDirection() {
for (int i = -1; i <= 1; ++i) {
for (int j = -1; j <= 1; ++j) {
if (std::abs(i) + std::abs(j) != 1) {
continue;
}
if (X + i == PrevX && Y + j == PrevY) {
continue;
}
unsigned char next = Lines.at(Y + j).at(X + i);
if (next == ' ') {
continue;
}
if ((next == '-' || next == '+') && i == -1) {
return TDirection::LEFT;
}
if ((next == '-' || next == '+') && i == 1) {
return TDirection::RIGHT;
}
if ((next == '|' || next == '+') && j == -1) {
return TDirection::UP;
}
if ((next == '|' || next == '+') && j == 1) {
return TDirection::DOWN;
}
}
}
return TDirection::NONE;
}
void FindStartingPosition() {
for (size_t i = 0; i < Lines[0].size(); ++i) {
if (Lines[0][i] == '|') {
X = i;
break;
}
}
}
private:
std::vector<std::string> Lines;
int X, Y;
int PrevX, PrevY;
TDirection Direction;
std::stringstream Letters;
};
int main() {
std::ifstream input{"input.txt"};
std::string line;
std::vector<std::string> lines;
while (getline(input, line)) {
lines.push_back(line);
}
TMap map{lines};
while (map.Step()) {
std::cout << map.GetX() << " " << map.GetY() << " " << map.GetCurrent() << " " << map.GetNext() << " " << static_cast<int>(map.GetDirection()) << std::endl;
}
std::cout << map.GetLetters() << std::endl;
return 0;
}
|
779ff5f526cbd07564c07b802d34d59cf60a4300
|
090abfcb3f83a84a20b956f38179d45a070d2818
|
/cnnplus/include/cufulllayer.hh
|
ebbc47f4015c4a80b8cf8c27f9d7bd151e756806
|
[] |
no_license
|
deniskovalchuck/cnnplus
|
628c4ead823c73b4cdf873ab3d4ac5d6ff56fb0e
|
e5b78442a24266703383d6017f675da9c411ac86
|
refs/heads/master
| 2022-04-02T15:18:06.904598
| 2020-01-02T18:40:27
| 2020-01-02T18:40:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,188
|
hh
|
cufulllayer.hh
|
/**************************************************************************//**
*
* \file cufulllayer.hh
* \author Daniel Strigl, Klaus Kofler
* \date Jun 05 2009
*
* $Id: cufulllayer.hh 1904 2009-07-30 19:29:56Z dast $
*
* \brief Header for cnnplus::CuFullLayer.
*
*****************************************************************************/
#ifndef CNNPLUS_CUFULLLAYER_HH
#define CNNPLUS_CUFULLLAYER_HH
#include "common.hh"
#include "culayer.hh"
#include "cusquasher.hh"
CNNPLUS_NS_BEGIN
//! Fully connected layer
template< typename T, class SquFnc = CuTanh<T> >
class CuFullLayer : public CuLayer<T>
{
public:
//! Ctr
/*! \param sizeIn input size
\param sizeOut output size
*/
CuFullLayer(Size const & sizeIn, Size const & sizeOut);
//! Dtr
virtual ~CuFullLayer();
virtual void forget(T sigma, bool scale = false);
virtual void forget();
virtual void reset();
virtual void update(T eta);
virtual void fprop(T const * in, size_t strideIn,
T * out, size_t strideOut);
virtual void bprop(T * in, size_t strideIn,
T const * out, size_t strideOut,
bool accumGradients = false);
#ifdef CNNPLUS_MATLAB_FOUND
virtual void load(mxArray const * arr);
virtual mxArray * save() const;
#endif // CNNPLUS_MATLAB_FOUND
virtual Size sizeIn() const { return sizeIn_; }
virtual Size sizeOut() const { return sizeOut_; }
virtual void trainableParam(typename Layer<T>::TrainableParam & param);
virtual std::string toString() const;
virtual size_t numTrainableParam() const;
virtual size_t numConnections() const;
private:
Size const sizeIn_;
Size const sizeOut_;
SquFnc squasher_;
// GPU
T * d_in_;
T * d_weights_;
size_t d_strideWeights_;
T * d_dWeights_;
size_t d_strideDWeights_;
T * d_biases_;
T * d_dBiases_;
T * d_sum_;
T * d_delta_;
T * d_tmp_;
// CPU
T * h_weights_;
size_t h_strideWeights_;
T * h_biases_;
};
CNNPLUS_NS_END
#endif // CNNPLUS_CUFULLLAYER_HH
|
63db84957d2143f532bf79ac714ee08eca80f636
|
6a0633b246f58522f376cf0d9608fccdafc47da4
|
/theEarliestMomentWhenEveryoneBecomeFriends1101.cpp
|
609868a5fcc02066f4271e3108170ec924b62471
|
[] |
no_license
|
studentBC/justExercise
|
9ec10dbea9b2fe62d5d673fc39a91d08c9723bf7
|
c5a022a6b46f56598234fb410b5d317f08dcda9c
|
refs/heads/master
| 2023-06-26T12:28:18.144489
| 2023-06-11T15:27:36
| 2023-06-11T15:27:36
| 130,351,745
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,483
|
cpp
|
theEarliestMomentWhenEveryoneBecomeFriends1101.cpp
|
/*
There are n people in a social group labeled from 0 to n - 1. You are given an array logs where logs[i] = [timestampi, xi, yi] indicates that xi and yi will be friends at the time timestampi.
Friendship is symmetric. That means if a is friends with b, then b is friends with a. Also, person a is acquainted with a person b if a is friends with b, or a is a friend of someone acquainted with b.
Return the earliest time for which every person became acquainted with every other person. If there is no such earliest time, return -1.
Example 1:
Input: logs = [[20190101,0,1],[20190104,3,4],[20190107,2,3],[20190211,1,5],[20190224,2,4],[20190301,0,3],[20190312,1,2],[20190322,4,5]], n = 6
Output: 20190301
Explanation:
The first event occurs at timestamp = 20190101 and after 0 and 1 become friends we have the following friendship groups [0,1], [2], [3], [4], [5].
The second event occurs at timestamp = 20190104 and after 3 and 4 become friends we have the following friendship groups [0,1], [2], [3,4], [5].
The third event occurs at timestamp = 20190107 and after 2 and 3 become friends we have the following friendship groups [0,1], [2,3,4], [5].
The fourth event occurs at timestamp = 20190211 and after 1 and 5 become friends we have the following friendship groups [0,1,5], [2,3,4].
The fifth event occurs at timestamp = 20190224 and as 2 and 4 are already friends anything happens.
The sixth event occurs at timestamp = 20190301 and after 0 and 3 become friends we have that all become friends.
Example 2:
Input: logs = [[0,2,0],[1,0,1],[3,0,3],[4,1,2],[7,3,1]], n = 4
Output: 3
Constraints:
2 <= n <= 100
1 <= logs.length <= 104
logs[i].length == 3
0 <= timestampi <= 109
0 <= xi, yi <= n - 1
xi != yi
All the values timestampi are unique.
All the pairs (xi, yi) occur at most one time in the input.
*/
class Solution {
public:
class UnionFind {
public:
vector<int>id;
UnionFind(int n): id(n) {
iota(begin(id), end(id), 0);
}
void connect (int a, int b) {
id[find(b)] = find(a);
}
int find(int i) {
return id[i] == i? i : (id[i] = find(id[i]));
}
bool connected (int a, int b) {
return find(a) == find(b);
}
void reset(int i) {
id[i] = i;
}
};
int earliestAcq(vector<vector<int>>& logs, int n) {
UnionFind uf(n);
unordered_set<int>uniq;
int critical = n/2+2;
sort(logs.begin(), logs.end());
for (int i = 0; i < logs.size(); i++) {
//cout << logs[i][0] << endl;
uf.connect(logs[i][1], logs[i][2]);
uniq.clear();
for (int i : uf.id) {
uniq.insert(i);
//cout << i <<", ";
}
//cout << endl;
if (uniq.size() == 1){
return logs[i][0];
} else if (uniq.size() < critical) {
vector<int>tmp;
//cout <<"inside tmp " << endl;
for (int i : uniq) {
//cout << i <<", ";
tmp.push_back(i);
}
bool valid = true;
for (int j = tmp.size()-1; j > 0; j--) {
if (!uf.connected(tmp[j], tmp[j-1])) {
valid = false;
break;
}
}
if (valid)return logs[i][0];
}
//return logs[i][0];
}
return -1;
}
};
//19 ms solution
class Solution {
public:
static bool tsCmp(vector<int> &v1, vector<int> &v2) {
return v1[0] < v2[0];
}
int find(int a,vector<int>&pa)
{
if(pa[a]==-1)
{
return a;
}
return pa[a]=find(pa[a],pa);
}
int dunion(int a,int b,vector<int>&pa,vector<int>&o)
{
int s1=find(a,pa);
int s2=find(b,pa);
if(s1!=s2)
{
if(o[s1]<o[s2])
{
pa[s1]=s2;
o[s2]+=o[s1];
}
else
{
pa[s2]=s1;
o[s1]+=o[s2];
}
}
return max(o[s1],o[s2]);
}
int earliestAcq(vector<vector<int>>& logs, int n) {
sort(logs.begin(),logs.end(),tsCmp);
vector<int>parent(n);
for (int i = 0; i < n; i++) {
parent[i] = -1;
}
vector<int>order(n,1);
for (vector<int> &eachLog : logs) {
if (dunion(eachLog[1], eachLog[2], parent, order) == n) {
return eachLog[0];
}
}
return -1;
}
};
/*
To visualize the final relationships, we draw the following graph, where each node represents an individual and the link between nodes represents the friendship relationship between two individuals. In addition, the label on top of the link indicates the moment when two individuals become friends.
graph
As one can see, at the timestamp 4, eventually everyone gets to know each other. Note that, the connections of 3 and 5 do not contribute to the overall connections among the friends. They are redundant connections, as we discussed before. To highlight them, we mark the connections with a dashed line.
Now, given the above example, we show step by step how our Union-Find algorithm works.
Initially, we have four groups, where each individual is a group itself. We use a directed link to point to the group that an individual belongs to. We show them in the following graph.
graph
Starting from the first event (1, A, B), we merge the groups of A and B together with the union(A, B) function. By merging, we assign the group of either A or B to the other one. As a result, the merged group (A, B) contains two elements. The total number of groups is now reduced to three.
graph
With the event (2, B, C), we then merge the group of (A, B) with the group of (C) together. To optimize the merging operations, we merge a smaller group (i.e. the one with smaller rank value) into a larger group. Therefore, we merge the group of (C) into the group of (A, B). The total number of groups is now reduced to two. Note: The keen observer will notice that C should actually point to A because of the effects of union by rank, but the main point here is that C has now joined the group with A and B. For simplicity, we will point C to B.
graph
With the event (3, A, C), as it turns out, the individuals A and C already belong to the same group. Therefore, no merging operation is needed. The landscape of groups remains the same.
graph
Finally with the event (4, C, D), we merge the group of (D) into the group of (A, B, C). The total number of groups is reduced to one. And this is the earliest moment when everyone becomes friends.
graph
Complexity Analysis
Since we applied the Union-Find data structure in our algorithm, we would like to start with a statement on the time complexity of the data structure, as follows:
Statement: If MM operations, either Union or Find, are applied to NN elements, the total run time is O(M \cdot \alpha(N))O(M⋅α(N)), where \alpha (N)α(N) is the Inverse Ackermann Function.
One can refer to this article on Union-Find complexity for more details.
In our case, the number of elements in the Union-Find data structure is equal to the number of people, and the number of operations on the Union-Find data structure is up to the number of logs.
Let NN be the number of people and MM be the number of logs.
Time Complexity: O(N + M \log M + M \alpha (N))O(N+MlogM+Mα(N))
First of all, we sort the logs in the order of timestamp. The time complexity of (quick) sorting is O(M \log M)O(MlogM).
Then we created a Union-Find data structure, which takes O(N)O(N) time to initialize the array of group IDs.
We then iterate through the sorted logs. At each iteration, we invoke the union(a, b) function. According to the statement we made above, the amortized time complexity of the entire process is O(M \alpha (N))O(Mα(N)).
To sum up, the overall time complexity of our algorithm is O(N+MlogM+Mα(N)).
Space Complexity: O(N + M)O(N+M) or O(N + \log M)O(N+logM)
The space complexity of our Union-Find data structure is O(N)O(N), because we keep track of the group ID for each individual.
The space complexity of the sorting algorithm depends on the implementation of each program language.
For instance, the list.sort() function in Python is implemented with the Timsort algorithm whose space complexity is O(M)O(M). While in Java, the Arrays.sort() is implemented as a variant of quicksort algorithm whose space complexity is O(\log{M})O(logM).
To sum up, the overall space complexity of the algorithm is O(N+M) for Python and O(N+logM) for Java.
*/
// official solution
class Solution {
public int earliestAcq(int[][] logs, int n) {
// First, we need to sort the events in chronological order.
Arrays.sort(logs, new Comparator<int[]>() {
@Override
public int compare(int[] log1, int[] log2) {
Integer tsp1 = new Integer(log1[0]);
Integer tsp2 = new Integer(log2[0]);
return tsp1.compareTo(tsp2);
}
});
// Initially, we treat each individual as a separate group.
int groupCount = n;
UnionFind uf = new UnionFind(n);
for (int[] log : logs) {
int timestamp = log[0], friendA = log[1], friendB = log[2];
// We merge the groups along the way.
if (uf.union(friendA, friendB)) {
groupCount -= 1;
}
// The moment when all individuals are connected to each other.
if (groupCount == 1) {
return timestamp;
}
}
// There are still more than one groups left,
// i.e. not everyone is connected.
return -1;
}
}
class UnionFind {
private int[] group;
private int[] rank;//rank here means the number of people in this group
public UnionFind(int size) {
this.group = new int[size];
this.rank = new int[size];
for (int person = 0; person < size; ++person) {
this.group[person] = person;
this.rank[person] = 0;
}
}
/** Return the id of group that the person belongs to. */
public int find(int person) {
if (this.group[person] != person)
this.group[person] = this.find(this.group[person]);
return this.group[person];
}
/**
* If it is necessary to merge the two groups that x, y belong to.
* @return true: if the groups are merged.
*/
public boolean union(int a, int b) {
int groupA = this.find(a);
int groupB = this.find(b);
boolean isMerged = false;
// The two people share the same group.
if (groupA == groupB)
return isMerged;
// Otherwise, merge the two groups.
isMerged = true;
// Merge the lower-rank group into the higher-rank group.
if (this.rank[groupA] > this.rank[groupB]) {
this.group[groupB] = groupA;
} else if (this.rank[groupA] < this.rank[groupB]) {
this.group[groupA] = groupB;
} else {
this.group[groupA] = groupB;
this.rank[groupB] += 1;
}
return isMerged;
}
}
|
4a779fa5a2a266041864f9741d9d711a24fabcdd
|
a1efd9d28a011c0d5161244c16b3cb11badc5a98
|
/software/target/apps/equalize/equalize.h
|
1b102370f818b5cd0900be2acd0990bb40a6ab9d
|
[
"MIT"
] |
permissive
|
maxpark/ztachip
|
e3bf7ae1e353c3602a782f2f02cca2280eb736d2
|
21cc9f058e8b0eba59d0f2930d33cfde2bb4962d
|
refs/heads/master
| 2023-04-05T05:35:14.864884
| 2021-04-18T21:23:07
| 2021-04-18T21:23:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,252
|
h
|
equalize.h
|
#ifndef _TARGET_APPS_EQUALIZE_EQUALIZE_H_
#define _TARGET_APPS_EQUALIZE_EQUALIZE_H_
#include "../../base/tensor.h"
#include "../../base/graph.h"
// Graph node to do image equalization (improve image contrast)
// Calculate pixel value histogram and then apply image
// equalization.
#define HISTOGRAM(h,j) ((h)[(j)]*1000 + (h)[(j)+32])
#define HISTOGRAM_BIN_SIZE 8
#define HISTOGRAM_BIN_COUNT (256/HISTOGRAM_BIN_SIZE)
class GraphNodeEqualize : public GraphNode {
public:
GraphNodeEqualize();
GraphNodeEqualize(TENSOR *input,TENSOR *output);
virtual ~GraphNodeEqualize();
ZtaStatus Create(TENSOR *input,TENSOR *output);
virtual ZtaStatus Verify();
virtual ZtaStatus Schedule(int queue);
ZTA_SHARED_MEM GenEqualizer();
float GetContrast() {return m_contrast;}
void SetContrast(float _contrast);
public:
ZTA_SHARED_MEM m_spu;
private:
void Cleanup();
static float SpuCallback(float input,void *pparm,uint32_t parm);
private:
TENSOR *m_input;
TENSOR *m_output;
TENSOR m_result;
int m_threshold;
int m_w;
int m_h;
int m_nChannel;
uint32_t m_func;
float m_contrast;
int m_histogram[HISTOGRAM_BIN_COUNT];
int m_histogram_sum[HISTOGRAM_BIN_COUNT];
bool m_histogramAvail;
};
#endif
|
28b2717610c9b41b1023b7da0b40b97552c9bc51
|
4e3e6b3a0ef70dfddf6b10d93c3e10e1cb4df2b3
|
/EmbeddedResource.h
|
44f74ebeae144d605f58358df094eac80c55bfb7
|
[
"BSD-3-Clause"
] |
permissive
|
ankurvdev/embedresource
|
b1a23fe128592f22128608d3518a7c6a48259dec
|
872145c39f6b7c20a5aeeaedeb897a79393931c3
|
refs/heads/main
| 2023-08-18T02:19:39.240151
| 2023-07-22T09:06:40
| 2023-07-22T09:06:40
| 257,459,094
| 0
| 1
|
BSD-3-Clause
| 2023-08-02T17:07:17
| 2020-04-21T02:28:34
|
Python
|
UTF-8
|
C++
| false
| false
| 5,354
|
h
|
EmbeddedResource.h
|
#pragma once
#pragma warning(push, 3)
#pragma clang diagnostic push
#pragma GCC diagnostic push
#pragma clang diagnostic ignored "-Weverything"
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#pragma warning(disable : 5262) /*xlocale(2010,13): implicit fall-through occurs here*/
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <optional>
#include <span>
#include <stdexcept>
#include <string_view>
#include <type_traits>
#pragma GCC diagnostic pop
#pragma clang diagnostic pop
#pragma warning(pop)
#if defined(_MSC_VER) // compiling with VisualStudio
#if defined(EMBEDDED_RESOURCE_EXPORTED_API_IMPL)
#define EMBEDDED_RESOURCE_EXPORTED_API extern "C" __declspec(dllexport)
#else
#define EMBEDDED_RESOURCE_EXPORTED_API extern "C" __declspec(dllimport)
#endif
#elif defined(__GNUC__) // compiling with GCC
#define EMBEDDED_RESOURCE_EXPORTED_API extern "C" __attribute__((visibility("protected")))
#else
#error "Unknown Compiler. Dont know how to export symbol"
#endif
#define EMBEDDEDRESOURCE_ABI_RESOURCE_FUNCNAME(collection, symbol, func) EmbeddedResource_ABI_##collection##_Resource_##symbol##_##func
#define EMBEDDEDRESOURCE_ABI_COLLECTION_FUNCNAME(collection, func) EmbeddedResource_ABI_##collection##_##func
#undef MY_CONCAT
#undef MY_CONCAT2
namespace EmbeddedResource::ABI
{
template <typename T> struct Data
{
T const* data;
size_t len;
};
struct ResourceInfo
{
Data<wchar_t> name;
Data<uint8_t> data;
};
typedef ResourceInfo GetCollectionResourceInfo();
typedef Data<GetCollectionResourceInfo> GetCollectionResourceInfoTable();
} // namespace EmbeddedResource::ABI
#define DECLARE_IMPORTED_RESOURCE_COLLECTION(collection) \
EMBEDDED_RESOURCE_EXPORTED_API EmbeddedResource::ABI::Data<EmbeddedResource::ABI::GetCollectionResourceInfo*> \
EmbeddedResource_ABI_##collection##_##GetCollectionResourceInfoTable()
#define DECLARE_IMPORTED_RESOURCE(collection, resource) \
EMBEDDED_RESOURCE_EXPORTED_API EmbeddedResource::ABI::ResourceInfo \
EmbeddedResource_ABI_##collection##_Resource_##resource##_##GetCollectionResourceInfo()
#define DECLARE_RESOURCE_COLLECTION(collection) \
EmbeddedResource::ABI::Data<EmbeddedResource::ABI::GetCollectionResourceInfo*> \
EmbeddedResource_ABI_##collection##_##GetCollectionResourceInfoTable()
#define DECLARE_RESOURCE(collection, resource) \
EmbeddedResource::ABI::ResourceInfo EmbeddedResource_ABI_##collection##_Resource_##resource##_##GetCollectionResourceInfo()
struct ResourceLoader
{
ResourceLoader(EmbeddedResource::ABI::ResourceInfo info) : _info(info) {}
~ResourceLoader() = default;
ResourceLoader() = delete;
ResourceLoader(ResourceLoader const&) = delete;
ResourceLoader(ResourceLoader&&) = delete;
ResourceLoader& operator=(ResourceLoader const&) = delete;
ResourceLoader& operator=(ResourceLoader&&) = delete;
std::wstring_view name() const { return std::wstring_view(_info.name.data, _info.name.len); }
/* template <typename T auto data() const
{
auto const ptr = reinterpret_cast<const T*>(_info.data.data);
size_t const size = _info.data.len / sizeof(T);
assert(_info.data.len % sizeof(T) == 0);
return std::span<const T>{ptr, ptr + size};
}*/
std::string_view string() const { return std::string_view(reinterpret_cast<const char*>(_info.data.data), _info.data.len); }
EmbeddedResource::ABI::ResourceInfo const _info;
};
struct CollectionLoader
{
struct Iterator
{
CollectionLoader* _ptr;
size_t _index;
bool operator!=(Iterator const& it) const { return _ptr != it._ptr || _index != it._index; }
Iterator& operator++()
{
_index++;
return *this;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage"
ResourceLoader operator*() const { return ResourceLoader((*(_ptr->_collection.data + _index))()); }
#pragma clang diagnostic pop
};
CollectionLoader(EmbeddedResource::ABI::Data<EmbeddedResource::ABI::GetCollectionResourceInfo*> collection) : _collection(collection) {}
~CollectionLoader() = default;
CollectionLoader() = delete;
CollectionLoader(CollectionLoader const&) = delete;
CollectionLoader(CollectionLoader&&) = delete;
CollectionLoader& operator=(CollectionLoader const&) = delete;
CollectionLoader& operator=(CollectionLoader&&) = delete;
Iterator begin() { return Iterator{this, 0}; }
Iterator end() { return Iterator{this, _collection.len}; }
EmbeddedResource::ABI::Data<EmbeddedResource::ABI::GetCollectionResourceInfo*> const _collection;
};
#define LOAD_RESOURCE_COLLECTION(collection) CollectionLoader(EmbeddedResource_ABI_##collection##_##GetCollectionResourceInfoTable())
#define LOAD_RESOURCE(collection, resource) EmbeddedResource_ABI_##collection##_Resource_##resource##_##GetCollectionResourceInfo()
|
29c25a9abd8de6a9753ec9797518f3ea3f374915
|
a300c35fc8e99b67d1d2b02e23b77e49771a63bc
|
/Solved/URI/1803 - Matring.cpp
|
130d5d11a7fa224bd3eeeb2f152663655a29ba76
|
[] |
no_license
|
FabiOquendo/Competitive-Programming
|
c035b865eb79b89b587ad919e45cf00e0b35de83
|
adbcde84bbd10fee10143101b56bb3dbb0b79b6b
|
refs/heads/master
| 2021-01-18T22:55:56.307662
| 2017-06-01T16:21:17
| 2017-06-01T16:21:17
| 49,735,500
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,180
|
cpp
|
1803 - Matring.cpp
|
//============================================================
// Name : 1803 - Matring.cpp
// Author : Team UQuick
// Author : Fabio Stiven Oquendo Soler & Gaitan
// Description : Programming Problems URI
// Number : 1803
//============================================================
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
int main() {
int tam, f, l, m;
char c;
string line1;
string line2;
string line3;
string line4;
while(cin >> line1) {
cin >> line2;
cin >> line3;
cin >> line4;
tam = line1.size();
f = (line1[0]-48)*1000;
f += (line2[0]-48)*100;
f += (line3[0]-48)*10;
f += (line4[0]-48);
l = (line1[tam-1]-48)*1000;
l += (line2[tam-1]-48)*100;
l += (line3[tam-1]-48)*10;
l += (line4[tam-1]-48);
for(int i = 1; i < tam-1; i++) {
m = (line1[i]-48)*1000;
m += (line2[i]-48)*100;
m += (line3[i]-48)*10;
m += (line4[i]-48);
c = (char)((f*m+l)%257);
cout << c;
}
cout << endl;
}
return 0;
}
|
fc0affa1e7f954acefc973288bd7e402b7468d13
|
b99bff76c2f79de323461c7a66dcc78f5fba7691
|
/src/net/link_redis.h
|
dba77980061f5519d5a19a1a9ec40d8cbad4142f
|
[
"BSD-3-Clause"
] |
permissive
|
qwang2505/ssdb-source-comments
|
1be3687d561c07861f2cf0f9e2f6797c6b779149
|
0ee33b7305656581190e2971f9185f612c258ea0
|
refs/heads/master
| 2021-05-15T02:00:00.707177
| 2017-03-14T03:37:28
| 2017-03-14T03:37:28
| 34,109,193
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,938
|
h
|
link_redis.h
|
/*
Copyright (c) 2012-2014 The SSDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
*/
#ifndef NET_REDIS_LINK_H_
#define NET_REDIS_LINK_H_
#include <vector>
#include <string>
#include "../util/bytes.h"
// 请求描述?
struct RedisRequestDesc
{
// 策略
int strategy;
// redis命令
std::string redis_cmd;
// ssdb命令
std::string ssdb_cmd;
// 返回类型
int reply_type;
};
// 表示一个redis连接?
//
// 大致了解了这个类的功能,主要功能就是将redis协议的请求转换成ssdb的请求,转换过程中可能
// 需要针对命令的参数/返回结果等做一些处理。请求转换的过程是将输入缓冲区中的数据转换成Bytes
// 数组,以供后续处理。响应转换的过程是将string数组中表示的输出内容放到输出缓冲区中。在
// 这里没有处理任何网络相关的功能和流程,只是进行输入输出的转换以及格式解析和处理。
class RedisLink
{
private:
// 命令
std::string cmd;
// 请求描述
RedisRequestDesc *req_desc;
// 这个需要看,是请求吗?
//
// 存储解析完毕的请求数据,最终请求解析完毕后会把recv_bytes返回
std::vector<Bytes> recv_bytes;
// 这个不知道是什么
//
// 在从redis命令切换为ssdb命令的过程中,使用recv_string作为中间存储,最终返回解析
// 后的请求时会再次将recv_string中的内容放到recv_bytes中去返回
std::vector<std::string> recv_string;
// 解析请求
int parse_req(Buffer *input);
// 转换请求
int convert_req();
public:
RedisLink(){
// 请其描述对象的指针,会再convert_req函数中被赋值
req_desc = NULL;
}
// 接受请求
const std::vector<Bytes>* recv_req(Buffer *input);
// 发送响应
int send_resp(Buffer *output, const std::vector<std::string> &resp);
};
#endif
|
11e38aabc108aae968f3f93b636da46be911db4e
|
82a349d4a39ea90cfbd0ed051b1661751b1f7040
|
/CoolBox_CubeIDE_V1.1/TouchGFX/generated/fonts/src/Kerning_verdana_34_4bpp.cpp
|
d79ef4c15fae1dc9117b98fa0e99fe74b2e8e141
|
[] |
no_license
|
Coolab-Community/CoolBox
|
c67f9b8621e585515b1069afe1671ba81421eb91
|
2836dca9c5592a20319ca8377ddbaf3926a3551b
|
refs/heads/master
| 2023-02-09T22:07:16.816988
| 2020-12-22T10:07:57
| 2020-12-22T10:07:57
| 266,549,565
| 8
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 854
|
cpp
|
Kerning_verdana_34_4bpp.cpp
|
#include <touchgfx/Font.hpp>
FONT_KERNING_LOCATION_FLASH_PRAGMA
KEEP extern const touchgfx::KerningNode kerning_verdana_34_4bpp[] FONT_KERNING_LOCATION_FLASH_ATTRIBUTE =
{
{ 0x0054, 1 }, // (First char = [0x0054, T], Second char = [0x003F, ?], Kerning dist = 1)
{ 0x0044, -1 }, // (First char = [0x0044, D], Second char = [0x0054, T], Kerning dist = -1)
{ 0x0054, -1 }, // (First char = [0x0054, T], Second char = [0x0054, T], Kerning dist = -1)
{ 0x0065, -2 }, // (First char = [0x0065, e], Second char = [0x0054, T], Kerning dist = -2)
{ 0x0054, -4 }, // (First char = [0x0054, T], Second char = [0x0065, e], Kerning dist = -4)
{ 0x0054, -4 }, // (First char = [0x0054, T], Second char = [0x006F, o], Kerning dist = -4)
{ 0x0054, -3 }, // (First char = [0x0054, T], Second char = [0x0073, s], Kerning dist = -3)
};
|
67c39bf2f1a3f459a8e001c493d0fc7dc765473a
|
fa6ae1d8602633cc68c62d7b094e2300f052ce5c
|
/ieeextreme/x10_paintersdilemma.cpp
|
5601f53ac355c3603fb75399fda0c30d41824a13
|
[
"MIT"
] |
permissive
|
ieeeunswsb/cpworkshop
|
ab680cd9ad9a6522e14ea6a90dcd9d1c122e5f7b
|
8da33deb295f4ca04ec025adc510d67a65d3d56c
|
refs/heads/master
| 2020-06-08T06:43:57.516420
| 2019-10-14T10:24:48
| 2019-10-14T10:24:48
| 193,179,764
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,561
|
cpp
|
x10_paintersdilemma.cpp
|
//============================================================================
// Name : x10_paintersdilemma.cpp
// Author : Luke Sy
// Version :
// Description : https://www.hackerrank.com/contests/ieeextreme-challenges/challenges/painters-dilemma
// Dynamic programming problem
//============================================================================
#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
static int NMAX = 1000;
static int CMAX = 20;
int T;
int main() {
cin >> T;
int N;
for(int TIdx=0; TIdx<T; TIdx++) {
cin >> N;
int color[N];
for(int i=0; i<N; i++) cin >> color[i];
int val[CMAX+1][N];
for(int i=0; i<=CMAX; i++) val[i][0] = NMAX;
val[0][0] = 1;
// for(int p=0; p<=CMAX; p++) cout << val[p][0] << ' ';
// cout << '\n';
for(int i=1; i<N; i++) {
int inc = (color[i]==color[i-1])? 0 : 1;
int minVal = NMAX;
for(int j=0; j<=CMAX; j++) {
if (val[j][i-1] == NMAX) {
val[j][i] = NMAX;
} else {
val[j][i] = val[j][i-1] + inc;
}
int buf = val[j][i-1] + ((j==color[i]) ? 0 : 1);
if(buf < minVal) {
minVal = buf;
}
}
val[color[i-1]][i] = minVal;
// for(int p=0; p<=CMAX; p++) cout << val[p][i] << ' ';
// cout << '\n';
}
int minVal = NMAX;
for(int i=0; i<=CMAX; i++)
if(val[i][N-1] < minVal)
minVal = val[i][N-1];
cout << minVal << '\n';
// for(int i=0; i<N; i++) cout << color[i] << ' ';
// printf("\n");
}
return 0;
}
|
80e558555dd7686bebc86114f467218c3e032b62
|
c5843992e233b92e90b53bd8a90a9e68bfc1f6d6
|
/code/synthesis/TransformMachines2/AWProjectWBFTNew.h
|
191d4acd9101440e32a48bec92ff403ef418503d
|
[] |
no_license
|
pkgw/casa
|
17662807d3f9b5c6b57bf3e36de3b804e202c8d3
|
0f676fa7b080a9815a0b57567fd4e16cfb69782d
|
refs/heads/master
| 2021-09-25T18:06:54.510905
| 2017-08-16T21:53:54
| 2017-08-16T21:53:54
| 100,752,745
| 2
| 1
| null | 2020-02-24T18:50:59
| 2017-08-18T21:51:10
|
C++
|
UTF-8
|
C++
| false
| false
| 3,173
|
h
|
AWProjectWBFTNew.h
|
//# AWProjectWBFTNew.h: Definition for AWProjectWBFTNew
//# Copyright (C) 1996,1997,1998,1999,2000,2002
//# Associated Universities, Inc. Washington DC, USA.
//#
//# This library is free software; you can redistribute it and/or modify it
//# under the terms of the GNU Library General Public License as published by
//# the Free Software Foundation; either version 2 of the License, or (at your
//# option) any later version.
//#
//# This library is distributed in the hope that it will be useful, but WITHOUT
//# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
//# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
//# License for more details.
//#
//# You should have received a copy of the GNU Library General Public License
//# along with this library; if not, write to the Free Software Foundation,
//# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
//#
//# Correspondence concerning AIPS++ should be adressed as follows:
//# Internet email: aips2-request@nrao.edu.
//# Postal address: AIPS++ Project Office
//# National Radio Astronomy Observatory
//# 520 Edgemont Road
//# Charlottesville, VA 22903-2475 USA
//#
//#
//# $Id$
#ifndef SYNTHESIS_TRANSFORM2_AWPROJECTWBFTNEW_H
#define SYNTHESIS_TRANSFORM2_AWPROJECTWBFTNEW_H
#define DELTAPA 1.0
#define MAGICPAVALUE -999.0
#include <synthesis/TransformMachines2/AWProjectWBFT.h>
namespace casa { //# NAMESPACE CASA - BEGIN
namespace refim {
class AWProjectWBFTNew : public AWProjectWBFT {
public:
AWProjectWBFTNew(casacore::Int nFacets, casacore::Long cachesize,
casacore::CountedPtr<CFCache>& cfcache,
casacore::CountedPtr<ConvolutionFunction>& cf,
casacore::CountedPtr<VisibilityResamplerBase>& visResampler,
casacore::Bool applyPointingOffset=true,
casacore::Bool doPBCorr=true,
casacore::Int tilesize=16,
casacore::Float paSteps=5.0,
casacore::Float pbLimit=5e-4,
casacore::Bool usezero=false,
casacore::Bool conjBeams_p=true,
casacore::Bool doublePrecGrid=false):
AWProjectWBFT(nFacets, cachesize, cfcache, cf, visResampler, applyPointingOffset,
doPBCorr, tilesize, paSteps, pbLimit, usezero, conjBeams_p, doublePrecGrid){}
// Construct from a casacore::Record containing the AWProjectWBFT state
AWProjectWBFTNew(const casacore::RecordInterface& stateRec):AWProjectWBFT(stateRec){};
// Copy constructor
//AWProjectWBFTNew(const AWProjectWBFTNew &other):AWProjectWBFT() {operator=(other);};
virtual casacore::String name() const {return "AWProjectWBFTNew";};
~AWProjectWBFTNew(){};
FTMachine* cloneFTM();
virtual casacore::Bool useWeightImage(){return true;};
virtual void setDryRun(casacore::Bool val)
{
isDryRun=val;
//cerr << "###### " << isDryRun << endl;
};
protected:
void ftWeightImage(casacore::Lattice<casacore::Complex>& wtImage,
const casacore::Matrix<casacore::Float>& sumWt,
const casacore::Bool& doFFTNorm);
private:
};
} //# NAMESPACE CASA - END
};
#endif
|
14132c9b632c5236cf96e601dd5d441e2577c97d
|
a88a79dbf9107acf181141e32a1409dafdcaffbc
|
/math/类欧几里得.cpp
|
cf8946ea5b76985edf37535d8e819ecc1e5b625a
|
[] |
no_license
|
wcy1122/ACM-ICPC-template
|
b5e66b2990b8aae3671af0f147e9094cb79ee203
|
478557e5db4fffb1cf79e0f2a565d5c33989c8ec
|
refs/heads/master
| 2020-03-23T18:27:48.468697
| 2020-01-23T14:01:57
| 2020-01-23T14:01:57
| 141,910,347
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 405
|
cpp
|
类欧几里得.cpp
|
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll a,b,c;
ll f(ll a,ll b,ll c,ll n)
{
if(!c)return 0;
ll m=(a*n+b)/c;
if(a<c&&b<c)return n*m-f(c,c-b-1,a,m-1);
return (a/c)*n*(n+1)/2+(b/c)*(n+1)+f(a%c,b%c,c,n);
}
//(ax+b)/c在0到n上的正整数点个数
//记得加上 c/a+1
int main()
{
scanf("%lld%lld%lld",&a,&b,&c);
printf("%lld\n",f(a,c%a,b,c/a)+c/a+1);
return 0;
}
|
d4b1cb1d84a205340677a76b119451230da69c3d
|
8027aef1a47dfee4f7b7fb1c31d715f38e95bedb
|
/RecipeGenerator/Vegetable.cpp
|
f1daf5cc133d333ba63ccf819a105bac532d334c
|
[] |
no_license
|
adamsh25/FirstMFCProject
|
98e9a7807a82eb2757c1507b12cce5dff21f61d4
|
8a830d790df38ac1383834820fb19b4839226ea1
|
refs/heads/master
| 2021-05-14T12:23:58.620255
| 2018-01-20T16:57:47
| 2018-01-20T16:57:47
| 116,408,078
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,061
|
cpp
|
Vegetable.cpp
|
#include "stdafx.h"
#include "Vegetable.h"
IMPLEMENT_SERIAL(Vegetable, Ingredient, 1)
Vegetable::Vegetable()
{
}
Vegetable::Vegetable(CString _name, CString _color)
{
name = _name;
color = _color;
}
Vegetable::Vegetable(Vegetable const & other) : Ingredient(other)
{
color = other.color;
}
CString Vegetable::GetCategory() const
{
return CString(L"Vegetable");
}
CString Vegetable::GetColor() const
{
return color;
}
CString Vegetable::GetName() const
{
CString formmated = L"";
formmated.Format(L"%s %s", color, Ingredient::GetName());
return formmated;
}
CString Vegetable::GetImagePath() const
{
return CString(L"Dairy.png");
}
int Vegetable::GetHealthScore() const
{
return Ingredient::GetHealthScore() - 2;
}
void Vegetable::Serialize(CArchive & archive)
{
Ingredient::Serialize(archive);
if (archive.IsStoring())
{
archive << color;
}
else
{
archive >> color;
}
}
CString Vegetable::GetInfo()
{
CString formmated = L"";
formmated.Format(L"%s_%s_%s", GetCategory(), color, Ingredient::GetInfo());
return formmated;
}
|
099f18d59ed8d55bef07f2b362e64367b72b4604
|
4e1c98a5550a0a70fe5ded7160e1c2f992cfdf21
|
/flac.cpp
|
fe7e29f192856869c225e04b2dfc696a7a1105cb
|
[] |
no_license
|
MacroMachinesEngineering/Arduino-Teensy-Codec-lib
|
02d931f13d86cd7dfad313c3f4073b6a3926b4a3
|
d536c69f330b8ff3e83fc789d950b26865d35db0
|
refs/heads/master
| 2020-12-28T23:50:17.125039
| 2014-12-22T21:29:35
| 2014-12-22T21:29:35
| 28,461,131
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 543
|
cpp
|
flac.cpp
|
//Ram Usage:
//Blocksize 128 : 3852 Bytes
#define VERSION "1.3.1"
#define FLAC__INTEGER_ONLY_LIBRARY 1
//#define FLAC__OVERFLOW_DETECT 1
#define HAVE_BSWAP32 1
#define HAVE_BSWAP16 1
//TODO:
//- Option to disable CRC
//- Use Teensy-CRC-Unit
#include "flac/all.h"
#include "flac/lpc.c"
#include "flac/format.c"
#include "flac/float.c"
#include "flac/fixed.c"
#include "flac/md5.c"
#include "flac/crc.c"
#include "flac/bitreader.c"
#include "flac/bitmath.c"
#include "flac/memory.c"
#include "flac/stream_decoder.c"
#include "flac/cpu.c"
|
9854709f844ae819715f0e2210e782bf9dd3f470
|
cd783c0d99f07c29f394adb6e029ab0e4ed74475
|
/Lab1/lab1_II_7.cpp
|
fc233e6f5aaf2e4f7144dd785ededbf1b2952f02
|
[] |
no_license
|
Werstef/Facultate-CP
|
4fd9c1605458f203e872687f0f1be06609afc869
|
6fadf0234f7876d938afb8cb961139e5192c59e8
|
refs/heads/master
| 2021-08-19T01:57:46.449535
| 2017-11-24T12:13:56
| 2017-11-24T12:13:56
| 108,106,546
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 173
|
cpp
|
lab1_II_7.cpp
|
#include <iostream>
using namespace std;
int main () {
for ( int i=1 ; i<= 100 ; i++ ){
if ( i>=32 && i<=39)
cout<<i<<"\n";
}
return 0;
}
|
2cefe5bdf224ccdabdaa14764037c7b20d22b009
|
665ce4b4538660b51c504497895dd814b53feb73
|
/roboticsProject/flameDetection.cpp
|
2d5332ad7f405bbb2e206b40962852300d606804
|
[] |
no_license
|
zavalza/roboticsProject
|
a1be365d511d58a5f9038c902fbb69ed27e7a98b
|
7fd028a4579e984bcb970ec3c2aaac7c28290a28
|
refs/heads/master
| 2021-01-20T00:57:01.699016
| 2014-03-25T04:43:34
| 2014-03-25T04:43:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,225
|
cpp
|
flameDetection.cpp
|
#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <fstream>
#include <iostream>
#include <Windows.h>
#include <queue>
#define imageHeight 480
#define imageWidth 640
using std::cout;
using std::cin;
using std::endl;
using namespace cv;
vector <Mat> hsv_planes;
int coordinateX = 0, coordinateY = 0;
int redClick = 0, blueClick = 0, greenClick = 0;
int hueClick = 0, saturationClick = 0, valueClick = 0;
int maxRed = 0, maxBlue = 0, maxGreen = 0;
int minRed = 0, minBlue = 0, minGreen = 0;
int nClicks = 0;
RNG rng(12345);
Mat currentImage = Mat(imageHeight, imageWidth, CV_8UC3);
Mat gammaImage = Mat(imageHeight, imageWidth, CV_8UC3);
Mat complementedImage = Mat(imageHeight, imageWidth, CV_8UC3);
Mat hsvImage = Mat(imageHeight, imageWidth, CV_8UC3);
Mat binImageYellow = Mat(imageHeight, imageWidth, CV_8UC1);
Mat binImageGreen = Mat(imageHeight, imageWidth, CV_8UC1);
Mat binImageGreenDetail = Mat(imageHeight, imageWidth, CV_8UC1);
Mat binImage = Mat(imageHeight, imageWidth, CV_8UC1);
Mat filledImage = Mat(imageHeight, imageWidth, CV_8UC1);
Mat grayImage = Mat(imageHeight, imageWidth, CV_8UC3);
void mouseCoordinates(int event, int x, int y, int flags, void* param);
Mat correctGamma(Mat &img, double gamma);
void complementImage(const Mat &sourceImage, Mat &destinationImage);
void thresholdImage(const Mat &sourceImage, Mat &destinationImage);
void deteccion_fuego(Mat frame);
void print();
int main()
{
VideoCapture cameraFeed;
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
Mat element = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1,-1));
Mat cannyOutput;
//Mat kernel = Mat::ones(Size(5, 5), CV_8UC1);
char key = ' ';
double gamma = 0.1;
int counter = 0;
int thresh = 100;
char freeze = 0;
cameraFeed.open(0);
//namedWindow("Camera Feed");
//namedWindow("Complemented image");
namedWindow("HSV");
//setMouseCallback("Complemented image", mouseCoordinates);
setMouseCallback("HSV", mouseCoordinates);
//imshow("Camera Feed", currentImage);
while(key != 27)
{
// system("cls");
// print();
if(key == 'f')
{
freeze = !freeze;
key = '0';
}
if(!freeze)
{
cameraFeed >> currentImage;
gammaImage = correctGamma(currentImage, 0.2);
//complementImage(gammaImage, complementedImage);
bitwise_not(gammaImage, complementedImage);
cvtColor(complementedImage, hsvImage, CV_BGR2HSV);
imshow("HSV", hsvImage);
//split(hsvImage, hsv_planes);
inRange(hsvImage, Scalar(85, 230, 185), Scalar(106, 255, 225), binImageYellow);
inRange(hsvImage, Scalar(90, 250, 5), Scalar(120, 255, 144), binImageGreen);
bitwise_or(binImageYellow, binImageGreen, binImage);
//erode(binImage, filledImage, element);
morphologyEx(binImage, filledImage, MORPH_OPEN, element);
Canny(filledImage, cannyOutput, thresh, thresh *2, 3);
findContours(cannyOutput, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0,0));
Mat drawing = Mat::zeros( cannyOutput.size(), CV_8UC3);
for(unsigned int i = 0; i < contours.size(); i++ )
{
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255));
drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
}
imshow("Binary", filledImage);
imshow("Contours", drawing);
}
key = waitKey(15);
//Sleep(15);
}
return 0;
}
void print()
{
cout << "X: " << coordinateX << ", Y: " << coordinateY << endl;
cout << "R: " << redClick << ", G: " << greenClick << ", B: " << blueClick << endl;
cout << "H: " << hueClick << ", S: " << saturationClick << ", V: " << valueClick << endl;
}
void mouseCoordinates(int event, int x, int y, int flags, void* param)
{
switch (event)
{
/*CV_EVENT_MOUSEMOVE - when the mouse pointer moves over the specified window
CV_EVENT_LBUTTONDOWN - when the left button of the mouse is pressed on the specified window
CV_EVENT_RBUTTONDOWN - when the right button of the mouse is pressed on the specified window
CV_EVENT_MBUTTONDOWN - when the middle button of the mouse is pressed on the specified window
CV_EVENT_LBUTTONUP - when the left button of the mouse is released on the specified window
CV_EVENT_RBUTTONUP - when the right button of the mouse is released on the specified window
CV_EVENT_MBUTTONUP - when the middle button of the mouse is released on the specified window */
case CV_EVENT_LBUTTONDOWN:
coordinateX = x;
coordinateY = y;
redClick = currentImage.at<Vec3b>(y, x)[2];
greenClick = currentImage.at<Vec3b>(y, x)[1];
blueClick = currentImage.at<Vec3b>(y, x)[0];
hueClick = hsvImage.at<Vec3b>(y, x)[0];
saturationClick = hsvImage.at<Vec3b>(y, x)[1];
valueClick = hsvImage.at<Vec3b>(y, x)[2];
print();
break;
case CV_EVENT_RBUTTONDOWN:
system("cls");
break;
}
}
Mat correctGamma(Mat &img, double gamma) {
double inverse_gamma = 1.0 / gamma;
Mat lut_matrix(1, 256, CV_8UC1);
uchar * ptr = lut_matrix.ptr();
for(int i = 0; i < 256; i++)
ptr[i] = (int)(pow((double) i / 255.0, inverse_gamma) * 255.0);
Mat result;
LUT(img, lut_matrix, result);
return result;
}
|
ab6d38a07fd8105ac33f9ee4f977e4acf5520f9d
|
3a02c26115c1b4180e32d1d9aa7e5b74952c460b
|
/src/headers/FileInfo.h
|
fb25fb98abed25b058d7597a7b8b859092c94366
|
[] |
no_license
|
sfeeling/Oodle
|
9c38dfd5f429e88dba6823d220531d382f86ba85
|
c4124860166ebd6c06fa3016fba7bb0deca2374b
|
refs/heads/master
| 2020-03-17T03:51:07.236082
| 2018-06-17T06:28:24
| 2018-06-17T06:28:24
| 133,252,851
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 524
|
h
|
FileInfo.h
|
//
// Created by sfeeling on 18-4-20.
//
#ifndef OODLE_FILEINFO_H
#define OODLE_FILEINFO_H
#include <string>
class FileInfo
{
public:
FileInfo();
FileInfo(const std::string &, const int &, const time_t &, const bool &);
~FileInfo();
const std::string &Name() const;
const long long int &Size() const;
const time_t &LastModified() const;
bool IsDirectory();
private:
std::string name_;
long long int size_;
time_t modified_time_;
bool is_dir_;
};
#endif //OODLE_FILEINFO_H
|
60e46539a7eaea8dd5a521ec2df6b1b3671d2d04
|
02095cd4aeaa3a0d724f7362cdb8795fe9a81620
|
/oplink/algorithms/team/src/plugins/algorithms/MonoGA_GlobalSearch/MonoGA_GlobalSearch.cpp
|
579432abd6b7a4552749b5045a1935781b3d470a
|
[] |
no_license
|
PAL-ULL/software-metco
|
ba5123cb1423fed4a2ac678ab375728ba4bbfbc8
|
59edc4e49bddbd9fc7237bf2f24271bdfc8afd79
|
refs/heads/master
| 2021-04-15T04:12:56.292543
| 2021-03-08T13:29:14
| 2021-03-08T13:29:14
| 126,484,450
| 10
| 5
| null | 2020-07-21T18:43:10
| 2018-03-23T12:49:10
|
C++
|
UTF-8
|
C++
| false
| false
| 44,323
|
cpp
|
MonoGA_GlobalSearch.cpp
|
/***********************************************************************************
* AUTHORS
* - Eduardo Segredo Gonzalez
* - Carlos Segura Gonzalez
*
* DATE
* March 2011
*
**********************************************************************************/
#include <cstdlib>
#include <iostream>
#include <signal.h>
#include <math.h>
#include "MonoGA_GlobalSearch.h"
// Algorithm initialization
bool MonoGA_GlobalSearch::init(const vector<string> ¶ms){
// Check number of parameters
if (params.size() != 5){
cout << "Parametros: popSize pm pc survivalSelection globalSearchType" << endl;
cout << "Survival Selection: " << endl;
cout << " 0: Steady State" << endl;
cout << " 1: Generational" << endl;
cout << " 2: Replace worst from parent and offspring" << endl;
cout << "Global Search Mechanism: " << endl;
cout << " 0: Similarity-based Global Search" << endl;
cout << " 1: Original Global Search" << endl;
cout << " 2: No Global Search" << endl;
return false;
}
// Only mono-objective optimization is supported
if (getSampleInd()->getNumberOfObj() != 1){
cout << "Multi-Objective not supported" << endl;
return false;
}
// Parameters initialization
setPopulationSize(atoi(params[0].c_str()));
this->pm = atof(params[1].c_str());
this->pc = atof(params[2].c_str());
this->survivalSelectionType = atof(params[3].c_str());
this->globalSearchType = atof(params[4].c_str());
if ((globalSearchType == GLOBAL_SEARCH_SIMILARITY) || (globalSearchType == GLOBAL_SEARCH_ORIGINAL)) {
globalSearchRequired = true;
}
else if (globalSearchType == GLOBAL_SEARCH_NO) {
globalSearchRequired = false;
}
else {
cerr << "MonoGA_GlobalSearch: globalSearchType not supported" << endl;
exit(-1);
}
maxVarValues = 1000;
varThreshold = 0.4;
maxMeanDCN = DBL_MIN;
maxMeanPairwise = DBL_MIN;
return true;
}
void MonoGA_GlobalSearch::fillPopWithOppositionBasedLearning() {
// Generates a total number of individuals equal to (getPopulationSize() - population->size()) * 2
vector<Individual *> genPopulation;
for (int i = 0; i < (getPopulationSize() - population->size()); i++) {
Individual *ind = getSampleInd()->internalClone();
Individual *opp_ind = getSampleInd()->internalClone();
for (int j = 0; j < ind->getNumberOfVar(); j++) {
// Generates a random population
//double aux = (double) generator() / (double) generator.max();
double aux = ((double) rand () / (double) RAND_MAX);
ind->setVar(j, aux * (ind->getMaximum(j) - ind->getMinimum(j)) + ind->getMinimum(j));
// Generates the oppositional population
opp_ind->setVar(j, opp_ind->getMinimum(j) + opp_ind->getMaximum(j) - ind->getVar(j));
}
evaluate(ind);
evaluate(opp_ind);
genPopulation.push_back(ind);
genPopulation.push_back(opp_ind);
}
sort(genPopulation.begin(), genPopulation.end(), sortByObj0);
for (int i = 0; i < genPopulation.size() / 2; i++) {
population->push_back(genPopulation[i]);
delete genPopulation[genPopulation.size() - 1 - i];
}
genPopulation.clear();
}
void MonoGA_GlobalSearch::fillPopWithNewIndsAndEvaluate() {
fillPopWithOppositionBasedLearning();
}
void MonoGA_GlobalSearch::evaluateOffspring(){
for (int i = 0; i < offSpring.size(); i++){
evaluate(offSpring[i]);
}
}
// MonoGA generation
void MonoGA_GlobalSearch::runGeneration() {
sortPopulation();//Se ordena cada vez porque el paralelo podria desordenarlo TODO: ordenar solo 1 vez
createOffSprings();
evaluateOffspring();
survivalSelection();
if (globalSearchRequired) {
globalSearch();
}
//NelderMeadNoShrink();
// Calculates different diversity metrics at each generation
/*if (getGeneration() % 1000 == 0) {
cout << "Generation: " << getGeneration() << ", ";
cout << "Number of evaluations: " << getPerformedEvaluations() << ", ";
cout << "Normalised Mean DCN: " << getNormalisedMeanDistanceToClosestNeighbour() << ", ";
cout << "Normalised Mean Pairwise: " << getNormalisedMeanPairwiseDistanceAllIndividuals() << endl;
}*/
}
void MonoGA_GlobalSearch::sortPopulation(){
sort(population->begin(), population->end(), sortByObj0);
}
bool MonoGA_GlobalSearch::sortByDistanceToBest(const Individual *i1, const Individual *i2, const Individual *best) {
return (i1->getEuclideanDistanceDecisionSpace(best) < i2->getEuclideanDistanceDecisionSpace(best));
}
bool MonoGA_GlobalSearch::sortByDistanceToBestReversed(const Individual *i1, const Individual *i2, const Individual *best) {
return (i1->getEuclideanDistanceDecisionSpace(best) > i2->getEuclideanDistanceDecisionSpace(best));
}
void MonoGA_GlobalSearch::binaryTournamentSelection(int &p1, int &p2){//Supone que population esta ordenada
int opt1 = (int) (((double)(getPopulationSize()))*rand()/(RAND_MAX+1.0));
int opt2 = (int) (((double)(getPopulationSize()))*rand()/(RAND_MAX+1.0));
p1 = min(opt1, opt2);
opt1 = (int) (((double)(getPopulationSize()))*rand()/(RAND_MAX+1.0));
opt2 = (int) (((double)(getPopulationSize()))*rand()/(RAND_MAX+1.0));
p2 = min(opt1, opt2);
}
void MonoGA_GlobalSearch::parentSelection(int &p1, int &p2){
binaryTournamentSelection(p1, p2);
}
void MonoGA_GlobalSearch::createOffSpring(){//Crear 2 hijos
int p1, p2;
parentSelection(p1, p2);
Individual *of1 = (*population)[p1]->internalClone();
Individual *of2 = (*population)[p2]->internalClone();
double vcross = rand() / (RAND_MAX + 1.0);
if (vcross < pc) {
of1->crossover(of2);
}
of1->mutation(pm);
of2->mutation(pm);
offSpring.push_back(of1);
offSpring.push_back(of2);
}
void MonoGA_GlobalSearch::createOffSprings(){
offSpring.clear();
if (survivalSelectionType == SURVIVAL_SELECTION_SS){//Crear un unico hijo
createOffSpring();
delete(offSpring[1]);
offSpring.pop_back();
} else if ((survivalSelectionType == SURVIVAL_SELECTION_GENERATIONAL) || (survivalSelectionType == SURVIVAL_SELECTION_REPLACEWORST_FROMPARENTANDOFFSPRING)){
if (survivalSelectionType == SURVIVAL_SELECTION_GENERATIONAL){//Elitism
offSpring.push_back((*population)[0]->internalClone());
}
while(offSpring.size() < getPopulationSize()){
createOffSpring();
}
}
if (offSpring.size() > getPopulationSize()){
delete(offSpring[offSpring.size()-1]);
offSpring.pop_back();
}
}
void MonoGA_GlobalSearch::survivalSelection(){
if (survivalSelectionType == SURVIVAL_SELECTION_SS){
if ((*population)[0]->getInternalOptDirection(0) == MINIMIZE){
if ((*population)[getPopulationSize() - 1]->getObj(0) > offSpring[0]->getObj(0)){
delete (*population)[getPopulationSize() - 1];
(*population)[getPopulationSize() - 1] = offSpring[0];//Ojo: Queda desornado
} else {
delete offSpring[0];
}
} else {//Maximizar
if ((*population)[getPopulationSize() - 1]->getObj(0) < offSpring[0]->getObj(0)){
delete (*population)[getPopulationSize() - 1];
(*population)[getPopulationSize() - 1] = offSpring[0];//Ojo: Queda desornado
} else {
delete offSpring[0];
}
}
} else if (survivalSelectionType == SURVIVAL_SELECTION_GENERATIONAL){
for (int i = 0; i < getPopulationSize(); i++){
delete (*population)[i];
(*population)[i] = offSpring[i];
}
} else if (survivalSelectionType == SURVIVAL_SELECTION_REPLACEWORST_FROMPARENTANDOFFSPRING){
//Nota este replace worst no es el que esta explicado en el libro de Eiben
//Aqui nos estamos "cargando" los peores entre padres e hijos
//En el libro de Eiben dice que se generan nu hijos (< n) y se borran los nu peores
//padres.
//Habria que hacer otro operador mas y a este llamarlo RPELACEWORSTFROMPARENTSANDOFFSPRING
//Al otro lo podemos llamar GENITOR
//Nota: en la pagina 27 si llama replace worst a un esquema en que se eligen los mejores entre
//padres e hijos, pero puede llevar a confusion...
for (int i = 0; i < offSpring.size(); i++){
population->push_back(offSpring[i]);
}
sortPopulation();
for (int i = 0; i < offSpring.size(); i++){
delete ((*population)[population->size()-1]);
population->pop_back();
}
}
}
void MonoGA_GlobalSearch::getSolution(MOFront *p) {
sortPopulation();
p->insert((*population)[0]);
}
void MonoGA_GlobalSearch::printInfo(ostream &os) const {
os << "MonoObjective Genetic Algorithm" << endl;
os << "Number of Evaluations = " << getEvaluations() << endl;
os << "Mutation Probability = " << pm << endl;
os << "Crossover Probability = " << pc << endl;
os << "Population Size = " << getPopulationSize() << endl;
os << "Survival Selection Type = " << survivalSelectionType << endl;
os << "Global Search Type = " << globalSearchType << endl;
}
void MonoGA_GlobalSearch::globalSearch() {
if (globalSearchType == GLOBAL_SEARCH_SIMILARITY) {
GlobalSearchGlobalNeighbourhood12();
}
else if (globalSearchType == GLOBAL_SEARCH_ORIGINAL) {
GlobalSearchGlobalNeighbourhood();
}
}
// Implementation of the original proposal
void MonoGA_GlobalSearch::GlobalSearchGlobalNeighbourhood() {
// Three random numbers (a1, a2, a3) belonging to the range [0, 1] are obtained
// The condition a1 + a2 + a3 == 1 must be satisfied
double a1, a2, a3;
do {
a1 = ((double) rand () / (double) RAND_MAX);
a2 = ((double) rand () / (double) RAND_MAX);
a3 = 1.0 - a1 - a2;
} while (abs(a1) + abs(a2) + abs(a3) != 1.0);
// Randomly selects three mutually exclusive integers belonging to
// the set {0, 1, ..., NP - 1}
int k, r1, r2;
k = getRandomInteger0_N(getPopulationSize() - 1);
do {
r1 = getRandomInteger0_N(getPopulationSize() - 1);
} while (r1 == k);
do {
r2 = getRandomInteger0_N(getPopulationSize() - 1);
} while ((r2 == r1) || (r2 == k));
// Determines the best individual in the population
Individual *best = (*population)[0];
for (int i = 1; i < getPopulationSize(); i++) {
if ((((*population)[i]->getOptDirection(0) == MINIMIZE) && ((*population)[i]->getObj(0) < best->getObj(0))) ||
(((*population)[i]->getOptDirection(0) == MAXIMIZE) && ((*population)[i]->getObj(0) > best->getObj(0)))) {
best = (*population)[i];
}
}
// Applies global neighbourhood search strategy
Individual *v = getSampleInd()->internalClone();
for (int i = 0; i < v->getNumberOfVar(); i++) {
v->setVar(i, a1 * (*population)[k]->getVar(i) + a2 * best->getVar(i) + a3 * ((*population)[r1]->getVar(i) - (*population)[r2]->getVar(i)));
// Checks lower and upper limits of variables
if ((v->getVar(i) < v->getMinimum(i)) || (v->getVar(i) > v->getMaximum(i))) {
double r = ((double) rand () / (double) RAND_MAX);
v->setVar(i, r * (v->getMaximum(i) - v->getMinimum(i)) + v->getMinimum(i));
}
v->setVar(i, max(v->getVar(i), v->getMinimum(i)));
v->setVar(i, min(v->getVar(i), v->getMaximum(i)));
}
// Evaluates the new individual
evaluate(v);
// Selects the best individual between v and k
if (((v->getOptDirection(0) == MINIMIZE) && (v->getObj(0) < (*population)[k]->getObj(0))) ||
((v->getOptDirection(0) == MAXIMIZE) && (v->getObj(0) > (*population)[k]->getObj(0)))) {
delete (*population)[k];
(*population)[k] = v;
} else {
delete v;
}
}
void MonoGA_GlobalSearch::globalNeighbourhoodPathSearch() {
sortPopulation();
vector<bool> explored (getPopulationSize(), false);
int numberImp;
int numberExp = 0;
do {
bool improvement = false;
numberImp = 0;
int k;
do {
k = getRandomInteger0_N(getPopulationSize() - 1);
} while (explored[k]);
explored[k] = true;
numberExp++;
do {
// Three random numbers (a1, a2, a3) belonging to the range [0, 1] are obtained
// The condition a1 + a2 + a3 == 1 must be satisfied
double a1, a2, a3;
do {
a1 = ((double) rand () / (double) RAND_MAX);
a2 = ((double) rand () / (double) RAND_MAX);
a3 = 1.0 - a1 - a2;
} while (abs(a1) + abs(a2) + abs(a3) != 1.0);
int r1, r2;
do {
r1 = getRandomInteger0_N(getPopulationSize() - 1);
} while (r1 == k);
do {
r2 = getRandomInteger0_N(getPopulationSize() - 1);
} while ((r2 == r1) || (r2 == k));
// Applies global neighbourhood search strategy
Individual *v = getSampleInd()->internalClone();
for (int i = 0; i < v->getNumberOfVar(); i++) {
v->setVar(i, a1 * (*population)[k]->getVar(i) + a2 * (*population)[0]->getVar(i) + a3 * ((*population)[r1]->getVar(i) - (*population)[r2]->getVar(i)));
// Checks lower and upper limits of variables
if ((v->getVar(i) < v->getMinimum(i)) || (v->getVar(i) > v->getMaximum(i))) {
double r = ((double) rand () / (double) RAND_MAX);
v->setVar(i, r * (v->getMaximum(i) - v->getMinimum(i)) + v->getMinimum(i));
}
v->setVar(i, max(v->getVar(i), v->getMinimum(i)));
v->setVar(i, min(v->getVar(i), v->getMaximum(i)));
}
// Evaluates the new individual
evaluate(v);
// Selects the best individual between v and k
if (((v->getOptDirection(0) == MINIMIZE) && (v->getObj(0) < (*population)[k]->getObj(0))) || ((v->getOptDirection(0) == MAXIMIZE) && (v->getObj(0) > (*population)[k]->getObj(0)))) {
//delete (*population)[k];
population->push_back((*population)[k]);
(*population)[k] = v;
improvement = true;
numberImp++;
} else {
delete v;
improvement = false;
}
} while (improvement);
} while ((numberImp > 0) && (numberExp < getPopulationSize()));
// Selects the best individuals from the current population and the global neighbourhood path
sortPopulation();
for (int i = 0; i < (population->size() - getPopulationSize()); i++) {
delete (*population)[population->size() - 1];
population->pop_back();
}
}
void MonoGA_GlobalSearch::GlobalSearchGlobalNeighbourhood3_2() {
sortPopulation();
Individual *best = (*population)[0];
vector<bool> explored (getPopulationSize(), false);
int numberImp;
int numberExp = 0;
for (int i = 0; i < getPopulationSize(); i++)
explored[i] = false;
do {
bool improvement = false;
numberImp = 0;
int k;
do {
k = getRandomInteger0_N(getPopulationSize() - 1);
} while (explored[k]);
explored[k] = true;
numberExp++;
do {
// Three random numbers (a1, a2, a3) belonging to the range [0, 1] are obtained
// The condition a1 + a2 + a3 == 1 must be satisfied
double a1, a2, a3;
do {
a1 = ((double) rand () / (double) RAND_MAX);
a2 = ((double) rand () / (double) RAND_MAX);
a3 = 1.0 - a1 - a2;
} while (abs(a1) + abs(a2) + abs(a3) != 1.0);
int r1, r2;
do {
r1 = getRandomInteger0_N(getPopulationSize() - 1);
} while (r1 == k);
do {
r2 = getRandomInteger0_N(getPopulationSize() - 1);
} while ((r2 == r1) || (r2 == k));
// Applies global neighbourhood search strategy
Individual *v = getSampleInd()->internalClone();
for (int i = 0; i < v->getNumberOfVar(); i++) {
v->setVar(i, a1 * (*population)[k]->getVar(i) + a2 * best->getVar(i) + a3 * ((*population)[r1]->getVar(i) - (*population)[r2]->getVar(i)));
// Checks lower and upper limits of variables
if ((v->getVar(i) < v->getMinimum(i)) || (v->getVar(i) > v->getMaximum(i))) {
double r = ((double) rand () / (double) RAND_MAX);
v->setVar(i, r * (v->getMaximum(i) - v->getMinimum(i)) + v->getMinimum(i));
}
v->setVar(i, max(v->getVar(i), v->getMinimum(i)));
v->setVar(i, min(v->getVar(i), v->getMaximum(i)));
}
// Evaluates the new individual
evaluate(v);
// Selects the best individual between v and k
if (((v->getOptDirection(0) == MINIMIZE) && (v->getObj(0) < (*population)[k]->getObj(0))) || ((v->getOptDirection(0) == MAXIMIZE) && (v->getObj(0) > (*population)[k]->getObj(0)))) {
//delete (*population)[k];
population->push_back((*population)[k]);
(*population)[k] = v;
improvement = true;
numberImp++;
// Checks if the new individual v is the best one
if ((v->getOptDirection(0) == MINIMIZE) && (v->getObj(0) < best->getObj(0)))
best = v;
else if ((v->getOptDirection(0) == MAXIMIZE) && (v->getObj(0) > best->getObj(0)))
best = v;
} else {
delete v;
improvement = false;
}
} while (improvement);
} while ((numberImp > 0) && (numberExp < getPopulationSize()));
// Selects the best individuals from the current population and the global neighbourhood path
sortPopulation();
for (int i = 0; i < (population->size() - getPopulationSize()); i++) {
delete (*population)[population->size() - 1];
population->pop_back();
}
}
void MonoGA_GlobalSearch::GlobalSearchGlobalNeighbourhood6() {
sortPopulation();
vector<bool> explored (getPopulationSize(), false);
int numberImp;
int numberExp = 0;
for (int i = 0; i < getPopulationSize(); i++)
explored[i] = false;
// Calculates the centroid of the current population
Individual *c = getSampleInd()->internalClone();
for (int i = 0; i < c->getNumberOfVar(); i++) {
double sum = 0;
for (int j = 0; j < getPopulationSize(); j++) {
sum += (*population)[j]->getVar(i);
}
c->setVar(i, sum / getPopulationSize());
}
do {
bool improvement = false;
numberImp = 0;
int k;
do {
k = getRandomInteger0_N(getPopulationSize() - 1);
} while (explored[k]);
explored[k] = true;
numberExp++;
do {
// Three random numbers (a1, a2, a3) belonging to the range [0, 1] are obtained
// The condition a1 + a2 + a3 == 1 must be satisfied
double a1, a2, a3;
do {
a1 = ((double) rand () / (double) RAND_MAX);
a2 = ((double) rand () / (double) RAND_MAX);
a3 = 1.0 - a1 - a2;
} while (abs(a1) + abs(a2) + abs(a3) != 1.0);
int r1;
do {
r1 = getRandomInteger0_N(getPopulationSize() - 1);
} while (r1 == k);
/*do {
r2 = getRandomInteger0_N(getPopulationSize() - 1);
} while ((r2 == r1) || (r2 == k));*/
// Applies global neighbourhood search strategy considering the centroid of the population
Individual *v = getSampleInd()->internalClone();
for (int i = 0; i < v->getNumberOfVar(); i++) {
v->setVar(i, a1 * (*population)[k]->getVar(i) + a2 * c->getVar(i) + a3 * ((*population)[0]->getVar(i) - (*population)[r1]->getVar(i)));
// Checks lower and upper limits of variables
if ((v->getVar(i) < v->getMinimum(i)) || (v->getVar(i) > v->getMaximum(i))) {
double r = ((double) rand () / (double) RAND_MAX);
v->setVar(i, r * (v->getMaximum(i) - v->getMinimum(i)) + v->getMinimum(i));
}
v->setVar(i, max(v->getVar(i), v->getMinimum(i)));
v->setVar(i, min(v->getVar(i), v->getMaximum(i)));
}
// Evaluates the new individual
evaluate(v);
// Selects the best individual between v and k
if (((v->getOptDirection(0) == MINIMIZE) && (v->getObj(0) < (*population)[k]->getObj(0))) || ((v->getOptDirection(0) == MAXIMIZE) && (v->getObj(0) > (*population)[k]->getObj(0)))) {
//delete (*population)[k];
population->push_back((*population)[k]);
(*population)[k] = v;
improvement = true;
numberImp++;
} else {
delete v;
improvement = false;
}
} while (improvement);
} while ((numberImp > 0) && (numberExp < getPopulationSize()));
// Selects the best individuals from the current population and the global neighbourhood path
sortPopulation();
for (int i = 0; i < (population->size() - getPopulationSize()); i++) {
delete (*population)[population->size() - 1];
population->pop_back();
}
}
void MonoGA_GlobalSearch::GlobalSearchGlobalNeighbourhood6_2() {
sortPopulation();
Individual *best = (*population)[0];
vector<bool> explored (getPopulationSize(), false);
int numberImp;
int numberExp = 0;
for (int i = 0; i < getPopulationSize(); i++)
explored[i] = false;
// Calculates the centroid of the current population
Individual *c = getSampleInd()->internalClone();
for (int i = 0; i < c->getNumberOfVar(); i++) {
double sum = 0;
for (int j = 0; j < getPopulationSize(); j++) {
sum += (*population)[j]->getVar(i);
}
c->setVar(i, sum / getPopulationSize());
}
do {
bool improvement = false;
numberImp = 0;
int k;
do {
k = getRandomInteger0_N(getPopulationSize() - 1);
} while (explored[k]);
explored[k] = true;
numberExp++;
do {
// Three random numbers (a1, a2, a3) belonging to the range [0, 1] are obtained
// The condition a1 + a2 + a3 == 1 must be satisfied
double a1, a2, a3;
do {
a1 = ((double) rand () / (double) RAND_MAX);
a2 = ((double) rand () / (double) RAND_MAX);
a3 = 1.0 - a1 - a2;
} while (abs(a1) + abs(a2) + abs(a3) != 1.0);
int r1;
do {
r1 = getRandomInteger0_N(getPopulationSize() - 1);
} while (r1 == k);
/*do {
r2 = getRandomInteger0_N(getPopulationSize() - 1);
} while ((r2 == r1) || (r2 == k));*/
// Applies global neighbourhood search strategy considering the centroid of the population
Individual *v = getSampleInd()->internalClone();
for (int i = 0; i < v->getNumberOfVar(); i++) {
v->setVar(i, a1 * (*population)[k]->getVar(i) + a2 * c->getVar(i) + a3 * (best->getVar(i) - (*population)[r1]->getVar(i)));
// Checks lower and upper limits of variables
if ((v->getVar(i) < v->getMinimum(i)) || (v->getVar(i) > v->getMaximum(i))) {
double r = ((double) rand () / (double) RAND_MAX);
v->setVar(i, r * (v->getMaximum(i) - v->getMinimum(i)) + v->getMinimum(i));
}
v->setVar(i, max(v->getVar(i), v->getMinimum(i)));
v->setVar(i, min(v->getVar(i), v->getMaximum(i)));
}
// Evaluates the new individual
evaluate(v);
// Selects the best individual between v and k
if (((v->getOptDirection(0) == MINIMIZE) && (v->getObj(0) < (*population)[k]->getObj(0))) || ((v->getOptDirection(0) == MAXIMIZE) && (v->getObj(0) > (*population)[k]->getObj(0)))) {
//delete (*population)[k];
population->push_back((*population)[k]);
(*population)[k] = v;
improvement = true;
numberImp++;
// Checks if the new individual v is the best one
if ((v->getOptDirection(0) == MINIMIZE) && (v->getObj(0) < best->getObj(0)))
best = v;
else if ((v->getOptDirection(0) == MAXIMIZE) && (v->getObj(0) > best->getObj(0)))
best = v;
} else {
delete v;
improvement = false;
}
} while (improvement);
} while ((numberImp > 0) && (numberExp < getPopulationSize()));
// Selects the best individuals from the current population and the global neighbourhood path
sortPopulation();
for (int i = 0; i < (population->size() - getPopulationSize()); i++) {
delete (*population)[population->size() - 1];
population->pop_back();
}
}
void MonoGA_GlobalSearch::GlobalSearchGlobalNeighbourhood8() {
// Three random numbers (a1, a2, a3) belonging to the range [0, 1] are obtained
// The condition a1 + a2 + a3 == 1 must be satisfied
double a1, a2, a3;
do {
a1 = ((double) rand () / (double) RAND_MAX);
a2 = ((double) rand () / (double) RAND_MAX);
a3 = 1.0 - a1 - a2;
} while (abs(a1) + abs(a2) + abs(a3) != 1.0);
bool improvement = false;
int k;
k = getRandomInteger0_N(getPopulationSize() - 1);
// Calculate the number of elegible individuals for r1 and r2 depending on the
// current moment of the search (given by the number of evaluations performed)
int min_pop = max((int)(round(getPopulationSize() * 0.1)), 4);
int max_pop = getPopulationSize();
double m = (double)(min_pop - max_pop) / (double)getEvaluations();
int y = (int)(round(m * getPerformedEvaluations() + max_pop));
do {
// Determines the best individual in the population
Individual *best = (*population)[0];
for (int i = 1; i < getPopulationSize(); i++) {
if ((((*population)[i]->getOptDirection(0) == MINIMIZE) && ((*population)[i]->getObj(0) < best->getObj(0))) ||
(((*population)[i]->getOptDirection(0) == MAXIMIZE) && ((*population)[i]->getObj(0) > best->getObj(0)))) {
best = (*population)[i];
}
}
// Sort the population in ascending order in terms of the distance with respect to
// the fittest individual
sort(population->begin(), population->end(), bind(&MonoGA_GlobalSearch::sortByDistanceToBest, this, std::placeholders::_1, std::placeholders::_2, best));
int r1, r2;
do {
r1 = getRandomInteger0_N(y - 1);
} while (r1 == k);
do {
r2 = getRandomInteger0_N(y - 1);
} while ((r2 == r1) || (r2 == k));
// Applies global neighbourhood search strategy
Individual *v = getSampleInd()->internalClone();
for (int i = 0; i < v->getNumberOfVar(); i++) {
v->setVar(i, a1 * (*population)[k]->getVar(i) + a2 * best->getVar(i) + a3 * ((*population)[r1]->getVar(i) - (*population)[r2]->getVar(i)));
// Checks lower and upper limits of variables
if ((v->getVar(i) < v->getMinimum(i)) || (v->getVar(i) > v->getMaximum(i))) {
double r = ((double) rand () / (double) RAND_MAX);
v->setVar(i, r * (v->getMaximum(i) - v->getMinimum(i)) + v->getMinimum(i));
}
v->setVar(i, max(v->getVar(i), v->getMinimum(i)));
v->setVar(i, min(v->getVar(i), v->getMaximum(i)));
}
// Evaluates the new individual
evaluate(v);
// Selects the best individual between v and k
if (((v->getOptDirection(0) == MINIMIZE) && (v->getObj(0) < (*population)[k]->getObj(0))) ||
((v->getOptDirection(0) == MAXIMIZE) && (v->getObj(0) > (*population)[k]->getObj(0)))) {
delete (*population)[k];
(*population)[k] = v;
improvement = true;
} else {
delete v;
improvement = false;
}
} while (improvement);
}
void MonoGA_GlobalSearch::GlobalSearchGlobalNeighbourhood9() {
// Three random numbers (a1, a2, a3) belonging to the range [0, 1] are obtained
// The condition a1 + a2 + a3 == 1 must be satisfied
double a1, a2, a3;
do {
a1 = ((double) rand () / (double) RAND_MAX);
a2 = ((double) rand () / (double) RAND_MAX);
a3 = 1.0 - a1 - a2;
} while (abs(a1) + abs(a2) + abs(a3) != 1.0);
bool improvement = false;
int k;
k = getRandomInteger0_N(getPopulationSize() - 1);
// Calculate the number of elegible individuals for r1 and r2 depending on the
// current moment of the search (given by the number of evaluations performed)
int min_pop = max((int)(round(getPopulationSize() * 0.1)), 4);
int max_pop = getPopulationSize();
double m = (double)(max_pop - min_pop) / (double)getEvaluations();
int y = (int)(round(m * getPerformedEvaluations() + min_pop));
do {
// Determines the best individual in the population
Individual *best = (*population)[0];
for (int i = 1; i < getPopulationSize(); i++) {
if ((((*population)[i]->getOptDirection(0) == MINIMIZE) && ((*population)[i]->getObj(0) < best->getObj(0))) ||
(((*population)[i]->getOptDirection(0) == MAXIMIZE) && ((*population)[i]->getObj(0) > best->getObj(0)))) {
best = (*population)[i];
}
}
// Sort the population in ascending order in terms of the distance with respect to
// the fittest individual
sort(population->begin(), population->end(), bind(&MonoGA_GlobalSearch::sortByDistanceToBest, this, std::placeholders::_1, std::placeholders::_2, best));
int r1, r2;
do {
r1 = getRandomInteger0_N(y - 1);
} while (r1 == k);
do {
r2 = getRandomInteger0_N(y - 1);
} while ((r2 == r1) || (r2 == k));
// Applies global neighbourhood search strategy
Individual *v = getSampleInd()->internalClone();
for (int i = 0; i < v->getNumberOfVar(); i++) {
v->setVar(i, a1 * (*population)[k]->getVar(i) + a2 * best->getVar(i) + a3 * ((*population)[r1]->getVar(i) - (*population)[r2]->getVar(i)));
// Checks lower and upper limits of variables
if ((v->getVar(i) < v->getMinimum(i)) || (v->getVar(i) > v->getMaximum(i))) {
double r = ((double) rand () / (double) RAND_MAX);
v->setVar(i, r * (v->getMaximum(i) - v->getMinimum(i)) + v->getMinimum(i));
}
v->setVar(i, max(v->getVar(i), v->getMinimum(i)));
v->setVar(i, min(v->getVar(i), v->getMaximum(i)));
}
// Evaluates the new individual
evaluate(v);
// Selects the best individual between v and k
if (((v->getOptDirection(0) == MINIMIZE) && (v->getObj(0) < (*population)[k]->getObj(0))) ||
((v->getOptDirection(0) == MAXIMIZE) && (v->getObj(0) > (*population)[k]->getObj(0)))) {
delete (*population)[k];
(*population)[k] = v;
improvement = true;
} else {
delete v;
improvement = false;
}
} while (improvement);
}
void MonoGA_GlobalSearch::GlobalSearchGlobalNeighbourhood10() {
// Three random numbers (a1, a2, a3) belonging to the range [0, 1] are obtained
// The condition a1 + a2 + a3 == 1 must be satisfied
double a1, a2, a3;
do {
a1 = ((double) rand () / (double) RAND_MAX);
a2 = ((double) rand () / (double) RAND_MAX);
a3 = 1.0 - a1 - a2;
} while (abs(a1) + abs(a2) + abs(a3) != 1.0);
bool improvement = false;
int k;
k = getRandomInteger0_N(getPopulationSize() - 1);
do {
// Calculates the mean value of each decision variable of the current population
vector<double> means((*population)[0]->getNumberOfVar(), 0);
for (int i = 0; i < (*population)[0]->getNumberOfVar(); i++) {
double sum = 0;
for (int j = 0; j < getPopulationSize(); j++) {
sum += (*population)[j]->getVar(i);
}
means[i] = sum / getPopulationSize();
}
// Calculates the diversity of the current population
double var = 0;
for (int i = 0; i < getPopulationSize(); i++) {
double sum = 0;
for (int j = 0; j < (*population)[0]->getNumberOfVar(); j++) {
double aux = (*population)[i]->getVar(j) - means[j];
sum += (aux * aux);
}
var += sqrt(sum);
}
var /= getPopulationSize();
//cout << "var (no norm): " << var << endl;
// Inserts the new variance value into the variance value vector
if (varValues.size() < maxVarValues) {
varValues.push_back(var);
}
else {
varValues.erase(varValues.begin());
varValues.push_back(var);
}
// Normalises the value of the variance taking into account the
// different values of the variance value vector
double maxVar = DBL_MIN;
for (int i = 0; i < varValues.size(); i++) {
if (varValues[i] > maxVar) {
maxVar = varValues[i];
}
}
var /= maxVar;
//cout << "var (norm): " << var << endl;
//cout << "varThreshold: " << varThreshold << endl;
// Determines the best individual in the population
Individual *best = (*population)[0];
for (int i = 1; i < getPopulationSize(); i++) {
if ((((*population)[i]->getOptDirection(0) == MINIMIZE) && ((*population)[i]->getObj(0) < best->getObj(0))) ||
(((*population)[i]->getOptDirection(0) == MAXIMIZE) && ((*population)[i]->getObj(0) > best->getObj(0)))) {
best = (*population)[i];
}
}
// Sort the population in ascending order in terms of the distance with respect to
// the fittest individual
sort(population->begin(), population->end(), bind(&MonoGA_GlobalSearch::sortByDistanceToBest, this, std::placeholders::_1, std::placeholders::_2, best));
// Calculate the range of elegible individuals for r1 and r2 depending on the
// current moment of the search (given by the variance of the population)
int minRange, maxRange;
int minPop = max((int)(round(getPopulationSize() * 0.1)), 4);
// We should promote exploitation
if (var >= varThreshold) {
minRange = 0;
maxRange = max((int)(round((1 - var) * getPopulationSize()) - 1), minPop - 1);
}
// we should promote diversification
else {
minRange = min((int)(round((1 - var) * getPopulationSize()) - 1), getPopulationSize() - minPop - 1);
maxRange = getPopulationSize() - 1;
}
//cout << "minRange: " << minRange << endl;
//cout << "maxRange: " << maxRange << endl;
int r1, r2;
do {
r1 = generateRandom(minRange, maxRange);
} while (r1 == k);
do {
r2 = generateRandom(minRange, maxRange);
} while ((r2 == r1) || (r2 == k));
//cout << "r1: " << r1 << endl;
//cout << "r2: " << r2 << endl;
// Applies global neighbourhood search strategy
Individual *v = getSampleInd()->internalClone();
for (int i = 0; i < v->getNumberOfVar(); i++) {
v->setVar(i, a1 * (*population)[k]->getVar(i) + a2 * best->getVar(i) + a3 * ((*population)[r1]->getVar(i) - (*population)[r2]->getVar(i)));
// Checks lower and upper limits of variables
if ((v->getVar(i) < v->getMinimum(i)) || (v->getVar(i) > v->getMaximum(i))) {
double r = ((double) rand () / (double) RAND_MAX);
v->setVar(i, r * (v->getMaximum(i) - v->getMinimum(i)) + v->getMinimum(i));
}
v->setVar(i, max(v->getVar(i), v->getMinimum(i)));
v->setVar(i, min(v->getVar(i), v->getMaximum(i)));
}
// Evaluates the new individual
evaluate(v);
// Selects the best individual between v and k
if (((v->getOptDirection(0) == MINIMIZE) && (v->getObj(0) < (*population)[k]->getObj(0))) ||
((v->getOptDirection(0) == MAXIMIZE) && (v->getObj(0) > (*population)[k]->getObj(0)))) {
delete (*population)[k];
(*population)[k] = v;
improvement = true;
} else {
delete v;
improvement = false;
}
} while (improvement);
}
void MonoGA_GlobalSearch::GlobalSearchGlobalNeighbourhood12() {
// Three random numbers (a1, a2, a3) belonging to the range [0, 1] are obtained
// The condition a1 + a2 + a3 == 1 must be satisfied
double a1, a2, a3;
/*do {
a1 = ((double) rand () / (double) RAND_MAX);
a2 = ((double) rand () / (double) RAND_MAX);
a3 = 1.0 - a1 - a2;
} while (abs(a1) + abs(a2) + abs(a3) != 1.0);*/
a1 = ((double) rand () / (double) RAND_MAX);
a2 = 1.0 - a1;
//a1 = ((double) getPerformedEvaluations() / (double) getEvaluations());
//a2 = 1.0 - a1;
//cout << "a1: " << a1 << ", a2: " << a2 << ", a3: " << a3 << endl;
int k = getRandomInteger0_N(getPopulationSize() - 1);
// Calculate the number of elegible individuals for r1 depending on the
// current moment of the search (given by the number of evaluations performed)
int min_pop = max((int)(round(getPopulationSize() * 0.1)), 5) - 1;
int max_pop = getPopulationSize() - 1;
double m = (double)(max_pop - min_pop) / (double)getEvaluations();
int upper = (int)(round(m * getPerformedEvaluations() + min_pop));
int lower = upper - min_pop;
//cout << "lower: " << lower << ", upper: " << upper << endl;
// Determines the best individual in the population
Individual *best = (*population)[0];
for (int i = 1; i < getPopulationSize(); i++) {
if ((((*population)[i]->getOptDirection(0) == MINIMIZE) && ((*population)[i]->getObj(0) < best->getObj(0))) ||
(((*population)[i]->getOptDirection(0) == MAXIMIZE) && ((*population)[i]->getObj(0) > best->getObj(0)))) {
best = (*population)[i];
}
}
// Sorts the population in descending order in terms of the Euclidean distance in the decision space
// with respect to the fittest individual
sort(population->begin(), population->end(), bind(&MonoGA_GlobalSearch::sortByDistanceToBestReversed, this, std::placeholders::_1, std::placeholders::_2, best));
//for (int i = 0; i < getPopulationSize(); i++)
// cout << "i: " << i << " Fitness: " << (*population)[i]->getObj(0) << " Distance to best: " << getEuclideanDistance(best, (*population)[i]) << endl;
int r1, r2;
do {
//r1 = getRandomInteger0_N(upper - 1);
r1 = generateRandom(lower, upper);
} while (r1 == k);
/*do {
r2 = generateRandom(lower, upper);
} while ((r2 == r1) || (r2 == k));*/
//cout << "k: " << k << ", r1: " << r1 << ", r2: " << r2 << endl;
// Applies global neighbourhood search strategy
Individual *v = getSampleInd()->internalClone();
for (int i = 0; i < v->getNumberOfVar(); i++) {
//v->setVar(i, (*population)[k]->getVar(i) + a1 * ((*population)[r1]->getVar(i) - (*population)[k]->getVar(i)));
v->setVar(i, (*population)[k]->getVar(i) + a1 * (best->getVar(i) - (*population)[k]->getVar(i)) + a2 * ((*population)[r1]->getVar(i) - (*population)[k]->getVar(i)));
//v->setVar(i, a1 * (*population)[k]->getVar(i) + a2 * best->getVar(i) + a3 * ((*population)[r1]->getVar(i) - (*population)[r2]->getVar(i)));
// Checks lower and upper limits of variables
if ((v->getVar(i) < v->getMinimum(i)) || (v->getVar(i) > v->getMaximum(i))) {
double r = ((double) rand () / (double) RAND_MAX);
v->setVar(i, r * (v->getMaximum(i) - v->getMinimum(i)) + v->getMinimum(i));
}
v->setVar(i, max(v->getVar(i), v->getMinimum(i)));
v->setVar(i, min(v->getVar(i), v->getMaximum(i)));
}
// Evaluates the new individual
evaluate(v);
//cout << "Fitness del nuevo individuo generado: " << v->getObj(0) << " Distancia al mejor: " << getEuclideanDistance(best, v) << endl;
// 1. Looks for the best individual's closest neighbour in order to replace it by the novel individual
/*int index_closest = getPopulationSize() - 1;
while ((getEuclideanDistance(best, (*population)[index_closest]) == 0) && (index_closest > 0))
index_closest--;
//cout << "Individuo mas cercano al best: " << index_closest << endl;
delete (*population)[index_closest];
(*population)[index_closest] = v;*/
// 2. Looks for the best individual's most far away neighbour in order to replace it by the novel individual
/*int index_far = 0;
delete (*population)[index_far];
(*population)[index_far] = v;*/
// 3. Selects the best individual between v and k
if (((v->getOptDirection(0) == MINIMIZE) && (v->getObj(0) < (*population)[k]->getObj(0))) ||
((v->getOptDirection(0) == MAXIMIZE) && (v->getObj(0) > (*population)[k]->getObj(0)))) {
delete (*population)[k];
(*population)[k] = v;
} else {
delete v;
}
}
void MonoGA_GlobalSearch::NelderMeadNoShrink() {
int dimension = (*population)[0]->getNumberOfVar() + 1;
vector<Individual *> nelderPop;
if (population->size() >= dimension) {
for (int i = 0; i < dimension; i++) {
Individual* ind = (*population)[i]->internalClone();
nelderPop.push_back(ind);
}
}
else {
for (int i = 0; i < population->size(); i++) {
Individual* ind = (*population)[i]->internalClone();
nelderPop.push_back(ind);
}
for (int i = 0; i < (dimension - population->size()); i++) {
int k = getRandomInteger0_N(population->size() - 1);
Individual *ind = (*population)[k]->internalClone();
nelderPop.push_back(ind);
}
}
bool shrink = false;
while(!shrink)
{
sort(nelderPop.begin(), nelderPop.end(), sortByObj0);
Individual *xc = getSampleInd()->internalClone();
for (int i = 0; i < xc->getNumberOfVar(); i++) {
double sum = 0;
for (int j = 0; j < dimension - 1; j++) {
sum += nelderPop[j]->getVar(i);
}
xc->setVar(i, sum / (dimension - 1)); //Calculamos el centroide de toda la poblaci\F3n excepto del peor
}
Individual *xr = getSampleInd()->internalClone(); // punto reflejado
for (int i = 0; i < xr->getNumberOfVar(); i++) {
double valorCalculado=xc->getVar(i) + NM1 * (xc->getVar(i) - nelderPop[dimension - 1]->getVar(i));
xr->setVar(i, valorCalculado);
}
evaluate(xr);
if(xr->getObj(0) < nelderPop[0]->getObj(0)) // Si el reflejado mejora la mejor soluci\F3n
{
Individual *xe = getSampleInd()->internalClone(); // punto extendido
for (int i = 0; i < xe->getNumberOfVar(); i++) {
double valorCalculado = xc->getVar(i) + NM2 * (xr->getVar(i) - xc->getVar(i));
xe->setVar(i, valorCalculado);
}
evaluate(xe);
if(xe->getObj(0) < nelderPop[0]->getObj(0))
{
delete nelderPop[dimension - 1];
nelderPop[dimension - 1] = xe; // agregamos el nuevo
}
else
{
delete nelderPop[dimension - 1];
nelderPop[dimension - 1] = xr; // agregamos el nuevo
}
}
else if((xr->getObj(0) >= nelderPop[0]->getObj(0)) && (xr->getObj(0) < nelderPop[dimension-1]->getObj(0)))
{
delete nelderPop[dimension - 1];
nelderPop[dimension - 1] = xr; // agregamos el nuevo
}
else if(xr->getObj(0) >= nelderPop[dimension - 1]->getObj(0))
{
if(xr->getObj(0) < nelderPop[dimension - 1]->getObj(0))
{
Individual *xcf = getSampleInd()->internalClone(); // punto de expansi\F3n
for (int i = 0; i < xcf->getNumberOfVar(); i++) {
double valorCalculado = xc->getVar(i) + NM3 * (xr->getVar(i) - xc->getVar(i));
xcf->setVar(i, valorCalculado);
}
evaluate(xcf);
if(xcf->getObj(0) < nelderPop[0]->getObj(0))
{
delete nelderPop[dimension - 1];
nelderPop[dimension - 1] = xcf; // agregamos el nuevo
}
else
{
shrink = true;
}
}
else
{
Individual *xcd = getSampleInd()->internalClone(); // punto de contracci\F3n
for (int i = 0; i < xcd->getNumberOfVar(); i++) {
double valorCalculado=xc->getVar(i) - NM3*(xc->getVar(i)-nelderPop[dimension - 1]->getVar(i));
xcd->setVar(i, valorCalculado);
}
evaluate(xcd);
if(xcd->getObj(0) < nelderPop[0]->getObj(0))
{
delete nelderPop[dimension - 1];
nelderPop[dimension - 1] = xcd; // agregamos el nuevo
}
else
{
shrink = true;
}
}
}
}
// Replaces the current population with the Nelder population
if (population->size() >= dimension) {
for (int i = 0; i < dimension; i++) {
delete (*population)[i];
(*population)[i] = nelderPop[i];
}
}
else {
for (int i = 0; i < population->size(); i++) {
delete (*population)[i];
(*population)[i] = nelderPop[i];
}
}
}
double MonoGA_GlobalSearch::getEuclideanDistance(Individual *ind1, Individual *ind2) {
double dist = 0.0;
for (int i = 0; i < ind1->getNumberOfVar(); i++) {
dist += ((ind1->getVar(i) - ind2->getVar(i)) * (ind1->getVar(i) - ind2->getVar(i)));
}
return sqrt(dist);
}
double MonoGA_GlobalSearch::getDistanceToClosestNeighbour(Individual *ind) {
double minDist = DBL_MAX;
for (int i = 0; i < getPopulationSize(); i++) {
if (ind != (*population)[i]) {
double dist = getEuclideanDistance(ind, (*population)[i]);
if (dist < minDist)
minDist = dist;
}
}
return minDist;
}
double MonoGA_GlobalSearch::getMeanDistanceToClosestNeighbour() {
double sumDist = 0.0;
for (int i = 0; i < getPopulationSize(); i++) {
sumDist += getDistanceToClosestNeighbour((*population)[i]);
}
double meanDCN = sumDist / (double)getPopulationSize();
if (meanDCN > maxMeanDCN)
maxMeanDCN = meanDCN;
return meanDCN;
}
double MonoGA_GlobalSearch::getNormalisedMeanDistanceToClosestNeighbour() {
return getMeanDistanceToClosestNeighbour() / maxMeanDCN;
}
double MonoGA_GlobalSearch::getMeanPairwiseDistanceAllIndividuals() {
double sumDist = 0.0;
for (int i = 0; i < getPopulationSize(); i++) {
for (int j = i + 1; j < getPopulationSize(); j++) {
sumDist += getEuclideanDistance((*population)[i], (*population)[j]);
}
}
double meanPairwise = sumDist / (double)(getPopulationSize() * (getPopulationSize() - 1) / 2.0);
if (meanPairwise > maxMeanPairwise)
maxMeanPairwise = meanPairwise;
return meanPairwise;
}
double MonoGA_GlobalSearch::getNormalisedMeanPairwiseDistanceAllIndividuals() {
return getMeanPairwiseDistanceAllIndividuals() / maxMeanPairwise;
}
bool sortByObj0(const Individual *i1, const Individual *i2){
return (i1->getInternalOptDirection(0) == MINIMIZE)?(i1->getObj(0) < i2->getObj(0)):(i1->getObj(0) > i2->getObj(0));
}
|
4d69f74b691fede84aca29172f6bba95310dbce5
|
983786cac7fccdbfde0ecf549f9d43101e6daacb
|
/Source/RestartButton.cpp
|
e941a67082718dd8c1fca33ddd1fb1c402a65e8b
|
[] |
no_license
|
Saftur/pow
|
a31ed7a90eb1e061418c2c010179737e10ffd3bf
|
ff992ccffacf807a44bea61950e99dd70cc3c336
|
refs/heads/master
| 2018-09-08T14:37:50.956036
| 2018-08-24T01:53:01
| 2018-08-24T01:53:01
| 120,832,124
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 541
|
cpp
|
RestartButton.cpp
|
#include "stdafx.h"
#include "RestartButton.h"
#include "Engine.h"
#include "Space.h"
RestartButton::RestartButton() : Button("RestartButton") {
}
Component * RestartButton::Clone() const {
return new RestartButton(*this);
}
void RestartButton::ClickEffect(float dt) {
Space::GetLayer(0)->GetLevelManager()->Restart();
if (Space::GetLayerCount() > 1) {
PopupMenu::Shutdown();
for (unsigned i = 1; i < MAX_LAYERS; i++) {
if (Space::GetLayer(i))
Space::GetLayer(i)->GetLevelManager()->Quit();
}
}
}
|
e56df755910ec0e776199feb835662f232b46b49
|
31fc627f1c1184d3edbe910460fcbf2947d415da
|
/genetic_algo_for_opener_2.cpp
|
8ddfb27fa996498de67fcaa764c2856d32a6e5dd
|
[] |
no_license
|
Grechiha-Nikita/code_samples
|
562c39efb5f927eff1e519675115d0373cf21e67
|
9f936d4c169c58d0d3309d849be26ab1dd5cd03d
|
refs/heads/master
| 2021-06-13T20:08:20.075705
| 2021-04-22T22:09:38
| 2021-04-22T22:09:38
| 188,268,172
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,602
|
cpp
|
genetic_algo_for_opener_2.cpp
|
//#pragma comment(linker, "/STACK:200000000")
//#pragma GCC optimize("O2")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <bits/stdc++.h>
#define all(v) (v).begin(),(v).end()
#ifndef LOCAL
#define cerr if(false)cerr
#endif
using namespace std;
template<class T> using V = vector<T>;
template<class T1, class T2> istream& operator>>(istream&, pair<T1, T2>&);
template<class T> istream& operator>>(istream& in, vector<T>& v) {
for (auto& it : v) {
in >> it;
}
return in;
}
template<class T1, class T2> istream& operator>>(istream& in, pair<T1, T2>& p) {
return in >> p.first >> p.second;
}
template<class T1, class T2> ostream& operator<<(ostream&, const pair<T1, T2>&);
template<class T> ostream& operator<<(ostream& out, const vector<T>& v) {
out << "[";
for (int i = 0; i < v.size(); ++i) {
out << v[i];
if (i + 1 != v.size()) {
out << ", ";
}
}
out << "]";
return out;
}
template<class T1, class T2> ostream& operator<<(ostream& out, const pair<T1, T2>& p) {
out << "(" << p.first << ", " << p.second << ")";
return out;
}
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//template<class Key, class Value = __gnu_pbds::null_type>
//using ordered_set = __gnu_pbds::tree<
// Key,
// Value,
// less<Key>,
// __gnu_pbds::rb_tree_tag,
// __gnu_pbds::tree_order_statistics_node_update
//>; // find_by_order, order_of_key
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<long long, long long> pll;
typedef vector<int> vi;
typedef vector<long long> vll;
struct MainInitializer {
int mainStartTime;
MainInitializer() {
ios_base::Init();
cin.sync_with_stdio(false);
cout.sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cout << fixed << setprecision(11);
cerr << fixed << setprecision(11);
#ifdef LOCAL
freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
this->mainStartTime = clock();
#endif
}
~MainInitializer() {
#ifdef LOCAL
cerr << fixed << setprecision(9) << "\nTime = " << (long double)(clock() - this->mainStartTime) / CLOCKS_PER_SEC << endl;
#endif
}
} mainInitializer;
const int INF = 1e9 + 1e3;
const long long LINF = 1e18 + 1e3;
const int MOD = 1e9 + 7;
const int SZ = 24;
/////////////////////////////////////
const int SEED = 846;
const int N = 15;
const int CROSS_ITER = 5;
const int CROSS_BEST_ITER = 5;
const bool CROSS_TWO_BEST = true;
const int MUT_ITER = 20;
const int MUT_BEST_ITER = 1;
const int MAX_MUT_CNT = 10;
const int PENALTY = 3;
const int STAT_RATE = 100000;
/////////////////////////////////////
struct Item {
ll r[SZ], c[SZ];
int val;
inline int get(size_t i, size_t j) const {
return (r[i] >> (j << 1)) & 3;
}
inline void set(size_t i, size_t j, int val) {
ll f = get(i, j) ^ val;
r[i] ^= f << (j << 1);
c[j] ^= f << (i << 1);
}
void eval() {
int seqEq = 0;
for (int i = 0; i < SZ; ++i) {
for (int j = 2; j < SZ; ++j) {
int val = get(i, j);
if (val < 2 && get(i, j - 1) == val && get(i, j - 2) == val) {
++seqEq;
}
val = get(j, i);
if (val < 2 && get(j - 1, i) == val && get(j - 2, i) == val) {
++seqEq;
}
}
}
int emptyCnt = 0;
int twelveEq = 0;
for (int i = 0; i < SZ; ++i) {
int cntR[] = {0, 0}, cntC[] = {0, 0};
for (int j = 0; j < SZ; ++j) {
int val = get(i, j);
if (val < 2) {
++cntR[val];
} else {
++emptyCnt;
}
val = get(j, i);
if (val < 2) {
++cntC[val];
}
}
if (cntR[0] > 12 || cntR[1] > 12) {
++twelveEq;
}
if (cntC[0] > 12 || cntC[1] > 12) {
++twelveEq;
}
}
V<ll> fullR, fullC;
for (int i = 0; i < SZ; ++i) {
if ((r[i] & 187649984473770) == 0) {
fullR.push_back(r[i]);
}
if ((c[i] & 187649984473770) == 0) {
fullC.push_back(c[i]);
}
}
int eq = (fullR.size() - unordered_set<ll>(all(fullR)).size()) + (fullC.size() - unordered_set<ll>(all(fullC)).size());
this->val = emptyCnt + PENALTY * (seqEq + twelveEq + eq);
}
};
bool operator<(const Item& x, const Item& y) {
return x.val < y.val;
}
bool operator==(const Item& x, const Item& y) {
return x.r == y.r;
}
ostream& operator<<(ostream& out, const Item& x) {
out << "Item { " << x.val << endl;
for (int i = 0; i < SZ; ++i) {
for (int j = 0; j < SZ; ++j) {
out << x.get(i, j) << ' ';
}
out << endl;
}
out << "}";
return out;
}
mt19937 gen(SEED);
vi okX, okY;
Item mutate(const Item& x) {
Item res(x);
int iterNum = gen() % MAX_MUT_CNT;
for (int iter = 0; iter <= iterNum; ++iter) {
auto r = gen();
int i = r % okX.size(), val = (r >> 16) % 3;
res.set(okX[i], okY[i], val);
}
res.eval();
return res;
}
Item cross(const Item& x, const Item& y) {
Item res(x);
int r = gen() % (SZ + 1);
for (int i = r; i < SZ; ++i) {
for (int j = 0; j < SZ; ++j) {
res.set(i, j, y.get(i, j));
}
}
res.eval();
return res;
}
V<vi> table(SZ, vi(SZ));
Item generate() {
Item res;
for (int i = 0; i < SZ; ++i) {
for (int j = 0; j < SZ; ++j) {
res.set(i, j, (table[i][j] == -1 ? gen() % 3 : table[i][j]));
}
}
res.eval();
return res;
}
void solve() {
cout << SEED << ' ' << N << ' ' << CROSS_ITER << ' ' << CROSS_BEST_ITER << ' ' << CROSS_TWO_BEST << ' ' << MUT_ITER << ' ' << MUT_BEST_ITER << ' ' << MAX_MUT_CNT << ' ' << PENALTY << ' ' << STAT_RATE << endl;
cin >> table;
for (int i = 0; i < SZ; ++i) {
for (int j = 0; j < SZ; ++j) {
if (table[i][j] == -1) {
okX.push_back(i);
okY.push_back(j);
}
}
}
V<Item> data(N);
for (int i = 0; i < N; ++i) {
data[i] = generate();
}
for (ll iteration = 0; ; ++iteration) {
sort(all(data));
unique(all(data));
data.resize(N);
if (iteration % STAT_RATE == 0) {
cout << "Iteration " << iteration << "\n" << data.front() << endl;
}
for (int iter = 0; iter < CROSS_ITER; ++iter) {
int x = gen() % N, y = gen() % N;
if (x != y) {
data.push_back(cross(data[x], data[y]));
}
}
for (int iter = 0; iter < CROSS_BEST_ITER; ++iter) {
data.push_back(cross(data.front(), data[1 + gen() % (N - 1)]));
}
if (CROSS_TWO_BEST) {
data.push_back(cross(data[0], data[1]));
}
for (int iter = 0; iter < MUT_ITER; ++iter) {
data.push_back(mutate(data[gen() % N]));
}
for (int iter = 0; iter < MUT_BEST_ITER; ++iter) {
data.push_back(mutate(data.front()));
}
}
}
int main() {
solve();
return 0;
}
|
323087cc38d631106ef587352da14e7aa1e1a596
|
618590a3de9617b899d1951359d831da64c37f95
|
/Lab1/main.cpp
|
8d31735c46e539de5c5e09bfe203a6c8937d6cda
|
[] |
no_license
|
ContiuDragos/SortingAlgorithms
|
c2ce82b1710b7acb88d125091946719b716f804e
|
d31e6a783f5eaf48e40fb28fb6d8f7810a9731f6
|
refs/heads/main
| 2023-03-02T15:26:14.239231
| 2021-01-21T15:03:56
| 2021-01-21T15:03:56
| 331,650,264
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,292
|
cpp
|
main.cpp
|
#include <stdio.h>
#include "Profiler.h"
#define MAX_SIZE 5000
#define STEP_SIZE 100
#define NR_TESTS 5
Profiler p("medie");
void Swap(int *a, int*b)
{
int aux=*a;
*a=*b;
*b=aux;
}
int BinarySearch(int v[], int element, int left, int right, int n)
{
Operation opCompInsertion=p.createOperation("InsertionSort-comp",n);
if(right<=left)
{
opCompInsertion.count();
if(element>=v[left])
return left+1;
return left;
}
int mid=(left+right)/2;
opCompInsertion.count();
if(v[mid]==element)
return mid+1;
opCompInsertion.count();
if(element<v[mid])
return BinarySearch(v,element,left,mid-1,n);
return BinarySearch(v,element,mid+1,right,n);
}
void BubbleSort(int v[], int n)
{
Operation opCompBubble=p.createOperation("BubbleSort-comp",n);
Operation opAtrBubble=p.createOperation("BubbleSort-atr",n);do{
ok=1;
for(i=1;i<n;i++)
{
opCompBubble.count();
if (v[i - 1] > v[i]) {
opAtrBubble.count(3);
Swap(&v[i - 1], &v[i]);
ok = 0;
}
}
}while(ok==0);
int ok=0, i=0;
}
void SelectionSort(int v[], int n)
{
Operation opCompSelection=p.createOperation("SelectionSort-comp",n);
Operation opAtrSelection=p.createOperation("SelectionSort-atr",n);
int pozMin=-1;
for(int i=0;i<n-1;i++)
{
pozMin=i;
for(int j=i+1;j<n;j++)
{
opCompSelection.count();
if(v[j]<v[pozMin])
pozMin=j;
}
if(pozMin!=i)
{
opAtrSelection.count(3);
Swap(&v[pozMin],&v[i]);
}
}
}
void InsertionSort(int v[], int n)
{
Operation opAtrInsertion=p.createOperation("InsertionSort-atr",n);
int aux=0, poz=-1, j=0;
for(int i=1;i<n;i++)
{
aux=v[i];
j=i-1;
poz= BinarySearch(v,aux,0,j,n);
while (j>=poz)
{
opAtrInsertion.count();
v[j+1]=v[j];
j--;
}
v[j+1]=aux;
opAtrInsertion.count();
}
}
void Show_vector(int v[], int n)
{
for(int i=0;i<n;i++)
printf("%d ",v[i]);
printf("\n");
}
void demo()
{
int v[]={ 7,2,8,5,9,1,6 };
int n=sizeof(v)/ sizeof(v[0]);
///BubbleSort(v,n);
///SelectionSort(v,n);
InsertionSort(v,n);
Show_vector(v,n);
}
void perf(int order)
{
int v[MAX_SIZE];
int n;
for(n=STEP_SIZE; n<=MAX_SIZE; n+=STEP_SIZE) {
for(int i=1;i<=NR_TESTS;i++)
{
FillRandomArray(v, n,10,50000, false,order);
BubbleSort(v,n);
if (order < 2)
FillRandomArray(v, n, 10, 50000, false, order);
else
{
///ca sa obtinem worst case pentru selection sort o sa duc primul element pe ultima pozitie din vectorul sortat crescator
int aux = v[0];
for (int j = 0; j < n - 1; j++)
{
v[j] = v[j + 1];
}
v[n - 1] = aux;
}
SelectionSort(v,n);
FillRandomArray(v,n,10,5000,false,order);
InsertionSort(v,n);
}
}
p.divideValues("BubbleSort-comp", NR_TESTS);
p.divideValues("BubbleSort-atr", NR_TESTS);
p.divideValues("SelectionSort-comp", NR_TESTS);
p.divideValues("SelectionSort-atr", NR_TESTS);
p.divideValues("InsertionSort-comp", NR_TESTS);
p.divideValues("InsertionSort-atr", NR_TESTS);
p.addSeries("BubbleSort-total", "BubbleSort-comp", "BubbleSort-atr");
p.addSeries("SelectionSort-total", "SelectionSort-comp", "SelectionSort-atr");
p.addSeries("InsertionSort-total", "InsertionSort-comp", "InsertionSort-atr");
p.createGroup("Comp", "BubbleSort_comp", "SelectionSort_comp", "InsertionSort_comp");
p.createGroup("Atr", "BubbleSort_atr", "SelectionSort_atr", "InsertionSort_atr");
p.createGroup("Total", "BubbleSort_total", "SelectionSort_total", "InsertionSort_total");
}
int main() {
demo();
///UNSORTED
///perf(0);
///ASCENDING
/// p.reset("best");
///perf(1);
///DESCENDING
/// p.reset("worst");
/// perf(2);
/// p.showReport();
return 0;
}
|
20b0c0f6cf533ff8172a38b89280f3373afb8d4e
|
2205b8d9ba3841e665128c8caaf5e950e98c3c9e
|
/src/controllableAgent/controllableAgent.cpp
|
834f1721178a57288a26d18ce3e0027f8e920dd8
|
[] |
no_license
|
johnlime/UnitNeuronAgents
|
980045512ee84168ff2a949eae87c245d4408563
|
d1e5ceb6c799ecb76f8fb630ea6477ed93597c89
|
refs/heads/master
| 2023-01-30T11:23:02.692964
| 2020-12-14T06:40:13
| 2020-12-14T06:40:13
| 275,292,188
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,191
|
cpp
|
controllableAgent.cpp
|
//
// controllableAgent.cpp
// UnitNeuronAgents
//
// Created by John Lime on 2020/06/26.
//
#include "controllableAgent.hpp"
ControllableAgent :: ControllableAgent(ofVec2f _init_position, ofVec3f _color)
{
position = _init_position;
color = _color;
}
void ControllableAgent :: update_target(ofVec2f _position)
{
target_position = _position;
}
void ControllableAgent :: move()
{
// stop completely if agent is on target position
if ((position - target_position).length() < 2)
{
return;
}
ofVec2f normalized_direction = (target_position - position).normalize();
// obtain target orientation ratio in radian
float target_orientation = acos(normalized_direction.x) / M_PI;;
if ((asin(normalized_direction.y) < 0) - (asin(normalized_direction.y) > 0)) // obtain sign of angle
{
target_orientation *= -1;
}
// translate body if the direction the agent is facing and the target orientation is the same
if (orientation == target_orientation)
{
position += normalized_direction;
}
// snap to orientation if close
else if (abs(orientation - target_orientation) <= 0.01)
{
orientation = target_orientation;
}
// rotate body if otherwise
else
{
if ((target_orientation - orientation) >= 0)
{
orientation += 0.01;
}
else
{
orientation -= 0.01;
}
}
}
void ControllableAgent :: display()
{
ofSetColor(color.x, color.y, color.z);
ofSetLineWidth(2.0f);
float sqrt_3_div_2 = sqrt(3) / 2;
// Save global coordinates
ofPushMatrix();
// Translate position and orientation of local coordinates to the agent
ofTranslate(position.x, position.y);
ofRotateDeg(orientation * 360, 0, 0, 1);
// Agent shape
ofDrawLine(0.0f, radius, sqrt_3_div_2 * radius, - radius / 2);
ofDrawLine(sqrt_3_div_2 * radius, - radius / 2, 0.0f, 0.0f);
ofDrawLine(0.0f, 0.0f, - sqrt_3_div_2 * radius, - radius / 2);
ofDrawLine(- sqrt_3_div_2 * radius, - radius / 2, 0.0f, radius);
// Restore global coordinates
ofPopMatrix();
}
|
27e3b9070ce43a8137101aad4c553b380ce5710b
|
3cb9bc615b9c12e1cc1f5b118b155e01108ff6e0
|
/lib/Proyecto Final/Cpp Code/Shared Path/Logic.cpp
|
5a8d0ea248c6665f34b15471bcc0afaf325a3ba4
|
[] |
no_license
|
Youngermaster/ST0247
|
1cb04f39060c602e58563a726af72f106b1799bc
|
c0f53e7fb7affc3058646dc5b2ea522198bc64d9
|
refs/heads/master
| 2020-04-21T10:34:46.173021
| 2019-06-05T01:08:13
| 2019-06-05T01:08:13
| 169,490,371
| 0
| 0
| null | null | null | null |
WINDOWS-1250
|
C++
| false
| false
| 4,298
|
cpp
|
Logic.cpp
|
#include "pch.h"
#include "Logic.h"
const int NUMBER_OF_NODES = 4;
const double TIME_RATE_CHANGE = 1.2;
int costMatrix[NUMBER_OF_NODES + 1][NUMBER_OF_NODES + 1];
Logic::Logic()
{
core();
}
Logic::~Logic()
{
}
void Logic::core()
{
auto start = std::chrono::system_clock::now(); // Starts to counting time.
fillMatrix();
std::cout << "NUMBER_OF_NODES: " << NUMBER_OF_NODES << " TIME_RATE_CHANGE: " << TIME_RATE_CHANGE << std::endl;
readFile(NUMBER_OF_NODES, TIME_RATE_CHANGE);
algorithm();
auto end = std::chrono::system_clock::now(); // Finishes to counting time.
std::chrono::duration<double> elapsed_seconds = end - start; // It calcs the execution time.
std::cout << std::endl << "elapsed time: " << elapsed_seconds.count() << " seconds\n"; // Prints the execution time on seconds.
}
void Logic::readFile(const int NUMBER_OF_NODES, const double TIME_RATE_CHANGE)
{
std::ifstream myReadFile;
myReadFile.open("../Datasets/dataset-ejemplo-U=4-p=1.2.txt");
std::string line;
std::string id;
std::string xCoord;
std::string yCoord;
std::string name;
int lineNumber = 0;
if (myReadFile.is_open())
{
while (!myReadFile.eof())
{
lineNumber++;
if (lineNumber < 5 || lineNumber == NUMBER_OF_NODES + 6 || lineNumber == NUMBER_OF_NODES + 7)
{
myReadFile.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input
continue;
}
// We have to minus 1 if the NUMBER_OF_NODES is equal to 4
// 'cause the teacher did it bad.
if (lineNumber >= 5 && lineNumber < NUMBER_OF_NODES + 6)
{
std::getline(myReadFile, id, ' ');
std::getline(myReadFile, xCoord, ' ');
std::getline(myReadFile, yCoord, ' ');
std::getline(myReadFile, name, '\n');
User newUser(id, name);
users.push_back(newUser);
continue;
}
if (lineNumber > NUMBER_OF_NODES + 7)
{
std::string begin;
std::string end;
std::string cost;
std::getline(myReadFile, begin, ' ');
std::getline(myReadFile, end, ' ');
std::getline(myReadFile, cost, '\n');
if (begin == "")
break;
if (begin == "1" || begin == "\n1")
{
users.at(std::stoi(end) - 1).setHeuristicValue(std::stoi(cost));
}
costMatrix[std::stoi(begin) - 1][std::stoi(end) - 1] = std::stoi(cost);
}
}
}
else
std::cout << "ERROR: file open" << std::endl;
myReadFile.close();
}
void Logic::algorithm()
{
const int usersPerVehicle = 5;
int maxTime = 0;
int timeAcummulated = 0;
int quantityOfPeopleOnCar = 0;
int iterator = 0;
// Sorts the users depending of their heuristic value.
std::sort(users.begin(), users.end(), [](const auto& user1, const auto& user2)
{ return user1.getHeuristicValue() > user2.getHeuristicValue(); });
while (quantityOfPeopleOnCar != users.size())
{
// Detectamos si el usuario en la posición del iterador está montado en un carro.
if (users.at(iterator).getOnCar())
{
iterator++;
continue;
}
std::vector<User> car;
int minimun = 1000;
int auxuliaryIterator = iterator;
int iteratorWithTheMinimumValue = iterator;
while (auxuliaryIterator != -1)
{
if (car.size() <= usersPerVehicle)
{
car.push_back(users.at(auxuliaryIterator));
users.at(auxuliaryIterator).setOnCar(true);
quantityOfPeopleOnCar++;
}
for (int minimumIterator = 0; minimumIterator <= NUMBER_OF_NODES; minimumIterator++)
if (minimun > costMatrix[std::stoi(users.at(auxuliaryIterator).getId())][minimumIterator]
&& !users.at(minimumIterator).getOnCar()
&& costMatrix[std::stoi(users.at(auxuliaryIterator).getId())][minimumIterator] != 0
)
{
minimun = costMatrix[std::stoi(users.at(auxuliaryIterator).getId())][minimumIterator];
iteratorWithTheMinimumValue = minimumIterator;
}
if (iteratorWithTheMinimumValue == 0)
{
iteratorWithTheMinimumValue = -1;
}
auxuliaryIterator = iteratorWithTheMinimumValue;
}
iterator++;
std::cout << "\t ->";
for (auto x : car)
std::cout << x.getId() << " ";
}
}
void Logic::fillMatrix()
{
for (int rows = 0; rows <= NUMBER_OF_NODES; rows++)
for (int columns = 0; columns <= NUMBER_OF_NODES; columns++)
costMatrix[rows][columns] = 0;
}
/*
1 2 3 4 5
1 0 7 19 27 17
2 7 0 12 15 10
3 19 12 0 8 14
4 27 15 8 0 10
5 17 10 14 10 0
*/
|
d09bf681bd40ffff97b5077383d8227a9133f535
|
f7786f389182b498802b056f458a1089c24dc98c
|
/embedded/selector.cpp
|
d05cb7446323753d089ff22d6f109fe63f6dc4d3
|
[] |
no_license
|
buotex/pknn_al
|
160bc81cf34fdf2dbdeb08a9995fb47d70c9fffd
|
d9867ad35da45f46288548be7ff5d087538b88bc
|
refs/heads/master
| 2020-06-03T20:02:35.868330
| 2013-01-23T11:11:21
| 2013-01-23T11:11:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,017
|
cpp
|
selector.cpp
|
#include <armadillo>
#include <random>
#include <algorithm>
int __getSampleIndex(const arma::vec & data, double alpha) {
//rescale data
int lastIndex = alpha * data.n_elem - 1;
double max = data[0];
double treshold = data[lastIndex];
arma::vec probabilities = (data.rows(0,lastIndex) - treshold) / (max - treshold);
probabilities /= arma::accu(probabilities);
//probabilities.print("probabilities");
arma::vec summed_probabilities = arma::cumsum(probabilities);
//summed_probabilities.print("summed");
srand((unsigned)time(NULL));
double X=((double)rand()/(double)RAND_MAX);
int index = std::lower_bound(summed_probabilities.begin(), summed_probabilities.end(), X) - summed_probabilities.begin();
return index;
}
extern "C" {
int getSampleIndex(double * data, int n_elem, double alpha) {
arma::vec vec(data, n_elem, false);
arma::uvec indices = arma::sort_index(vec, 1);
int index = __getSampleIndex(arma::sort(vec, 1), alpha);
return indices[index];
}
}
|
3da3a2cb3c43c45b4efa7ac2c0103762e22fabe0
|
9e83e357538639cfe29356901640072fce261cad
|
/_Examples And Testing/Sound_01/Sound_01/Sound_01.cpp
|
695ec052a6716519c8196ce92096f868e21518d2
|
[] |
no_license
|
ConnerTenn/Legacy_CPP
|
615fa4ca4b5a5824e27c8a213e559e0678f7b690
|
fd150a8f81d2606622dfa9ac199f20009962f5da
|
refs/heads/master
| 2021-05-09T21:46:23.880623
| 2018-05-01T20:29:33
| 2018-05-01T20:29:33
| 118,735,762
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,388
|
cpp
|
Sound_01.cpp
|
// Sound_01.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <cmath>
#include <limits>
#include <fstream>
#include <string>
#include <playsoundapi.h>
#include <mmsystem.h>
#pragma comment(lib, "winmm.lib")
//typedef signed short BitDepth;// 16bit audio
typedef signed char BitDepth;// 8bit audio
typedef unsigned long long QWORD;
const double pi = 3.141592653589;
const DWORD samplerate = 44100;
const WORD channels = 1;
const unsigned short SOUND_DURATION = 2;// 1 second for example.
const QWORD NUM_SAMPLES = SOUND_DURATION * samplerate * channels;
//const QWORD NUM_SAMPLES = samplerate / 16;
void sineWave(BitDepth buffer[], double freq)
{
//BitDepth amplitude = 32767 * 0.5;
BitDepth amplitude = pow(2, 8 * sizeof(BitDepth)) * 0.5;
QWORD c = 0;
double d = (samplerate / freq);
for (QWORD i = 0; i<NUM_SAMPLES; i += channels)
{
double deg = 360.0 / d;
buffer[i] = buffer[i + (1 * (channels - 1))] = sin((c++*deg)*pi / 180)*amplitude;
}
}
template<typename _Ty> void write(std::ofstream& stream, const _Ty& ty)
{
stream.write((const char*)&ty, sizeof(_Ty));
}
void writeWaveFile(const char* filename, BitDepth* buffer)
{
std::ofstream stream(filename, std::ios::binary);
stream.write("RIFF", 4);
::write<int>(stream, 36 + (NUM_SAMPLES*sizeof(BitDepth)));
stream.write("WAVEfmt ", 8);
::write<int>(stream, 16);
::write<short>(stream, 1);
::write<unsigned short>(stream, channels);
::write<int>(stream, samplerate);
::write<int>(stream, samplerate*channels*sizeof(BitDepth));
::write<short>(stream, channels*sizeof(BitDepth));
::write<short>(stream, sizeof(BitDepth) * 8);
stream.write("data", 4);
::write<int>(stream, NUM_SAMPLES*sizeof(BitDepth));
stream.write((const char*)&buffer[0], NUM_SAMPLES*sizeof(BitDepth));
stream.close();
}
/*
int main(int argc, char** argv)
{
SetConsoleTitleA("PCM Audio Example");
std::string filename = "Audio";
BitDepth* buffer = new BitDepth[NUM_SAMPLES];
memset(buffer, 0, NUM_SAMPLES*sizeof(BitDepth));
sineWave(buffer, 440.0);
writeWaveFile(std::string(filename + std::string(".wav")).c_str(), buffer);
//delete[] buffer;
PlaySound(TEXT("..\\Sound_01\\Audio.wav"), NULL, SND_FILENAME | SND_SYNC);
sineWave(buffer, 220.0);
writeWaveFile(std::string(filename + std::string(".wav")).c_str(), buffer);
delete[] buffer;
PlaySound(TEXT("..\\Sound_01\\Audio.wav"), NULL, SND_FILENAME | SND_SYNC);
std::cout << filename << "Done!" << std::endl;
std::cin.get();
return 0;
}
*/
int main(int argc, char** argv)
{
SetConsoleTitleA("PCM Audio Example");
std::string filename = "Audio";
BitDepth* buffer = new BitDepth[NUM_SAMPLES];
memset(buffer, 0, NUM_SAMPLES*sizeof(BitDepth));
sineWave(buffer, 440.0);
writeWaveFile(std::string(filename + std::string(".wav")).c_str(), buffer);
//delete[] buffer;
PlaySound(TEXT("..\\Sound_01\\Audio.wav"), NULL, SND_FILENAME | SND_SYNC);
sineWave(buffer, 220.0);
writeWaveFile(std::string(filename + std::string(".wav")).c_str(), buffer);
//delete[] buffer;
PlaySound(TEXT("..\\Sound_01\\Audio.wav"), NULL, SND_FILENAME | SND_SYNC);
delete[] buffer;
std::cout << filename << "Done!" << std::endl;
std::cin.get();
return 0;
}
|
ff25eb8c9385e591868c25cace5ac04f242d2c69
|
84309c941ed75cc2486c58385c6cfefb12bfe558
|
/Printf.ino
|
4d920dc87503edd7d09a38a616560f9f88c60d4d
|
[] |
no_license
|
mkarliner/TropeLights
|
63aa70dbe5b59d8e267b31f1cff07173ac8be5fd
|
490f24e9dba87039554f0ea7337004f6f8e1578e
|
refs/heads/master
| 2020-04-20T06:19:04.856497
| 2014-11-16T17:24:05
| 2014-11-16T17:24:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 518
|
ino
|
Printf.ino
|
// create a output function
// This works because Serial.write, although of
// type virtual, already exists.
static int uart_putchar (char c, FILE *stream)
{
Serial.write(c) ;
return 0 ;
}
char *ftoa(char *a, double f, int precision)
{
long p[] = {0,10,100,1000,10000,100000,1000000,10000000,100000000};
char *ret = a;
long heiltal = (long)f;
itoa(heiltal, a, 10);
while (*a != '\0') a++;
*a++ = '.';
long desimal = abs((long)((f - heiltal) * p[precision]));
itoa(desimal, a, 10);
return ret;
}
|
7593e406539ae1700e4d128573dd6576fa474153
|
0d894b3233402efb44d9ac12d716f1983609a088
|
/Contour.h
|
b98853a0c05d7e031a182363aa159a6cb074dab2
|
[] |
no_license
|
happog/Text-line-extraction-using-seam-carving
|
40ceb3e82d0b1db6179bb42d3cb9b1c675e476c0
|
5a4ad4d068fd3b84f4ba1a5f065962eb7b2d3fb0
|
refs/heads/master
| 2020-03-24T22:49:34.880962
| 2018-03-08T14:18:51
| 2018-03-08T14:18:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,757
|
h
|
Contour.h
|
#ifndef _Contour_H
#define _Contour_H
#include <vector>
#include <opencv/cv.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
using namespace std;
class Contour {
protected:
vector<cv::Point> _points;
cv::Rect _brect;
cv::Point _center;
public:
Contour() { ; }
~Contour() { ; }
Contour(std::vector<cv::Point>& points) {
assert(points.size() > 2);
_center = cv::Point(0, 0);
_brect = cv::Rect(points[0], points[1]);
_points.push_back(points[0]);
_center += points[0];
_points.push_back(points[1]);
_center += points[1];
for (int i = 2; i < points.size(); i++){
_brect += points[i];
_center += points[i];
_points.push_back(points[i]);
}
_center /= (int)_points.size();
}
Contour(const Contour &contour) {
_points.insert(_points.end(), contour._points.begin(), contour._points.end());
_brect = contour._brect;
_center = contour._center;
}
void set(const Contour &contour) {
_points.erase(_points.begin(), _points.end());
_points.insert(_points.end(), contour._points.begin(), contour._points.end());
_brect = contour._brect;
_center = contour._center;
}
void setPoints(vector<cv::Point>& p) {
_points.erase(_points.begin(), _points.end());
_points.insert(_points.end(), p.begin(), p.end());
_brect = boundingRect(p);
setCenter();
}
vector<cv::Point>& getPoints(){
return _points;
}
cv::Rect& getBoundRect() {
return _brect;
}
float inside(cv::Point p){
return (float)pointPolygonTest(_points, p, false);
}
void setCenter();
cv::Point getCenter() { return _center; }
cv::Mat getMat(vector<cv::Point>& pts);
vector<cv::Point> getConvexHull(bool clockwise);
};
#endif
|
b051251828af28dd40e3cd9744ab18e4f1f2cac5
|
33fcbed17ab7aa8ade90da79d3f92126a84a186f
|
/ws/11/e.cpp
|
21510c562469a8200794621dd0eb1e0ad94f703e
|
[] |
no_license
|
kusosuha6vt/kusosuha6vt
|
7b5380351c6d7f211c03608fbb2fbcc6f9fef25f
|
b07397112f638bf6736c70c404c7dcff57ad3299
|
refs/heads/main
| 2023-04-02T00:39:41.086109
| 2021-03-28T19:39:16
| 2021-03-28T19:39:16
| 352,417,902
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,925
|
cpp
|
e.cpp
|
//#pragma comment(linker, "/STACK:16777216")
#include <bits/stdc++.h>
#define all(a) (a).begin(), (a).end()
#define mid(l, r) (((r) + (l)) >> 1)
using namespace std;
typedef long long ll;
//#define int ll
void set_file(string s) {
freopen((s + ".in").c_str(), "r", stdin);
freopen((s + ".out").c_str(), "w", stdout);
}
mt19937 gen;
typedef uniform_int_distribution<int> uid;
int rnd(int l, int r) {
return uid(l, r - 1)(gen);
}
const int N = 200000 * 2, A = 'z' - 'a' + 1 + 200000;
int s[N], p[N], pn[N], c[N], cn[N], b[N], lcp[N], rp[N];
int safe(int x, int n) {
return x >= n ? x - n : x;
}
void build(int n) {
memset(b, 0, n * sizeof(b[0]));
for (int i = 0; i < n; ++i) {
c[i] = s[i];
p[i] = i;
b[1 + s[i]]++;
}
partial_sum(b, b + A + 1, b);
for (int l = 0; l < n; l = (l ? l << 1 : 1)) {
for (int i = 0; i < n; ++i) {
int j = safe(p[i] - l + n, n);
pn[b[c[j]]++] = j;
}
int t = 0;
for (int i = 0; i < n; ++i) {
if (i == 0 || c[pn[i]] != c[pn[i - 1]] || c[safe(pn[i] + l, n)] != c[safe(pn[i - 1] + l, n)])
b[t++] = i;
cn[pn[i]] = t - 1;
}
memcpy(c, cn, n * sizeof(c[0]));
memcpy(p, pn, n * sizeof(p[0]));
}
}
void build_lcp(int n) {
for (int i = 0; i < n; ++i) {
rp[p[i]] = i;
}
int k = 0;
for (int i = 0; i < n; ++i) {
if (rp[i] == n - 1) {
k = 0;
continue;
}
int j = p[rp[i] + 1];
while (max(i, j) + k < n && s[i + k] == s[j + k])
k++;
lcp[rp[i]] = k;
k = max(0, k - 1);
}
}
int t[N];
void add(int i, int v, int n) {
for (; i < n; i = i | (i + 1)) {
t[i] += v;
}
}
int sum(int i, int n) {
int ans = 0;
for (; i >= 0; i = (i & (i + 1)) - 1) {
ans += t[i];
}
return ans;
}
int sum(int l, int r, int n) {
return sum(r, n) - sum(l - 1, n);
}
int st[N];
void f(int *a, int n) {
int m = 0;
st[m++] = -1;
for (int i = 0; i < n; ++i) {
while (m > 1 && lcp[st[m - 1]] >= lcp[i])
m--;
a[i] = i - st[m - 1];
st[m++] = i;
}
}
int l[N], r[N], tp[N];
typedef tuple<int, int, int> ti;
ti y[N];
int last[N];
int ans[N];
void solve() {
int k;
cin >> k;
int n = 0;
for (int i = 0; i < k; ++i) {
string s_;
cin >> s_;
for (char it : s_) {
s[n++] = int(it) - 'a' + k;
tp[n - 1] = i;
}
s[n++] = i;
}
build(n);
build_lcp(n);
f(l, n - 1);
reverse(lcp, lcp + n);
f(r, n - 1);
reverse(lcp, lcp + n);
reverse(r, r + n);
int it = 0;
for (int i = k; i < n - 1; ++i) {
y[it++] = {i + r[i], i - l[i] + 1, lcp[i]};
}
sort(y, y + it);
fill(last, last + k, -1);
int ___ = it;
it = 0;
for (int i = k; i < n; ++i) {
int j = p[i];
if (last[tp[j]] != -1) {
add(last[tp[j]], -1, n);
}
last[tp[j]] = i;
add(i, 1, n);
while (it < ___ && get<0>(y[it]) == i) {
int lb = get<1>(y[it]);
int val = get<2>(y[it]);
it++;
int cnt = sum(lb, i, n);
ans[cnt] = max(ans[cnt], val);
}
}
for (int i = k; i >= 3; i --) {
ans[i - 1] = max(ans[i], ans[i - 1]);
}
for (int i = 2; i <= k; ++i) {
cout << ans[i] << '\n';
}
}
signed main() {
#ifdef LOCAL_DEFINE
freopen("input.txt", "r", stdin);
#else
// set_file("game");
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// set_file("memory");
#endif
solve();
return 0;
}
|
41c4f26132be5aa0814b09323e65e3f008ffba80
|
86ff0325bdb0ddcc75cbbbc404886511f291b3ca
|
/src/RayVec.hpp
|
f80c306a8e413eca5812112669da6cf8197faa2b
|
[] |
no_license
|
Roudovic/GlintsPathTracer
|
38d8e183bf41505b9f36f01c37a22b972099decb
|
59a5cf86592d8af648562772301d4693b86026bf
|
refs/heads/master
| 2020-12-30T09:05:10.301748
| 2020-04-24T13:21:14
| 2020-04-24T13:21:14
| 238,941,798
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,856
|
hpp
|
RayVec.hpp
|
//
// RayVec.hpp
// PathTracer
//
// Created by Ludovic Theobald on 05/11/2019.
// Copyright © 2019 Ludovic Theobald. All rights reserved.
//
#ifndef RayVec_hpp
#define RayVec_hpp
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <iostream>
struct Vec {
double x, y, z;
Vec(double x_=0, double y_=0, double z_=0){ x=x_; y=y_; z=z_; }
Vec operator+(const Vec &b) const { return Vec(x+b.x,y+b.y,z+b.z); }
Vec operator-(const Vec &b) const { return Vec(x-b.x,y-b.y,z-b.z); }
Vec operator*(double b) const { return Vec(x*b,y*b,z*b); }
double& operator[](int i){
if(i==0) return x;
else if(i==1) return y;
else return z;
}
double operator[](int i) const{
if(i==0) return x;
else if(i==1) return y;
else return z;
}
Vec mult(const Vec &b) const { return Vec(x*b.x,y*b.y,z*b.z); }
inline Vec& normalize(){ return *this = *this * (1.0/sqrt(x*x+y*y+z*z)); }
double norm(){ return sqrt(x*x+y*y+z*z);}
double dot(const Vec &b) const { return x*b.x+y*b.y+z*b.z; }
Vec cross(Vec&b) const{return Vec(y*b.z-z*b.y,z*b.x-x*b.z,x*b.y-y*b.x);}
Vec TangentSpaceToWorld(Vec n, Vec t, Vec b){
t.normalize();
b.normalize();
// b = n.cross(t).normalize();
// Vec n_ = Vec(this->dot(t),this->dot(b),this->dot(n) ).normalize();
// return n_;
return (n * z + t * x + b * y).normalize();
// return t.cross(b) + n.cross(b)*x + t.cross(n)*y;
}
Vec toTangentSpace(Vec n, Vec t, Vec b){
t.normalize();
b.normalize();
Vec n_ = Vec(this->dot(t),this->dot(b),this->dot(n) ).normalize();
return n_;
}
};
Vec operator*(double b , Vec const & o);
void generateRandomPointOnSphere(double & theta , double & phi);
Vec randomSampleOnSphere() ;
Vec randomSampleOnHemisphere( Vec const & upDirection ) ;
Vec cosineSampleHemisphere(Vec const &upDirection);
struct Ray {
Vec o, d;
Ray(Vec o_, Vec d_) : o(o_), d(d_) {
d.normalize();
}
};
struct RayDifferentials : public Ray{
bool hasDifferentials;
Vec ox, oy, dir_x, dir_y;
RayDifferentials(Vec o_, Vec d_, Vec ox_, Vec oy_, Vec dir_x_, Vec dir_y_):
Ray(o_, d_),
ox(ox_),
oy(oy_),
dir_x(dir_x_),
dir_y(dir_y_){
d.normalize();
dir_x.normalize();
dir_y.normalize();
hasDifferentials = true;
}
RayDifferentials(Vec o_, Vec d_) : Ray(o_, d_) {
d.normalize();
hasDifferentials = false;
}
};
struct Vec2 {
double x, y;
Vec2(double x_=0, double y_=0){ x=x_; y=y_;}
Vec2 operator+(const Vec2 &b) const { return Vec2(x+b.x,y+b.y); }
Vec2 operator-(const Vec2 &b) const { return Vec2(x-b.x,y-b.y); }
Vec2 operator*(double b) const { return Vec2(x*b,y*b); }
double dot(const Vec2 &b) const { return x*b.x+y*b.y; }
};
template<typename T> Vec2 operator*(T b, Vec2& v){
return Vec2(v.x*b,v.y*b);
}
struct Mat2{
double a,b,c,d;
Mat2(double a_ =0, double b_=0, double c_=0, double d_=0):a(a_), b(b_), c(c_), d(d_){}
Mat2 operator+(const Mat2 &M) const{return Mat2(a+M.a, b+M.b, c+M.c, d+M.d);}
Mat2 operator-(const Mat2 &M) const{return Mat2(a-M.a, b-M.b, c-M.c, d-M.d);}
Mat2 operator*(double s) const{return Mat2(s*a, s*b, s*c, s*d);}
double& operator[](int i){
if(i==0) return a;
else if(i==1) return b;
else if(i==2) return c;
else return d;
}
double operator[](int i) const{
if(i==0) return a;
else if(i==1) return b;
else if(i==2) return c;
else return d;
}
Mat2 mult(const Mat2 &M) const{
return Mat2(a*M.a +b*M.c, a*M.b+ b*M.d,
c*M.a + d*M.c, c*M.b + d*M.d );
}
Mat2 inv(){
return Mat2(d, -b, -c , a)*(1./(a*d - b*c));
}
Mat2 T(){
return Mat2(a,c,b,d);
}
double det() const{
return a*d - b*c;
}
Vec2 mult(const Vec2& v){
return Vec2(a*v.x + b*v.y, c*v.x + d*v.y);
}
};
//Row-major storage
struct Mat3{
double data[9];
Mat3(double* data_){
for(int i = 0; i<9; i++){
data[i] = data_[i];
}
}
double& operator[](int id){
return data[id];
}
Mat3 operator+(const Mat3 &M) const{
double datanew[9];
for(int i = 0; i<9; i++){
datanew[i] = data[i] + M.data[i];
}
return Mat3(datanew);
}
Mat3 operator-(const Mat3 &M) const{
double datanew[9];
for(int i = 0; i<9; i++){
datanew[i] = data[i] - M.data[i];
}
return Mat3(datanew);
}
Mat3 operator*(double s) const{
double datanew[9];
for(int i = 0; i<9; i++){
datanew[i] = data[i]*s;
}
return Mat3(datanew);
}
Mat3 mult(const Mat3 &M) const{
double datanew[9] = {0,0,0,0,0,0,0,0,0};
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
for (int k = 0; k<3; k++){
datanew[3*i + j] += data[3*i+ k]*M.data[3*k +j];
}
}
}
return Mat3(datanew);
}
Vec mult(const Vec& v){
float datavec[3] = {0,0,0};
for(int i = 0; i<3; i++){
for (int k = 0; k<3; k++){
datavec[i] += data[3*i+ k]*v[i];
}
}
return Vec(datavec[0], datavec[1], datavec[2]);
}
static Mat3 Id(){
double data[9] = {1,0,0,0,1,0,0,0,1};
return Mat3(data);
}
// static Mat3 rotate(Vec axis, double angle){
// double data[9] ={0,0,0,0,0,0,0,0,0};
//
// }
};
#endif /* RayVec_hpp */
|
ff133931fd220f3bcb219f235a5065095ca9fd95
|
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
|
/generated/src/aws-cpp-sdk-securityhub/include/aws/securityhub/model/ActionLocalPortDetails.h
|
f9164a912b11b6d0267ced363fdd699f865824e3
|
[
"Apache-2.0",
"MIT",
"JSON"
] |
permissive
|
aws/aws-sdk-cpp
|
aff116ddf9ca2b41e45c47dba1c2b7754935c585
|
9a7606a6c98e13c759032c2e920c7c64a6a35264
|
refs/heads/main
| 2023-08-25T11:16:55.982089
| 2023-08-24T18:14:53
| 2023-08-24T18:14:53
| 35,440,404
| 1,681
| 1,133
|
Apache-2.0
| 2023-09-12T15:59:33
| 2015-05-11T17:57:32
| null |
UTF-8
|
C++
| false
| false
| 3,219
|
h
|
ActionLocalPortDetails.h
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/securityhub/SecurityHub_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace SecurityHub
{
namespace Model
{
/**
* <p>For <code>NetworkConnectionAction</code> and <code>PortProbeDetails</code>,
* <code>LocalPortDetails</code> provides information about the local port that was
* involved in the action.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/securityhub-2018-10-26/ActionLocalPortDetails">AWS
* API Reference</a></p>
*/
class ActionLocalPortDetails
{
public:
AWS_SECURITYHUB_API ActionLocalPortDetails();
AWS_SECURITYHUB_API ActionLocalPortDetails(Aws::Utils::Json::JsonView jsonValue);
AWS_SECURITYHUB_API ActionLocalPortDetails& operator=(Aws::Utils::Json::JsonView jsonValue);
AWS_SECURITYHUB_API Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The number of the port.</p>
*/
inline int GetPort() const{ return m_port; }
/**
* <p>The number of the port.</p>
*/
inline bool PortHasBeenSet() const { return m_portHasBeenSet; }
/**
* <p>The number of the port.</p>
*/
inline void SetPort(int value) { m_portHasBeenSet = true; m_port = value; }
/**
* <p>The number of the port.</p>
*/
inline ActionLocalPortDetails& WithPort(int value) { SetPort(value); return *this;}
/**
* <p>The port name of the local connection.</p>
*/
inline const Aws::String& GetPortName() const{ return m_portName; }
/**
* <p>The port name of the local connection.</p>
*/
inline bool PortNameHasBeenSet() const { return m_portNameHasBeenSet; }
/**
* <p>The port name of the local connection.</p>
*/
inline void SetPortName(const Aws::String& value) { m_portNameHasBeenSet = true; m_portName = value; }
/**
* <p>The port name of the local connection.</p>
*/
inline void SetPortName(Aws::String&& value) { m_portNameHasBeenSet = true; m_portName = std::move(value); }
/**
* <p>The port name of the local connection.</p>
*/
inline void SetPortName(const char* value) { m_portNameHasBeenSet = true; m_portName.assign(value); }
/**
* <p>The port name of the local connection.</p>
*/
inline ActionLocalPortDetails& WithPortName(const Aws::String& value) { SetPortName(value); return *this;}
/**
* <p>The port name of the local connection.</p>
*/
inline ActionLocalPortDetails& WithPortName(Aws::String&& value) { SetPortName(std::move(value)); return *this;}
/**
* <p>The port name of the local connection.</p>
*/
inline ActionLocalPortDetails& WithPortName(const char* value) { SetPortName(value); return *this;}
private:
int m_port;
bool m_portHasBeenSet = false;
Aws::String m_portName;
bool m_portNameHasBeenSet = false;
};
} // namespace Model
} // namespace SecurityHub
} // namespace Aws
|
67e3e1ea3ad7d0556e8fb14839b423969eddc1a9
|
2f396d9c1cff7136f652f05dd3dea2e780ecc56e
|
/_studio/shared/umc/codec/h264_dec/include/umc_h264_headers.h
|
930cc1791b577e186a93f5aa34ad7995a285cdc8
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Intel"
] |
permissive
|
Intel-Media-SDK/MediaSDK
|
d90c84f37fd93afc9f0a0b98ac20109d322c3337
|
7a72de33a15d6e7cdb842b12b901a003f7154f0a
|
refs/heads/master
| 2023-08-24T09:19:16.315839
| 2023-05-17T16:55:38
| 2023-05-17T16:55:38
| 87,199,173
| 957
| 595
|
MIT
| 2023-05-17T16:55:40
| 2017-04-04T14:52:06
|
C++
|
UTF-8
|
C++
| false
| false
| 5,488
|
h
|
umc_h264_headers.h
|
// Copyright (c) 2017-2018 Intel Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "umc_defs.h"
#if defined (MFX_ENABLE_H264_VIDEO_DECODE)
#ifndef __UMC_H264_HEADERS_H
#define __UMC_H264_HEADERS_H
#include "umc_h264_dec_defs_dec.h"
#include "umc_h264_heap.h"
#include "umc_h264_slice_decoding.h"
namespace UMC
{
template <typename T>
class HeaderSet
{
public:
HeaderSet(H264_Heap_Objects *pObjHeap)
: m_pObjHeap(pObjHeap)
, m_currentID(-1)
{
}
virtual ~HeaderSet()
{
Reset(false);
}
T * AddHeader(T* hdr)
{
uint32_t id = hdr->GetID();
if (id >= m_Header.size())
{
m_Header.resize(id + 1);
}
m_currentID = id;
if (m_Header[id])
{
m_Header[id]->DecrementReference();
}
T * header = m_pObjHeap->AllocateObject<T>();
*header = *hdr;
//ref. counter may not be 0 here since it can be copied from given [hdr] object
header->ResetRefCounter();
header->IncrementReference();
m_Header[id] = header;
return header;
}
T * GetHeader(int32_t id)
{
if ((uint32_t)id >= m_Header.size())
{
return 0;
}
return m_Header[id];
}
const T * GetHeader(int32_t id) const
{
if ((uint32_t)id >= m_Header.size())
{
return 0;
}
return m_Header[id];
}
void RemoveHeader(void * hdr)
{
T * tmp = (T *)hdr;
if (!tmp)
{
VM_ASSERT(false);
return;
}
uint32_t id = tmp->GetID();
if (id >= m_Header.size())
{
VM_ASSERT(false);
return;
}
if (!m_Header[id])
{
VM_ASSERT(false);
return;
}
VM_ASSERT(m_Header[id] == hdr);
m_Header[id]->DecrementReference();
m_Header[id] = 0;
}
void Reset(bool isPartialReset = false)
{
if (!isPartialReset)
{
for (uint32_t i = 0; i < m_Header.size(); i++)
{
if (m_Header[i])
m_Header[i]->DecrementReference();
}
m_Header.clear();
m_currentID = -1;
}
}
void SetCurrentID(int32_t id)
{
if (GetHeader(id))
m_currentID = id;
}
int32_t GetCurrentID() const
{
return m_currentID;
}
T * GetCurrentHeader()
{
if (m_currentID == -1)
return 0;
return GetHeader(m_currentID);
}
const T * GetCurrentHeader() const
{
if (m_currentID == -1)
return 0;
return GetHeader(m_currentID);
}
private:
std::vector<T*> m_Header;
H264_Heap_Objects *m_pObjHeap;
int32_t m_currentID;
};
/****************************************************************************************************/
// Headers stuff
/****************************************************************************************************/
class Headers
{
public:
Headers(H264_Heap_Objects *pObjHeap)
: m_SeqParams(pObjHeap)
, m_SeqExParams(pObjHeap)
, m_SeqParamsMvcExt(pObjHeap)
, m_SeqParamsSvcExt(pObjHeap)
, m_PicParams(pObjHeap)
, m_SEIParams(pObjHeap)
{
memset(&m_nalExtension, 0, sizeof(m_nalExtension));
}
void Reset(bool isPartialReset = false)
{
m_SeqParams.Reset(isPartialReset);
m_SeqExParams.Reset(isPartialReset);
m_SeqParamsMvcExt.Reset(isPartialReset);
m_SeqParamsSvcExt.Reset(isPartialReset);
m_PicParams.Reset(isPartialReset);
m_SEIParams.Reset(isPartialReset);
}
HeaderSet<UMC_H264_DECODER::H264SeqParamSet> m_SeqParams;
HeaderSet<UMC_H264_DECODER::H264SeqParamSetExtension> m_SeqExParams;
HeaderSet<UMC_H264_DECODER::H264SeqParamSetMVCExtension> m_SeqParamsMvcExt;
HeaderSet<UMC_H264_DECODER::H264SeqParamSetSVCExtension> m_SeqParamsSvcExt;
HeaderSet<UMC_H264_DECODER::H264PicParamSet> m_PicParams;
HeaderSet<UMC_H264_DECODER::H264SEIPayLoad> m_SEIParams;
UMC_H264_DECODER::H264NalExtension m_nalExtension;
};
} // namespace UMC
#endif // __UMC_H264_HEADERS_H
#endif // MFX_ENABLE_H264_VIDEO_DECODE
|
7c68b080a33d7fbd1b15e6b02fa0664ace3a06d0
|
7f7e2e7ed09fd4ff372ec60e2b3566163fe96dc4
|
/PA6/AttendanceApp.cpp
|
d31f010a5685213340ab87ffcdcdbbd23efa250b
|
[] |
no_license
|
Ogieriakhi17/CPTS-122
|
c8679786853d478be86988561f54e1f765427a8e
|
782c61a4cd6ed5838195f8920ce8d8ed7fa6b307
|
refs/heads/master
| 2023-04-07T00:47:17.238584
| 2018-09-26T03:00:44
| 2018-09-26T03:00:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,601
|
cpp
|
AttendanceApp.cpp
|
#include "AttendanceApp.h"
///////////////////////////////////////////////////////////////////////////////
/// \file AttendanceApp.cpp
/// \author Gal Zahavi
/// \date
/// \brief This application is an attendance tracker
/// \function AttendanceApp.cpp
/// \description
///
/// REVISION HISTORY:
/// \date 3/20/18 (created)
///
///////////////////////////////////////////////////////////////////////////////
AttendanceApp::AttendanceApp()
{
}
///////////////////////////////////////////////////////////////////////////////
/// \file AttendanceApp.cpp
/// \author Gal Zahavi
/// \date
/// \brief This application is an attendance tracker
/// \function ~AttendanceApp()
/// \description
///
/// REVISION HISTORY:
/// \date 3/20/18 (created)
///
///////////////////////////////////////////////////////////////////////////////
AttendanceApp::~AttendanceApp()
{
//In destructor
}
///////////////////////////////////////////////////////////////////////////////
/// \file AttendanceApp.cpp
/// \author Gal Zahavi
/// \date
/// \brief This application is an attendance tracker
/// \function DisplayMenu();
/// \description
///
/// REVISION HISTORY:
/// \date 3/20/18 (created)
///
///////////////////////////////////////////////////////////////////////////////
int AttendanceApp::DisplayMenu()
{
int i;
cout << "Welcome to Attendence Tracker" << endl;
cout << " 1) Load Course List" << endl;
cout << " 2) Load Master List" << endl;
cout << " 3) Store Master List" << endl;
cout << " 4) Mark Absences" << endl;
cout << " 5) Edit Absences" << endl;
cout << " 6) Generate Report" << endl;
cout << " 7) Exit" << endl;
cin >> i;
return i;
}
///////////////////////////////////////////////////////////////////////////////
/// \file AttendanceApp.cpp
/// \author Gal Zahavi
/// \date
/// \brief This application is an attendance tracker
/// \function ImportList();
/// \description
///
/// REVISION HISTORY:
/// \date 3/20/18 (created)
///
///////////////////////////////////////////////////////////////////////////////
bool AttendanceApp::ImportList(string name)
{
if (!inFile.is_open())
{
inFile.open(name);
list.load(inFile);
return true;
}
else if (inFile.is_open())
{
list.load(inFile);
return true;
}
else
{
cout << "ERROR CHECK FILE !!" << endl;
return false;
}
}
///////////////////////////////////////////////////////////////////////////////
/// \file AttendanceApp.cpp
/// \author Gal Zahavi
/// \date
/// \brief This application is an attendance tracker
/// \function StoreList()
/// \description
///
/// REVISION HISTORY:
/// \date 3/20/18 (created)
///
///////////////////////////////////////////////////////////////////////////////
bool AttendanceApp::StoreList(string name)
{
if (!outFile.is_open())
{
outFile.open(name);
list.store(outFile);
return true;
}
else if (outFile.is_open())
{
list.store(outFile);
return true;
}
else
{
cout << "ERROR CHECK FILE !!" << endl;
return false;
}
}
///////////////////////////////////////////////////////////////////////////////
/// \file AttendanceApp.cpp
/// \author Gal Zahavi
/// \date
/// \brief This application is an attendance tracker
/// \function run();
/// \description
///
/// REVISION HISTORY:
/// \date 3/20/18 (created)
///
///////////////////////////////////////////////////////////////////////////////
void AttendanceApp::run()
{
int i = 0, x =0;
while (i <=6)
{
i = DisplayMenu();
switch (i)
{
case 1:ImportList("ClassList.csv");
_sleep(1000);
system("cls");
break;
case 2:ImportList("masterList.csv");
_sleep(1000);
system("cls");
break;
case 3:StoreList("masterList.csv");
_sleep(1000);
system("cls");
break;
case 4:list.markAbs();
break;
case 5:cout << "???Currently Under Development???" << endl;
_sleep(1000);
system("cls");
break;
case 6:
cout << "Welcome to Sub Attendence Tracker Menu" << endl;
cout << " 1) Generate Report for All Student" << endl;
cout << " 2) Load Master List" << endl;
cin >> x;
switch (x)
{
case 1:list.RecAbs();
break;
case 2:
cout << "Generate a Report of students that have been absent for 1 - 180 days : how many days ?" << endl;
cin >> x;
list.allAbs(x);
break;
}
}
}
}
|
536829d52e056da6622d7991328ac579a6be9e48
|
6c1fdcc17015be4983d900745f2b7a459249431c
|
/YBCtrl/inc/menu/YBMenu.h
|
cf731244e10241a9995193da7a52bc29cf985967
|
[] |
no_license
|
AlexByYao/YBCtrl
|
6051c2106ab4472f6662b2397f98b78c19c941c7
|
6f00bf461dbf4df810533c4f6ad20dee17563ca0
|
refs/heads/master
| 2021-01-12T11:43:15.204863
| 2016-10-29T08:30:24
| 2016-10-29T08:30:24
| 72,273,919
| 1
| 0
| null | 2016-10-29T08:34:38
| 2016-10-29T08:34:37
| null |
UTF-8
|
C++
| false
| false
| 1,539
|
h
|
YBMenu.h
|
#ifndef __YBMENU_H__
#define __YBMENU_H__
#include "frame/YBCtrlBase.h"
#include <string>
#include <map>
#include <deque>
YBCTRL_NAMESPACE_BEGIN
namespace Gdiplus{
class Image;
class Graphics;
}
class YBCtrlImageBase;
class YBCtrlImageStatic;
class YBCTRL_API YBMenu : public YBCtrlBase{
public:
struct YBMenuItem{
std::basic_string< TCHAR > m_tstrText;
WORD m_wordCtrlId;
bool m_bShowChildWindow;
};
typedef std::deque< YBMenuItem* > mi_container_type;
typedef std::map< HWND, YBMenu* > hwndYBMenu_map_type;
typedef std::basic_string< TCHAR >tstring_type;
public:
YBMenu();
virtual ~YBMenu();
public:
YBCTRL_WNDMSGMAP_DECLARE();
public:
HWND Create( int x, int y, int nWidth, int nHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInstance );
void SetBkImage( unsigned int uBkImageId );
void SetFontId( unsigned int uFontId );
BOOL InsertMenuItem( YBMenuItem* pYBMenuItem );
private:
void _onWM_PAINT( YBCtrlWndMsg* pYBCtrlWndMsg );
void _onWM_KILLFOCUS( YBCtrlWndMsg* pYBCtrlWndMsg );
void _onWM_LBUTTONDOWN( YBCtrlWndMsg* pYBCtrlWndMsg );
void _drawBk( HDC hDC );
YBCtrlImageStatic* _getBkImageStatic( unsigned int uBkImageId );
void _clearAllMenuItem();
BOOL _calcItemRect( unsigned int uIndex, RECT& rcItemRect );
void _drawText( HDC hDC );
private:
unsigned int m_uBkImageId;
unsigned int m_uFontId;
#pragma warning(push)
#pragma warning(disable:4251)
mi_container_type m_containerMenuItem;
hwndYBMenu_map_type g_mapHWNDMenu;
#pragma warning(pop)
};
YBCTRL_NAMESPACE_END
#endif //__YBMENU_H__
|
79d95d0f3da9f80482e5db7133e727602d54a0b0
|
7a9d2a5d591e72db615ccdf081d64f2d1becaa1e
|
/solutions/1046/c++/solution.cpp
|
d7848a6c808327e0fdd8e2459642b68b107c5a82
|
[] |
no_license
|
Krazune/LeetCode
|
7efa7553caf43b05c5b7fa8600c2f29a065082fe
|
5fd0e339e9eb7d166572090fb71217cfb8874bc2
|
refs/heads/master
| 2023-06-07T13:53:13.444428
| 2023-05-31T17:50:28
| 2023-05-31T17:50:28
| 111,018,262
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 824
|
cpp
|
solution.cpp
|
// 1046. Last Stone Weight
#include <vector>
#include <algorithm>
using namespace std;
class Solution
{
public:
int lastStoneWeight(vector<int>& stones)
{
if (stones.size() == 1)
{
return stones[0];
}
int nonZeroStoneCount = stones.size();
do
{
sort(stones.begin(), stones.end());
int heaviestWeight = stones[stones.size() - 1];
int secondHeaviestWeight = stones[stones.size() - 2];
if (heaviestWeight == secondHeaviestWeight)
{
stones[stones.size() - 1] = 0;
stones[stones.size() - 2] = 0;
nonZeroStoneCount -= 2;
}
else
{
stones[stones.size() - 1] -= secondHeaviestWeight;
stones[stones.size() - 2] = 0;
--nonZeroStoneCount;
}
}
while (nonZeroStoneCount > 1);
sort(stones.begin(), stones.end());
return stones[stones.size() - 1];
}
};
|
be3bfdf95352609dc0f6073afef6996d4860a536
|
081cc2fac1350d22438a730fd36885549ba92d21
|
/Unterricht/10_BoyerMoore/sequence.cpp
|
004447e922c0260ec6d7516471da31306f5cf7a4
|
[] |
no_license
|
streusselhirni/AAD_GUI_Stoff
|
1231f81825464e663a77bfa571ab934783cce08d
|
0b33fc300ee8598831271dc39f17033d45f1279c
|
refs/heads/master
| 2020-06-04T09:34:54.690226
| 2019-06-14T15:37:50
| 2019-06-14T15:37:50
| 191,967,590
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 535
|
cpp
|
sequence.cpp
|
#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>
using namespace std;
class FastaReader {
public:
static string read(const string & file, bool & success);
};
string FastaReader::read(const string & file, bool & success) {
ifstream fs(file);
if (!fs) {
success = false;
return "";
}
success = true;
string result = "", line;
while (getline(fs, line)) {
if (line.at(0) != '>') {
result += line;
}
}
return result;
}
int main(int argc, char **argv) {
return 0;
}
|
a395f319562ffd109c804f750b90d933d96c3e35
|
4418812306f6c434970b6fee2b6614c5dae1ca5a
|
/MonteCarloSpinTest/Grid.cpp
|
0c1ffe2b1354080885a15902f1e1ef26e9f70f76
|
[] |
no_license
|
08jne01/Monte-Carlo-Ising-Model-Example
|
5e1689c3e632bbd90fc5ce46dbd1516dfa049fd3
|
ff40f1630621f74140185c5006260d704b7dbf9b
|
refs/heads/master
| 2020-04-22T05:12:54.877651
| 2019-02-11T15:29:13
| 2019-02-11T15:29:13
| 170,152,139
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,700
|
cpp
|
Grid.cpp
|
#include "Grid.h"
Grid::Grid(int w, int h) : width(w), height(h), temp(15), curTime(-2), drawTime(w*h), gen(1), coupleJ(5e-23)
{
srand(10);
rand();
for (int i = 0; i < w; i++)
{
std::vector<int> buffer;
for (int j = 0; j < h; j++)
{
buffer.push_back(random(0.5));
}
gridValues.push_back(buffer);
}
}
double Grid::energy(Vec2 pos_, int spin)
{
int up, down, left, right, iUp, iDown, iLeft, iRight;
Vec2 pos = pos_;
iUp = pos.y - 1;
iDown = pos.y + 1;
iLeft = pos.x - 1;
iRight = pos.x + 1;
//if (pos.x > width - 2) iRight = 0;
//if (pos.x < 1) iLeft = width - 1;
//if (pos.y > height - 2) iDown = 0;
//if (pos.y < 1) pos.y = iUp = height - 1;
if (pos.x > width - 2) iRight = width - 3;
if (pos.x < 1) iLeft = 1;
if (pos.y > height - 2) iDown = height - 3;
if (pos.y < 1) pos.y = iUp = 1;
up = gridValues[pos.x][iUp];
down = gridValues[pos.x][iDown];
left = gridValues[iLeft][pos.y];
right = gridValues[iRight][pos.y];
return -coupleJ * spin * (up + down + left + right);
}
void Grid::flip()
{
int x, y;
x = rand() % (width);
y = rand() % (height);
Vec2 pos(x, y);
int spin = gridValues[pos.x][pos.y];
eCur = energy(pos, spin);
eTrial = energy(pos, -spin);
double r = exp(-(eTrial - eCur) / (K_BOLTZ*temp));
//std::cout << -(eTrial - eCur) / (K_BOLTZ*temp) << std::endl;
if (r > 1)
{
gridValues[pos.x][pos.y] = -spin;
}
else
{
gridValues[pos.x][pos.y] = spin * random(r);
}
curTime++;
}
double Grid::mag()
{
std::vector<std::vector<int>> buffer = gridValues;
double total = 0;
for (int i = 0; i < buffer.size(); i++)
{
for (int j = 0; j < buffer[i].size(); j++)
{
total += (double)buffer[i][j];
}
}
return total / (width*height);
}
void Grid::draw(sf::RenderWindow& window)
{
if (curTime > drawTime || curTime < 0)
{
std::cout << "Generation: " << gen << std::endl;
std::cout << "Temp: " << temp << std::endl;
std::cout << "Magnetisation: " << mag() << std::endl;
gen++;
vertices.clear();
std::vector<std::vector<int>> buffer = gridValues;
for (int i = 0; i < buffer.size(); i++)
{
for (int j = 0; j < buffer[i].size(); j++)
{
int spin = buffer[i][j];
spin += 1;
spin /= 2;
vertices.append(sf::Vertex(sf::Vector2f(i, j), sf::Color(spin * 255, spin * 255, spin * 255, 255)));
}
}
curTime = 0;
//temp -= 0.01*(temp);
if (direction == 1)
{
temp += 0.01;
}
else if (direction == -1)
{
temp -= 0.001*temp;
}
}
window.draw(vertices);
}
int Grid::random(double probability)
{
int number = rand() % (10000 + 1);
double value = (double)number / 10000.0;
if (value < probability)
{
return -1;
}
else
{
return 1;
}
}
|
eb7487194f154fd8ac3b75a463f5d35366ab7c39
|
013cc68b61c675642bf0a6ae8721969f60cc3e16
|
/Movement.cpp
|
3589b94578e674e631f75b454a3bf1004fd479f9
|
[] |
no_license
|
ixi150/Arcanoid
|
7ad678b14ea4b6624d934b27926b485e89f80bdc
|
bba66abeb20ec8ea5328543504cca93a2196d45d
|
refs/heads/master
| 2021-01-10T10:27:45.663652
| 2015-11-14T23:33:19
| 2015-11-14T23:33:19
| 46,195,872
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,851
|
cpp
|
Movement.cpp
|
#include "Header.h"
void GameObject::MoveByAngle(double delta, double Multiplier){
x += Multiplier * speed * sin(angle * 3.14 / 180) * delta;
y -= Multiplier * speed * cos(angle * 3.14 / 180) * delta;
}
void GamePlayer::Move(double delta, GameObjects* Objects){
x -= force_x2 * delta;
x += force_x1 * delta;
if (OutOfMap())
{
}
else
{
for (short i = 0; i < MAX_BALLS; i++)
{
if (Objects->Ball[i].glued)
{
Objects->Ball[i].x -= force_x2 * delta;
Objects->Ball[i].x += force_x1 * delta;
}
}
}
}
void GameBall::Move(double delta, GameObjects* Objects){
if (alive)
{
double Multiplier = 1;
if (glued)
Multiplier = 0;
if (Objects->Player.ActiveBonus[SLOW] > 0)
Multiplier /= 2;
MoveByAngle(delta, Multiplier);
int Resoult = NONE;
Resoult += CollidesWith(Objects->Player);
if (Resoult % 10 == LEFT)
x = Objects->Player.x + Objects->Player.w + r;
if (Resoult % 10 == RIGHT)
x = Objects->Player.x - r;
if (Resoult == CENTER)
y = Objects->Player.y - r;
Resoult += OutOfMap();
Resoult += CollidesWith(Objects->Brick);
CollidesWith(Objects->Block);
if (Resoult)
{
MoveByAngle(delta, -Multiplier);
if (Resoult % 10 > 0)
BounceVertical();
if (Resoult / 10 > 0)
BounceHorizontal();
if (newAngle)
{
angle = newAngle;
newAngle = 0.0f;
}
}
}
}
void GameBonus::Move(double delta, GameObjects* Objects){
if (alive)
{
double Multiplier = 1;
if (Objects->Player.ActiveBonus[SLOW] > 0)
Multiplier /= 2;
MoveByAngle(delta, Multiplier);
CollidesWith(Objects->Player);
if (OutOfMap() == DOWN)
Destroy();
}
}
void GameBullet::Move(double delta, GameObjects* Objects){
if (alive)
{
MoveByAngle(delta, 1.0f);
CollidesWith(Objects->Brick);
OutOfMap();
}
}
void GameBlock::Move(double delta, GameObjects* Objects){
if (alive)
{
angle += (rand()%20 - 10);
double Multiplier = 1;
MoveByAngle(delta, Multiplier);
int Resoult = NONE;
Resoult += CollidesWith(Objects->Player);
if (Resoult % 10 == LEFT)
x = Objects->Player.x + Objects->Player.w + r;
if (Resoult % 10 == RIGHT)
x = Objects->Player.x - r;
Resoult += OutOfMap();
Resoult += CollidesWith(Objects->Brick);
Resoult += CollidesWith(Objects->Block);
if (Resoult)
{
MoveByAngle(delta, -Multiplier);
if (Resoult % 10 > 0)
BounceVertical();
if (Resoult / 10 > 0)
BounceHorizontal();
}
}
}
void MoveGameObjects(GameObjects* Objects, double delta){
Objects->Player.Move(delta, Objects);
for (short i = 0; i < MAX_BALLS; i++)
Objects->Ball[i].Move(delta, Objects);
for (short i = 0; i < MAX_BONUSES; i++)
Objects->Bonus[i].Move(delta, Objects);
for (short i = 0; i < MAX_BULLETS; i++)
Objects->Bullet[i].Move(delta, Objects);
for (short i = 0; i < MAX_BLOCKS; i++)
Objects->Block[i].Move(delta, Objects);
}
|
aeda652ecd67b5fb33b46f31af06df115cd010c1
|
3779d117981db2a864fc5d15c9a716abc652aceb
|
/communication/task_user.cpp
|
cc58dd14d87c371f4e4e54ec4ecc100184170118
|
[] |
no_license
|
eddieruano/ME405
|
f6826da4879ad5507b320f2e3cc7405dfef61270
|
4456b3f9e64b978ffdabaa95e3065d9e7dfb2954
|
refs/heads/master
| 2020-12-24T18:14:07.857410
| 2016-06-10T18:37:38
| 2016-06-10T18:37:38
| 56,257,523
| 0
| 1
| null | 2016-04-21T01:53:36
| 2016-04-14T17:37:05
|
C++
|
UTF-8
|
C++
| false
| false
| 7,827
|
cpp
|
task_user.cpp
|
//*****************************************************************************
/** @file task_user.cpp
* @brief This is the file for the 'task_user' class that is what any
* user will mainly interact with
*
* @details Built on top of JR Ridgely's architecture, this task uses case
* statements that infinitely loop in order to perform certain
* operations. In this version of this class (v1.1) the only
* module avaliable is the 'Main Motor Module' which allows the
* user to control both motors in on either HBridge
* simultaneously.
*
* @author Eddie Ruano
* @author JR Ridgely
*
* Revisions: @li 4/26/2016 ERR added a new module for testing of the encoder
* task
* @li 4/23/2016 added a bunch of helper methods to make testing
* easier in the future
* @li 4/21/2016 overhauled entire case structure
* @li 09-30-2012 JRR Original file was a one-file demonstration
* with two tasks
* @li 10-05-2012 JRR Split into multiple files, one for each task
* @li 10-25-2012 JRR Changed to a more fully C++ version with
* class task_user
* @li 11-04-2012 JRR Modified from the data acquisition example
* to the test suite
* @li 01-04-2014 JRR Changed base class names to TaskBase,
* TaskShare, etc.
* License:
* This file is copyright 2012 by JR Ridgey and released under the Lesser
* GNU
* Public License, version 2. It intended for educational use only, but its
* use
* is not limited thereto. */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUEN-
* TIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
//*****************************************************************************
#include <avr/io.h> // Port I/O for SFR's
#include <avr/wdt.h>
#include "task_user.h" // task_user header file
#include "ansi_terminal.h" //testing ansi
#include "adc.h"
#include "task_user_library.h"
//#include "mirf.h"
//#include "spi.h"
#include "spi_driver.h"
#include "nrf24_driver.h"
#include "nRF24L01.h"
//Set these defines in case we want to change things later.
#define W 1
#define R 0
/** This constant sets how many RTOS ticks the task delays if the user's not
* talking The duration is calculated to be about 5 ms.
*/
const TickType_t ticks_to_delay = ((configTICK_RATE_HZ / 1000) * 5);
//-----------------------------------------------------------------------------
/**
* @brief Constructor that creates a new task to interact with the user.
* All incoming paramters are initialized in the parent class
* construtor TaskBase.
* @details Added new initializations for private variables added in order
* to clean up the clutter in the main case statement in the
* 'run()' method.
*
* @param[in] a_name A character string which will be the name of
* this task
* @param[in] a_priority The priority at which this task will initially
* run (default: 0)
* @param[in] a_stack_size The size of this task's stack in bytes
* (default: configMINIMAL_STACK_SIZE)
* @param p_ser_dev Pointer to a serial device (port, radio, SD
* card, etc.
*/
task_user::task_user (const char* a_name,
unsigned portBASE_TYPE a_priority,
size_t a_stack_size,
emstream* p_ser_dev
)
: TaskBase (a_name, a_priority, a_stack_size, p_ser_dev)
{
*p_serial << ATERM_BKG_WHITE;
}
/**
* @brief This method runs when the 'task_user' is called.
*
* @details This method runs inifitely when the task is called so all logic
* is contained in here. A for(;;) loop runs until it gets to the
* end where it delays for 1 ms to allow other lower level
* priority tasks a chance to run.
*/
void task_user::run (void)
{
time_stamp a_time; // Holds the time so it can be displayed
number_entered = 0; // Holds a number being entered by user
uint8_t count;
count = 0;
uint8_t data[16];
//
for (;;)
{
switch (state)
{
// Initialize first task where we wait for
case (0):
printMainMenu();
// If the user typed a character, read
if (hasUserInput())
{
switch (char_in)
{
case ('p'):
*p_serial << PMS("PORTA: ") << bin << PINA << endl;
*p_serial << PMS("PORTB: ") << bin << PINB << endl;
*p_serial << PMS("PORTC: ") << bin << PINC << endl;
*p_serial << PMS("PORTD: ") << bin << PIND << endl;
*p_serial << PMS("PORTE: ") << bin << PINE << endl;
break;
case ('c'):
transition_to(1);
break;
default:
*p_serial << '"' << char_in << PMS ("\": WTF?") << endl;
break;
}; // End switch for characters
} // End if a character was received
break; // End of state 0
case (1):
nrf24_driver* main_nrf24;
main_nrf24 = new nrf24_driver(p_serial);
main_nrf24 -> printNRF(p_serial, main_nrf24);
main_nrf24 -> initialize();
//Space
*p_serial << endl << endl << endl;
main_nrf24 -> printNRF(p_serial, main_nrf24);
PORTD |= (1 << PD1);
//delay(500);
while (main_nrf24 -> readRegister(STATUS) != 0x40)
{
//main_nrf24 -> printNRF(p_serial, main_nrf24);
}
*p_serial << "Broke Loop! " << endl;
uint8_t data_read[32];
main_nrf24 -> recPayload(4, data_read);
// *p_serial << endl << endl << "DATA READ: "<< hex << data_read[0] << " " << data_read[1] << " " << data_read[2] << " " << data_read[3] << " " << data_read[4] << " " << endl;
*p_serial << "Data Read" << endl;
uint8_t count;
for (count = 0; count < 4; count++)
{
*p_serial << hex << count << ": " << data_read[count] << endl;
}
PORTD &= ~(1 << PD1);
break;
default:
*p_serial << PMS ("Illegal state! Resetting AVR") << endl;
wdt_enable (WDTO_120MS);
for (;;);
break;
} // End switch state
runs++; // Increment counter for debugging
// No matter the state, wait for approximately a millisecond before we
// run the loop again. This gives lower priority tasks a chance to run
delay_ms (1);
}
}
|
58833995b147700af41a92c424e24aebd279ba0d
|
0604bc1e638164443a8b69cbb8edfa9ace2aa9b2
|
/interpolation_search.cpp
|
6b2981971c9d24c339b6fea84856fe1cc596fe40
|
[] |
no_license
|
Rahul172000/C-codes
|
ee7cc55afbc78b39364a701001270eb36236f504
|
a4aceb05f3d277fcc6f75e5773fc1812fc611b99
|
refs/heads/master
| 2022-03-22T20:08:38.651096
| 2019-11-23T03:42:34
| 2019-11-23T03:42:34
| 203,303,855
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 899
|
cpp
|
interpolation_search.cpp
|
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int inter_search(int *arr,int h,int l,int x)
{
while(h>=l)
{
int mid=l+((h-l)*(x-arr[l]))/(arr[h]-arr[l]);
if(arr[mid]>arr[h]||arr[mid]<arr[l])
{
return -1;
}
if(arr[mid]>x)
{
h=mid-1;
}
else if(arr[mid]<x)
{
l=mid+1;
}
else
{
return mid;
}
}
return -1;
}
int main()
{
int n;
cin>>n;
int *arr=new int[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int x;
cin>>x;
sort(arr,arr+n);
cout<<"\nAfter sorting array is\n";
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
int ans=inter_search(arr,n-1,0,x);
if(ans!=-1){cout<<"PRESENT AT "<<ans;}
else{cout<<"NOT PRESENT";}
}
|
d96a5aa672aa0b02b35b671628b51a752d5a38a0
|
ae3253b4a9c21d11e6a2ca5ae1f75ad847965550
|
/Random_Problems/231C.cpp
|
b82c85828502ba1cb974c97dd7e6e4d4b6f4bd62
|
[] |
no_license
|
Mehulcoder/Codeforces
|
c02c3b1956593b196c3082e27f753ed3f70982a7
|
1cac2862d2aa604e1413399eb083de9229d368f5
|
refs/heads/master
| 2021-08-20T05:03:35.015294
| 2021-06-26T17:57:49
| 2021-06-26T17:57:49
| 201,782,304
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 722
|
cpp
|
231C.cpp
|
#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define int long long
const int N=1e5+5;
int n, k, store;
int a[N], pref[N];
int check(int f)
{
for(int i=f;i<=n;i++)
{
int reqd=(a[i]*f)-(pref[i]-pref[i-f]);
if(reqd<=k)
{
store=a[i];
return 1;
}
}
return 0;
}
int binsearch(int lo, int hi)
{
while(lo<hi)
{
int mid=(lo+hi+1)>>1;
if(check(mid))
lo=mid;
else
hi=mid-1;
}
check(lo);
return lo;
}
int32_t main()
{
IOS;
cin>>n>>k;
for(int i=1;i<=n;i++)
cin>>a[i];
sort(a+1, a+n+1);
for(int i=1;i<=n;i++)
pref[i]=pref[i-1]+a[i];
int ans=binsearch(1, n);
cout<<ans<<" "<<store;
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.