hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
9a4c545f7d7970ebd62784026561a3524d260312
1,288
cpp
C++
src/Cyril/Ops/CyrilPaletteItem.cpp
danhett/cyril
38702d3334bdce56b2a4fcabcf4fd43dd08d6f95
[ "MIT" ]
87
2016-05-14T22:43:32.000Z
2021-12-19T04:33:20.000Z
src/Cyril/Ops/CyrilPaletteItem.cpp
danhett/cyril
38702d3334bdce56b2a4fcabcf4fd43dd08d6f95
[ "MIT" ]
15
2016-05-10T12:49:13.000Z
2020-04-15T12:21:52.000Z
src/Cyril/Ops/CyrilPaletteItem.cpp
danhett/cyril
38702d3334bdce56b2a4fcabcf4fd43dd08d6f95
[ "MIT" ]
12
2016-05-16T22:56:19.000Z
2022-01-06T22:45:06.000Z
// // CyrilPaletteItem.cpp // cyril2 // // Created by Darren Mothersele on 06/11/2013. // // #include "CyrilPaletteItem.h" CyrilPaletteItem::CyrilPaletteItem(float _f, Cyril* _e) : d(_f), e(_e) { /* string converter(_s); stringstream sr(converter.substr(0,2)); stringstream sg(converter.substr(2,2)); stringstream sb(converter.substr(4,2)); int ir, ig, ib; sr >> hex >> ir; sg >> hex >> ig; sb >> hex >> ib; r = ir; g = ig; b = ib; */ int sz = _e->size(); if (!(sz == 3)) { yyerror("Palette item requires 3 arguments"); valid = false; } paletteCalc = false; } CyrilPaletteItem::CyrilPaletteItem (const CyrilPaletteItem &other) { d = other.d; r = other.r; g = other.g; b = other.b; } CyrilPaletteItem::~CyrilPaletteItem () { } void CyrilPaletteItem::print() { cout << "PaletteItem" << endl; } Cyril * CyrilPaletteItem::clone () { return new CyrilPaletteItem (*this); } int CyrilPaletteItem::size() { return 4; } void CyrilPaletteItem::eval(CyrilState &_s) { if (!paletteCalc) { e->eval(_s); b = _s.stk->top(); _s.stk->pop(); g = _s.stk->top(); _s.stk->pop(); r = _s.stk->top(); _s.stk->pop(); paletteCalc = true; } _s.stk->push(r); _s.stk->push(g); _s.stk->push(b); _s.stk->push(d); }
18.666667
72
0.599379
danhett
9a52ea0aef02599d5037c5593ca66778a7958eb2
18,342
cc
C++
src/c/dfs_jni.cc
fossabot/xdagj
b30c48eb6584aec24c34a3a87e04d7e97932f10e
[ "MIT" ]
null
null
null
src/c/dfs_jni.cc
fossabot/xdagj
b30c48eb6584aec24c34a3a87e04d7e97932f10e
[ "MIT" ]
null
null
null
src/c/dfs_jni.cc
fossabot/xdagj
b30c48eb6584aec24c34a3a87e04d7e97932f10e
[ "MIT" ]
null
null
null
#include "crc.h" #include "jni.h" #include "dfslib_crypt.h" #include "dfslib_random.h" #include "dnet_crypt.h" #include "dfsrsa.h" #include <string.h> #include <stdio.h> #include <stdlib.h> #define DNET_KEY_SIZE 4096 //#define DNET_KEYLEN 32 #define DNET_KEYLEN ((DNET_KEY_SIZE * 2) / (sizeof(dfsrsa_t) * 8)) #define MINERS_PWD "minersgonnamine" #define SECTOR0_BASE 0x1947f3acu #define SECTOR0_OFFSET 0x82e9d1b5u #define SECTOR_LOG 9 #define SECTOR_SIZE (1 << SECTOR_LOG) static int g_keylen = 0; struct dnet_packet_header { uint8_t type; uint8_t ttl; uint16_t length; uint32_t crc32; }; struct xsector { union { uint8_t byte[SECTOR_SIZE]; uint32_t word[SECTOR_SIZE / sizeof(uint32_t)]; struct xsector *next; struct dnet_packet_header head; }; }; struct xdnet_keys { struct dnet_key priv, pub; struct xsector sect0_encoded, sect0; }; struct dnet_keys { struct dnet_key priv; struct dnet_key pub; }; static struct xdnet_keys g_test_xkeys; static struct dnet_keys *g_dnet_keys = 0; static struct dnet_keys *g_dnet_user_keys = 0; static struct dfslib_crypt *g_test_crypt = 0; static struct dfslib_crypt *g_dnet_user_crypt = 0; static struct dfslib_crypt *g_crypt = 0; //crypt start int crypt_start(void) { struct dfslib_string str; uint32_t sector0[128]; int i; g_crypt = (struct dfslib_crypt*)malloc(sizeof(struct dfslib_crypt)); if(!g_crypt) return -1; dfslib_crypt_set_password(g_crypt, dfslib_utf8_string(&str, MINERS_PWD, strlen(MINERS_PWD))); for(i = 0; i < 128; ++i) { sector0[i] = SECTOR0_BASE + i * SECTOR0_OFFSET; } for(i = 0; i < 128; ++i) { dfslib_crypt_set_sector0(g_crypt, sector0); dfslib_encrypt_sector(g_crypt, sector0, SECTOR0_BASE + i * SECTOR0_OFFSET); } return 0; } static void dnet_sector_to_password(uint32_t sector[SECTOR_SIZE / 4], char password[PWDLEN + 1]) { int i; for (i = 0; i < PWDLEN / 8; ++i) { unsigned crc = crc_of_array((unsigned char *)(sector + i * SECTOR_SIZE / 4 / (PWDLEN / 8)), SECTOR_SIZE / (PWDLEN / 8)); sprintf(password + 8 * i, "%08X", crc); } } static void dnet_make_key(dfsrsa_t *key, int keylen) { unsigned i; for(i = keylen; i < DNET_KEYLEN; i += keylen) { memcpy(key + i, key, keylen * sizeof(dfsrsa_t)); } } //生成random static void dnet_random_sector(uint32_t sector[SECTOR_SIZE / 4]) { char password[PWDLEN + 1] = "Iyf&%d#$jhPo_t|3fgd+hf(s@;)F5D7gli^kjtrd%.kflP(7*5gt;Y1sYRC4VGL&"; int i, j; for (i = 0; i < 3; ++i) { struct dfslib_string str; dfslib_utf8_string(&str, password, PWDLEN); dfslib_random_sector(sector, 0, &str, &str); for (j = KEYLEN_MIN / 8; j <= SECTOR_SIZE / 4; j += KEYLEN_MIN / 8) sector[j - 1] &= 0x7FFFFFFF; if (i == 2) break; dfsrsa_crypt((dfsrsa_t *)sector, SECTOR_SIZE / sizeof(dfsrsa_t), g_dnet_keys->priv.key, DNET_KEYLEN); dnet_sector_to_password(sector, password); } } int dnet_generate_random_array(void *array, unsigned long size) { uint32_t sector[SECTOR_SIZE / 4]; unsigned long i; if (size < 4 || size & (size - 1)) return -1; if (size >= 512) { for (i = 0; i < size; i += 512) dnet_random_sector((uint32_t *)((uint8_t *)array + i)); } else { dnet_random_sector(sector); for (i = 0; i < size; i += 4) { *(uint32_t *)((uint8_t *)array + i) = crc_of_array((unsigned char *)sector + i * 512 / size, 512 / size); } } return 0; } static int dnet_detect_keylen(dfsrsa_t *key, int keylen) { if (g_keylen && (key == g_dnet_keys->priv.key || key == g_dnet_keys->pub.key)) return g_keylen; while (keylen >= 8) { if (memcmp(key, key + keylen / 2, keylen * sizeof(dfsrsa_t) / 2)) break; keylen /= 2; } return keylen; } static int set_user_crypt(struct dfslib_string *pwd) { uint32_t sector0[128]; int i; g_dnet_user_crypt = (struct dfslib_crypt*)malloc(sizeof(struct dfslib_crypt)); if (!g_dnet_user_crypt) return -1; //置0 memset(g_dnet_user_crypt->pwd, 0, sizeof(g_dnet_user_crypt->pwd)); dfslib_crypt_set_password(g_dnet_user_crypt, pwd); for (i = 0; i < 128; ++i) sector0[i] = 0x4ab29f51u + i * 0xc3807e6du; for (i = 0; i < 128; ++i) { dfslib_crypt_set_sector0(g_dnet_user_crypt, sector0); dfslib_encrypt_sector(g_dnet_user_crypt, sector0, 0x3e9c1d624a8b570full + i * 0x9d2e61fc538704abull); } return 0; } static int dnet_test_keys(void) { uint32_t src[SECTOR_SIZE / 4], dest[SECTOR_SIZE / 4]; dnet_random_sector(src); memcpy(dest, src, SECTOR_SIZE); if (dfsrsa_crypt((dfsrsa_t *)dest, SECTOR_SIZE / sizeof(dfsrsa_t), g_dnet_keys->priv.key, DNET_KEYLEN)) return 1; if (dfsrsa_crypt((dfsrsa_t *)dest, SECTOR_SIZE / sizeof(dfsrsa_t), g_dnet_keys->pub.key, DNET_KEYLEN)) return 2; if (memcmp(dest, src, SECTOR_SIZE)) return 3; memcpy(dest, src, SECTOR_SIZE); if (dfsrsa_crypt((dfsrsa_t *)dest, SECTOR_SIZE / sizeof(dfsrsa_t), g_dnet_keys->pub.key, DNET_KEYLEN)) return 4; if (dfsrsa_crypt((dfsrsa_t *)dest, SECTOR_SIZE / sizeof(dfsrsa_t), g_dnet_keys->priv.key, DNET_KEYLEN)) return 5; if (memcmp(dest, src, SECTOR_SIZE)) return 6; return 0; } extern "C" JNIEXPORT jint JNICALL Java_io_xdag_crypto_jni_Native_load_1dnet_1keys( JNIEnv *env, jobject *obj, jbyteArray keybytes, jint length) { char buf[3072] = {0}; env->GetByteArrayRegion(keybytes,0,length,(jbyte*)buf); memcpy(&g_test_xkeys,buf,sizeof(struct xdnet_keys)); return 3072; } extern "C" JNIEXPORT jint JNICALL Java_io_xdag_crypto_jni_Native_dnet_1crypt_1init( JNIEnv *env, jobject *obj) { char password[PWDLEN + 1]; struct dfslib_string str; g_test_crypt = (struct dfslib_crypt*)malloc(sizeof(struct dfslib_crypt)); g_dnet_user_crypt = (struct dfslib_crypt*)malloc(sizeof(struct dfslib_crypt)); g_dnet_keys = (struct dnet_keys*)malloc(sizeof(struct dnet_keys)); memset(g_test_crypt,0,sizeof(struct dfslib_crypt)); memset(g_dnet_user_crypt,0,sizeof(struct dfslib_crypt)); memset(g_dnet_keys,0,sizeof(struct dnet_keys)); if (crc_init()) { return -1; } dnet_sector_to_password(g_test_xkeys.sect0.word, password); //为密码做置换操作 dfslib_crypt_set_password(g_test_crypt, dfslib_utf8_string(&str, password, PWDLEN)); //加密密码到sector0 dfslib_crypt_set_sector0(g_test_crypt, g_test_xkeys.sect0.word); return 0; } extern "C" JNIEXPORT jbyteArray JNICALL Java_io_xdag_crypto_jni_Native_dfslib_1encrypt_1byte_1sector( JNIEnv *env, jobject *obj, jbyteArray raw, jint length, jlong sectorNo) { //LOGI("get raw byte length is %d",length); //加密数据 char buf[512] = {0}; env->GetByteArrayRegion(raw,0,512,(jbyte*)buf); dfslib_encrypt_sector(g_test_crypt,(dfs32*)buf, (unsigned long long)sectorNo); jbyteArray jba = env->NewByteArray(512); env->SetByteArrayRegion(jba,0, 512, (jbyte*)buf); return jba; } extern "C" JNIEXPORT jbyteArray JNICALL Java_io_xdag_crypto_jni_Native_dfslib_1uncrypt_1byte_1sector( JNIEnv *env, jobject *obj, jbyteArray encrypted, jint length, jlong sectorNo) { //LOGI("get encrypted byte length is %d",length); char buf[512] = {0}; env->GetByteArrayRegion(encrypted,0,512,(jbyte*)buf); //解密数据 dfslib_uncrypt_sector(g_test_crypt,(dfs32*)buf,(unsigned long long)sectorNo); //LOGI("uncrypted data is %s ",buf); jbyteArray jba = env->NewByteArray(512); env->SetByteArrayRegion(jba,0,512,(jbyte*)buf); return jba; } extern "C" JNIEXPORT jlong JNICALL Java_io_xdag_crypto_jni_Native_get_1user_1dnet_1crypt( JNIEnv *env, jobject *obj) { return (jlong)g_dnet_user_crypt; } extern "C" JNIEXPORT jlong JNICALL Java_io_xdag_crypto_jni_Native_get_1dnet_1keys( JNIEnv *env, jobject *obj) { return (jlong)g_dnet_keys; } extern "C" JNIEXPORT jint JNICALL Java_io_xdag_crypto_jni_Native_set_1user_1dnet_1crypt( JNIEnv *env, jobject *obj, jstring input_pwd) { jboolean isCopy=JNI_TRUE; struct dfslib_string str; uint32_t sector0[128]; const char* pwd = env->GetStringUTFChars(input_pwd,&isCopy); dfslib_utf8_string(&str, pwd, strlen(pwd)); dfslib_crypt_set_password(g_dnet_user_crypt, &str); for(int i = 0; i < 128; ++i) { sector0[i] = 0x4ab29f51u + i * 0xc3807e6du; } for(int i = 0; i < 128; ++i) { dfslib_crypt_set_sector0(g_dnet_user_crypt, sector0); dfslib_encrypt_sector(g_dnet_user_crypt, sector0, 0x3e9c1d624a8b570full + i * 0x9d2e61fc538704abull); } return 0; } extern "C" JNIEXPORT void JNICALL Java_io_xdag_crypto_jni_Native_set_1user_1random( JNIEnv *env, jobject *obj, jstring input_random_keys) { jboolean isCopy=JNI_TRUE; struct dfslib_string str; const char* random_keys = env->GetStringUTFChars(input_random_keys,&isCopy); dfslib_random_fill(g_dnet_keys->pub.key, DNET_KEYLEN * sizeof(dfsrsa_t), 0, dfslib_utf8_string(&str, random_keys, strlen(random_keys))); } extern "C" JNIEXPORT jbyteArray JNICALL Java_io_xdag_crypto_jni_Native_make_1dnet_1keys( JNIEnv *env, jobject *obj, jint keylen) { dfsrsa_keygen(g_dnet_keys->priv.key, g_dnet_keys->pub.key, keylen); dnet_make_key(g_dnet_keys->priv.key, keylen); dnet_make_key(g_dnet_keys->pub.key, keylen); if(g_dnet_user_crypt) { for(int i = 0; i < 4; ++i) { dfslib_encrypt_sector(g_dnet_user_crypt, (uint32_t *)g_dnet_keys + 128 * i, ~(uint64_t)i); } } jbyteArray jba = env->NewByteArray(sizeof(dnet_keys)); env->SetByteArrayRegion(jba,0,sizeof(dnet_keys),(jbyte*)g_dnet_keys); if(g_dnet_user_crypt) { for(int i = 0; i < 4; ++i) { dfslib_uncrypt_sector(g_dnet_user_crypt, (uint32_t *)g_dnet_keys + 128 * i, ~(uint64_t)i); } } //dnet keys returned to java layer and written by java's file stream return jba; } //Java_io_xdag_crypto_jni_Native_dfslib_1encrypt_1byte_1sector extern "C" JNIEXPORT jbyteArray JNICALL Java_io_xdag_crypto_jni_Native_encrypt_1wallet_1key( JNIEnv *env, jobject *obj, jbyteArray privkey, jint n) { uint32_t privkey_bytes[8] = {0}; env->GetByteArrayRegion(privkey,0,8 * sizeof(uint32_t),(jbyte*)privkey_bytes); //8 * 32 dfslib_encrypt_array(g_dnet_user_crypt, privkey_bytes, 8, n); jbyteArray jba = env->NewByteArray(sizeof(privkey_bytes)); env->SetByteArrayRegion(jba,0,sizeof(privkey_bytes),(jbyte*)privkey_bytes); return jba; } //Java_io_xdag_crypto_jni_Native extern "C" JNIEXPORT jbyteArray JNICALL Java_io_xdag_crypto_jni_Native_uncrypt_1wallet_1key( JNIEnv *env, jobject *obj, jbyteArray privkey, jint n) { uint32_t privkey_bytes[8] = {0}; env->GetByteArrayRegion(privkey,0,8 * sizeof(uint32_t),(jbyte*)privkey_bytes); //8 * 32 dfslib_uncrypt_array(g_dnet_user_crypt, privkey_bytes, 8, n); jbyteArray jba = env->NewByteArray(sizeof(privkey_bytes)); env->SetByteArrayRegion(jba,0,sizeof(privkey_bytes),(jbyte*)privkey_bytes); return jba; } //generate_random_array extern "C" JNIEXPORT jbyteArray JNICALL Java_io_xdag_crypto_jni_Native_generate_1random_1array( JNIEnv *env, jobject *obj, jbyteArray array, jint size) { uint32_t array_bytes[8] = {0}; env->GetByteArrayRegion(array,0,8 * sizeof(uint32_t),(jbyte*)array_bytes); //8*32 dnet_generate_random_array(array_bytes,size); jbyteArray jba = env->NewByteArray(sizeof(array_bytes)); env->SetByteArrayRegion(jba,0,sizeof(array_bytes),(jbyte*)array_bytes); return jba; } extern "C" JNIEXPORT jbyteArray JNICALL Java_io_xdag_crypto_jni_Native_generate_1random_1bytes( JNIEnv *env, jobject *obj, jbyteArray array, jint size) { uint8_t array_bytes[8] = {0}; env->GetByteArrayRegion(array,0,8 * sizeof(uint8_t),(jbyte*)array_bytes); //8*1 dnet_generate_random_array(array_bytes,size); jbyteArray jba = env->NewByteArray(sizeof(array_bytes)); env->SetByteArrayRegion(jba,0,sizeof(array_bytes),(jbyte*)array_bytes); return jba; } /* * Class: io_xdag_Myron_jni_MyJni * Method: dfslib_uncrypt_array * Signature: ([BIJ)[B */ extern "C" JNIEXPORT jbyteArray JNICALL Java_io_xdag_crypto_jni_Native_dfslib_1uncrypt_1array( JNIEnv *env, jobject *obj, jbyteArray encrypt, jint nfiled, jlong sectorNo) { int size = 32 * nfiled; char buf[512] = {0}; env -> GetByteArrayRegion(encrypt, 0 , size, (jbyte*)buf); int pos = 0; //解密数据这里要循环解密 for (int i = 0; i< nfiled ;i++) { dfslib_uncrypt_array(g_crypt, (dfs32*)(buf+ pos), 8, sectorNo++); pos = pos+32; } jbyteArray jba = env -> NewByteArray(size); //env->SetByteArrayRegion(jba,0,512,(jbyte*)buf); env-> SetByteArrayRegion(jba, 0, size, (jbyte*)buf); return jba; } /* * Class: io_xdag_Myron_jni_MyJni * Method: dfslib_encrypt_array * Signature: ([BIJ)[B */ extern "C" JNIEXPORT jbyteArray JNICALL Java_io_xdag_crypto_jni_Native_dfslib_1encrypt_1array (JNIEnv *env, jobject *obj, jbyteArray encrypt, jint nfiled, jlong sectorNo ){ int size = 32 * nfiled; char buf[512] = {0}; env -> GetByteArrayRegion(encrypt, 0 , size, (jbyte*)buf); int pos = 0; //解密数据这里要循环解密 for (int i = 0; i< nfiled ;i++) { dfslib_encrypt_array(g_crypt, (dfs32*)(buf+ pos), 8, sectorNo++); pos = pos+32; } jbyteArray jba = env -> NewByteArray(size); env-> SetByteArrayRegion(jba, 0, size, (jbyte*)buf); return jba; } //开始写三个主要的函数 // JNIEXPORT void JNICALL Java_io_xdag_Myron_jni_MyJni_init_1g_1crypt extern "C" JNIEXPORT jint JNICALL Java_io_xdag_crypto_jni_Native_crypt_1start( JNIEnv *env, jobject *obj) { return crypt_start(); } extern "C" JNIEXPORT void JNICALL Java_io_xdag_crypto_jni_Native_dfslib_1random_1init( JNIEnv *env, jobject *obj) { dfslib_random_init(); } extern "C" JNIEXPORT void JNICALL Java_io_xdag_crypto_jni_Native_crc_1init( JNIEnv *env, jobject *obj) { crc_init(); } extern "C" JNIEXPORT jint JNICALL Java_io_xdag_crypto_jni_Native_dnet_1detect_1keylen( JNIEnv *env, jobject *obj,jint len) { return dnet_detect_keylen(g_dnet_keys->pub.key,len); } extern "C" JNIEXPORT jint JNICALL Java_io_xdag_crypto_jni_Native_verify_1dnet_1key( JNIEnv *env, jobject *obj, jstring password, jbyteArray key) { char buf[2048] = {0}; env -> GetByteArrayRegion(key, 0 , 2048, (jbyte*)buf); memcpy(g_dnet_keys, buf, 2048); jboolean isCopy=JNI_TRUE; struct dfslib_string str; uint32_t sector0[128]; const char* pwd = env->GetStringUTFChars(password,&isCopy); dfslib_utf8_string(&str, pwd, strlen(pwd)); g_keylen = dnet_detect_keylen(g_dnet_keys->pub.key,DNET_KEYLEN); if (dnet_test_keys()) { //---------------------------------------------------- memset(g_dnet_user_crypt->pwd, 0, sizeof(g_dnet_user_crypt->pwd)); dfslib_crypt_set_password(g_dnet_user_crypt, &str); //给sector0进行赋值 每一个都是固定的 for (int i = 0; i < 128; ++i) { sector0[i] = 0x4ab29f51u + i * 0xc3807e6du; } for (int i = 0; i < 128; ++i) { //128次加密?? dfslib_crypt_set_sector0(g_dnet_user_crypt, sector0); dfslib_encrypt_sector(g_dnet_user_crypt, sector0, 0x3e9c1d624a8b570full + i * 0x9d2e61fc538704abull); } if (g_dnet_user_crypt) { for (int i = 0; i < (sizeof(struct dnet_keys) >> 9); ++i) { dfslib_uncrypt_sector(g_dnet_user_crypt, (uint32_t *)g_dnet_keys + 128 * i, ~(uint64_t)i); } } //----------------------------------------------------------------------------------------------------- g_keylen = 0; g_keylen = dnet_detect_keylen(g_dnet_keys->pub.key, DNET_KEYLEN); } return -dnet_test_keys(); } extern "C" JNIEXPORT jbyteArray JNICALL Java_io_xdag_crypto_jni_Native_general_1dnet_1key( JNIEnv *env, jobject *obj, jstring password, jstring random) { jbyteArray jba = env->NewByteArray(sizeof(dnet_keys)); jboolean isCopy=JNI_TRUE; struct dfslib_string str; uint32_t sector0[128]; const char* pwd = env->GetStringUTFChars(password,&isCopy); dfslib_utf8_string(&str, pwd, strlen(pwd)); dfslib_crypt_set_password(g_dnet_user_crypt, &str); for(int i = 0; i < 128; ++i) { sector0[i] = 0x4ab29f51u + i * 0xc3807e6du; } for(int i = 0; i < 128; ++i) { dfslib_crypt_set_sector0(g_dnet_user_crypt, sector0); dfslib_encrypt_sector(g_dnet_user_crypt, sector0, 0x3e9c1d624a8b570full + i * 0x9d2e61fc538704abull); } //rand fill struct dfslib_string str1; const char* random_keys = env->GetStringUTFChars(random,&isCopy); dfslib_random_fill(g_dnet_keys->pub.key, DNET_KEYLEN * sizeof(dfsrsa_t), 0, dfslib_utf8_string(&str1, random_keys, strlen(random_keys))); dfsrsa_keygen(g_dnet_keys->priv.key, g_dnet_keys->pub.key, DNET_KEYLEN); dnet_make_key(g_dnet_keys->priv.key, DNET_KEYLEN); dnet_make_key(g_dnet_keys->pub.key, DNET_KEYLEN); if (g_dnet_user_crypt) { for (int i = 0; i < (sizeof(struct dnet_keys) >> 9); ++i) { dfslib_encrypt_sector(g_dnet_user_crypt, (uint32_t *)g_dnet_keys + 128 * i, ~(uint64_t)i); } //把密钥返回 env->SetByteArrayRegion(jba,0,sizeof(dnet_keys),(jbyte*)g_dnet_keys); } if (g_dnet_user_crypt) { for (int i = 0; i < (sizeof(struct dnet_keys) >> 9); ++i){ dfslib_uncrypt_sector(g_dnet_user_crypt, (uint32_t *)g_dnet_keys + 128 * i, ~(uint64_t)i); } } return jba; }
30.167763
145
0.657017
fossabot
9a532ceacb03eda34f93e2483ea1039b1af28261
1,879
cpp
C++
src/entity_systems/ffi_layer.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
11
2015-03-02T07:43:00.000Z
2021-12-04T04:53:02.000Z
src/entity_systems/ffi_layer.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
1
2015-03-28T17:17:13.000Z
2016-10-10T05:49:07.000Z
src/entity_systems/ffi_layer.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
3
2016-11-04T01:14:31.000Z
2020-05-07T23:42:27.000Z
/**************************** Copyright © 2014 Luke Salisbury This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ****************************/ #include "ffi_layer.h" #include "ffi_functions.h" #include "display/display.h" #include "elix/elix_endian.hpp" /** * @brief Lux_FFI_Layer_Rotation * @param layer * @param roll * @param pitch * @param yaw */ void Lux_FFI_Layer_Rotation( int8_t layer, int16_t roll, int16_t pitch, int16_t yaw ) { lux::display->ChangeLayerRotation( layer, roll, pitch, yaw ); } /** * @brief Lux_FFI_Layer_Offset * @param layer * @param x * @param y */ void Lux_FFI_Layer_Offset( int8_t layer, int32_t fixed_x, int32_t fixed_y ) { if ( layer == -1) lux::display->SetCameraView( (fixed)fixed_x, (fixed)fixed_y ); else lux::display->SetCameraView( layer, (fixed)fixed_x, (fixed)fixed_y ); } /** * @brief Lux_FFI_Layer_Colour * @param layer * @param colour */ void Lux_FFI_Layer_Colour( int8_t layer, uint32_t colour) { cell_colour temp_colour; temp_colour.hex = elix::endian::host32( colour ); if ( layer >= 0 ) lux::display->SetLayerColour( layer, temp_colour.rgba ); }
33.553571
243
0.728579
mokoi
9a54d2abbb11bce9c69996a17f854e121989a061
828
hpp
C++
detail/itoa.hpp
isadchenko/brig
3e65a44fa4b8690cdfa8bdaca08d560591afcc38
[ "MIT" ]
null
null
null
detail/itoa.hpp
isadchenko/brig
3e65a44fa4b8690cdfa8bdaca08d560591afcc38
[ "MIT" ]
null
null
null
detail/itoa.hpp
isadchenko/brig
3e65a44fa4b8690cdfa8bdaca08d560591afcc38
[ "MIT" ]
null
null
null
// Andrew Naplavkov // http://stackoverflow.com/questions/6713420/c-convert-integer-to-string-at-compile-time #ifndef BRIG_DETAIL_ITOA_HPP #define BRIG_DETAIL_ITOA_HPP #include <boost/mpl/string.hpp> #include <string> namespace brig { namespace detail { template <bool Top, size_t N> struct itoa_impl { typedef typename ::boost::mpl::push_back<typename itoa_impl<false, N / 10>::type, ::boost::mpl::char_<'0' + N % 10>>::type type; }; template <> struct itoa_impl<false, 0> { typedef ::boost::mpl::string<> type; }; template <> struct itoa_impl<true, 0> { typedef ::boost::mpl::string<'0'> type; }; template <size_t N> struct itoa { typedef typename ::boost::mpl::c_str<typename itoa_impl<true, N>::type>::type type; }; } } // brig::detail #endif // BRIG_DETAIL_ITOA_HPP
20.7
131
0.672705
isadchenko
9a5506e36068522004539a4f8ab99dbdfa483cf4
140
cpp
C++
references/aoapc-book/BeginningAlgorithmContests/exercises/ch5/5.5.2/UVaOJ/10055.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
68
2017-10-08T04:44:23.000Z
2019-08-06T20:15:02.000Z
references/aoapc-book/BeginningAlgorithmContests/exercises/ch5/5.5.2/UVaOJ/10055.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
null
null
null
references/aoapc-book/BeginningAlgorithmContests/exercises/ch5/5.5.2/UVaOJ/10055.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
18
2017-05-31T02:52:23.000Z
2019-07-05T09:18:34.000Z
#include<iostream> using namespace std; int main() { long long a,b,c; while(cin >>a >> b){ c=(a-b>0)?a-b:b-a; cout << c<<endl;} return 0; }
15.555556
57
0.6
voleking
9a587b91b82d42978cca68c9c5c1d99100b877aa
3,198
cpp
C++
util/auv_map_projection.cpp
mattjr/benthicQT
bd5415d5a18f528b5b2ce4cc1524b7f4f651a1e8
[ "Apache-2.0" ]
9
2016-06-07T09:38:03.000Z
2021-11-25T17:30:59.000Z
util/auv_map_projection.cpp
mattjr/benthicQT
bd5415d5a18f528b5b2ce4cc1524b7f4f651a1e8
[ "Apache-2.0" ]
null
null
null
util/auv_map_projection.cpp
mattjr/benthicQT
bd5415d5a18f528b5b2ce4cc1524b7f4f651a1e8
[ "Apache-2.0" ]
4
2016-06-16T16:55:33.000Z
2019-04-29T02:34:46.000Z
//! //! \file auv_map_projection.cpp //! //! Conversion between geographic coordinates 2D map projection coordinates //! //! \author Ian Mahon //! #include "auv_map_projection.hpp" #include <GeographicConversions/ufLocalRedfearn.h> using namespace UF::GeographicConversions; using namespace std; #define LOCAL_REDFEARN_ELLIPSOID_NAME "WGS84" #define LOCAL_REDFEARN_GRID_NAME "UTM" // // FIXME: What are grid_convergence and point_scale, and what should I do // with them? // //! Create a Local_WGS84_TM_Projection object Local_WGS84_TM_Projection::Local_WGS84_TM_Projection( double origin_latitude, double origin_longitude ) { double grid_convergence, point_scale; // Create projection object local_redfearn = new LocalRedfearn( LOCAL_REDFEARN_ELLIPSOID_NAME, LOCAL_REDFEARN_GRID_NAME, origin_longitude ); // Calculate the map coords produced by LocalRedfearn for the origin. // These offsets will are stored in the instance variables origin_easting and // origin_northing, are are used to transform the map coords such that the // origin is (0,0). local_redfearn->GetGridCoordinates( origin_latitude, origin_longitude, origin_zone, origin_easting, origin_northing, grid_convergence, point_scale ); } //! Local_WGS84_TM_Projection destructor Local_WGS84_TM_Projection::~Local_WGS84_TM_Projection( void ) { delete local_redfearn; } //! Calculate map coordinates for the given geographic coordinates (latitude //! and longitude) void Local_WGS84_TM_Projection::calc_map_coords( double latitude, double longitude, double &map_northing, double &map_easting ) const { double grid_convergence, point_scale; double northing, easting; local_redfearn->GetZoneGridCoordinates( latitude, longitude, origin_zone, easting, northing, grid_convergence, point_scale ); // Remove origin offset map_northing = northing - origin_northing; map_easting = easting - origin_easting; } //! Calculate geographic coordinates (latitude and longitude) for the given //! map coordinates void Local_WGS84_TM_Projection::calc_geo_coords( double map_northing, double map_easting, double &latitude, double &longitude ) const { // Add origin offset double northing = map_northing + origin_northing; double easting = map_easting + origin_easting; double grid_convergence, point_scale; local_redfearn->GetGeographicCoordinates( origin_zone, easting, northing, latitude, longitude, grid_convergence, point_scale ); }
35.932584
80
0.605691
mattjr
9a591b4a1748d455b834f77cb6f9839b65a2b4a1
6,382
cc
C++
lib/correspondence.cc
dbs4261/smvs
5a4ff04d7642a354c543ffadbead14c4be73918e
[ "BSD-3-Clause" ]
null
null
null
lib/correspondence.cc
dbs4261/smvs
5a4ff04d7642a354c543ffadbead14c4be73918e
[ "BSD-3-Clause" ]
null
null
null
lib/correspondence.cc
dbs4261/smvs
5a4ff04d7642a354c543ffadbead14c4be73918e
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2017, Fabian Langguth * TU Darmstadt - Graphics, Capture and Massively Parallel Computing * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the LICENSE.txt file for details. */ #include "correspondence.h" namespace smvs { Correspondence::Correspondence (mve::math::Matrix3d const& M, mve::math::Vec3d const& t, double u, double v, double w, double w_dx, double w_dy) { this->update(M, t, u, v, w, w_dx, w_dy); } void Correspondence::update (mve::math::Matrix3d const& M, mve::math::Vec3d const& t, double u, double v, double w, double w_dx, double w_dy) { this->t = t; this->w = w; this->p_prime[0] = M(0,0); this->p_prime[1] = M(0,1); this->q_prime[0] = M(1,0); this->q_prime[1] = M(1,1); this->r_prime[0] = M(2,0); this->r_prime[1] = M(2,1); this->w_prime[0] = w_dx; this->w_prime[1] = w_dy; this->p = M(0,0) * u + M(0,1) * v + M(0,2); this->q = M(1,0) * u + M(1,1) * v + M(1,2); this->r = M(2,0) * u + M(2,1) * v + M(2,2); this->a = w * p + t[0]; this->b = w * q + t[1]; this->d = w * r + t[2]; this->d2 = d * d; } void Correspondence::fill (double * corr) const { corr[0] = a / d; corr[1] = b / d; } void Correspondence::get_derivative ( double const* dn00, double const* dn10, double const* dn01, double const* dn11, mve::math::Vec2d * c_dn00, mve::math::Vec2d * c_dn10, mve::math::Vec2d * c_dn01, mve::math::Vec2d * c_dn11) const { double du_w = (p * d - r * a) / d2; double dv_w = (q * d - r * b) / d2; for (int i = 0; i < 4; ++i) { c_dn00[i] = mve::math::Vec2d(du_w, dv_w) * dn00[i]; c_dn10[i] = mve::math::Vec2d(du_w, dv_w) * dn10[i]; c_dn01[i] = mve::math::Vec2d(du_w, dv_w) * dn01[i]; c_dn11[i] = mve::math::Vec2d(du_w, dv_w) * dn11[i]; } } void Correspondence::fill_derivative (double const* dn, mve::math::Vec2d * c_dn) const { double du_w = (p * d - r * a) / d2; double dv_w = (q * d - r * b) / d2; for (int n = 0; n < 4; ++n) for (int i = 0; i < 4; ++i) { c_dn[n * 4 + i][0] = du_w * dn[n * 24 + i]; c_dn[n * 4 + i][1] = dv_w * dn[n * 24 + i]; } } void Correspondence::fill_jacobian(double * jac) const { jac[0] = (w_prime[0] * p + w * p_prime[0]) / d; jac[2] = (w_prime[1] * p + w * p_prime[1]) / d; jac[0] -= a * (w_prime[0] * r + w * r_prime[0]) / d2; jac[2] -= a * (w_prime[1] * r + w * r_prime[1]) / d2; jac[1] = (w_prime[0] * q + w * q_prime[0]) / d; jac[3] = (w_prime[1] * q + w * q_prime[1]) / d; jac[1] -= b * (w_prime[0] * r + w * r_prime[0]) / d2; jac[3] -= b * (w_prime[1] * r + w * r_prime[1]) / d2; } void Correspondence::fill_jacobian_derivative_grad(double const* grad, double const* dn, mve::math::Vec2d * jac_dn) const { double d4 = d2 * d2; double d_prime = 2.0 * d * r; mve::math::Vec2d du_a_temp; du_a_temp[0] = w * (p_prime[0] * r - p * r_prime[0]); du_a_temp[1] = w * (p_prime[1] * r - p * r_prime[1]); mve::math::Vec2d du_a_prime; du_a_prime[0] = 2.0 * du_a_temp[0]; du_a_prime[1] = 2.0 * du_a_temp[1]; mve::math::Vec2d du_b_prime; du_b_prime[0] = (p_prime[0] * t[2] - r_prime[0] * t[0]); du_b_prime[1] = (p_prime[1] * t[2] - r_prime[1] * t[0]); double du_c_prime = (p * t[2] - r * t[0]); mve::math::Vec2d du_c; du_c[0] = w_prime[0] * du_c_prime; du_c[1] = w_prime[1] * du_c_prime; mve::math::Vec2d dv_a_temp; dv_a_temp[0] = w * (q_prime[0] * r - q * r_prime[0]); dv_a_temp[1] = w * (q_prime[1] * r - q * r_prime[1]); mve::math::Vec2d dv_a_prime; dv_a_prime[0] = 2.0 * dv_a_temp[0]; dv_a_prime[1] = 2.0 * dv_a_temp[1]; mve::math::Vec2d dv_b_prime; dv_b_prime[0] = (q_prime[0] * t[2] - r_prime[0] * t[1]); dv_b_prime[1] = (q_prime[1] * t[2] - r_prime[1] * t[1]); double dv_c_prime = (q * t[2] - r * t[1]); mve::math::Vec2d dv_c; dv_c[0] = w_prime[0] * dv_c_prime; dv_c[1] = w_prime[1] * dv_c_prime; mve::math::Vec2d du_a_b_c; du_a_b_c[0] = w * (du_a_temp[0] + du_b_prime[0]) + du_c[0]; du_a_b_c[1] = w * (du_a_temp[1] + du_b_prime[1]) + du_c[1]; mve::math::Vec2d dv_a_b_c; dv_a_b_c[0] = w * (dv_a_temp[0] + dv_b_prime[0]) + dv_c[0]; dv_a_b_c[1] = w * (dv_a_temp[1] + dv_b_prime[1]) + dv_c[1]; mve::math::Vec2d du_ap_bp_d; du_ap_bp_d[0] = (du_a_prime[0] + du_b_prime[0]) / d2; du_ap_bp_d[1] = (du_a_prime[1] + du_b_prime[1]) / d2; mve::math::Vec2d dv_ap_bp_d; dv_ap_bp_d[0] = (dv_a_prime[0] + dv_b_prime[0]) / d2; dv_ap_bp_d[1] = (dv_a_prime[1] + dv_b_prime[1]) / d2; mve::math::Vec2d du_a_b_c_d_prime; du_a_b_c_d_prime[0] = du_a_b_c[0] * d_prime / d4; du_a_b_c_d_prime[1] = du_a_b_c[1] * d_prime / d4; mve::math::Vec2d dv_a_b_c_d_prime; dv_a_b_c_d_prime[0] = dv_a_b_c[0] * d_prime / d4; dv_a_b_c_d_prime[1] = dv_a_b_c[1] * d_prime / d4; double du_c_prime_d = du_c_prime / d2; double dv_c_prime_d = dv_c_prime / d2; mve::math::Vec2d du_ap_bp_d_du_a_b_c_d_prime; du_ap_bp_d_du_a_b_c_d_prime[0] = du_ap_bp_d[0] - du_a_b_c_d_prime[0]; du_ap_bp_d_du_a_b_c_d_prime[1] = du_ap_bp_d[1] - du_a_b_c_d_prime[1]; mve::math::Vec2d dv_ap_bp_d_dv_a_b_c_d_prime; dv_ap_bp_d_dv_a_b_c_d_prime[0] = dv_ap_bp_d[0] - dv_a_b_c_d_prime[0]; dv_ap_bp_d_dv_a_b_c_d_prime[1] = dv_ap_bp_d[1] - dv_a_b_c_d_prime[1]; mve::math::Vec2d du_dn; mve::math::Vec2d dv_dn; for (int n = 0; n < 4; ++n) for (int i = 0; i < 4; ++i) { int offset = n * 24; du_dn[0] = du_ap_bp_d_du_a_b_c_d_prime[0] * dn[offset + 0 + i]; du_dn[1] = du_ap_bp_d_du_a_b_c_d_prime[1] * dn[offset + 0 + i]; dv_dn[0] = dv_ap_bp_d_dv_a_b_c_d_prime[0] * dn[offset + 0 + i]; dv_dn[1] = dv_ap_bp_d_dv_a_b_c_d_prime[1] * dn[offset + 0 + i]; jac_dn[n * 4 + i][0] = (du_dn[0] + du_c_prime_d * dn[offset + 4 + i]) * grad[0] + (dv_dn[0] + dv_c_prime_d * dn[offset + 4 + i]) * grad[1]; jac_dn[n * 4 + i][1] = (du_dn[1] + du_c_prime_d * dn[offset + 8 + i]) * grad[0] + (dv_dn[1] + dv_c_prime_d * dn[offset + 8 + i]) * grad[1]; } } } // namespace smvs
33.589474
88
0.559072
dbs4261
9a59c458181420730463ff43414fdbdb0d97aaad
801
cpp
C++
KROSS/src/Kross/Renderer/Context.cpp
WillianKoessler/KROSS-ENGINE
0e680b455ffd071565fe8b99343805ad16ca1e91
[ "Apache-2.0" ]
null
null
null
KROSS/src/Kross/Renderer/Context.cpp
WillianKoessler/KROSS-ENGINE
0e680b455ffd071565fe8b99343805ad16ca1e91
[ "Apache-2.0" ]
null
null
null
KROSS/src/Kross/Renderer/Context.cpp
WillianKoessler/KROSS-ENGINE
0e680b455ffd071565fe8b99343805ad16ca1e91
[ "Apache-2.0" ]
null
null
null
#include <Kross_pch.h> #include "Context.h" #include "GFXAPI/OpenGL/GLContext.h" #include "Kross/Renderer/Renderer.h" #include "Kross/Core/Window.h" namespace Kross { Ref<Context> Context::CreateRef(Window* window) { switch (Renderer::GetAPI()) { case RendererAPI::API::None: KROSS_FATAL("Invalid Graphics API"); return nullptr; case RendererAPI::API::OpenGL: return makeRef<OpenGL::Context>(window); } KROSS_FATAL("Unknown Graphics API."); return nullptr; } Scope<Context> Context::CreateScope(Window* window) { switch (Renderer::GetAPI()) { case RendererAPI::API::None: KROSS_FATAL("Invalid Graphics API"); return nullptr; case RendererAPI::API::OpenGL: return makeScope<OpenGL::Context>(window); } KROSS_FATAL("Unknown Graphics API."); return nullptr; } }
28.607143
85
0.715356
WillianKoessler
9a5a0d1e3eefc78619d8c6434e6d9ad05e723465
1,510
cpp
C++
Fasta.cpp
yanlinlin82/crabber
b924e5e4e19e8072303b9b83ec7eb945b42e58b3
[ "Apache-2.0" ]
null
null
null
Fasta.cpp
yanlinlin82/crabber
b924e5e4e19e8072303b9b83ec7eb945b42e58b3
[ "Apache-2.0" ]
null
null
null
Fasta.cpp
yanlinlin82/crabber
b924e5e4e19e8072303b9b83ec7eb945b42e58b3
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <fstream> #include "String.h" #include "Fasta.h" bool Fasta::Load(const std::string& filename, bool verbose) { std::ifstream file(filename, std::ios::in); if (!file.is_open()) { std::cerr << "Error: Can not open file '" << filename << "'!" << std::endl; return false; } if (verbose) { std::cerr << "Loading fasta '" << filename << "'" << std::endl; } std::string chrom; std::string line; while (std::getline(file, line)) { if (line.empty()) continue; if (line[0] == '>') { chrom = TrimLeft(line.substr(1)); std::string::size_type pos = chrom.find_first_of(" \t"); if (pos != std::string::npos) { chrom = chrom.substr(0, pos); } if (verbose) { std::cerr << " loading '" << chrom << "'\r" << std::flush; } } else { seq_[chrom] += Trim(line); } } file.close(); if (verbose) { std::cerr << "Total " << seq_.size() << " sequence(s) loaded" << std::endl; } return true; } bool Fasta::Has(const std::string& chrom) const { return (seq_.find(chrom) != seq_.end()); } size_t Fasta::GetLength(const std::string& chrom) const { auto it = seq_.find(chrom); if (it == seq_.end()) { return 0; } return it->second.size(); } std::string Fasta::GetSeq(const std::string& chrom, size_t pos, size_t size) const { std::string res; auto it = seq_.find(chrom); if (it != seq_.end()) { std::string s = it->second.substr(pos, size); for (size_t i = 0; i < s.size(); ++i) { res += std::toupper(s[i]); } } return res; }
21.884058
82
0.586755
yanlinlin82
9a5a18a89b6ab92e063758607dfe74e5cc84694b
2,385
cpp
C++
Section02/Problem04/Source.cpp
0xdec0de5/cpp-training
afa15c3bd9cbbe1ee7f219f5a5cae563cbe004b8
[ "MIT" ]
null
null
null
Section02/Problem04/Source.cpp
0xdec0de5/cpp-training
afa15c3bd9cbbe1ee7f219f5a5cae563cbe004b8
[ "MIT" ]
null
null
null
Section02/Problem04/Source.cpp
0xdec0de5/cpp-training
afa15c3bd9cbbe1ee7f219f5a5cae563cbe004b8
[ "MIT" ]
null
null
null
#include <iostream> int main() { std::cout << "Enter the character class for your player." << std::endl; std::cout << "(B)arbarian, (M)age, (R)ogue, (D)ruid: "; // TODO - handle user input: (b/B), (m/M), (r/R), or (d/D) char character_class; std::cin >> character_class; // Barbarian Character unsigned short barbarian_strength = 20; unsigned short barbarian_agility = 12; unsigned short barbarian_intelligence = 5; unsigned short barbarian_wisdom = 7; // Mage Character unsigned short mage_strength = 5; unsigned short mage_agility = 10; unsigned short mage_intelligence = 20; unsigned short mage_wisdom = 11; // Rogue Character unsigned short rogue_strength = 9; unsigned short rogue_agility = 20; unsigned short rogue_intelligence = 14; unsigned short rogue_wisdom = 6; // Druid Character unsigned short druid_strength = 14; unsigned short druid_agility = 8; unsigned short druid_intelligence = 5; unsigned short druid_wisdom = 20; // TODO - from the user's selection, print their character's properties to the console. switch(character_class) { case 'b': case 'B': std::cout << "The player is a Barbarian" << std::endl << "\tStrength = " << barbarian_strength << std::endl << "\tAgility = " << barbarian_agility << std::endl << "\tIntelligence = " << barbarian_intelligence << std::endl << "\tWisdom = " << barbarian_wisdom << std::endl; break; case 'm': case 'M': std::cout << "The player is a Mage" << std::endl << "\tStrength = " << mage_strength << std::endl << "\tAgility = " << mage_agility << std::endl << "\tIntelligence = " << mage_intelligence << std::endl << "\tWisdom = " << mage_wisdom << std::endl; break; case 'r': case 'R': std::cout << "The player is a Rogue" << std::endl << "\tStrength = " << rogue_strength << std::endl << "\tAgility = " << rogue_agility << std::endl << "\tIntelligence = " << rogue_intelligence << std::endl << "\tWisdom = " << rogue_wisdom << std::endl; break; case 'd': case 'D': std::cout << "The player is a Druid" << std::endl << "\tStrength = " << druid_strength << std::endl << "\tAgility = " << druid_agility << std::endl << "\tIntelligence = " << druid_intelligence << std::endl << "\tWisdom = " << druid_wisdom << std::endl; break; default: std::cout << "You didn't enter a valid character class."; break; } return 0; }
31.381579
88
0.644025
0xdec0de5
9a5aa085c813c6b48e74bc8a36d558c55d6f4782
135
hpp
C++
src/util/constants.hpp
VIGameStudio/Particles
160beb20b3f23cf0973fd57043d901b3f01efa42
[ "MIT" ]
null
null
null
src/util/constants.hpp
VIGameStudio/Particles
160beb20b3f23cf0973fd57043d901b3f01efa42
[ "MIT" ]
null
null
null
src/util/constants.hpp
VIGameStudio/Particles
160beb20b3f23cf0973fd57043d901b3f01efa42
[ "MIT" ]
null
null
null
#pragma once #define PI 3.14159265359 #define RAD2DEG 57.2957795056 #define DEG2RAD 0.01745329252 #define EPSILON 0.00000000001
16.875
29
0.777778
VIGameStudio
9a5f133a811451882eca9e72f5488fc016e042b3
13,186
cpp
C++
Development/ActorX/Source/MayaPLE_Plugin/UnEdPlug/unEditorCmd.cpp
addstone/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
37
2020-05-22T18:18:47.000Z
2022-03-19T06:51:54.000Z
Development/ActorX/Source/MayaPLE_Plugin/UnEdPlug/unEditorCmd.cpp
AdanosGotoman/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
null
null
null
Development/ActorX/Source/MayaPLE_Plugin/UnEdPlug/unEditorCmd.cpp
AdanosGotoman/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
27
2020-05-17T01:03:30.000Z
2022-03-06T19:10:14.000Z
// // Copyright (C) 2002 Secret Level // // File: unEditorCmd.cpp // // MEL Command: unEditor // // Author: Maya SDK Wizard // // Description: Implementation of plugin interface for unEditor.mll // // Includes everything needed to register a simple MEL command with Maya. // //#include <maya/MSimple.h> #include <maya/MFnPlugin.h> #include <maya/MGlobal.h> #include "precompiled.h" #include "DynArray.h" #include "Vertebrate.h" #include "UnrealEdImport.h" #include "CSetInfo.h" #include "SceneIFC.h" #include "maattrval.h" #include <maya/MStringArray.h> #include <maya/MEventMessage.h> #include <maya/MFnMesh.h> #include "ExportMesh.h" #include "CStaticMeshGen.h" // Use helper macro to register a command with Maya. It creates and // registers a command that does not support undo or redo. The // created class derives off of MPxCommand. // class unEditor : public MPxCommand { public: unEditor(void) {} virtual ~unEditor(void) {} virtual MStatus doIt ( const MArgList& ); static void* creator(); void doAnim( const MArgList& ); void doMesh( const MArgList& ); static void idleCB(void * data); static void onQuit(void * data); static MCallbackId idleCallbackId; static MCallbackId quitCallbackId; static void onOpen(void); static void onClose(void); private: INT GenerateActor(const CSetInfo& setinfo) const; INT GenerateMesh(const MFnMesh& mesh, const CSetInfo& setinfo) const; INT GenerateMesh(const CSetInfo& setinfo) const; void PrepareOutAnimation(VActor& vactor) const; void TransferSkinToUnreal(VActor& vactor, const CSetInfo& setinfo) const; void TransferAnimToUnreal(VActor& vactor, const CSetInfo& setinfo) const; }; void* unEditor::creator() { return new unEditor; } MStatus initializePlugin( MObject _obj ) { MFnPlugin plugin( _obj, "Secret Level", "4.0" ); MStatus stat; unEditor::onOpen(); stat = plugin.registerCommand( "unEditor", unEditor::creator ); if ( !stat ) stat.perror("registerCommand"); return stat; } // Warning: Currently, if you return MS::kSuccess, Maya crashes. // The result here is not much better (Maya closes down), but at least // there is no erroneous dialog box MStatus uninitializePlugin( MObject _obj ) { unEditor::onClose(); return MS::kFailure; /* MFnPlugin plugin( _obj ); MStatus stat; unEditor::onClose(); stat = plugin.deregisterCommand( "unEditor" ); if ( !stat ) stat.perror("deregisterCommand"); return stat; */ } // Idle calls go through to unreal editor -to make unrealed update its windows, play animations, etc. void unEditor::idleCB(void * data) { PollEditor(); } void unEditor::onQuit(void * data) { onClose(); } MCallbackId unEditor::idleCallbackId = 0; MCallbackId unEditor::quitCallbackId = 0; void unEditor::onOpen(void) { if (!IsLaunched()) { HMODULE hmodule = GetModuleHandle("UnrealEdDLL"); if( hmodule ) { LaunchEditor( hmodule, 0,SW_SHOW); idleCallbackId = MEventMessage::addEventCallback("idle",&idleCB,NULL); quitCallbackId = MEventMessage::addEventCallback("quitApplication",&onQuit,NULL); } } } void unEditor::onClose(void) { if (idleCallbackId) { MMessage::removeCallback(idleCallbackId); idleCallbackId = 0; MMessage::removeCallback(quitCallbackId); quitCallbackId = 0; } ShutDownEditor(); } MStatus unEditor::doIt( const MArgList& args ) // // Description: // implements the MEL unEditor command. // // Arguments: // args - the argument list that was passes to the command from MEL // // Return Value: // MS::kSuccess - command succeeded // MS::kFailure - command failed (returning this value will cause the // MEL script that is being run to terminate unless the // error is caught using a "catch" statement. // { MStatus stat = MS::kSuccess; setResult( "unEditor command executed!\n" ); if (IsLaunched() && !IsShutdown() && args.length() > 0) { if (args.asString(0) == MString("anim")) { doAnim(args); } else if (args.asString(0) == MString("mesh")) { doMesh(args); } else if (args.asString(0) == MString("help") || args.asString(0) == MString("-help")) { MString res("\nunEditor help\n=============\n"); res += MString("usage:\n"); res += MString("\t> unEditor anim (<setname>)*\n"); res += MString("where each set mentioned contains exactly the main joint\n"); res += MString("for an IK skeleton.\n"); res += MString("This set should have a string attribute \"package\"\n"); res += MString("to indicate which package the skin+animations should\n"); res += MString("export to. The object name will be the set name.\n"); res += MString("A string attribute \"animargs\" communicates the animations\n"); res += MString("to be exported - this string should be trios of\n"); res += MString("<label> <from> <to> such as \"walk 1 21 run 22 45\".\n"); res += MString("An optional float attribute \"scale\" (default 1.0)\n"); res += MString("is used to control the size of the mesh when imported\n"); res += MString("\n"); res += MString("\t> unEditor mesh (<setname>)*\n"); res += MString("Each set here contains a textured mesh.\n"); res += MString("Scale and package name are determined as for \"unEditor anim\" \n"); setResult(res); } } else { MString res("\nunEditor warning\n=============\n"); res += MString("Once closed, UnrealEd cannot be re-launched\n"); res += MString("To use this feature, restart Maya.\n"); setResult(res); } return stat; } void unEditor::doAnim( const MArgList& args) { int ActorCount = 0; for (unsigned int i = 1; i < args.length(); ++i) { CSetInfo set_i( args.asString(i) ); if (set_i.GetSet()) { if( GenerateActor(set_i) ) ActorCount++; } } FinishAnimImport(); char resultString[1024]; if( ActorCount ) { sprintf(resultString," [%i] animating meshes(s) exported.",ActorCount); } else { sprintf(resultString,"unEditor anim : model data not found or main set not linked correctly.\n"); } setResult(resultString); } void unEditor::doMesh( const MArgList& args ) { int MeshCount = 0; for (unsigned int i = 1; i < args.length(); ++i) { MString err; const char * aschar = args.asString(i).asChar(); CSetInfo set_i( args.asString(i) ); if (set_i.GetSet()) { if( GenerateMesh(set_i) ) MeshCount++; } } FinishMeshImport(); char resultString[1024]; if( MeshCount ) { sprintf(resultString," [%i] static meshes(s) exported.",MeshCount); } else { sprintf(resultString,"unEditor mesh : model data not found or main set not linked correctly.\n"); } setResult(resultString); } int unEditor::GenerateActor(const CSetInfo& setinfo) const { VActor vactor; SceneIFC OurScene(setinfo.GetRoot()); OurScene.SurveyScene(); OurScene.GetSceneInfo(&vactor); OurScene.EvaluateSkeleton(1); OurScene.DigestSkeleton( &vactor ); // Digest skeleton into tempactor // Skin OurScene.DigestSkin( &vactor ); { // run check int count = 0; for (int i = 0; i < vactor.SkinData.Faces.ArrayNum; ++i) { VTriangle const& face_i = vactor.SkinData.Faces[i]; VVertex& vert = vactor.SkinData.Wedges[ face_i.WedgeIndex[0] ]; if (vert.MatIndex != face_i.MatIndex) { vert.MatIndex = face_i.MatIndex; } } } // Collate bones vactor.SkinData.RefBones = vactor.RefSkeletonBones; INT NumBones = vactor.RefSkeletonBones.ArrayNum; TransferSkinToUnreal( vactor, setinfo ); MString animargs; if (MGetAttribute(*setinfo.GetNode(),"animargs").GetBasicValue(animargs) == MS::kSuccess) { // obtain animation arguments MStringArray splitargs; animargs.split(' ',splitargs); for (unsigned int i = 0; i+2 < splitargs.length(); i += 3) { MString label = splitargs[i]; if (splitargs[i+1].isInt() && splitargs[i+2].isInt()) { int from = splitargs[i+1].asInt(); int to = splitargs[i+2].asInt(); OurScene.DigestAnim(&vactor, label.asChar(), from, to); OurScene.FixRootMotion( &vactor ); // PopupBox("Digested animation:%s Betakeys: %i Current animation # %i", animname, TempActor.BetaKeys.Num(), TempActor.Animations.Num() ); if(OurScene.DoForceRate ) vactor.FrameRate = OurScene.PersistentRate; vactor.RecordAnimation(); } } PrepareOutAnimation(vactor); } // Obtain animation arguments. TransferAnimToUnreal( vactor, setinfo ); return ( (NumBones > 0)? 1 : 0 ); } void unEditor::PrepareOutAnimation(VActor& vactor) const { int NameUnique = 1; int ReplaceIndex = -1; int ConsistentBones = 1; // Go over animations in 'inbox' and copy or add to outbox. for( INT c=0; c<vactor.Animations.Num(); c++) { INT AnimIdx = c; // Name uniqueness check as well as bonenum-check for every sequence; _overwrite_ if a name already exists... for( INT t=0;t<vactor.OutAnims.Num(); t++) { if( strcmp( vactor.OutAnims[t].AnimInfo.Name, vactor.Animations[AnimIdx].AnimInfo.Name ) == 0) { NameUnique = 0; ReplaceIndex = t; } if( vactor.OutAnims[t].AnimInfo.TotalBones != vactor.Animations[AnimIdx].AnimInfo.TotalBones) ConsistentBones = 0; } // Add or replace. if( ConsistentBones ) { INT NewIdx = 0; if( NameUnique ) // Add - { NewIdx = vactor.OutAnims.Num(); vactor.OutAnims.AddZeroed(1); // Add a single element. } else // Replace.. delete existing. { NewIdx = ReplaceIndex; vactor.OutAnims[NewIdx].KeyTrack.Empty(); } vactor.OutAnims[NewIdx].AnimInfo = vactor.Animations[AnimIdx].AnimInfo; vactor.OutAnims[NewIdx].KeyTrack.Append( vactor.Animations[AnimIdx].KeyTrack ); } else { setResult("ERROR !! Aborting the quicksave/move, inconsistent bone counts detected."); return; } } // Delete 'left-box' items. if( ConsistentBones ) { // Clear 'left pane' anims.. {for( INT c=0; c<vactor.Animations.Num(); c++) { vactor.Animations[c].KeyTrack.Empty(); }} vactor.Animations.Empty(); } } void unEditor::TransferSkinToUnreal(VActor& vactor, const CSetInfo& setinfo) const { // determine parameters double scale = 1.0; MString package_name("MyPackage"); MString skin_name(setinfo.GetName()); if (setinfo.GetNode()) { MGetAttribute( *setinfo.GetNode(), "scale" ).GetBasicValue(scale); MGetAttribute( *setinfo.GetNode(), "package" ).GetBasicValue(package_name); } LoadSkin( package_name.asChar(), skin_name.asChar(), &vactor.SkinData, scale ); } void unEditor::TransferAnimToUnreal(VActor& vactor, const CSetInfo& setinfo) const { // determine parameters MString package_name("MyPackage"); MString skin_name(setinfo.GetName()); if (setinfo.GetNode()) { MGetAttribute( *setinfo.GetNode(), "package" ).GetBasicValue(package_name); } VAnimationList animlist(&vactor.OutAnims); LoadAnimations( package_name.asChar(), skin_name.asChar(), &vactor.SkinData, &animlist ); } int unEditor::GenerateMesh(const MFnMesh& mesh, const CSetInfo& setinfo) const { CStaticMeshGenerator staticmesh; staticmesh.AddMesh(mesh); MString package_name("MyPackage"); MString mesh_name(setinfo.GetName()); int PackageFound = 0; bool have_group = false; MString group_name; if (setinfo.GetNode()) { if( MGetAttribute( *setinfo.GetNode(), "package" ).GetBasicValue(package_name) == MS::kSuccess ) { PackageFound = 1; } have_group = (MS::kSuccess == MGetAttribute( *setinfo.GetNode(), "group" ).GetBasicValue(group_name)); } if ( have_group && PackageFound ) { LoadMesh( package_name.asChar(), group_name.asChar(), mesh_name.asChar(), &staticmesh.GetResult() ); } else { LoadMesh( package_name.asChar(), 0, mesh_name.asChar(), &staticmesh.GetResult() ); } return PackageFound; } int unEditor::GenerateMesh(const CSetInfo& setinfo) const { CStaticMeshGenerator staticmesh; MSelectionList setMembers; // Attempt to get the members of the set. if(setinfo.GetSet()->getMembers(setMembers, false) != MS::kSuccess) { return 0; } for (unsigned int i = 0; i < setMembers.length(); ++i) { MObject node_i; setMembers.getDependNode(i,node_i); MString err; CExportMesh mesh_i(node_i,err); if (mesh_i.GetMesh()) { staticmesh.AddMesh(*mesh_i.GetMesh()); } } MString package_name("MyPackage"); MString mesh_name(setinfo.GetName()); bool have_group = false; MString group_name; if (setinfo.GetNode()) { MGetAttribute( *setinfo.GetNode(), "package" ).GetBasicValue(package_name); have_group = (MS::kSuccess == MGetAttribute( *setinfo.GetNode(), "group" ).GetBasicValue(group_name)); float scale = 1.0f; if (MS::kSuccess == MGetAttribute( *setinfo.GetNode(), "scale" ).GetBasicValue(scale)) { staticmesh.Scale(scale); } } if (have_group) { LoadMesh( package_name.asChar(), group_name.asChar(), mesh_name.asChar(), &staticmesh.GetResult() ); } else { LoadMesh( package_name.asChar(), 0, mesh_name.asChar(), &staticmesh.GetResult() ); } return 1; }
25.068441
142
0.667602
addstone
9a6087ab262f30d73951a4ee120da2c7333c789f
162
cpp
C++
src/examples/04_module/08_strings/main.cpp
acc-cosc-1337-summer-2020-classroom/acc-cosc-1337-summer-2020-Gabe-Cpp
f5b7d8610054c975b67ff04a41a7a054325e3c7e
[ "MIT" ]
null
null
null
src/examples/04_module/08_strings/main.cpp
acc-cosc-1337-summer-2020-classroom/acc-cosc-1337-summer-2020-Gabe-Cpp
f5b7d8610054c975b67ff04a41a7a054325e3c7e
[ "MIT" ]
null
null
null
src/examples/04_module/08_strings/main.cpp
acc-cosc-1337-summer-2020-classroom/acc-cosc-1337-summer-2020-Gabe-Cpp
f5b7d8610054c975b67ff04a41a7a054325e3c7e
[ "MIT" ]
null
null
null
#include<string> #include<iostream> #include "strings.h" int main() { std::string str1 = "john"; loop_string_w_index(str1); std::cout << str1; return 0; }
12.461538
27
0.666667
acc-cosc-1337-summer-2020-classroom
9a644442cd27c9a5dbbf78b59d431f194d1b234e
343
hpp
C++
lib/inc/cpp-pcp-client/ws_config.hpp
puppetlabs/cpp-pcp-client
b22db78a97a78e7f8cc189223af820756d4c0a8c
[ "Apache-2.0" ]
1
2018-09-25T20:01:07.000Z
2018-09-25T20:01:07.000Z
lib/inc/cpp-pcp-client/ws_config.hpp
puppetlabs/cpp-pcp-client
b22db78a97a78e7f8cc189223af820756d4c0a8c
[ "Apache-2.0" ]
100
2015-10-12T20:06:20.000Z
2021-12-03T19:30:07.000Z
lib/inc/cpp-pcp-client/ws_config.hpp
puppetlabs/cpp-pcp-client
b22db78a97a78e7f8cc189223af820756d4c0a8c
[ "Apache-2.0" ]
34
2015-10-06T10:00:03.000Z
2022-01-18T22:35:52.000Z
#pragma once #include <websocketpp/config/asio_client.hpp> namespace PCPClient { struct ws_config : public websocketpp::config::asio_tls_client { static const websocketpp::log::level elog_level = websocketpp::log::elevel::all; static const websocketpp::log::level alog_level = websocketpp::log::alevel::all; }; }
26.384615
66
0.714286
puppetlabs
9a687bec546f6af34b69585b9cb0c9fa53d4b918
1,658
cpp
C++
vm/compiler/codegen/x86/lightcg/CompilationUnit.cpp
HazouPH/android_dalvik
5e66532f06bbf1f43b23ff408ee64dc30c31fc9d
[ "Apache-2.0" ]
null
null
null
vm/compiler/codegen/x86/lightcg/CompilationUnit.cpp
HazouPH/android_dalvik
5e66532f06bbf1f43b23ff408ee64dc30c31fc9d
[ "Apache-2.0" ]
null
null
null
vm/compiler/codegen/x86/lightcg/CompilationUnit.cpp
HazouPH/android_dalvik
5e66532f06bbf1f43b23ff408ee64dc30c31fc9d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2013 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CompilationUnit.h" bool CompilationUnit_O1::getCanSpillRegister (int reg) { //Check overflow first if (reg < 0 || reg >= PhysicalReg_Null) { return false; } //Otherwise, use what is in the array return canSpillRegister[reg]; } bool CompilationUnit_O1::setCanSpillRegister (int reg, bool value) { //Check overflow first if (reg < 0 || reg >= PhysicalReg_Null) { //Cannot update it return false; } //Otherwise, use what is in the array canSpillRegister[reg] = value; //Update succeeded return true; } int CompilationUnit_O1::getFPAdjustment (void) { //In order to get adjustment we multiply the window shift by size of VR int adjustment = registerWindowShift * sizeof (u4); //Stack grows in a negative direction and when we have a register window shift we push the //stack up. Thus taking that into account, the shift is negative. //Namely desiredFP = actualFP - adjustment adjustment = adjustment * (-1); return adjustment; }
28.101695
94
0.694813
HazouPH
9a6bf681d119656a39fe600124d3a3094b65a541
13,720
cc
C++
hackt_docker/hackt/src/Object/sizes-entity.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/sizes-entity.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/sizes-entity.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "Object/sizes-entity.cc" Just dumps the sizeof for most HAC::entity classes. This file came from "art_persistent_table.cc". $Id: sizes-entity.cc,v 1.3 2010/04/07 00:12:32 fang Exp $ */ #include <iostream> #include "common/sizes-common.hh" #include "util/what.tcc" // use default typeinfo-based mangled names #include "Object/sizes-entity.hh" // include all Object/*.hh header files to evaluate struct sizes. #include "Object/module.hh" #include "Object/global_entry.hh" #include "Object/def/footprint.hh" #include "Object/def/enum_datatype_def.hh" #include "Object/def/process_definition.hh" #include "Object/def/process_definition_alias.hh" #include "Object/def/user_def_chan.hh" #include "Object/def/user_def_datatype.hh" #include "Object/def/datatype_definition_alias.hh" #include "Object/def/channel_definition_alias.hh" #include "Object/def/built_in_datatype_def.hh" #include "Object/def/channel_definition_base.hh" #include "Object/def/param_definition.hh" #include "Object/type/builtin_channel_type_reference.hh" #include "Object/type/canonical_generic_chan_type.hh" #include "Object/type/canonical_type.hh" #include "Object/type/channel_type_reference.hh" #include "Object/type/data_type_reference.hh" #include "Object/type/fundamental_type_reference.hh" #include "Object/type/param_type_reference.hh" #include "Object/type/process_type_reference.hh" #include "Object/type/template_actuals.hh" #include "Object/traits/preal_traits.hh" #include "Object/expr/pbool_const.hh" #include "Object/expr/pint_const.hh" #include "Object/expr/preal_const.hh" #include "Object/expr/bool_logical_expr.hh" #include "Object/expr/bool_negation_expr.hh" #include "Object/expr/int_arith_expr.hh" #include "Object/expr/int_relational_expr.hh" #include "Object/expr/int_negation_expr.hh" // #include "Object/expr/real_arith_expr.hh" // #include "Object/expr/real_relational_expr.hh" // #include "Object/expr/real_negation_expr.hh" #include "Object/expr/const_collection.hh" #include "Object/expr/const_index.hh" #include "Object/expr/const_range.hh" #include "Object/expr/pint_range.hh" #include "Object/expr/const_param_expr_list.hh" #include "Object/expr/dynamic_param_expr_list.hh" #include "Object/expr/const_index_list.hh" #include "Object/expr/dynamic_meta_index_list.hh" #include "Object/expr/const_range_list.hh" #include "Object/expr/dynamic_meta_range_list.hh" #include "Object/expr/pbool_logical_expr.hh" #include "Object/expr/pbool_unary_expr.hh" #include "Object/expr/pint_arith_expr.hh" #include "Object/expr/pint_unary_expr.hh" #include "Object/expr/pint_relational_expr.hh" #include "Object/expr/preal_arith_expr.hh" #include "Object/expr/preal_unary_expr.hh" #include "Object/expr/preal_relational_expr.hh" #include "Object/inst/alias_actuals.hh" #include "Object/inst/alias_empty.hh" #include "Object/inst/alias_printer.hh" #include "Object/inst/alias_visitee.hh" #include "Object/inst/alias_visitor.hh" #include "Object/inst/bool_instance.hh" #include "Object/inst/bool_instance_collection.hh" #include "Object/inst/channel_instance.hh" #include "Object/inst/channel_instance_collection.hh" #include "Object/inst/collection_fwd.hh" #include "Object/inst/datatype_instance_collection.hh" #include "Object/inst/enum_instance.hh" #include "Object/inst/enum_instance_collection.hh" #include "Object/inst/general_collection_type_manager.hh" #include "Object/inst/instance_alias_info.hh" #include "Object/inst/instance_collection.hh" #include "Object/inst/instance_collection_base.hh" #include "Object/inst/instance_array.hh" #include "Object/inst/instance_scalar.hh" #include "Object/inst/port_formal_array.hh" #include "Object/inst/port_actual_collection.hh" #include "Object/inst/instance_fwd.hh" #include "Object/inst/instance_pool.hh" #include "Object/inst/int_collection_type_manager.hh" #include "Object/inst/int_instance.hh" #include "Object/inst/int_instance_collection.hh" #include "Object/inst/internal_aliases_policy.hh" #include "Object/inst/null_collection_type_manager.hh" #include "Object/inst/param_value_collection.hh" #include "Object/inst/parameterless_collection_type_manager.hh" #include "Object/inst/pbool_instance.hh" #include "Object/inst/pbool_value_collection.hh" #include "Object/inst/physical_instance_collection.hh" #include "Object/inst/pint_instance.hh" #include "Object/inst/pint_value_collection.hh" #include "Object/inst/port_alias_tracker.hh" #include "Object/inst/preal_instance.hh" #include "Object/inst/preal_value_collection.hh" #include "Object/inst/process_instance.hh" #include "Object/inst/process_instance_collection.hh" #include "Object/inst/state_instance.hh" #include "Object/inst/struct_instance.hh" #include "Object/inst/struct_instance_collection.hh" #include "Object/inst/subinstance_manager.hh" #include "Object/inst/substructure_alias_base.hh" #include "Object/inst/value_collection.hh" #include "Object/inst/value_scalar.hh" #include "Object/inst/value_array.hh" #include "Object/inst/value_placeholder.hh" #include "Object/inst/instance_placeholder.hh" #include "Object/inst/datatype_instance_placeholder.hh" #include "Object/ref/aggregate_meta_instance_reference.hh" #include "Object/ref/aggregate_meta_value_reference.hh" #include "Object/ref/data_nonmeta_instance_reference.hh" #include "Object/ref/inst_ref_implementation.hh" #include "Object/ref/member_meta_instance_reference.hh" #include "Object/ref/meta_instance_reference_subtypes.hh" #include "Object/ref/meta_reference_union.hh" #include "Object/ref/meta_value_reference.hh" #include "Object/ref/nonmeta_instance_reference_subtypes.hh" #include "Object/ref/references_fwd.hh" #include "Object/ref/simple_meta_instance_reference.hh" #include "Object/ref/simple_meta_value_reference.hh" #include "Object/ref/simple_nonmeta_instance_reference.hh" #include "Object/ref/simple_nonmeta_value_reference.hh" #include "util/multikey_map.hh" #include "util/multikey.hh" #include "util/packed_array.hh" namespace HAC { namespace entity { using std::ostream; using std::cerr; using std::endl; using util::memory::never_ptr; using util::memory::some_ptr; using util::memory::excl_ptr; using util::memory::count_ptr; using util::packed_array; using util::packed_array_generic; //============================================================================= /** Diagnostic for inspecting sizes of classes. Has nothing to do with class persistence. */ ostream& dump_class_sizes(ostream& o) { o << "util library structures:" << endl; __dump_class_size<never_ptr<int> >(o); __dump_class_size<excl_ptr<int> >(o); __dump_class_size<some_ptr<int> >(o); __dump_class_size<count_ptr<int> >(o); // __dump_class_size<packed_array<1, size_t, char*> >(o); // error // TODO: need specialization on coeffs_type here __dump_class_size<packed_array<4, size_t, char*> >(o); __dump_class_size<packed_array_generic<size_t, char*> >(o); o << "HAC::entity general classes:" << endl; __dump_class_size<module>(o); o << "HAC::entity definition classes:" << endl; __dump_class_size<footprint>(o); __dump_class_size<footprint_base<process_tag> >(o); __dump_class_size<footprint_manager>(o); __dump_class_size<definition_base>(o); __dump_class_size<process_definition_base>(o); __dump_class_size<process_definition>(o); __dump_class_size<channel_definition_base>(o); __dump_class_size<user_def_chan>(o); __dump_class_size<datatype_definition_base>(o); __dump_class_size<user_def_datatype>(o); __dump_class_size<enum_datatype_def>(o); __dump_class_size<enum_member>(o); __dump_class_size<built_in_datatype_def>(o); // __dump_class_size<built_in_channel_def>(o); __dump_class_size<template_formals_manager>(o); __dump_class_size<port_formals_manager>(o); __dump_class_size<typedef_base>(o); __dump_class_size<process_definition_alias>(o); __dump_class_size<channel_definition_alias>(o); __dump_class_size<datatype_definition_alias>(o); __dump_class_size<built_in_param_def>(o); o << "HAC::entity expression classes:" << endl; __dump_class_size<data_expr>(o); __dump_class_size<param_expr>(o); __dump_class_size<bool_expr>(o); __dump_class_size<bool_logical_expr>(o); __dump_class_size<bool_negation_expr>(o); __dump_class_size<pbool_expr>(o); __dump_class_size<pbool_logical_expr>(o); __dump_class_size<pbool_const>(o); __dump_class_size<pbool_const_collection>(o); __dump_class_size<int_expr>(o); __dump_class_size<int_arith_expr>(o); __dump_class_size<int_relational_expr>(o); __dump_class_size<int_negation_expr>(o); __dump_class_size<pint_expr>(o); __dump_class_size<pint_unary_expr>(o); __dump_class_size<pint_arith_expr>(o); __dump_class_size<pint_relational_expr>(o); __dump_class_size<pint_const>(o); __dump_class_size<pint_const_collection>(o); __dump_class_size<real_expr>(o); __dump_class_size<preal_expr>(o); __dump_class_size<preal_arith_expr>(o); __dump_class_size<preal_unary_expr>(o); __dump_class_size<preal_relational_expr>(o); __dump_class_size<preal_const>(o); __dump_class_size<preal_const_collection>(o); __dump_class_size<meta_index_expr>(o); __dump_class_size<const_index>(o); __dump_class_size<const_param>(o); __dump_class_size<meta_range_expr>(o); __dump_class_size<const_range>(o); __dump_class_size<pint_range>(o); __dump_class_size<param_expr_list>(o); __dump_class_size<const_param_expr_list>(o); __dump_class_size<dynamic_param_expr_list>(o); __dump_class_size<meta_index_list>(o); __dump_class_size<const_index_list>(o); __dump_class_size<dynamic_meta_index_list>(o); __dump_class_size<meta_range_list>(o); __dump_class_size<const_range_list>(o); __dump_class_size<dynamic_meta_range_list>(o); __dump_class_size<nonmeta_index_expr_base>(o); __dump_class_size<nonmeta_range_expr_base>(o); o << "HAC::entity type classes:" << endl; __dump_class_size<type_reference_base>(o); __dump_class_size<fundamental_type_reference>(o); __dump_class_size<channel_type_reference_base>(o); __dump_class_size<channel_type_reference>(o); __dump_class_size<builtin_channel_type_reference>(o); __dump_class_size<canonical_generic_chan_type>(o); __dump_class_size<canonical_process_type>(o); __dump_class_size<data_type_reference>(o); __dump_class_size<process_type_reference>(o); __dump_class_size<template_actuals>(o); // __dump_class_size<resolved_template_actuals>(o); o << "HAC::entity instance classes:" << endl; __dump_class_size<instance_collection_base>(o); __dump_class_size<physical_instance_collection>(o); __dump_class_size<param_value_collection>(o); __dump_class_size<bool_instance_collection>(o); __dump_class_size<int_instance_collection>(o); __dump_class_size<channel_instance_collection>(o); __dump_class_size<substructure_alias_base<true> >(o); __dump_class_size<substructure_alias_base<false> >(o); __dump_class_size<subinstance_manager>(o); __dump_class_size<bool_instance_collection>(o); __dump_class_size<port_actual_collection<bool_tag> >(o); __dump_class_size<bool_instance>(o); __dump_class_size<instance_alias_info<bool_tag> >(o); __dump_class_size<bool_scalar>(o); __dump_class_size<bool_array_1D>(o); __dump_class_size<bool_array_4D>(o); __dump_class_size<bool_port_formal_array>(o); __dump_class_size<process_instance_collection>(o); __dump_class_size<port_actual_collection<process_tag> >(o); __dump_class_size<process_instance>(o); __dump_class_size<instance_alias_info<process_tag> >(o); __dump_class_size<process_scalar>(o); __dump_class_size<process_array_1D>(o); __dump_class_size<process_array_4D>(o); __dump_class_size<process_port_formal_array>(o); __dump_class_size<pint_instance_collection>(o); __dump_class_size<pint_instance>(o); __dump_class_size<pint_scalar>(o); __dump_class_size<pint_array_1D>(o); __dump_class_size<pint_array_4D>(o); __dump_class_size<pbool_instance_collection>(o); __dump_class_size<pbool_instance>(o); __dump_class_size<pbool_scalar>(o); __dump_class_size<pbool_array_1D>(o); __dump_class_size<pbool_array_4D>(o); __dump_class_size<instance_placeholder_base>(o); __dump_class_size<physical_instance_placeholder>(o); __dump_class_size<param_value_placeholder>(o); __dump_class_size<bool_instance_placeholder>(o); __dump_class_size<int_instance_placeholder>(o); __dump_class_size<process_instance_placeholder>(o); __dump_class_size<pbool_value_placeholder>(o); __dump_class_size<pint_value_placeholder>(o); __dump_class_size<preal_value_placeholder>(o); o << "HAC::entity reference classes:" << endl; __dump_class_size<nonmeta_instance_reference_base>(o); __dump_class_size<meta_instance_reference_base>(o); __dump_class_size<simple_meta_indexed_reference_base>(o); __dump_class_size<simple_nonmeta_instance_reference_base>(o); // __dump_class_size<simple_param_meta_value_reference>(o); __dump_class_size<aggregate_meta_value_reference_base>(o); __dump_class_size<aggregate_meta_instance_reference_base>(o); __dump_class_size<bool_meta_instance_reference_base>(o); __dump_class_size<process_meta_instance_reference_base>(o); __dump_class_size<pbool_meta_value_reference_base>(o); __dump_class_size<pint_meta_value_reference_base>(o); __dump_class_size<simple_bool_nonmeta_instance_reference>(o); __dump_class_size<simple_process_nonmeta_instance_reference>(o); __dump_class_size<simple_bool_meta_instance_reference>(o); __dump_class_size<simple_process_meta_instance_reference>(o); __dump_class_size<aggregate_bool_meta_instance_reference>(o); __dump_class_size<aggregate_process_meta_instance_reference>(o); __dump_class_size<bool_member_meta_instance_reference>(o); __dump_class_size<process_member_meta_instance_reference>(o); return o; } //============================================================================= } // end namespace entity } // end namespace HAC
41.829268
79
0.810277
broken-wheel
9a74044bfd7cdd3f820a4ebcc19a7f2aaa2931ae
2,642
cpp
C++
cstatgen/src/umich/general/BaseUtilities.cpp
statgenetics/rvnpl
22053ca4e24e5486e1179a5e85aaf316a218391f
[ "MIT" ]
1
2021-11-28T12:00:34.000Z
2021-11-28T12:00:34.000Z
cstatgen/src/umich/general/BaseUtilities.cpp
changebio/rvnpl
22053ca4e24e5486e1179a5e85aaf316a218391f
[ "MIT" ]
8
2020-03-18T02:39:45.000Z
2020-12-12T08:05:24.000Z
cstatgen/src/umich/general/BaseUtilities.cpp
changebio/rvnpl
22053ca4e24e5486e1179a5e85aaf316a218391f
[ "MIT" ]
3
2021-01-26T03:22:59.000Z
2021-11-15T14:27:51.000Z
/* * Copyright (C) 2010-2012 Regents of the University of Michigan * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "BaseUtilities.h" #include <ctype.h> #include "BaseAsciiMap.h" bool BaseUtilities::isAmbiguous(char base) { switch(base) { case 'N': case 'n': case '.': return(true); break; default: break; }; // Not 'N', 'n', or '.', so return false. return(false); } bool BaseUtilities::areEqual(char base1, char base2) { // If they are the same, return true. if(base1 == base2) { return(true); } // If one of the bases is '=', return true. if((base1 == '=') || (base2 == '=')) { return(true); } // Check both in upercase. if(toupper(base1) == toupper(base2)) { // same in upper case. return(true); } // The bases are different. return(false); } // Get phred base quality from the specified ascii quality. uint8_t BaseUtilities::getPhredBaseQuality(char charQuality) { if(charQuality == UNKNOWN_QUALITY_CHAR) { return(UNKNOWN_QUALITY_INT); } return(charQuality - 33); } char BaseUtilities::getAsciiQuality(uint8_t phredQuality) { if(phredQuality == UNKNOWN_QUALITY_INT) { return(UNKNOWN_QUALITY_CHAR); } return(phredQuality + 33); } void BaseUtilities::reverseComplement(std::string& sequence) { int start = 0; int end = sequence.size() - 1; char tempChar; while(start < end) { tempChar = sequence[start]; sequence[start] = BaseAsciiMap::base2complement[(int)(sequence[end])]; sequence[end] = BaseAsciiMap::base2complement[(int)tempChar]; // Move both pointers. ++start; --end; } // there was an odd number of entries, complement the middle one. if(start == end) { tempChar = sequence[start]; sequence[start] = BaseAsciiMap::base2complement[(int)tempChar]; } }
24.018182
78
0.62112
statgenetics
9a753b1acc734448b049111f8a0bb73bac5f8e00
2,145
cpp
C++
src/fastsynth/smt2_frontend.cpp
kroening/fastsynth
6a8aed3182c7156e3ea4981576e2d29ba4088a3c
[ "BSD-3-Clause" ]
3
2020-06-01T03:07:06.000Z
2021-01-21T12:42:04.000Z
src/fastsynth/smt2_frontend.cpp
kroening/fastsynth
6a8aed3182c7156e3ea4981576e2d29ba4088a3c
[ "BSD-3-Clause" ]
10
2019-09-13T21:18:15.000Z
2020-12-04T01:18:46.000Z
src/fastsynth/smt2_frontend.cpp
kroening/fastsynth
6a8aed3182c7156e3ea4981576e2d29ba4088a3c
[ "BSD-3-Clause" ]
2
2019-09-13T21:15:53.000Z
2019-09-15T04:42:31.000Z
#include <util/cmdline.h> #include <util/cout_message.h> #include <util/namespace.h> #include <util/symbol_table.h> #include <solvers/flattening/boolbv.h> #include <solvers/sat/satcheck.h> #include <solvers/smt2/smt2_parser.h> #include <fstream> #include <iostream> class smt2_frontendt:public smt2_parsert { public: smt2_frontendt( std::ifstream &_in, decision_proceduret &_solver): smt2_parsert(_in), solver(_solver) { } protected: decision_proceduret &solver; void command(const std::string &) override; }; void smt2_frontendt::command(const std::string &c) { if(c=="assert") { exprt e=expression(); solver.set_to_true(e); } else if(c=="check-sat") { switch(solver()) { case decision_proceduret::resultt::D_SATISFIABLE: std::cout << "(sat)\n"; break; case decision_proceduret::resultt::D_UNSATISFIABLE: std::cout << "(unsat)\n"; break; case decision_proceduret::resultt::D_ERROR: std::cout << "(error)\n"; } } else smt2_parsert::command(c); } int smt2_frontend(const cmdlinet &cmdline) { assert(cmdline.args.size()==1); #if 0 register_language(new_ansi_c_language); config.ansi_c.set_32(); #endif console_message_handlert message_handler; messaget message(message_handler); // this is our default verbosity unsigned int v=messaget::M_STATISTICS; if(cmdline.isset("verbosity")) { v=std::stol( cmdline.get_value("verbosity"));; if(v>10) v=10; } message_handler.set_verbosity(v); std::ifstream in(cmdline.args.front()); if(!in) { message.error() << "Failed to open input file" << messaget::eom; return 10; } symbol_tablet symbol_table; namespacet ns(symbol_table); satcheckt satcheck(message_handler); boolbvt solver(ns, satcheck, message_handler); smt2_frontendt smt2(in, solver); try { smt2.parse(); return 0; } catch(const smt2_tokenizert::smt2_errort &error) { message.error() << error.get_line_no() << ": " << error.what() << messaget::eom; return 20; } catch(...) { return 20; } }
18.815789
68
0.652681
kroening
9a77e1eabc656137780911f4cc82bb9207f1f000
6,003
cpp
C++
modules/futures_redis/src/RedisFuture.cpp
chyh1990/futures_cpp
8e60e74af0cffff0a9749682a4caf1768277c04b
[ "MIT" ]
71
2017-12-18T10:35:41.000Z
2021-12-11T19:57:34.000Z
modules/futures_redis/src/RedisFuture.cpp
chyh1990/futures_cpp
8e60e74af0cffff0a9749682a4caf1768277c04b
[ "MIT" ]
1
2017-12-19T09:31:46.000Z
2017-12-20T07:08:01.000Z
modules/futures_redis/src/RedisFuture.cpp
chyh1990/futures_cpp
8e60e74af0cffff0a9749682a4caf1768277c04b
[ "MIT" ]
7
2017-12-20T01:55:44.000Z
2019-12-06T12:25:55.000Z
#include <futures_redis/RedisFuture.h> #include "hiredis/async.h" #include "hiredis/hiredis.h" namespace futures { namespace redis_io { AsyncContext::AsyncContext(EventExecutor *loop, const std::string& addr, uint16_t port) : io::IOObject(loop), c_(nullptr), addr_(addr), port_(port), rev_(loop->getLoop()), wev_(loop->getLoop()) { connected_ = false; // reconnect(); } void AsyncContext::reconnect() { rev_.stop(); wev_.stop(); if (c_) { redisAsyncDisconnect(c_); c_ = nullptr; } FUTURES_DLOG(INFO) << "reconnecting to redis"; c_ = redisAsyncConnect(addr_.c_str(), port_); if (!c_) throw RedisException("redisAsyncContext"); if (c_->err) { std::string err(c_->errstr); redisAsyncFree(c_); throw RedisException(err); } c_->ev.addRead = redisAddRead; c_->ev.delRead = redisDelRead; c_->ev.addWrite = redisAddWrite; c_->ev.delWrite = redisDelWrite; c_->ev.cleanup = redisCleanup; c_->ev.data = this; c_->data = this; reading_ = false; writing_ = false; connected_ = false; rev_.set<AsyncContext, &AsyncContext::redisReadEvent>(this); rev_.set(c_->c.fd, ev::READ); wev_.set<AsyncContext, &AsyncContext::redisWriteEvent>(this); wev_.set(c_->c.fd, ev::WRITE); redisAsyncSetConnectCallback(c_, redisConnect); redisAsyncSetDisconnectCallback(c_, redisDisconnect); } AsyncContext::~AsyncContext() { FUTURES_DLOG(INFO) << "AsyncContext destroy: " << c_; rev_.stop(); wev_.stop(); if (c_) redisAsyncFree(c_); } void AsyncContext::redisReadEvent(ev::io &watcher, int revent) { if (revent & ev::ERROR) throw RedisException("failed to read"); redisAsyncHandleRead(c_); } void AsyncContext::redisWriteEvent(ev::io &watcher, int revent) { if (revent & ev::ERROR) throw RedisException("failed to write"); redisAsyncHandleWrite(c_); } void AsyncContext::redisAddRead(void *data) { AsyncContext *self = static_cast<AsyncContext*>(data); if (!self->reading_) { self->reading_ = true; self->rev_.start(); } } void AsyncContext::redisDelRead(void *data) { AsyncContext *self = static_cast<AsyncContext*>(data); if (self->reading_) { self->reading_ = false; self->rev_.stop(); } } void AsyncContext::redisAddWrite(void *data) { AsyncContext *self = static_cast<AsyncContext*>(data); if (!self->writing_) { self->writing_ = true; self->wev_.start(); } } void AsyncContext::redisDelWrite(void *data) { AsyncContext *self = static_cast<AsyncContext*>(data); if (self->writing_) { self->writing_ = false; self->wev_.stop(); } } void AsyncContext::redisCleanup(void *data) { AsyncContext *self = static_cast<AsyncContext*>(data); FUTURES_DLOG(INFO) << "redisCleanup"; if (self) { redisDelRead(self); redisDelWrite(self); } } void AsyncContext::redisConnect(const redisAsyncContext *c, int status) { AsyncContext *self = static_cast<AsyncContext*>(c->data); FUTURES_DLOG(INFO) << "redis connect: " << status; if (status != REDIS_OK) { self->c_ = nullptr; } else { self->connected_ = true; } } void AsyncContext::redisDisconnect(const redisAsyncContext *c, int status) { AsyncContext *self = static_cast<AsyncContext*>(c->data); FUTURES_DLOG(INFO) << "redis disconnect: " << status; self->c_ = nullptr; self->connected_ = false; // pending should be empty } io::intrusive_ptr<AsyncContext::CompletionToken> AsyncContext::asyncFormattedCommand(const char *cmd, size_t len, bool subscribe) { reconnectIfNeeded(); assert(c_); io::intrusive_ptr<CompletionToken> p(new CompletionToken(subscribe)); int status = redisAsyncFormattedCommand(c_, redisCallback, p.get(), cmd, len); if (status) { p->reply_ = Try<Reply>(RedisException(c_->errstr)); p->notifyDone(); } else { p->attach(this); p->addRef(); } return p; } void AsyncContext::redisCallback(struct redisAsyncContext* ctx, void *r, void *p) { AsyncContext *self = static_cast<AsyncContext*>(ctx->data); (void)self; auto handler = static_cast<CompletionToken*>(p); auto reply = static_cast<redisReply*>(r); if (!handler->subscribe_) { if (reply) { handler->reply_ = Try<Reply>(Reply(reply)); } else { handler->reply_ = Try<Reply>(FutureCancelledException()); } handler->notifyDone(); handler->decRef(); } else { if (reply) { // TODO unsubscribe handler->stream_.push_back(Try<Reply>(Reply(reply))); handler->notify(); } else { handler->stream_.push_back(Try<Reply>(FutureCancelledException())); handler->notifyDone(); handler->decRef(); } } } void AsyncContext::onCancel(CancelReason r) { FUTURES_DLOG(INFO) << "canceling all requests"; if (c_) { redisAsyncFree(c_); c_ = nullptr; connected_ = false; } } // RedisCommandFuture RedisCommandFuture::RedisCommandFuture(AsyncContext::Ptr ctx, const char *format, ...) : ctx_(ctx) { va_list ap; int len; char *cmd; va_start(ap,format); len = redisvFormatCommand(&cmd, format, ap); va_end(ap); if (len < 0) throw RedisException("invalid command"); assert(cmd != nullptr); cmd_.assign(cmd, len); } RedisCommandStream::RedisCommandStream(AsyncContext::Ptr ctx, const char *format, ...) : ctx_(ctx) { va_list ap; int len; char *cmd; va_start(ap,format); len = redisvFormatCommand(&cmd, format, ap); va_end(ap); if (len < 0) throw RedisException("invalid command"); assert(cmd != nullptr); cmd_.assign(cmd, len); } } }
27.791667
86
0.617191
chyh1990
9a799309ae4d8f47c9cc005df306f0a5d0e0eb91
1,643
cpp
C++
src/physics_animation.cpp
AleksanderSiwek/Fluide_Engine
12c626105b079a3dd21a3cc95b7d98342d041f5d
[ "MIT" ]
null
null
null
src/physics_animation.cpp
AleksanderSiwek/Fluide_Engine
12c626105b079a3dd21a3cc95b7d98342d041f5d
[ "MIT" ]
null
null
null
src/physics_animation.cpp
AleksanderSiwek/Fluide_Engine
12c626105b079a3dd21a3cc95b7d98342d041f5d
[ "MIT" ]
null
null
null
#include "physics_animation.hpp" PhysicsAnimation::PhysicsAnimation() { Initialize(); } PhysicsAnimation::~PhysicsAnimation() { } void PhysicsAnimation::AdvanceSingleFrame() { Frame f = _currentFrame; Update(++f); } void PhysicsAnimation::SetCurrentFrame(const Frame& frame) { _currentFrame = frame; } void PhysicsAnimation::SetNumberOfSubTimesteps(unsigned int numberOfSubTimesteps) { _numberOfSubTimesteps = numberOfSubTimesteps; } Frame PhysicsAnimation::GetCurrentFrame() const { return _currentFrame; } double PhysicsAnimation::GetCurrentTimeInSeconds() const { return _currentTime; } unsigned int PhysicsAnimation::GetNumberOfSubTimeSteps() const { return _numberOfTimeSteps; } void PhysicsAnimation::OnUpdate(const Frame& frame) { if(frame.GetIndex() > _currentFrame.GetIndex()) { long int numberOfFrames = frame.GetIndex() - _currentFrame.GetIndex(); for (size_t i = 0; i < numberOfFrames; ++i) { AdvanceTimeStep(frame.GetTimeIntervalInSeconds()); } _currentFrame = frame; } } void PhysicsAnimation::AdvanceTimeStep(double timeIntervalInSeconds) { _currentTime = _currentFrame.GetTimeInSeconds(); const double subTimestepInterval = _currentFrame.GetTimeIntervalInSeconds() / NumberOfSubTimeSteps(timeIntervalInSeconds); for(size_t i = 0; i < NumberOfSubTimeSteps(timeIntervalInSeconds); i++) { OnAdvanceTimeStep(subTimestepInterval); _currentTime += subTimestepInterval; } } void PhysicsAnimation::Initialize() { OnInitialize(); } void PhysicsAnimation::OnInitialize() { }
20.283951
126
0.720633
AleksanderSiwek
9a7ea5d5cb03f555ed8b370c08acadaee18ab31c
1,297
hpp
C++
Axis.Echinopsis/application/factories/collectors/HyperworksNodeCollectorFactory.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.Echinopsis/application/factories/collectors/HyperworksNodeCollectorFactory.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.Echinopsis/application/factories/collectors/HyperworksNodeCollectorFactory.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#pragma once #include "application/factories/collectors/CollectorFactory.hpp" #include "application/factories/collectors/GeneralNodeCollectorFactory.hpp" #include "HyperworksNodeCollectorBuilder.hpp" namespace axis { namespace application { namespace factories { namespace collectors { class HyperworksNodeCollectorFactory : public CollectorFactory { public: HyperworksNodeCollectorFactory(void); ~HyperworksNodeCollectorFactory(void); virtual void Destroy( void ) const; virtual axis::services::language::parsing::ParseResult TryParse( const axis::String& formatName, const axis::services::language::iterators::InputIterator& begin, const axis::services::language::iterators::InputIterator& end ); virtual CollectorBuildResult ParseAndBuild( const axis::String& formatName, const axis::services::language::iterators::InputIterator& begin, const axis::services::language::iterators::InputIterator& end, const axis::domain::analyses::NumericalModel& model, axis::application::parsing::core::ParseContext& context ); private: axis::application::factories::collectors::GeneralNodeCollectorFactory *factory_; HyperworksNodeCollectorBuilder builder_; }; } } } } // namespace axis::application::factories::collectors
41.83871
103
0.764842
renato-yuzup
9a7edf2c0ab8eefeb1da82969a5042d69f40a17e
8,422
cpp
C++
PyMI/PyMI.cpp
ader1990/PyMI
1af8af0b51afdc4c8c533a8ff4d4355f929b932e
[ "Apache-2.0" ]
19
2015-12-07T17:53:49.000Z
2021-11-25T14:48:06.000Z
PyMI/PyMI.cpp
ader1990/PyMI
1af8af0b51afdc4c8c533a8ff4d4355f929b932e
[ "Apache-2.0" ]
11
2017-02-01T14:34:27.000Z
2020-05-17T20:22:42.000Z
PyMI/PyMI.cpp
ader1990/PyMI
1af8af0b51afdc4c8c533a8ff4d4355f929b932e
[ "Apache-2.0" ]
18
2015-11-19T19:52:51.000Z
2022-02-09T08:22:32.000Z
// PyMI.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include "PyMI.h" #include "Application.h" #include "Session.h" #include "Class.h" #include "Operation.h" #include "Instance.h" #include "Serializer.h" #include "OperationOptions.h" #include "DestinationOptions.h" #include "MiError.h" #include <datetime.h> PyObject *PyMIError; PyObject *PyMITimeoutError; static PyMethodDef mi_methods[] = { { NULL, NULL, 0, NULL } /* Sentinel */ }; #ifdef IS_PY3K static PyModuleDef mimodule = { PyModuleDef_HEAD_INIT, "mi", "Management Infrastructure API module.", -1, mi_methods }; #endif PyObject* _initmi(void) { if (!PyEval_ThreadsInitialized()) { PyEval_InitThreads(); } PyDateTime_IMPORT; PyObject* m = NULL; if (PyType_Ready(&ApplicationType) < 0) return NULL; if (PyType_Ready(&SessionType) < 0) return NULL; if (PyType_Ready(&ClassType) < 0) return NULL; if (PyType_Ready(&InstanceType) < 0) return NULL; if (PyType_Ready(&OperationType) < 0) return NULL; if (PyType_Ready(&SerializerType) < 0) return NULL; if (PyType_Ready(&OperationOptionsType) < 0) return NULL; if (PyType_Ready(&DestinationOptionsType) < 0) return NULL; #ifdef IS_PY3K m = PyModule_Create(&mimodule); if (m == NULL) return NULL; #else m = Py_InitModule3("mi", mi_methods, "MI module."); if (m == NULL) return NULL; #endif Py_INCREF(&ApplicationType); PyModule_AddObject(m, "Application", (PyObject*)&ApplicationType); Py_INCREF(&SessionType); PyModule_AddObject(m, "Session", (PyObject*)&SessionType); Py_INCREF(&ClassType); PyModule_AddObject(m, "Class", (PyObject*)&ClassType); Py_INCREF(&InstanceType); PyModule_AddObject(m, "Instance", (PyObject*)&InstanceType); Py_INCREF(&OperationType); PyModule_AddObject(m, "Operation", (PyObject*)&OperationType); Py_INCREF(&SerializerType); PyModule_AddObject(m, "Serializer", (PyObject*)&SerializerType); Py_INCREF(&OperationOptionsType); PyModule_AddObject(m, "OperationOptions", (PyObject*)&OperationOptionsType); Py_INCREF(&DestinationOptionsType); PyModule_AddObject(m, "DestinationOptions", (PyObject*)&DestinationOptionsType); PyMIError = PyErr_NewException("PyMI.error", NULL, NULL); Py_INCREF(PyMIError); PyModule_AddObject(m, "error", PyMIError); PyMITimeoutError = PyErr_NewException("PyMI.timeouterror", PyMIError, NULL); Py_INCREF(PyMITimeoutError); PyModule_AddObject(m, "timeouterror", PyMITimeoutError); PyObject_SetAttrString(m, "PROTOCOL_WINRM", PyUnicode_FromString("WINRM")); PyObject_SetAttrString(m, "PROTOCOL_WMIDCOM", PyUnicode_FromString("WMIDCOM")); PyObject_SetAttrString(m, "MI_BOOLEAN", PyLong_FromLong(MI_BOOLEAN)); PyObject_SetAttrString(m, "MI_UINT8", PyLong_FromLong(MI_UINT8)); PyObject_SetAttrString(m, "MI_SINT8", PyLong_FromLong(MI_SINT8)); PyObject_SetAttrString(m, "MI_UINT16", PyLong_FromLong(MI_UINT16)); PyObject_SetAttrString(m, "MI_SINT16", PyLong_FromLong(MI_SINT16)); PyObject_SetAttrString(m, "MI_UINT32", PyLong_FromLong(MI_UINT32)); PyObject_SetAttrString(m, "MI_SINT32", PyLong_FromLong(MI_SINT32)); PyObject_SetAttrString(m, "MI_UINT64", PyLong_FromLong(MI_UINT64)); PyObject_SetAttrString(m, "MI_SINT64", PyLong_FromLong(MI_SINT64)); PyObject_SetAttrString(m, "MI_REAL32", PyLong_FromLong(MI_REAL32)); PyObject_SetAttrString(m, "MI_REAL64", PyLong_FromLong(MI_REAL64)); PyObject_SetAttrString(m, "MI_CHAR16", PyLong_FromLong(MI_CHAR16)); PyObject_SetAttrString(m, "MI_DATETIME", PyLong_FromLong(MI_DATETIME)); PyObject_SetAttrString(m, "MI_STRING", PyLong_FromLong(MI_STRING)); PyObject_SetAttrString(m, "MI_REFERENCE", PyLong_FromLong(MI_REFERENCE)); PyObject_SetAttrString(m, "MI_INSTANCE", PyLong_FromLong(MI_INSTANCE)); PyObject_SetAttrString(m, "MI_UINT8A", PyLong_FromLong(MI_UINT8A)); PyObject_SetAttrString(m, "MI_SINT8A", PyLong_FromLong(MI_SINT8A)); PyObject_SetAttrString(m, "MI_UINT16A", PyLong_FromLong(MI_UINT16A)); PyObject_SetAttrString(m, "MI_SINT16A", PyLong_FromLong(MI_SINT16A)); PyObject_SetAttrString(m, "MI_UINT32A", PyLong_FromLong(MI_UINT32A)); PyObject_SetAttrString(m, "MI_SINT32A", PyLong_FromLong(MI_SINT32A)); PyObject_SetAttrString(m, "MI_UINT64A", PyLong_FromLong(MI_UINT64A)); PyObject_SetAttrString(m, "MI_SINT64A", PyLong_FromLong(MI_SINT64A)); PyObject_SetAttrString(m, "MI_REAL32A", PyLong_FromLong(MI_REAL32A)); PyObject_SetAttrString(m, "MI_REAL64A", PyLong_FromLong(MI_REAL64A)); PyObject_SetAttrString(m, "MI_CHAR16A", PyLong_FromLong(MI_CHAR16A)); PyObject_SetAttrString(m, "MI_DATETIMEA", PyLong_FromLong(MI_DATETIMEA)); PyObject_SetAttrString(m, "MI_STRINGA", PyLong_FromLong(MI_STRINGA)); PyObject_SetAttrString(m, "MI_REFERENCEA", PyLong_FromLong(MI_REFERENCEA)); PyObject_SetAttrString(m, "MI_INSTANCEA", PyLong_FromLong(MI_INSTANCEA)); PyObject_SetAttrString(m, "MI_ARRAY", PyLong_FromLong(MI_ARRAY)); PyObject_SetAttrString(m, "MI_AUTH_TYPE_DEFAULT", PyUnicode_FromWideChar(MI_AUTH_TYPE_DEFAULT, wcslen(MI_AUTH_TYPE_DEFAULT))); PyObject_SetAttrString(m, "MI_AUTH_TYPE_NONE", PyUnicode_FromWideChar(MI_AUTH_TYPE_NONE, wcslen(MI_AUTH_TYPE_NONE))); PyObject_SetAttrString(m, "MI_AUTH_TYPE_DIGEST", PyUnicode_FromWideChar(MI_AUTH_TYPE_DIGEST, wcslen(MI_AUTH_TYPE_DIGEST))); PyObject_SetAttrString(m, "MI_AUTH_TYPE_NEGO_WITH_CREDS", PyUnicode_FromWideChar(MI_AUTH_TYPE_NEGO_WITH_CREDS, wcslen(MI_AUTH_TYPE_NEGO_WITH_CREDS))); PyObject_SetAttrString(m, "MI_AUTH_TYPE_NEGO_NO_CREDS", PyUnicode_FromWideChar(MI_AUTH_TYPE_NEGO_NO_CREDS, wcslen(MI_AUTH_TYPE_NEGO_NO_CREDS))); PyObject_SetAttrString(m, "MI_AUTH_TYPE_BASIC", PyUnicode_FromWideChar(MI_AUTH_TYPE_BASIC, wcslen(MI_AUTH_TYPE_BASIC))); PyObject_SetAttrString(m, "MI_AUTH_TYPE_KERBEROS", PyUnicode_FromWideChar(MI_AUTH_TYPE_KERBEROS, wcslen(MI_AUTH_TYPE_KERBEROS))); PyObject_SetAttrString(m, "MI_AUTH_TYPE_CLIENT_CERTS", PyUnicode_FromWideChar(MI_AUTH_TYPE_CLIENT_CERTS, wcslen(MI_AUTH_TYPE_CLIENT_CERTS))); PyObject_SetAttrString(m, "MI_AUTH_TYPE_NTLM", PyUnicode_FromWideChar(MI_AUTH_TYPE_NTLM, wcslen(MI_AUTH_TYPE_NTLM))); PyObject_SetAttrString(m, "MI_AUTH_TYPE_CREDSSP", PyUnicode_FromWideChar(MI_AUTH_TYPE_CREDSSP, wcslen(MI_AUTH_TYPE_CREDSSP))); PyObject_SetAttrString(m, "MI_AUTH_TYPE_ISSUER_CERT", PyUnicode_FromWideChar(MI_AUTH_TYPE_ISSUER_CERT, wcslen(MI_AUTH_TYPE_ISSUER_CERT))); PyObject_SetAttrString(m, "MI_TRANSPORT_HTTP", PyUnicode_FromWideChar(MI_DESTINATIONOPTIONS_TRANSPORT_HTTP, wcslen(MI_DESTINATIONOPTIONS_TRANSPORT_HTTP))); // The misspelling of 'transport' is intentional, as this is how it's defined by MI.h. PyObject_SetAttrString(m, "MI_TRANSPORT_HTTPS", PyUnicode_FromWideChar(MI_DESTINATIONOPTIONS_TRANPSORT_HTTPS, wcslen(MI_DESTINATIONOPTIONS_TRANPSORT_HTTPS))); PyObject* mi_error = MiError_Init(); if (mi_error == NULL) return NULL; else PyObject_SetAttrString(m, "mi_error", mi_error); return m; } #ifdef IS_PY3K PyMODINIT_FUNC PyInit_mi(void) #else PyMODINIT_FUNC initmi(void) #endif { PyObject* m = _initmi(); #ifdef IS_PY3K return m; #endif }
40.104762
98
0.66635
ader1990
9a846635ec4bc8ee32415cdc76a08ba1d8f16037
2,762
cc
C++
Neptune/Socket.cc
superly1213/Neptune
11e34a6c44bd10161c59560d24cbe6f83580855e
[ "BSD-2-Clause" ]
1
2017-01-30T04:32:27.000Z
2017-01-30T04:32:27.000Z
Neptune/Socket.cc
superly1213/Neptune
11e34a6c44bd10161c59560d24cbe6f83580855e
[ "BSD-2-Clause" ]
null
null
null
Neptune/Socket.cc
superly1213/Neptune
11e34a6c44bd10161c59560d24cbe6f83580855e
[ "BSD-2-Clause" ]
1
2019-03-21T07:09:16.000Z
2019-03-21T07:09:16.000Z
// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <Chaos/Logging/Logging.h> #include <Neptune/Kern/NetOps.h> #include <Neptune/InetAddress.h> #include <Neptune/Socket.h> namespace Neptune { Socket::~Socket(void) { NetOps::socket::close(sockfd_); } void Socket::bind_address(const InetAddress& local_addr) { NetOps::socket::bind(sockfd_, local_addr.get_address()); } void Socket::listen(void) { NetOps::socket::listen(sockfd_); } int Socket::accept(InetAddress& peer_addr) { struct sockaddr_in6 addr6{}; int connfd = NetOps::socket::accept(sockfd_, &addr6); if (connfd >= 0) peer_addr.set_address(addr6); return connfd; } void Socket::shutdown_write(void) { NetOps::socket::shutdown(sockfd_, NetOps::socket::SHUT_WRIT); } void Socket::set_tcp_nodelay(bool nodelay) { NetOps::socket::set_option( sockfd_, IPPROTO_TCP, TCP_NODELAY, nodelay ? 1 : 0); } void Socket::set_reuse_addr(bool reuse) { NetOps::socket::set_option(sockfd_, SOL_SOCKET, SO_REUSEADDR, reuse ? 1 : 0); } void Socket::set_reuse_port(bool reuse) { int r = -1; #if defined(SO_REUSEPORT) r = NetOps::socket::set_option( sockfd_, SOL_SOCKET, SO_REUSEPORT, reuse ? 1 : 0); #endif if (r < 0 && reuse) CHAOSLOG_SYSERR << "Socket::set_reuse_port - failed or not support"; } void Socket::set_keep_alive(bool keep_alive) { NetOps::socket::set_option( sockfd_, SOL_SOCKET, SO_KEEPALIVE, keep_alive ? 1 : 0); } }
33.277108
79
0.736061
superly1213
89412bbd52f4055b39f0530c4515f8abdd6d4ebb
14,199
cc
C++
wrappers/8.1.1/vtkGeoProjectionWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/8.1.1/vtkGeoProjectionWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/8.1.1/vtkGeoProjectionWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkObjectWrap.h" #include "vtkGeoProjectionWrap.h" #include "vtkObjectBaseWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkGeoProjectionWrap::ptpl; VtkGeoProjectionWrap::VtkGeoProjectionWrap() { } VtkGeoProjectionWrap::VtkGeoProjectionWrap(vtkSmartPointer<vtkGeoProjection> _native) { native = _native; } VtkGeoProjectionWrap::~VtkGeoProjectionWrap() { } void VtkGeoProjectionWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkGeoProjection").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("GeoProjection").ToLocalChecked(), ConstructorGetter); } void VtkGeoProjectionWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkGeoProjectionWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkObjectWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkObjectWrap::ptpl)); tpl->SetClassName(Nan::New("VtkGeoProjectionWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "ClearOptionalParameters", ClearOptionalParameters); Nan::SetPrototypeMethod(tpl, "clearOptionalParameters", ClearOptionalParameters); Nan::SetPrototypeMethod(tpl, "GetCentralMeridian", GetCentralMeridian); Nan::SetPrototypeMethod(tpl, "getCentralMeridian", GetCentralMeridian); Nan::SetPrototypeMethod(tpl, "GetDescription", GetDescription); Nan::SetPrototypeMethod(tpl, "getDescription", GetDescription); Nan::SetPrototypeMethod(tpl, "GetIndex", GetIndex); Nan::SetPrototypeMethod(tpl, "getIndex", GetIndex); Nan::SetPrototypeMethod(tpl, "GetName", GetName); Nan::SetPrototypeMethod(tpl, "getName", GetName); Nan::SetPrototypeMethod(tpl, "GetNumberOfOptionalParameters", GetNumberOfOptionalParameters); Nan::SetPrototypeMethod(tpl, "getNumberOfOptionalParameters", GetNumberOfOptionalParameters); Nan::SetPrototypeMethod(tpl, "GetNumberOfProjections", GetNumberOfProjections); Nan::SetPrototypeMethod(tpl, "getNumberOfProjections", GetNumberOfProjections); Nan::SetPrototypeMethod(tpl, "GetOptionalParameterKey", GetOptionalParameterKey); Nan::SetPrototypeMethod(tpl, "getOptionalParameterKey", GetOptionalParameterKey); Nan::SetPrototypeMethod(tpl, "GetOptionalParameterValue", GetOptionalParameterValue); Nan::SetPrototypeMethod(tpl, "getOptionalParameterValue", GetOptionalParameterValue); Nan::SetPrototypeMethod(tpl, "GetProjectionDescription", GetProjectionDescription); Nan::SetPrototypeMethod(tpl, "getProjectionDescription", GetProjectionDescription); Nan::SetPrototypeMethod(tpl, "GetProjectionName", GetProjectionName); Nan::SetPrototypeMethod(tpl, "getProjectionName", GetProjectionName); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "RemoveOptionalParameter", RemoveOptionalParameter); Nan::SetPrototypeMethod(tpl, "removeOptionalParameter", RemoveOptionalParameter); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetCentralMeridian", SetCentralMeridian); Nan::SetPrototypeMethod(tpl, "setCentralMeridian", SetCentralMeridian); Nan::SetPrototypeMethod(tpl, "SetName", SetName); Nan::SetPrototypeMethod(tpl, "setName", SetName); Nan::SetPrototypeMethod(tpl, "SetOptionalParameter", SetOptionalParameter); Nan::SetPrototypeMethod(tpl, "setOptionalParameter", SetOptionalParameter); #ifdef VTK_NODE_PLUS_VTKGEOPROJECTIONWRAP_INITPTPL VTK_NODE_PLUS_VTKGEOPROJECTIONWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkGeoProjectionWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkGeoProjection> native = vtkSmartPointer<vtkGeoProjection>::New(); VtkGeoProjectionWrap* obj = new VtkGeoProjectionWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkGeoProjectionWrap::ClearOptionalParameters(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->ClearOptionalParameters(); } void VtkGeoProjectionWrap::GetCentralMeridian(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); double r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetCentralMeridian(); info.GetReturnValue().Set(Nan::New(r)); } void VtkGeoProjectionWrap::GetDescription(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetDescription(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkGeoProjectionWrap::GetIndex(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetIndex(); info.GetReturnValue().Set(Nan::New(r)); } void VtkGeoProjectionWrap::GetName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkGeoProjectionWrap::GetNumberOfOptionalParameters(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetNumberOfOptionalParameters(); info.GetReturnValue().Set(Nan::New(r)); } void VtkGeoProjectionWrap::GetNumberOfProjections(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetNumberOfProjections(); info.GetReturnValue().Set(Nan::New(r)); } void VtkGeoProjectionWrap::GetOptionalParameterKey(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { char const * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->GetOptionalParameterKey( info[0]->Int32Value() ); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); return; } Nan::ThrowError("Parameter mismatch"); } void VtkGeoProjectionWrap::GetOptionalParameterValue(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { char const * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->GetOptionalParameterValue( info[0]->Int32Value() ); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); return; } Nan::ThrowError("Parameter mismatch"); } void VtkGeoProjectionWrap::GetProjectionDescription(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { char const * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->GetProjectionDescription( info[0]->Int32Value() ); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); return; } Nan::ThrowError("Parameter mismatch"); } void VtkGeoProjectionWrap::GetProjectionName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { char const * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->GetProjectionName( info[0]->Int32Value() ); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); return; } Nan::ThrowError("Parameter mismatch"); } void VtkGeoProjectionWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); vtkGeoProjection * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkGeoProjectionWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkGeoProjectionWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkGeoProjectionWrap *w = new VtkGeoProjectionWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkGeoProjectionWrap::RemoveOptionalParameter(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->RemoveOptionalParameter( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkGeoProjectionWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0])) { VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject()); vtkGeoProjection * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObjectBase *) a0->native.GetPointer() ); VtkGeoProjectionWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkGeoProjectionWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkGeoProjectionWrap *w = new VtkGeoProjectionWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkGeoProjectionWrap::SetCentralMeridian(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetCentralMeridian( info[0]->NumberValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkGeoProjectionWrap::SetName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetName( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkGeoProjectionWrap::SetOptionalParameter(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() > 1 && info[1]->IsString()) { Nan::Utf8String a1(info[1]); if(info.Length() != 2) { Nan::ThrowError("Too many parameters."); return; } native->SetOptionalParameter( *a0, *a1 ); return; } } Nan::ThrowError("Parameter mismatch"); }
31.48337
106
0.7347
axkibe
89427c5306d3cbf81dfd33f11c25a5c2e9fbb185
1,329
hpp
C++
include/interface_handler.hpp
rdavid/atm
c3a69799b5993cec694a69b0f881603aa092fc32
[ "0BSD" ]
null
null
null
include/interface_handler.hpp
rdavid/atm
c3a69799b5993cec694a69b0f881603aa092fc32
[ "0BSD" ]
null
null
null
include/interface_handler.hpp
rdavid/atm
c3a69799b5993cec694a69b0f881603aa092fc32
[ "0BSD" ]
null
null
null
#pragma once #include <interface.hpp> #include <future> namespace atm { class interface_handler { public: std::future<void> issue_money(unsigned amount) const { return std::async(&interface::issue_money, &m_interface, amount); } std::future<void> display_insufficient_funds() const { return std::async(&interface::display_insufficient_funds, &m_interface); } std::future<void> display_enter_pin() const { return std::async(&interface::display_enter_pin, &m_interface); } std::future<void> display_enter_card() const { return std::async(&interface::display_enter_card, &m_interface); } std::future<void> display_balance(unsigned balance) const { return std::async(&interface::display_balance, &m_interface, balance); } std::future<void> display_withdrawal_options() const { return std::async(&interface::display_withdrawal_options, &m_interface); } std::future<void> display_cancelled() const { return std::async(&interface::display_cancelled, &m_interface); } std::future<void> display_pin_incorrect_message() const { return std::async(&interface::display_pin_incorrect_message, &m_interface); } std::future<void> eject_card() const { return std::async(&interface::eject_card, &m_interface); } private: interface m_interface; }; } // namespace atm
30.906977
79
0.72912
rdavid
8945d2f322c94aad0085b1c9c7e31fbbfcc5e764
542
hpp
C++
libs/console/include/sge/console/callback/function_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/console/include/sge/console/callback/function_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/console/include/sge/console/callback/function_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_CONSOLE_CALLBACK_FUNCTION_TYPE_HPP_INCLUDED #define SGE_CONSOLE_CALLBACK_FUNCTION_TYPE_HPP_INCLUDED #include <sge/console/arg_list.hpp> #include <sge/console/object_ref.hpp> namespace sge::console::callback { using function_type = void(sge::console::arg_list const &, sge::console::object_ref); } #endif
27.1
85
0.756458
cpreh
89467c1eff0a4c084a1c7ba2d881639561f201f3
32,134
cpp
C++
tbc/src/physicsengine.cpp
highfestiva/life
b05b592502d72980ab55e13e84330b74a966f377
[ "BSD-3-Clause" ]
9
2019-09-03T18:33:31.000Z
2022-02-04T04:00:02.000Z
tbc/src/physicsengine.cpp
highfestiva/life
b05b592502d72980ab55e13e84330b74a966f377
[ "BSD-3-Clause" ]
null
null
null
tbc/src/physicsengine.cpp
highfestiva/life
b05b592502d72980ab55e13e84330b74a966f377
[ "BSD-3-Clause" ]
null
null
null
// Author: Jonas Byström // Copyright (c) Pixel Doctrine #include "pch.h" #include "../include/physicsengine.h" #include "../../lepra/include/lepraassert.h" #include "../../lepra/include/endian.h" #include "../../lepra/include/math.h" #include "../../lepra/include/vector2d.h" #include "../include/chunkybonegeometry.h" #include "../include/chunkyphysics.h" namespace tbc { #define kMaxAspectIndex 400 PhysicsEngine::PhysicsEngine(EngineType engine_type, float strength, float max_speed, float max_speed2, float friction, unsigned controller_index): engine_type_(engine_type), strength_(strength), max_speed_(max_speed), max_speed2_(max_speed2), friction_(friction), controller_index_(controller_index), intensity_(0) { ::memset(value_, 0, sizeof(value_)); ::memset(smooth_value_, 0, sizeof(smooth_value_)); } PhysicsEngine::~PhysicsEngine() { } void PhysicsEngine::RelocatePointers(const ChunkyPhysics* target, const ChunkyPhysics* source, const PhysicsEngine& original) { const size_t cnt = engine_node_array_.size(); for (size_t x = 0; x < cnt; ++x) { const int bone_index = source->GetIndex(original.engine_node_array_[x].geometry_); deb_assert(bone_index >= 0); engine_node_array_[x].geometry_ = target->GetBoneGeometry(bone_index); } } PhysicsEngine* PhysicsEngine::Load(ChunkyPhysics* structure, const void* data, unsigned byte_count) { const uint32* _data = (const uint32*)data; if (byte_count != sizeof(uint32)*7 + Endian::BigToHost(_data[6])*sizeof(uint32)*3) { log_.Error("Could not load; wrong data size."); deb_assert(false); return (0); } PhysicsEngine* engine = new PhysicsEngine(kEngineWalk, 0, 0, 0, 0, 0); engine->LoadChunkyData(structure, data); if (engine->GetChunkySize() != byte_count) { deb_assert(false); log_.Error("Corrupt data or error in loading algo."); delete (engine); engine = 0; } return (engine); } PhysicsEngine::EngineType PhysicsEngine::GetEngineType() const { return (engine_type_); } void PhysicsEngine::AddControlledGeometry(ChunkyBoneGeometry* geometry, float scale, EngineMode mode) { engine_node_array_.push_back(EngineNode(geometry, scale, mode)); } void PhysicsEngine::RemoveControlledGeometry(ChunkyBoneGeometry* geometry) { EngineNodeArray::iterator i = engine_node_array_.begin(); for (; i != engine_node_array_.end(); ++i) { if (i->geometry_ == geometry) { engine_node_array_.erase(i); return; } } } PhysicsEngine::GeometryList PhysicsEngine::GetControlledGeometryList() const { GeometryList list; EngineNodeArray::const_iterator i = engine_node_array_.begin(); for (; i != engine_node_array_.end(); ++i) { list.push_back(i->geometry_); } return list; } void PhysicsEngine::SetStrength(float strength) { strength_ = strength; } bool PhysicsEngine::SetValue(unsigned aspect, float value) { deb_assert(controller_index_ >= 0 && controller_index_ < kMaxAspectIndex); deb_assert(value >= -10000); deb_assert(value <= +10000); switch (engine_type_) { case kEngineWalk: case kEnginePushRelative: case kEnginePushAbsolute: case kEnginePushTurnRelative: case kEnginePushTurnAbsolute: case kEngineVelocityAbsoluteXY: { const unsigned controlled_aspects = 3; if (aspect >= controller_index_+0 && aspect <= controller_index_+controlled_aspects) { switch (aspect - controller_index_) { case 0: value_[kAspectPrimary] = value; break; case 2: value_[kAspectPrimary] += value; break; // Handbrake. case 1: value_[kAspectSecondary] = value; break; case 3: value_[kAspectTertiary] = value; break; } return (true); } } break; case kEngineHover: case kEngineHingeRoll: case kEngineHingeGyro: case kEngineHingeBrake: case kEngineHingeTorque: case kEngineHinge2Turn: case kEngineRotor: case kEngineRotorTilt: case kEngineJet: case kEngineSliderForce: case kEngineYawBrake: case kEngineAirBrake: { if (aspect == controller_index_) { value_[kAspectPrimary] = value; return (true); } } break; case kEngineGlue: case kEngineBallBrake: case kEngineStabilize: case kEngineUprightStabilize: case kEngineForwardStabilize: { // Fixed mode "engine". } break; default: { deb_assert(false); } break; } return (false); } void PhysicsEngine::ForceSetValue(unsigned aspect, float value) { deb_assert(value >= -1 && value <= +1); value_[aspect] = value; } void PhysicsEngine::OnMicroTick(PhysicsManager* physics_manager, const ChunkyPhysics* structure, float frame_time) const { const float limited_frame_time = std::min(frame_time, 0.1f); const float normalized_frame_time = limited_frame_time * 90; const float primary_force = (value_[kAspectLocalPrimary] > std::abs(value_[kAspectPrimary]))? value_[kAspectLocalPrimary] : value_[kAspectPrimary]; intensity_ = 0; EngineNodeArray::const_iterator i = engine_node_array_.begin(); for (; i != engine_node_array_.end(); ++i) { const EngineNode& engine_node = *i; ChunkyBoneGeometry* geometry = engine_node.geometry_; const float scale = engine_node.scale_; if (!geometry) { log_.Error("Missing node!"); continue; } switch (engine_type_) { case kEngineWalk: case kEnginePushRelative: case kEnginePushAbsolute: { vec3 axis[3] = {vec3(0, 1, 0), vec3(1, 0, 0), vec3(0, 0, 1)}; if (engine_type_ == kEnginePushRelative) { const ChunkyBoneGeometry* root_geometry = structure->GetBoneGeometry(0); const quat orientation = physics_manager->GetBodyOrientation(root_geometry->GetBodyId()) * structure->GetOriginalBoneTransformation(0).GetOrientation().GetInverse(); axis[0] = orientation*axis[0]; axis[1] = orientation*axis[1]; axis[2] = orientation*axis[2]; } vec3 offset; while (geometry->GetJointType() == ChunkyBoneGeometry::kJointExclude) { ChunkyBoneGeometry* parent = geometry->GetParent(); if (!parent) { break; } vec3 maya_offset = geometry->GetOriginalOffset(); std::swap(maya_offset.y, maya_offset.z); maya_offset.y = -maya_offset.y; offset += maya_offset; geometry = parent; } vec3 push_vector; for (int j = kAspectPrimary; j <= kAspectTertiary; ++j) { push_vector += value_[j] * axis[j]; } const float push_force = push_vector.GetLength(); if (push_force > 0.1f || friction_) { if (friction_) { vec3 velocity_vector; physics_manager->GetBodyVelocity(geometry->GetBodyId(), velocity_vector); velocity_vector /= max_speed_; if (engine_type_ == kEngineWalk) { velocity_vector.z = 0; // When walking we won't apply brakes in Z. } vec3 f = (velocity_vector-push_vector) * (0.5f*friction_); push_vector -= f; } physics_manager->AddForceAtRelPos(geometry->GetBodyId(), push_vector*strength_*scale, offset); } intensity_ += Math::Lerp(Math::Clamp(friction_,0.1f,0.5f), 1.0f, push_force); } break; case kEnginePushTurnRelative: case kEnginePushTurnAbsolute: { vec3 axis[3] = {vec3(0, 0, 1), vec3(1, 0, 0), vec3(0, 1, 0)}; if (engine_type_ == kEnginePushTurnRelative) { const ChunkyBoneGeometry* root_geometry = structure->GetBoneGeometry(0); const quat orientation = physics_manager->GetBodyOrientation(root_geometry->GetBodyId()) * structure->GetOriginalBoneTransformation(0).GetOrientation().GetInverse(); axis[0] = orientation*axis[0]; axis[1] = orientation*axis[1]; axis[2] = orientation*axis[2]; } vec3 push_vector; for (int j = kAspectPrimary; j <= kAspectTertiary; ++j) { push_vector += value_[j] * axis[j]; } const float push_force = push_vector.GetLength(); if (push_force > 0.1f || friction_ != 0) { if (friction_) { vec3 angular_velocity_vector; physics_manager->GetBodyAngularVelocity(geometry->GetBodyId(), angular_velocity_vector); angular_velocity_vector /= max_speed_; vec3 f = (angular_velocity_vector-push_vector) * (0.5f*friction_); push_vector -= f; } physics_manager->AddTorque(geometry->GetBodyId(), push_vector*strength_*scale); } intensity_ += Math::Lerp(Math::Clamp(friction_,0.1f,0.5f), 1.0f, push_force); } break; case kEngineVelocityAbsoluteXY: { vec3 axis[3] = { vec3(0, 1, 0), vec3(1, 0, 0), vec3(0, 0, 1) }; if (engine_type_ == kEnginePushRelative) { const ChunkyBoneGeometry* root_geometry = structure->GetBoneGeometry(0); const quat orientation = physics_manager->GetBodyOrientation(root_geometry->GetBodyId()) * structure->GetOriginalBoneTransformation(0).GetOrientation().GetInverse(); axis[0] = orientation*axis[0]; axis[1] = orientation*axis[1]; axis[2] = orientation*axis[2]; } vec3 velocity_vector; for (int j = kAspectPrimary; j <= kAspectTertiary; ++j) { velocity_vector += value_[j] * axis[j]; } velocity_vector *= strength_*scale; if (!value_[kAspectTertiary]) { vec3 vel; physics_manager->GetBodyVelocity(geometry->GetBodyId(), vel); velocity_vector.z = vel.z; } physics_manager->SetBodyVelocity(geometry->GetBodyId(), velocity_vector); } break; case kEngineHover: { if (primary_force != 0 || value_[kAspectSecondary] != 0) { // Arcade stabilization for lifter (typically hovercraft, elevator or similar vehicle). vec3 lift_pivot = physics_manager->GetBodyPosition(geometry->GetBodyId()) + vec3(0,0,1)*friction_*scale; const vec3 lift_force = vec3(0,0,1)*strength_*scale; physics_manager->AddForceAtPos(geometry->GetBodyId(), lift_force, lift_pivot); } } break; case kEngineHingeGyro: { // Apply a fake gyro torque to parent in order to emulate a heavier gyro than // it actually is. The gyro must be light weight, or physics simulation will be // unstable when rolling bodies around any other axis than the hinge one. deb_assert(geometry->GetJointId() != INVALID_JOINT); if (geometry->GetJointId() != INVALID_JOINT && friction_ >= 0) { vec3 axis; physics_manager->GetAxis1(geometry->GetJointId(), axis); vec3 __y; vec3 __z; axis.GetNormalized().GetOrthogonals(__y, __z); const float _strength = 3 * primary_force * strength_; __z *= _strength; vec3 pos; physics_manager->GetAnchorPos(geometry->GetJointId(), pos); physics_manager->AddForceAtPos(geometry->GetParent()->GetBodyId(), __z, pos+__y); physics_manager->AddForceAtPos(geometry->GetParent()->GetBodyId(), -__z, pos-__y); } } // TRICKY: fall through. case kEngineHingeRoll: { //deb_assert(geometry->GetJointId() != INVALID_JOINT); if (geometry->GetJointId() != INVALID_JOINT) { float _value = primary_force; float directional_max_speed = ((_value >= 0)? max_speed_ : -max_speed2_) * _value; float rotation_speed; physics_manager->GetAngleRate2(geometry->GetJointId(), rotation_speed); const float intensity = rotation_speed / max_speed_; intensity_ += std::abs(intensity); if (engine_type_ == kEngineHingeGyro) { _value = (_value+1)*0.5f; directional_max_speed = _value * (max_speed_ - max_speed2_) + max_speed2_; } else if (engine_type_ == kEngineHingeRoll) { //if (_value > 0) { // Torque curve approximation, (tested it out, looks ok to me): // -8*(x-0.65)^2*(x-0.02) + 1 // // Starts at about 100 % strength at 0 RPM, local strength minimum of approximately 75 % // at about 25 % RPM, maximum (in range) of 100 % strength at 65 % RPM, and drops to close // to 0 % strength at 100 % RPM. const float square = intensity - 0.65f; _value *= -8 * square * square * (intensity-0.02f) + 1; } } const float used_strength = strength_*(std::abs(_value) + std::abs(friction_)); float previous_strength = 0; float previous_target_speed = 0; physics_manager->GetAngularMotorRoll(geometry->GetJointId(), previous_strength, previous_target_speed); const float target_speed = Math::Lerp(previous_target_speed, directional_max_speed*scale, 0.5f); const float target_strength = Math::Lerp(previous_strength, used_strength, 0.5f); physics_manager->SetAngularMotorRoll(geometry->GetJointId(), target_strength, target_speed); } else { log_.Error("Missing roll joint!"); } } break; case kEngineHingeBrake: { //deb_assert(geometry->GetJointId() != INVALID_JOINT); if (geometry->GetJointId() != INVALID_JOINT) { // "Max speed" used as a type of "break threashold", so that a joystick or similar // won't start breaking on the tiniest movement. "Scaling" here determines part of // functionality (such as only affecting some wheels), may be positive or negative. const float abs_value = std::abs(primary_force); if (abs_value > max_speed_ && primary_force < scale) { const float break_force_used = strength_*abs_value; geometry->SetExtraData(1); physics_manager->SetAngularMotorRoll(geometry->GetJointId(), break_force_used, 0); } else if (geometry->GetExtraData()) { geometry->SetExtraData(0); physics_manager->SetAngularMotorRoll(geometry->GetJointId(), 0, 0); } } else { log_.Error("Missing break joint!"); } } break; case kEngineHingeTorque: case kEngineHinge2Turn: { ApplyTorque(physics_manager, limited_frame_time, geometry, engine_node); } break; case kEngineRotor: { deb_assert(geometry->GetJointId() != INVALID_JOINT); if (geometry->GetJointId() != INVALID_JOINT) { const vec3 rotor_force = GetRotorLiftForce(physics_manager, geometry, engine_node); vec3 lift_force = rotor_force * primary_force; const int parent_bone = structure->GetIndex(geometry->GetParent()); const quat orientation = physics_manager->GetBodyOrientation(geometry->GetParent()->GetBodyId()) * structure->GetOriginalBoneTransformation(parent_bone).GetOrientation().GetInverse(); vec3 rotor_pivot; physics_manager->GetAnchorPos(geometry->GetJointId(), rotor_pivot); const vec3 offset = orientation * vec3(0, 0, max_speed_*scale); rotor_pivot += offset; if (max_speed2_) { // Arcade stabilization for VTOL rotor. vec3 parent_angular_velocity; physics_manager->GetBodyAngularVelocity(geometry->GetParent()->GetBodyId(), parent_angular_velocity); parent_angular_velocity = orientation.GetInverse() * parent_angular_velocity; const vec3 parent_angle = orientation.GetInverse() * vec3(0, 0, 1); // TRICKY: assumes original joint direction is towards heaven. const float stability_x = -parent_angle.x * 0.5f + parent_angular_velocity.y * max_speed2_; const float stability_y = -parent_angle.y * 0.5f - parent_angular_velocity.x * max_speed2_; rotor_pivot += orientation * vec3(stability_x, stability_y, 0); } // Smooth rotor force - for digital controls and to make acceleration seem more realistic. const float smooth = normalized_frame_time * 0.05f * engine_node.scale_; lift_force.x = smooth_value_[kAspectPrimary] = Math::Lerp(smooth_value_[kAspectPrimary], lift_force.x, smooth); lift_force.y = smooth_value_[kAspectSecondary] = Math::Lerp(smooth_value_[kAspectSecondary], lift_force.y, smooth); lift_force.z = smooth_value_[kAspectTertiary] = Math::Lerp(smooth_value_[kAspectTertiary], lift_force.z, smooth); // Counteract rotor's movement through perpendicular air. vec3 drag_force; physics_manager->GetBodyVelocity(geometry->GetBodyId(), drag_force); drag_force = ((-drag_force*rotor_force.GetNormalized()) * friction_ * normalized_frame_time) * rotor_force; physics_manager->AddForceAtPos(geometry->GetParent()->GetBodyId(), lift_force + drag_force, rotor_pivot); } else { log_.Error("Missing rotor joint!"); } } break; case kEngineRotorTilt: { deb_assert(geometry->GetJointId() != INVALID_JOINT); if (geometry->GetJointId() != INVALID_JOINT) { const vec3 lift_force = GetRotorLiftForce(physics_manager, geometry, engine_node) * std::abs(primary_force); const int parent_bone = structure->GetIndex(geometry->GetParent()); const float placement = (primary_force >= 0)? 1.0f : -1.0f; const vec3 offset = physics_manager->GetBodyOrientation(geometry->GetParent()->GetBodyId()) * structure->GetOriginalBoneTransformation(parent_bone).GetOrientation().GetInverse() * vec3(placement*max_speed_, -placement*max_speed2_, 0); const vec3 world_pos = offset + physics_manager->GetBodyPosition(geometry->GetBodyId()); physics_manager->AddForceAtPos(geometry->GetParent()->GetBodyId(), lift_force, world_pos); //{ // static int cnt = 0; // if ((++cnt)%300 == 0) // { // //vec3 r = physics_manager->GetBodyOrientation(geometry->GetBodyId()).GetInverse() * rel_pos; // //vec3 r = rel_pos; // vec3 r = offset; // vec3 w = physics_manager->GetBodyPosition(geometry->GetBodyId()); // mLog.Infof("Got pos (%f, %f, %f - world pos is (%f, %f, %f)."), r.x, r.y, r.z, w.x, w.y, w.z); // } //} } else { log_.Error("Missing rotor joint!"); } } break; case kEngineJet: { deb_assert(false); // TODO: use relative push instead! ChunkyBoneGeometry* root_geometry = structure->GetBoneGeometry(0); vec3 velocity; physics_manager->GetBodyVelocity(root_geometry->GetBodyId(), velocity); if (primary_force != 0 && velocity.GetLengthSquared() < max_speed_*max_speed_) { const quat orientation = physics_manager->GetBodyOrientation(root_geometry->GetBodyId()) * structure->GetOriginalBoneTransformation(0).GetOrientation().GetInverse(); const vec3 push_force = orientation * vec3(0, primary_force*strength_, 0); physics_manager->AddForce(geometry->GetBodyId(), push_force); } intensity_ += primary_force; } break; case kEngineSliderForce: { deb_assert(geometry->GetJointId() != INVALID_JOINT); if (geometry->GetJointId() != INVALID_JOINT) { if (!primary_force && engine_node.mode_ == kModeNormal) { // Normal slider behavior is to pull back to origin while half-lock keep last motor target. float position; physics_manager->GetSliderPos(geometry->GetJointId(), position); if (!Math::IsEpsEqual(position, 0.0f, 0.1f)) { float _value = -position*std::abs(scale); _value = (_value > 0)? _value*max_speed_ : _value*max_speed2_; physics_manager->SetMotorTarget(geometry->GetJointId(), strength_, _value); } } else if (!primary_force && engine_node.mode_ == kModeRelease) { // Release slider behavior just lets go. physics_manager->SetMotorTarget(geometry->GetJointId(), 0, 0); } else { const float _value = (primary_force > 0)? primary_force*max_speed_ : primary_force*max_speed2_; physics_manager->SetMotorTarget(geometry->GetJointId(), strength_, _value*scale); } float speed = 0; physics_manager->GetSliderSpeed(geometry->GetJointId(), speed); intensity_ += std::abs(speed) / max_speed_; } } break; case kEngineGlue: case kEngineBallBrake: { deb_assert(geometry->GetJointId() != INVALID_JOINT); if (geometry->GetJointId() != INVALID_JOINT) { physics_manager->StabilizeJoint(geometry->GetJointId()); } } break; case kEngineYawBrake: { const tbc::PhysicsManager::BodyID body_id = geometry->GetBodyId(); vec3 angular_velocity; physics_manager->GetBodyAngularVelocity(body_id, angular_velocity); // Reduce rotation of craft. angular_velocity.z *= friction_; const float low_angular_velocity = max_speed_; if (Math::IsEpsEqual(primary_force, 0.0f) && std::abs(angular_velocity.z) < low_angular_velocity) { // Seriously kill speed depending on strength. angular_velocity.z *= 1/strength_; } physics_manager->SetBodyAngularVelocity(body_id, angular_velocity); } break; case kEngineAirBrake: { // 1 // F = - pv^2 C A // D 2 d const float cd_a = 0.5f * 1.225f * friction_; // Density of air multiplied with friction coefficient and area (the two latter combined in friction_). const tbc::PhysicsManager::BodyID body_id = geometry->GetBodyId(); vec3 velocity; physics_manager->GetBodyVelocity(body_id, velocity); const float speed = velocity.GetLength(); const vec3 drag = velocity * -speed * cd_a; physics_manager->AddForce(body_id, drag); } break; case kEngineStabilize: { Stabilize(physics_manager, structure, geometry, friction_*scale); } break; case kEngineUprightStabilize: { UprightStabilize(physics_manager, structure, geometry, strength_*scale*10, friction_); } break; case kEngineForwardStabilize: { ForwardStabilize(physics_manager, structure, geometry, strength_*scale*10, friction_); } break; default: { deb_assert(false); } break; } } if (intensity_) { intensity_ /= engine_node_array_.size(); } } vec3 PhysicsEngine::GetCurrentMaxSpeed(const PhysicsManager* physics_manager) const { vec3 max_velocity; float _max_speed = 0; EngineNodeArray::const_iterator i = engine_node_array_.begin(); for (; i != engine_node_array_.end(); ++i) { const EngineNode& engine_node = *i; ChunkyBoneGeometry* geometry = engine_node.geometry_; vec3 velocity; physics_manager->GetBodyVelocity(geometry->GetBodyId(), velocity); const float speed = velocity.GetLengthSquared(); if (speed > _max_speed) { _max_speed = speed; max_velocity = velocity; } } return max_velocity; } void PhysicsEngine::Stabilize(PhysicsManager* physics_manager, const ChunkyPhysics* structure, const ChunkyBoneGeometry* geometry, float friction) { // 1st: angular velocity damping. vec3 angular; physics_manager->GetBodyAngularVelocity(geometry->GetBodyId(), angular); angular -= angular * friction; physics_manager->SetBodyAngularVelocity(geometry->GetBodyId(), angular); // 2nd: slerp towards straight. const int root_bone = 0; // Use root bone for fetching original transform, or "up" will be off. quat current_orientation = physics_manager->GetBodyOrientation(geometry->GetBodyId()); const quat original_orientation = structure->GetOriginalBoneTransformation(root_bone).GetOrientation(); current_orientation.Slerp(current_orientation, original_orientation, friction); physics_manager->SetBodyOrientation(geometry->GetBodyId(), current_orientation); } void PhysicsEngine::UprightStabilize(PhysicsManager* physics_manager, const ChunkyPhysics* structure, const ChunkyBoneGeometry* geometry, float strength, float friction) { const int root_bone = 0; // Use root bone for fetching original transform, or "up" will be off. const quat orientation = physics_manager->GetBodyOrientation(geometry->GetBodyId()) * structure->GetOriginalBoneTransformation(root_bone).GetOrientation().GetInverse(); // 1st: angular velocity damping (skipping z). vec3 angular; physics_manager->GetBodyAngularVelocity(geometry->GetBodyId(), angular); angular = orientation.GetInverse() * angular; angular.z = 0; angular *= -friction; vec3 torque = orientation * angular; // 2nd: strive towards straight. angular = orientation * vec3(0, 0, 1); torque += vec3(+angular.y * friction*5, -angular.x * friction*5, 0); physics_manager->AddTorque(geometry->GetBodyId(), torque*strength); } void PhysicsEngine::ForwardStabilize(PhysicsManager* physics_manager, const ChunkyPhysics* structure, const ChunkyBoneGeometry* geometry, float strength, float friction) { const int bone = structure->GetIndex(geometry); const quat orientation = physics_manager->GetBodyOrientation(geometry->GetBodyId()) * structure->GetOriginalBoneTransformation(bone).GetOrientation().GetInverse(); // 1st: angular velocity damping in Z-axis. vec3 velocity3d; physics_manager->GetBodyAngularVelocity(geometry->GetBodyId(), velocity3d); const float angular_velocity = velocity3d.z; // 2nd: strive towards straight towards where we're heading. physics_manager->GetBodyVelocity(geometry->GetBodyId(), velocity3d); vec2 velocity2d(velocity3d.x, velocity3d.y); const vec3 forward3d = orientation * vec3(0, 1, 0); vec2 forward2d(forward3d.x, forward3d.y); if (forward2d.GetLengthSquared() > 0.1f && velocity2d.GetLengthSquared() > 0.3f) { float angle = forward2d.GetAngle(velocity2d); if (angle > PIF) { angle -= 2*PIF; } else if (angle < -PIF) { angle += 2*PIF; } velocity3d.Set(0, 0, (6*angle - angular_velocity*friction*1.5f) * strength); physics_manager->AddTorque(geometry->GetBodyId(), velocity3d); } } unsigned PhysicsEngine::GetControllerIndex() const { return (controller_index_); } float PhysicsEngine::GetValue() const { deb_assert(controller_index_ >= 0 && controller_index_ < kMaxAspectIndex); if (engine_type_ == kEngineWalk || engine_type_ == kEnginePushRelative || engine_type_ == kEnginePushAbsolute) { const float a = std::abs(value_[kAspectPrimary]); const float b = std::abs(value_[kAspectSecondary]); const float c = std::abs(value_[kAspectTertiary]); if (a > b && a > c) { return value_[kAspectPrimary]; } if (b > c) { return value_[kAspectSecondary]; } return value_[kAspectTertiary]; } return value_[kAspectPrimary]; } const float* PhysicsEngine::GetValues() const { return value_; } float PhysicsEngine::GetIntensity() const { return (intensity_); } float PhysicsEngine::GetMaxSpeed() const { return (max_speed_); } float PhysicsEngine::GetLerpThrottle(float up, float down, bool _abs) const { float& lerp_shadow = _abs? smooth_value_[kAspectLocalShadow] : smooth_value_[kAspectLocalShadowAbs]; float _value = GetPrimaryValue(); _value = _abs? std::abs(_value) : _value; lerp_shadow = Math::Lerp(lerp_shadow, _value, (_value > lerp_shadow)? up : down); return lerp_shadow; } bool PhysicsEngine::HasEngineMode(EngineMode mode) const { EngineNodeArray::const_iterator i = engine_node_array_.begin(); for (; i != engine_node_array_.end(); ++i) { if (i->mode_ == mode) { return true; } } return false; } unsigned PhysicsEngine::GetChunkySize() const { return ((unsigned)(sizeof(uint32)*6 + sizeof(uint32) + sizeof(uint32)*3*engine_node_array_.size())); } void PhysicsEngine::SaveChunkyData(const ChunkyPhysics* structure, void* data) const { uint32* _data = (uint32*)data; _data[0] = Endian::HostToBig(GetEngineType()); _data[1] = Endian::HostToBigF(strength_); _data[2] = Endian::HostToBigF(max_speed_); _data[3] = Endian::HostToBigF(max_speed2_); _data[4] = Endian::HostToBigF(friction_); _data[5] = Endian::HostToBig(controller_index_); _data[6] = Endian::HostToBig((uint32)engine_node_array_.size()); int x; for (x = 0; x < (int)engine_node_array_.size(); ++x) { const EngineNode& controlled_node = engine_node_array_[x]; _data[7+x*3] = Endian::HostToBig(structure->GetIndex(controlled_node.geometry_)); _data[8+x*3] = Endian::HostToBigF(controlled_node.scale_); _data[9+x*3] = Endian::HostToBig(controlled_node.mode_); } } float PhysicsEngine::GetPrimaryValue() const { const float force = GetValue(); const float primary_force = (value_[kAspectLocalPrimary] > std::abs(force))? value_[kAspectLocalPrimary] : force; return primary_force; } void PhysicsEngine::LoadChunkyData(ChunkyPhysics* structure, const void* data) { const uint32* _data = (const uint32*)data; engine_type_ = (EngineType)Endian::BigToHost(_data[0]); strength_ = Endian::BigToHostF(_data[1]); max_speed_ = Endian::BigToHostF(_data[2]); max_speed2_ = Endian::BigToHostF(_data[3]); friction_ = Endian::BigToHostF(_data[4]); controller_index_ = Endian::BigToHost(_data[5]); deb_assert(controller_index_ >= 0 && controller_index_ < kMaxAspectIndex); const int controlled_node_count = Endian::BigToHost(_data[6]); int x; for (x = 0; x < controlled_node_count; ++x) { ChunkyBoneGeometry* geometry = structure->GetBoneGeometry(Endian::BigToHost(_data[7+x*3])); deb_assert(geometry); float scale = Endian::BigToHostF(_data[8+x*3]); EngineMode _mode = (EngineMode)Endian::BigToHost(_data[9+x*3]); AddControlledGeometry(geometry, scale, _mode); } } vec3 PhysicsEngine::GetRotorLiftForce(PhysicsManager* physics_manager, ChunkyBoneGeometry* geometry, const EngineNode& engine_node) const { vec3 axis; physics_manager->GetAxis1(geometry->GetJointId(), axis); float angular_rotor_speed = 0; physics_manager->GetAngleRate1(geometry->GetJointId(), angular_rotor_speed); const float lift_force = angular_rotor_speed*angular_rotor_speed*strength_*engine_node.scale_; return (axis*lift_force); } void PhysicsEngine::ApplyTorque(PhysicsManager* physics_manager, float frame_time, ChunkyBoneGeometry* geometry, const EngineNode& engine_node) const { (void)frame_time; //deb_assert(geometry->GetJointId() != INVALID_JOINT); if (geometry->GetJointId() == INVALID_JOINT) { log_.Error("Missing torque joint!"); return; } float force = GetPrimaryValue(); const float scale = engine_node.scale_; //const float lReverseScale = (scale + 1) * 0.5f; // Move towards linear scaling. float lo_stop; float hi_stop; float bounce; physics_manager->GetJointParams(geometry->GetJointId(), lo_stop, hi_stop, bounce); //const float middle = (lo_stop+hi_stop)*0.5f; const float _target = 0; if (lo_stop < -1000 || hi_stop > 1000) { // Open interval -> relative torque. const float target_speed = force*scale*max_speed_; physics_manager->SetAngularMotorTurn(geometry->GetJointId(), strength_, target_speed); float actual_speed = 0; physics_manager->GetAngleRate2(geometry->GetJointId(), actual_speed); intensity_ += std::abs(target_speed - actual_speed) / max_speed_; return; } float irl_angle; if (!physics_manager->GetAngle1(geometry->GetJointId(), irl_angle)) { log_.Error("Bad joint angle!"); return; } // Flip angle if parent is "world". if (physics_manager->IsStaticBody(geometry->GetParent()->GetBodyId())) { irl_angle = -irl_angle; } const float irl_angle_direction = (hi_stop < lo_stop)? -irl_angle : irl_angle; if (engine_node.mode_ == kModeHalfLock) { if ((force < 0.02f && irl_angle_direction < _target) || (force > -0.02f && irl_angle_direction > _target)) { if (std::abs(force) > 0.02) { engine_node.lock_ = force; } else { force = engine_node.lock_; } } else { engine_node.lock_ = 0; } } if (friction_) { // Wants us to scale (down) rotation angle depending on vehicle speed. Otherwise most vehicles // quickly flips, not yeilding very fun gameplay. Plus, it's more like real racing cars! :) vec3 parent_velocity; physics_manager->GetBodyVelocity(geometry->GetParent()->GetBodyId(), parent_velocity); const float range_factor = ::pow(friction_, parent_velocity.GetLength()); hi_stop *= range_factor; lo_stop *= range_factor; } const float angle_span = (hi_stop-lo_stop)*0.9f; const float target_angle = Math::Lerp(lo_stop, hi_stop, scale*force*0.5f+0.5f); const float diff = (target_angle-irl_angle); const float abs_diff = std::abs(diff); float target_speed; const float abs_big_diff = std::abs(angle_span/7); const bool close_to_goal = (abs_diff < abs_big_diff); if (!close_to_goal) { target_speed = (diff > 0)? max_speed_ : -max_speed_; } else { target_speed = max_speed_*diff/abs_big_diff; } //target_speed *= (force > 0)? scale : lReverseScale; // If we're far from the desired target speed, we speed up. float current_speed = 0; if (engine_type_ == kEngineHinge2Turn) { physics_manager->GetAngleRate2(geometry->GetJointId(), current_speed); if (!close_to_goal) { target_speed *= 1+std::abs(current_speed)/30; } } else { physics_manager->GetAngleRate1(geometry->GetJointId(), current_speed); if (!close_to_goal) { target_speed += (target_speed-current_speed) * std::abs(scale); } } /*if (Math::IsEpsEqual(target_speed, 0.0f, 0.01f)) { // Stop when almost already at a halt. target_speed = 0; }*/ physics_manager->SetAngularMotorTurn(geometry->GetJointId(), strength_, target_speed); intensity_ += std::abs(target_speed / (max_speed_ * scale)); } loginstance(kPhysics, PhysicsEngine); }
38.762364
154
0.710929
highfestiva
8947abb1f31cde821893456393d10619c8c882f2
432
cpp
C++
cs162/labs/lab6/square.cpp
franzmk/Oregon-State-Schoolwork
20f8a72e78ec4baa131add2dda8026cd47f36188
[ "MIT" ]
null
null
null
cs162/labs/lab6/square.cpp
franzmk/Oregon-State-Schoolwork
20f8a72e78ec4baa131add2dda8026cd47f36188
[ "MIT" ]
null
null
null
cs162/labs/lab6/square.cpp
franzmk/Oregon-State-Schoolwork
20f8a72e78ec4baa131add2dda8026cd47f36188
[ "MIT" ]
null
null
null
#include "square.h" Square::Square() { //nothing here } Square::Square(float x, string name, string color) : Rectangle(x, x, name, color) { //nothing here } float Square::get_dimensions() { get_height(); } void Square::set_dimensions(float x) { set_height(x); set_width(x); } float Square::get_area() { float area = get_height() * get_width(); return area; } Square::~Square() { cout << "Destructor called" << endl; }
15.428571
83
0.662037
franzmk
8947c937c6e6c6c2121a55a3dd98ebdcc206856e
1,458
cpp
C++
oneEngine/oneGame/source/engine-common/entities/CWaypoint.cpp
jonting/1Engine
f22ba31f08fa96fe6405ebecec4f374138283803
[ "BSD-3-Clause" ]
8
2017-12-08T02:59:31.000Z
2022-02-02T04:30:03.000Z
oneEngine/oneGame/source/engine-common/entities/CWaypoint.cpp
jonting/1Engine
f22ba31f08fa96fe6405ebecec4f374138283803
[ "BSD-3-Clause" ]
2
2021-04-16T03:44:42.000Z
2021-08-30T06:48:44.000Z
oneEngine/oneGame/source/engine-common/entities/CWaypoint.cpp
jonting/1Engine
f22ba31f08fa96fe6405ebecec4f374138283803
[ "BSD-3-Clause" ]
1
2021-04-16T02:09:54.000Z
2021-04-16T02:09:54.000Z
#include "CWaypoint.h" #include "CPlayer.h" #include "engine/state/CGameState.h" #include "engine-common/network/playerlist.h" //DON'T LOSE YOUR WAY! std::vector<CWaypoint*> CWaypoint::WaypointList; CWaypoint::CWaypoint (void) : CPointBase(), entity (NULL), type (PLAIN) { WaypointList.push_back (this); distance = 0.0; in_range = false; } CWaypoint::~CWaypoint (void) { entity = NULL; auto findresult = std::find(WaypointList.begin(), WaypointList.end(), this); if (findresult != WaypointList.end()) { WaypointList.erase(findresult); } //We lost our way. : | } void CWaypoint::Update (void) { if ( IsServer() ) { auto playerList = Network::GetPlayerActors(); for ( uint i = 0; i < playerList.size(); ++i ) { if ( playerList[i].actor != NULL ) // If the actor is valid.... { // ....then work with that actor! distance = (m_position - playerList[i].actor->transform.world.position).magnitude(); //TODO: Check if the actor is indeed a player. if (distance < 3.0f && in_range == false) { //GameState->messenger.Send("CPlayer", Game::eGameMessages::MSG_WAYPOINTIN); CGameState::Active()->messenger.SendGlobal( Game::eGameMessages::MSG_WAYPOINTIN ); in_range = true; } if (distance > 3.0f && in_range == true) { CGameState::Active()->messenger.SendGlobal( Game::eGameMessages::MSG_WAYPOINTOUT ); in_range = false; } //go tell the responsible system it's zero } } } }
25.578947
135
0.659122
jonting
894b3f776fe234668789d7d38c52c0d12cc169aa
5,196
cpp
C++
Gpu/Material.cpp
ousttrue/FunnelPipe
380b52a7d41b4128b287ec02280bb703ed6b5d66
[ "MIT" ]
null
null
null
Gpu/Material.cpp
ousttrue/FunnelPipe
380b52a7d41b4128b287ec02280bb703ed6b5d66
[ "MIT" ]
null
null
null
Gpu/Material.cpp
ousttrue/FunnelPipe
380b52a7d41b4128b287ec02280bb703ed6b5d66
[ "MIT" ]
null
null
null
#include "Material.h" #include <Shader.h> namespace Gpu::dx12 { bool Material::Initialize(const ComPtr<ID3D12Device> &device, const ComPtr<ID3D12RootSignature> &rootSignature, const framedata::FrameMaterialPtr &material) { auto vs = material->Shader ? material->Shader->VS : nullptr; if (!vs) { return false; } auto inputLayout = vs->InputLayout(); m_rootSignature = rootSignature; // auto current = shader->Generation(); // if (current > m_lastGeneration) // { // m_pipelineState = nullptr; // m_lastGeneration = current; // } if (m_pipelineState) { // already return true; } D3D12_BLEND_DESC blend{ .AlphaToCoverageEnable = FALSE, .IndependentBlendEnable = FALSE, .RenderTarget = { { .BlendEnable = FALSE, .LogicOpEnable = FALSE, .SrcBlend = D3D12_BLEND_ONE, .DestBlend = D3D12_BLEND_ZERO, .BlendOp = D3D12_BLEND_OP_ADD, .SrcBlendAlpha = D3D12_BLEND_ONE, .DestBlendAlpha = D3D12_BLEND_ZERO, .BlendOpAlpha = D3D12_BLEND_OP_ADD, .LogicOp = D3D12_LOGIC_OP_NOOP, .RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL, }, }, }; D3D12_DEPTH_STENCIL_DESC depth{ .DepthEnable = TRUE, .DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL, .DepthFunc = D3D12_COMPARISON_FUNC_LESS_EQUAL, .StencilEnable = FALSE, .StencilReadMask = D3D12_DEFAULT_STENCIL_READ_MASK, .StencilWriteMask = D3D12_DEFAULT_STENCIL_WRITE_MASK, .FrontFace = { .StencilFailOp = D3D12_STENCIL_OP_KEEP, .StencilDepthFailOp = D3D12_STENCIL_OP_KEEP, .StencilPassOp = D3D12_STENCIL_OP_KEEP, .StencilFunc = D3D12_COMPARISON_FUNC_ALWAYS, }, .BackFace = {D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS}, }; switch (material->AlphaMode) { case framedata::AlphaMode::Opaque: break; case framedata::AlphaMode::Mask: // depth.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; break; case framedata::AlphaMode::Blend: blend.RenderTarget[0] = { .BlendEnable = TRUE, .LogicOpEnable = FALSE, .SrcBlend = D3D12_BLEND_SRC_ALPHA, .DestBlend = D3D12_BLEND_INV_SRC_ALPHA, .BlendOp = D3D12_BLEND_OP_ADD, .SrcBlendAlpha = D3D12_BLEND_ONE, .DestBlendAlpha = D3D12_BLEND_ONE, .BlendOpAlpha = D3D12_BLEND_OP_MAX, .LogicOp = D3D12_LOGIC_OP_NOOP, .RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL, }; depth.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ZERO; break; default: throw; } // Describe and create the graphics pipeline state object (PSO). auto [vsBytecode, vsSize] = vs->ByteCode(); auto [psBytecode, psSize] = material->Shader->PS->ByteCode(); D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = { .pRootSignature = rootSignature.Get(), .VS = {vsBytecode, vsSize}, .PS = {psBytecode, psSize}, .BlendState = blend, .SampleMask = UINT_MAX, .RasterizerState = { .FillMode = D3D12_FILL_MODE_SOLID, .CullMode = D3D12_CULL_MODE_BACK, // .CullMode = D3D12_CULL_MODE_NONE, .FrontCounterClockwise = TRUE, .DepthBias = D3D12_DEFAULT_DEPTH_BIAS, .DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP, .SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS, .DepthClipEnable = TRUE, .MultisampleEnable = FALSE, .AntialiasedLineEnable = FALSE, .ForcedSampleCount = 0, .ConservativeRaster = D3D12_CONSERVATIVE_RASTERIZATION_MODE_OFF, }, .DepthStencilState = depth, .InputLayout = {(const D3D12_INPUT_ELEMENT_DESC *)inputLayout.data(), (UINT)inputLayout.size()}, .PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, .NumRenderTargets = 1, .RTVFormats = {DXGI_FORMAT_R8G8B8A8_UNORM}, .DSVFormat = DXGI_FORMAT_D32_FLOAT, .SampleDesc{ .Count = 1, }, }; ThrowIfFailed(device->CreateGraphicsPipelineState( &psoDesc, IID_PPV_ARGS(&m_pipelineState))); return true; } // namespace Gpu::dx12 bool Material::SetPipeline(const ComPtr<ID3D12GraphicsCommandList> &commandList) { if (!m_pipelineState) { return false; } commandList->SetPipelineState(m_pipelineState.Get()); return true; } } // namespace Gpu::dx12
33.960784
81
0.575443
ousttrue
894b7539666e8d21a06b334927fc44a28e90be3b
6,976
cpp
C++
controllers/higher_level/src/qp/tasks/qr_joint_space_v2.cpp
ADVRHumanoids/DrivingFramework
34715c37bfe3c1f2bd92aeacecc12704a1a7820e
[ "Zlib" ]
1
2019-12-02T07:10:42.000Z
2019-12-02T07:10:42.000Z
controllers/higher_level/src/qp/tasks/qr_joint_space_v2.cpp
ADVRHumanoids/DrivingFramework
34715c37bfe3c1f2bd92aeacecc12704a1a7820e
[ "Zlib" ]
null
null
null
controllers/higher_level/src/qp/tasks/qr_joint_space_v2.cpp
ADVRHumanoids/DrivingFramework
34715c37bfe3c1f2bd92aeacecc12704a1a7820e
[ "Zlib" ]
2
2020-10-22T19:06:44.000Z
2021-06-07T03:32:52.000Z
#include "mgnss/higher_level/qp/tasks/qr_joint_space_v2.h" // #include <range/v3/view/zip.hpp> // #include <range/v3/view/concat.hpp> mgnss::higher_level::QRJointSpaceV2::QRJointSpaceV2(mgnss::higher_level::QrTask& task, const mwoibn::Matrix& jacobian, const mwoibn::VectorN& offset, mwoibn::robot_class::Robot& robot, double damping): mgnss::higher_level::QrTask(), _robot(robot), _task(task), _jacobian(jacobian), _offset(offset), _damping(damping){ } void mgnss::higher_level::QRJointSpaceV2::init(){ _task.init(); resize(_jacobian.cols(), _task.soft_inequality.rows()); _damp_vec.setConstant(_vars, _damping); _slack = _task.soft_inequality.rows(); // equality.clear(); // soft_inequality.clear(); // hard_inequality.clear(); for (auto& constraint: _task.equality) equality.add(Constraint(constraint->size(), _vars)); for (auto& constraint: _task.soft_inequality) addSoft(Constraint(constraint->size(), _vars), constraint->getGain()); for (auto& constraint: _task.hard_inequality) hard_inequality.add(Constraint(constraint->size(), _vars)); QrTask::init(); _return_state.setZero(_jacobian.rows()); _temp.setZero(_task.vars(), _jacobian.cols()); // _cost.quadratic.block(0,0,_vars, _vars).setIdentity(); } void mgnss::higher_level::QRJointSpaceV2::_update(){ _task._update(); // _marginJacobians(); _optimal_state.setZero();// = _robot.command.velocity.get(); // init from last command? for(auto&& zip: ranges::view::zip(_task.equality, ranges::view::slice(equality, ranges::end - _task.equality.size(), ranges::end) ) ){ int old_ = std::get<0>(zip)->getJacobian().cols(); int new_ = std::get<1>(zip)->getJacobian().cols(); int size_ = std::get<0>(zip)->getState().size(); std::get<1>(zip)->setState() = std::get<0>(zip)->getState(); std::get<1>(zip)->setState().noalias() += std::get<0>(zip)->getJacobian().leftCols(old_)*_offset; std::get<1>(zip)->setJacobian().block(0,0,size_, new_).noalias() = std::get<0>(zip)->getJacobian().leftCols(old_)*_jacobian.leftCols(new_); } for(auto&& zip: ranges::view::zip(_task.soft_inequality, ranges::view::slice(soft_inequality, ranges::end - _task.soft_inequality.size(), ranges::end) ) ){ int old_ = std::get<0>(zip)->getJacobian().cols(); int new_ = std::get<1>(zip)->getJacobian().cols(); int size_ = std::get<0>(zip)->getState().size(); std::get<1>(zip)->setState() = std::get<0>(zip)->getState(); std::get<1>(zip)->setState().noalias() += std::get<0>(zip)->getJacobian().leftCols(old_)*_offset; std::get<1>(zip)->setJacobian().block(0,0,size_, new_).noalias() = std::get<0>(zip)->getJacobian().leftCols(old_)*_jacobian.leftCols(new_); } for(auto&& zip: ranges::view::zip(_task.hard_inequality, ranges::view::slice(hard_inequality, ranges::end - _task.hard_inequality.size(), ranges::end)) ){ int old_ = std::get<0>(zip)->getJacobian().cols(); int new_ = std::get<1>(zip)->getJacobian().cols(); int size_ = std::get<0>(zip)->getState().size(); std::get<1>(zip)->setState() = std::get<0>(zip)->getState(); std::get<1>(zip)->setState().noalias() += std::get<0>(zip)->getJacobian().leftCols(old_)*_offset; std::get<1>(zip)->setJacobian().block(0,0,size_, new_).noalias() = std::get<0>(zip)->getJacobian().leftCols(old_)*_jacobian.leftCols(new_); } _temp.noalias() = _task.cost().quadratic.block(0,0,_task.vars(), _task.vars()) * _jacobian; _cost.quadratic.block(0,0,_vars, _vars).noalias() = _jacobian.transpose() * _temp; _cost.quadratic.block(0,0,_vars, _vars) += _damp_vec.asDiagonal(); int this_slack__ = _slack - _task.slack(); _updateGains(); // _cost.quadratic.block(_vars, _vars, this_slack__, this_slack__) = 1e3*mwoibn::Matrix::Identity(this_slack__, this_slack__);// this value should come from somewhere else (add memeber to the soft_inequality) // _cost.quadratic.block(_vars+this_slack__, _vars+this_slack__, _task.slack(), _task.slack()) = _task.cost().quadratic.block(_task.vars(), _task.vars(), _task.slack(), _task.slack()); _cost.quadratic.block(_vars, _vars, _slack, _slack) = _soft_gains.asDiagonal();// this value should come from somewhere else (add memeber to the soft_inequality) _cost.linear.head(_vars).noalias() = _task.cost().linear.head(_task.vars()).transpose() * _jacobian; _cost.linear.head(_vars).noalias() += 2*_offset.transpose()*_temp; // 2? //_cost.linear.head(_vars).noalias() += 2*_offset.transpose()*_temp; // 2? _cost.linear.tail(_task.slack()) = _task.cost().linear.tail(_task.slack()); QrTask::_update(); } void mgnss::higher_level::QRJointSpaceV2::log(mwoibn::common::Logger& logger){ // std::cout << "QR JOINT SPACE STATE" << std::endl; // if(_return_state.norm() > mwoibn::EPS){ // std::cout << "_offset\t" << _offset.transpose() << std::endl; // std::cout << "_jacobian\t" << _jacobian << std::endl; // std::cout << "_optimal_state\t" << _optimal_state.transpose() << std::endl; // std::cout << "_return_state\t" << _return_state.transpose() << std::endl; // std::cout << "_cost.linear\t" << _cost.linear.transpose() << std::endl; // std::cout << "_cost.quadratic\t" << _cost.quadratic.transpose() << std::endl; // // for(auto&& zip: ranges::view::zip(_task.equality, equality)){ // std::cout << "equality\n" << std::get<0>(zip)->getState().transpose() << "jacobian\n" << std::get<0>(zip)->getJacobian() << std::endl; // std::cout << "equality\n" << std::get<1>(zip)->getState().transpose() << "jacobian\n" << std::get<1>(zip)->getJacobian() << std::endl; // } // for(auto&& zip: ranges::view::zip(_task.soft_inequality, soft_inequality)){ // std::cout << "soft_inequality\n" << std::get<0>(zip)->getState().transpose() << "soft_inequality\n" << std::get<0>(zip)->getJacobian() << std::endl; // std::cout << "soft_inequality\n" << std::get<1>(zip)->getState().transpose() << "soft_inequality\n" << std::get<1>(zip)->getJacobian() << std::endl; // } // for(auto& constraint: hard_inequality ){ // std::cout << "hard_inequality\n" << constraint->getState().transpose() << std::endl; // } // } logger.add("cost", _optimal_cost); // // for (int i = 0; i < _vars; i++){ // logger.add("optimal_cp_" + std::to_string(i), _optimal_state[i]); // logger.add("final_cp_" + std::to_string(i), _return_state[i]); // } // // for (int i = 0; i < _slack; i++) // logger.add(std::string("slack_") + std::to_string(i), _optimal_state[_slack+i]); } void mgnss::higher_level::QRJointSpaceV2::_outputTransform(){ // std::cout << "_optimal_state.transpose" << _optimal_state.head(_vars).transpose() << std::endl; // std::cout << "_offset.transpose" << _offset.transpose() << std::endl; _return_state.noalias() = _jacobian*_optimal_state.head(_vars); _return_state += _offset; }
50.919708
211
0.647792
ADVRHumanoids
894b98f737b3d6f2eeb7c7def093bd7f68529f96
207
cpp
C++
2021.09.13-Homework-1/Task 5/Source.cpp
095238/Personal-Space
4950722f815193030674e7d899f5f07970e9e08f
[ "Apache-2.0" ]
null
null
null
2021.09.13-Homework-1/Task 5/Source.cpp
095238/Personal-Space
4950722f815193030674e7d899f5f07970e9e08f
[ "Apache-2.0" ]
null
null
null
2021.09.13-Homework-1/Task 5/Source.cpp
095238/Personal-Space
4950722f815193030674e7d899f5f07970e9e08f
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; int main(int argc, char* argv[]) { int x = 0; cin >> x; int a = x % 10; int b = (x % 100) / 10; int c = x / 100; cout << a+b+c << endl; return EXIT_SUCCESS; }
14.785714
32
0.565217
095238
8952432570536bb4be5eb04c84dcbd3c65bfd6b5
2,547
cpp
C++
homework/Kuznetsova/04/matrix.cpp
mtrempoltsev/msu_cpp_autumn_2017
0e87491dc117670b99d2ca2f7e1c5efbc425ae1c
[ "MIT" ]
10
2017-09-21T15:17:33.000Z
2021-01-11T13:11:55.000Z
homework/Kuznetsova/04/matrix.cpp
mtrempoltsev/msu_cpp_autumn_2017
0e87491dc117670b99d2ca2f7e1c5efbc425ae1c
[ "MIT" ]
null
null
null
homework/Kuznetsova/04/matrix.cpp
mtrempoltsev/msu_cpp_autumn_2017
0e87491dc117670b99d2ca2f7e1c5efbc425ae1c
[ "MIT" ]
22
2017-09-21T15:45:08.000Z
2019-02-21T19:15:25.000Z
#include "matrix.h" Matrix::Matrix(const size_t rows, const size_t columns) : rows_(rows), columns_(columns) { ptr_ = new double[columns_ * rows_]; } Matrix::Matrix(const Matrix& other) : rows_(other.rows_), columns_(other.columns_) { ptr_ = new double[columns_ * rows_]; for (size_t i = 0; i < rows_; i++) { for (size_t j = 0; j < columns_; j++) { ptr_[i * columns_ + j] =other.ptr_[i * columns_ + j]; } } } Matrix::~Matrix() { delete[] ptr_; } size_t Matrix::get_rows_number() { return rows_; } size_t Matrix::get_columns_number() { return columns_; } Matrix& Matrix::operator*=(double scalar) { for (size_t i = 0; i < rows_; i++) { for (size_t j = 0; j < columns_; j++) { ptr_[i * columns_ + j] *= scalar; } } return *this; } // multiply matrix with vector (vector1 = matrix * vector) std::vector<double> Matrix::operator*(std::vector<double>& vector) { if (columns_ != vector.size()) { assert(!"incorrect multiplication: can't match sizes"); } std::vector<double> result(rows_); auto result_it = result.begin(); for (size_t i = 0; ((i < rows_) && (result_it != result.end())); i++, result_it++) { double sum = 0; auto it = vector.begin(); for (size_t j = 0; (j < columns_) && (it != vector.end()); j++, it++) { sum += ptr_[i * columns_ + j] * (*it); } (*result_it) = sum; } return result; } // multiply matrix with vector (matrix *= vector) Matrix& Matrix::operator*=(std::vector<double>& vector) { if (columns_ != vector.size()) { assert(!"incorrect multiplication: can't match sizes"); } Matrix tmp(*this); this -> columns_ = 1; for (size_t i = 0; i < tmp.rows_; i++) { double sum = 0; auto it = vector.begin(); for (size_t j = 0; (j < tmp.columns_) && (it != vector.end()); j++, it++) { sum += tmp.ptr_[i * tmp.columns_ + j] * (*it); } ptr_[i] = sum; } return *this; } bool Matrix::operator==(const Matrix& other) { if (rows_ != other.rows_) return false; if (columns_ != other.columns_) return false; for (size_t i = 0; i < rows_; i++) { for (size_t j = 0; j < columns_; j++) { if (ptr_[i * columns_ + j] != other.ptr_[i * columns_ + j]) { return false; } } } return true; } bool Matrix::operator!=(const Matrix& other) { return !(*this == other); }
29.964706
84
0.535925
mtrempoltsev
89566a1d7c886db3bfac38c58df9b36a0a639ef4
19,308
cpp
C++
source/games/game_tetris.cpp
Chrscool8/Brick-Game-9999-in-1
5f5aa93729ded47d395f7546308b7ce89f035c17
[ "Zlib" ]
5
2021-04-06T06:18:26.000Z
2021-11-10T02:01:33.000Z
source/games/game_tetris.cpp
Chrscool8/Brick-Game-9999-in-1
5f5aa93729ded47d395f7546308b7ce89f035c17
[ "Zlib" ]
null
null
null
source/games/game_tetris.cpp
Chrscool8/Brick-Game-9999-in-1
5f5aa93729ded47d395f7546308b7ce89f035c17
[ "Zlib" ]
null
null
null
#include <games/game_tetris.h> #include <games/game_race.h> #include <grid_sprites.h> #include <game_tetris_shapes.h> #include <platform/control_layer.h> // Let's the subgame know what main game it belongs to. subgame_tetris::subgame_tetris(BrickGameFramework& _parent) : subgame(_parent) { name = "Tetris"; } // Runs once when the subgame starts (when the transition shade is fully black) void subgame_tetris::subgame_init() { printf("Initting Tetris!!\n"); // Create an instance of a snake object in game 'game' at position 5, 5. objects.push_back(std::make_unique<obj_tetris_rows>(game)); } // Runs every frame of the subgame unless the game is transitioning void subgame_tetris::subgame_step() { if (phase == -1) { // Be Prepared phase = 0; } else if (phase == 0) { // Create Object objects.push_back(std::make_unique<obj_tetromino>(game, grid_width(game.game_grid) / 2 - 1, -2, next_piece)); next_piece = rand() % tetris_shapes.size(); phase = 1; } else if (phase == 1) { // Wait for no more object if (!object_exists("obj_tetromino")) { phase = 2; } } else if (phase == 2) { highlighted_rows.clear(); // Check Rows game_object* rows = get_object_by_name("obj_tetris_rows"); if (rows != NULL) { obj_tetris_rows* row_obj = static_cast<obj_tetris_rows*>(rows); int width = grid_width(row_obj->filled_blocks); int height = grid_height(row_obj->filled_blocks); print_debug(to_string(width) + " " + to_string(height)); for (int i = 0; i < height; i++) { bool filled = true; for (int j = 0; j < width; j++) { if (!grid_get(row_obj->filled_blocks, j, i)) { filled = false; break; } } if (filled) { highlighted_rows.push_back(i); print_debug(to_string(i)); } } } phase = 3; ticker = 0; } else if (phase == 3) { // Animate Rows ticker += 1; game_object* rows = get_object_by_name("obj_tetris_rows"); if (rows != NULL) { obj_tetris_rows* row_obj = static_cast<obj_tetris_rows*>(rows); for (unsigned int i = 0; i < highlighted_rows.size(); i++) { for (int j = 0; j < grid_width(row_obj->filled_blocks); j++) { grid_set(row_obj->filled_blocks, j, highlighted_rows.at(i), (ticker % 50) > 25); } } } if (ticker > 150 || highlighted_rows.empty()) phase = 4; } else if (phase == 4) { // Remove row game_object* rows = get_object_by_name("obj_tetris_rows"); if (rows != NULL) { obj_tetris_rows* row_obj = static_cast<obj_tetris_rows*>(rows); while (!highlighted_rows.empty()) { //print_debug(to_string(highlighted_rows.size() - 1)); row_obj->shift_down(highlighted_rows.at(highlighted_rows.size() - 1)); highlighted_rows.erase(highlighted_rows.begin() + highlighted_rows.size() - 1); game.incrementScore(1); for (unsigned int i = 0; i < highlighted_rows.size(); i++) { highlighted_rows[i] += 1; } } } phase = 0; } } // Runs every frame of the subgame whether it's transitioning or not (to draw behind the shade) void subgame_tetris::subgame_draw() { //printf("Drawing Tetris!!\n"); vector<vector<bool>> spr = get_sprite(next_piece, 0); vector<vector<bool>> small_grid = grid_create(4, 4); place_grid_sprite(small_grid, spr, (grid_width(spr) <= 3), (grid_height(spr) <= 3)); draw_grid(small_grid, 1280 * .75, 720 / 2, 31); } void subgame_tetris::subgame_demo() { vector<vector<bool>> sprite; const int frames = 10; int frame = (game.game_time_in_frames / 30) % frames; switch (frame) { case 0: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 0, 0, 0, 1, 0 }, { 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; case 1: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 0, 0, 0, 1, 0 }, { 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; case 2: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, { 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 0, 0, 0, 1, 0 }, { 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; case 3: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 1, 1, 0, 0 }, { 0, 1, 1, 0, 0, 0, 1, 0, 0, 0 }, { 0, 0, 1, 1, 0, 0, 0, 0, 1, 0 }, { 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; case 4: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0, 1, 1, 1, 0, 0 }, { 0, 0, 1, 1, 0, 0, 1, 0, 1, 0 }, { 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; case 5: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 1, 1, 1, 1, 0 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; case 6: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 1, 1, 1, 1, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; case 7: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 1, 1, 1, 1, 0 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, }; break; case 8: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 1, 1, 1, 1, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; case 9: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 1, 1, 1, 1, 0 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; default: sprite = { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } }; } place_grid_sprite(game.game_grid, sprite, 0, 1); //print_debug(to_string(frame)); } // Clean up subgame objects here, runs once when the game is changing to a different // game and the transition shade is fully black void subgame_tetris::subgame_exit() { //printf("Exiting Tetris!!\n"); } std::string subgame_tetris::subgame_controls_text() { return "D-Pad: Move\nA: Clockwise\nY: Counter-C"; } subgame_tetris::obj_tetromino::obj_tetromino(BrickGameFramework& game, int _x, int _y, int _piece_type) : game_object(game, _x, _y) { name = "obj_tetromino"; angle = 0; time_til_drop_move = 60; pause_time_drop = 60; shape_index = _piece_type; } void subgame_tetris::obj_tetromino::change_rotation_by(int amount) { angle = (angle + amount + tetris_shapes.at(shape_index).size()) % tetris_shapes.at(shape_index).size(); } void subgame_tetris::obj_tetromino::check_spots(vector<vector<int>> _potentials, vector<vector<bool>> _sprite, int _direction) { for (unsigned int i = 0; i < _potentials.size(); i++) { int _x = _potentials.at(i)[0]; int _y = -_potentials.at(i)[1]; if (!check_collision(_sprite, x + _x, y + _y)) { change_rotation_by(_direction); x += _x; y += _y; break; } } } void subgame_tetris::obj_tetromino::rotate_piece(bool right) { int iter = (((double)right) - .5) * 2; vector<vector<bool>> new_shape = get_sprite(shape_index, angle + iter); if (!check_collision(new_shape, x, y)) { change_rotation_by(iter); } else { vector<vector<int>> offset_tests; // I piece if (shape_index == 0) { if (angle == 0) { if (iter == 1) { offset_tests = { {0, 0}, {-2, 0}, {1, 0}, {-2, -1}, {1, 2} }; } else { offset_tests = { {0, 0}, {-1, 0}, {2, 0}, {-1, 2}, {2, -1} }; } } else if (angle == 1) { if (iter == 1) { offset_tests = { {0, 0}, {-1, 0}, {2, 0}, {-1, 2}, {2, -1} }; } else { offset_tests = { {0, 0}, {2, 0}, {-1, 0}, {2, 1}, {-1, -2} }; } } else if (angle == 2) { if (iter == 1) { offset_tests = { {0, 0}, {2, 0}, {-1, 0}, {2, 1}, {-1, -2} }; } else { offset_tests = { {0, 0}, {1, 0}, {-2, 0}, {1, -2}, {-2, 1} }; } } else if (angle == 3) { if (iter == 1) { offset_tests = { {0, 0}, {1, 0}, {-2, 0}, {1, -2}, {-2, 1} }; } else { offset_tests = { {0, 0}, {-2, 0}, {1, 0}, {-2, -1}, {1, 2} }; } } } // not I piece else { if (angle == 0) { if (iter == 1) { offset_tests = { {0, 0}, {-1, 0}, {-1, 1}, {0, -2}, {-1, -2} }; } else { offset_tests = { {0, 0}, {1, 0}, {1, 1}, {0, -2}, {1, -2} }; } } else if (angle == 1) { if (iter == 1) { offset_tests = { {0, 0}, {1, 0}, {1, -1}, {0, 2}, {1, 2} }; } else { offset_tests = { {0, 0}, {1, 0}, {1, -1}, {0, 2}, {1, 2} }; } } else if (angle == 2) { if (iter == 1) { offset_tests = { {0, 0}, {1, 0}, {1, +1}, {0, -2}, {1, -2} }; } else { offset_tests = { {0, 0}, {-1, 0}, {-1, 1}, {0, -2}, {-1, -2} }; } } else if (angle == 3) { if (iter == 1) { offset_tests = { {0, 0}, {-1, 0}, {-1, -1}, {0, 2}, {-1, 2} }; } else { offset_tests = { {0, 0}, {-1, 0}, {-1, -1}, {0, 2}, {-1, 2} }; } } } check_spots(offset_tests, new_shape, iter); } } void subgame_tetris::obj_tetromino::step_function() { if (moving) { if (keyboard_check_pressed_left() || keyboard_check_pressed_right() || keyboard_check_pressed_down()) time_til_move = 0; if (keyboard_check_pressed_Y()) rotate_piece(false); if (keyboard_check_pressed_A()) rotate_piece(true); if (keyboard_check_left()) if (time_til_move <= 0) move_left(); if (keyboard_check_right()) if (time_til_move <= 0) move_right(); if (keyboard_check_down()) { if (time_til_move <= 0) { move_down(); time_til_drop_move = pause_time_drop; } } if (keyboard_check_left() || keyboard_check_right() || keyboard_check_down()) { if (time_til_move <= 0) time_til_move = pause_time; else time_til_move -= 1; } if (time_til_drop_move > 0) { time_til_drop_move -= 1; } else { time_til_drop_move = pause_time_drop; move_down(); } } } void subgame_tetris::obj_tetromino::draw_function() { vector<vector<bool>> spr = get_sprite(shape_index, angle); place_grid_sprite(game.game_grid, spr, x, y, true); } void subgame_tetris::obj_tetromino::destroy_function() { } int subgame_tetris::obj_tetromino::check_off_top(vector<vector<bool>> shape, int _x, int _y) { for (int i = 0; i < grid_width(shape); i++) { for (int j = 0; j < grid_height(shape); j++) { if (shape[j][i]) { //print_debug("> "+to_string(_x + i) + " " + to_string(_y + j)); if (_y + j < 0) { return 5; } } } } return 0; } // 0 - No Collision // 1 - Off Board Side Left // 2 - Off Board Side Right // 3 - Off Board Bottom // 4 - Another Piece int subgame_tetris::obj_tetromino::check_collision(vector<vector<bool>> shape, int _x, int _y) { game_object* rows = get_object_by_name("obj_tetris_rows"); for (int i = 0; i < grid_width(shape); i++) { for (int j = 0; j < grid_height(shape); j++) { if (shape[j][i]) { if (_x + i < 0) { return 1; } if (_x + i >= grid_width(game.game_grid)) { return 2; } if (_y + j >= grid_height(game.game_grid)) { return 3; } if (rows != NULL) { obj_tetris_rows* row_obj = static_cast<obj_tetris_rows*>(rows); if (grid_get(row_obj->filled_blocks, _x + i, _y + j)) { return 4; } } } } } return 0; } vector<vector<bool>> get_sprite(int _index, int _rotation) { return tetris_shapes.at(_index).at((_rotation + tetris_shapes.at(_index).size()) % tetris_shapes.at(_index).size()); } void subgame_tetris::obj_tetromino::move_left() { if (!check_collision(get_sprite(shape_index, angle), x - 1, y)) { x -= 1; } } void subgame_tetris::obj_tetromino::move_right() { if (!check_collision(get_sprite(shape_index, angle), x + 1, y)) { x += 1; } } void subgame_tetris::obj_tetromino::lose() { game.running = false; objects.push_back(std::make_unique<obj_explosion>(game, 5, 0)); } void subgame_tetris::obj_tetromino::move_down() { if (!check_collision(get_sprite(shape_index, angle), x, y + 1)) { y += 1; } else { game_object* rows = get_object_by_name("obj_tetris_rows"); if (rows != NULL) { obj_tetris_rows* row_obj = static_cast<obj_tetris_rows*>(rows); vector<vector<bool>> gtp = get_sprite(shape_index, angle); place_grid_sprite(row_obj->filled_blocks, gtp, x, y); //print_debug(to_string(x) + " " + to_string(y)); if (check_off_top(gtp, x, y)) lose(); } instance_destroy(); } } subgame_tetris::obj_tetris_rows::obj_tetris_rows(BrickGameFramework& game) : game_object(game, 0, 0) { filled_blocks = grid_create(grid_width(game.game_grid), grid_height(game.game_grid)); for (int i = 0; i < grid_height(game.game_grid); i++) { for (int j = 0; j < grid_width(game.game_grid); j++) { grid_set(game.game_grid, i, j, 0); } } name = "obj_tetris_rows"; } void subgame_tetris::obj_tetris_rows::step_function() { } void subgame_tetris::obj_tetris_rows::draw_function() { emplace_grid_in_grid(game.game_grid, filled_blocks, x, y, true); } void subgame_tetris::obj_tetris_rows::destroy_function() { } void subgame_tetris::obj_tetris_rows::shift_down(int starting_at) { for (int yy = starting_at; yy > 0; yy--) { for (int xx = 0; xx < grid_width(filled_blocks); xx++) { grid_set(filled_blocks, xx, yy, grid_get(filled_blocks, xx, yy - 1)); } } } void subgame_tetris::obj_tetris_rows::check_rows() { } int subgame_tetris::obj_tetris_rows::lowest_occupied_line(std::vector<std::vector<bool>>& grid) { return 0; }
24.596178
131
0.472757
Chrscool8
895721d9641fb87a5be26ca9e106fbb9a05aa193
2,088
cpp
C++
mc_rtc_rviz_panel/src/FormWidget.cpp
mmurooka/mc_rtc_ros
781b67729cd9375f558d55b190e77fee1993ca4e
[ "BSD-2-Clause" ]
null
null
null
mc_rtc_rviz_panel/src/FormWidget.cpp
mmurooka/mc_rtc_ros
781b67729cd9375f558d55b190e77fee1993ca4e
[ "BSD-2-Clause" ]
null
null
null
mc_rtc_rviz_panel/src/FormWidget.cpp
mmurooka/mc_rtc_ros
781b67729cd9375f558d55b190e77fee1993ca4e
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2016-2019 CNRS-UM LIRMM, CNRS-AIST JRL */ #include "FormWidget.h" namespace mc_rtc_rviz { FormWidget::FormWidget(const ClientWidgetParam & param) : ClientWidget(param) { vlayout_ = new QVBoxLayout(this); form_ = new QWidget(); layout_ = new QFormLayout(form_); auto button = new QPushButton(name().c_str()); connect(button, SIGNAL(released()), this, SLOT(released())); vlayout_->addWidget(form_); vlayout_->addWidget(button); } void FormWidget::update() { idx_ = 0; if(changed_) { auto item = vlayout_->takeAt(0); form_ = new QWidget(); layout_ = new QFormLayout(form_); vlayout_->insertWidget(0, form_); for(auto el : elements_) { el->setParent(form_); add_element_to_layout(el); } changed_ = false; item->widget()->deleteLater(); } } void FormWidget::released() { mc_rtc::Configuration out; std::string msg; bool ok = true; for(auto & el : elements_) { bool ret = el->can_fill(msg); if(!ret) { msg += '\n'; } else if(el->ready()) { out.add(el->name(), el->serialize()); } ok = ret && ok; } if(ok) { client().send_request(id(), out); } else { msg = msg.substr(0, msg.size() - 1); // remove last \n QMessageBox::critical(this, (name() + " filling incomplete").c_str(), msg.c_str()); } } void FormWidget::add_element(FormElement * element) { elements_.push_back(element); add_element_to_layout(element); } void FormWidget::add_element_to_layout(FormElement * element) { for(const auto & el : elements_) { element->update_dependencies(el); el->update_dependencies(element); } if(element->hidden()) { element->hide(); return; } auto label_text = element->name(); if(element->required()) { label_text += "*"; } if(!element->spanning()) { layout_->addRow(label_text.c_str(), element); } else { if(element->show_name()) { layout_->addRow(new QLabel(label_text.c_str(), form_)); } layout_->addRow(element); } } } // namespace mc_rtc_rviz
19.514019
87
0.617337
mmurooka
895a6c3a827ff05009eac170a1e39c165b2d1f38
30,545
inl
C++
src/fonts/stb_font_arial_28_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
3
2018-03-13T12:51:57.000Z
2021-10-11T11:32:17.000Z
src/fonts/stb_font_arial_28_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
null
null
null
src/fonts/stb_font_arial_28_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
null
null
null
// Font generated by stb_font_inl_generator.c (4/1 bpp) // // Following instructions show how to use the only included font, whatever it is, in // a generic way so you can replace it with any other font by changing the include. // To use multiple fonts, replace STB_SOMEFONT_* below with STB_FONT_arial_28_usascii_*, // and separately install each font. Note that the CREATE function call has a // totally different name; it's just 'stb_font_arial_28_usascii'. // /* // Example usage: static stb_fontchar fontdata[STB_SOMEFONT_NUM_CHARS]; static void init(void) { // optionally replace both STB_SOMEFONT_BITMAP_HEIGHT with STB_SOMEFONT_BITMAP_HEIGHT_POW2 static unsigned char fontpixels[STB_SOMEFONT_BITMAP_HEIGHT][STB_SOMEFONT_BITMAP_WIDTH]; STB_SOMEFONT_CREATE(fontdata, fontpixels, STB_SOMEFONT_BITMAP_HEIGHT); ... create texture ... // for best results rendering 1:1 pixels texels, use nearest-neighbor sampling // if allowed to scale up, use bilerp } // This function positions characters on integer coordinates, and assumes 1:1 texels to pixels // Appropriate if nearest-neighbor sampling is used static void draw_string_integer(int x, int y, char *str) // draw with top-left point x,y { ... use texture ... ... turn on alpha blending and gamma-correct alpha blending ... glBegin(GL_QUADS); while (*str) { int char_codepoint = *str++; stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR]; glTexCoord2f(cd->s0, cd->t0); glVertex2i(x + cd->x0, y + cd->y0); glTexCoord2f(cd->s1, cd->t0); glVertex2i(x + cd->x1, y + cd->y0); glTexCoord2f(cd->s1, cd->t1); glVertex2i(x + cd->x1, y + cd->y1); glTexCoord2f(cd->s0, cd->t1); glVertex2i(x + cd->x0, y + cd->y1); // if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct x += cd->advance_int; } glEnd(); } // This function positions characters on float coordinates, and doesn't require 1:1 texels to pixels // Appropriate if bilinear filtering is used static void draw_string_float(float x, float y, char *str) // draw with top-left point x,y { ... use texture ... ... turn on alpha blending and gamma-correct alpha blending ... glBegin(GL_QUADS); while (*str) { int char_codepoint = *str++; stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR]; glTexCoord2f(cd->s0f, cd->t0f); glVertex2f(x + cd->x0f, y + cd->y0f); glTexCoord2f(cd->s1f, cd->t0f); glVertex2f(x + cd->x1f, y + cd->y0f); glTexCoord2f(cd->s1f, cd->t1f); glVertex2f(x + cd->x1f, y + cd->y1f); glTexCoord2f(cd->s0f, cd->t1f); glVertex2f(x + cd->x0f, y + cd->y1f); // if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct x += cd->advance; } glEnd(); } */ #ifndef STB_FONTCHAR__TYPEDEF #define STB_FONTCHAR__TYPEDEF typedef struct { // coordinates if using integer positioning float s0,t0,s1,t1; signed short x0,y0,x1,y1; int advance_int; // coordinates if using floating positioning float s0f,t0f,s1f,t1f; float x0f,y0f,x1f,y1f; float advance; } stb_fontchar; #endif #define STB_FONT_arial_28_usascii_BITMAP_WIDTH 256 #define STB_FONT_arial_28_usascii_BITMAP_HEIGHT 102 #define STB_FONT_arial_28_usascii_BITMAP_HEIGHT_POW2 128 #define STB_FONT_arial_28_usascii_FIRST_CHAR 32 #define STB_FONT_arial_28_usascii_NUM_CHARS 95 #define STB_FONT_arial_28_usascii_LINE_SPACING 18 static unsigned int stb__arial_28_usascii_pixels[]={ 0x26000031,0x00988001,0x01310062,0x037d404c,0xfffb80ae,0x9ffff32f, 0x80000600,0x02600009,0x26000026,0x20011000,0x00040009,0x00000000, 0x0fe20011,0x3ffb2600,0x400aceff,0xfd80dffa,0x20bff701,0x06fa80fb, 0x754037a6,0xdff32ffe,0x3f6e207d,0x2001bdff,0xbefffec8,0x517e2001, 0x7f64c05f,0x203ec0ce,0x201dffd8,0xfb5003f9,0x75c0039f,0x75c02dff, 0x6d400bdf,0x404effff,0xfd3000fb,0xffb99bdf,0x7ecc09ff,0x981fd84f, 0x3f883fff,0xeb887930,0x202effff,0x80df32fe,0xffeffffa,0xffa804ff, 0x5ffffeff,0xfc87f500,0xfdfff701,0x00fdc1ff,0x05fd5bfb,0x7fe401f6, 0x4400ffec,0x5ffffffe,0xfffffe98,0xffff902f,0x401dffff,0xdffa804f, 0x3bfee602,0x361be600,0x204fb81f,0xffd8006c,0x02ffedec,0x81be65fd, 0x64c1dff9,0x3fee04ff,0x2ffdcc1e,0x1fa17dc0,0xfd517fd4,0xdf01fccd, 0x1fcc37cc,0xfb07fc40,0x12efd807,0xffe87ff7,0x41ffb88b,0x75cc3ffb, 0x803ee07f,0x22002ffa,0x43fc06fe,0x03fd81fd,0xf98007f3,0x1bf67b1f, 0x06f997f4,0xfa807ff3,0x04ff883f,0x36027fcc,0xfe837c0f,0x3e0ff984, 0x7f89f306,0xbf7007e8,0x7fc06fa8,0x3ee6fc83,0x746fa81f,0x0bfe604f, 0xff882fc4,0x7f440300,0x3f61fe04,0xfb01fd81,0xf737d401,0x0ff99ecb, 0x0df32fe8,0x7e4017fa,0x8037ec1f,0x1ba02ffb,0x0df309f3,0x01f9065c, 0x20fe85f7,0xdf7003fa,0x3e604fc8,0x367f980f,0x23ff106f,0x7ec01ff8, 0x3607fa04,0x7ffe4c2f,0x1fa29f94,0x0fec0ff8,0x2fcc0fec,0x4fc9bea0, 0x3fa008f6,0xff10df32,0x31ff4003,0x7ec003ff,0x3fffff64,0x4fffffff, 0xf50013f2,0x7f89f505,0xff100374,0xf007fea7,0x74df705f,0xf93f603f, 0x004c403f,0x44fa89f7,0xcffceff9,0x407f22fe,0x40fec0fe,0x03fc81fe, 0x4df737d4,0x25fd003d,0x06fa86f9,0xff52fec0,0x326fc800,0xeeeefeee, 0x3f63eeff,0x20179513,0x26f984f8,0x00fea6f9,0x7ffbff70,0x441dfb00, 0x80ffa3fe,0x2fff65fd,0x17e60000,0x1ff443f9,0xfa83fff2,0xfd83fd03, 0xfe81fe81,0xf337d401,0x2007b19f,0x90df32fe,0x6fb800bf,0xf5001bee, 0xfd07ee0f,0x3feebfa0,0x0fd03fff,0x87faf7f6,0xffd0006e,0x7fe4003d, 0x7ec3ffdd,0x44bff106,0x09befffe,0xfd1fe200,0xff884fe8,0xfd82fc47, 0x7fc0fec2,0x5400ff80,0x7fffdc6f,0x32fe800c,0x009fb0df,0xbf90ffa8, 0x81ff8800,0xf82fc0fd,0xffbbffdf,0x701fc83f,0x17d43bfd,0x77ffec00, 0x3ffa2000,0x7fdc0eff,0xc86ffb80,0x1dffffff,0x2fc1ff00,0x3fa01ff3, 0xdf506f85,0x2fdc1fd8,0x7d403fc4,0xffffea86,0x4cbfa01d,0x004fe86f, 0x5fd87fcc,0x40ffc400,0xf827cc6f,0x0ffb84ff,0x20201fcc,0x405edc6e, 0x5ffaefe9,0x6ffdc062,0x742ffeba,0xefd99cff,0xfd95105f,0xff007fff, 0x5fb8fe63,0xbf10ff60,0xfd977dc0,0x301dfb11,0x0df500df,0x17ffff4c, 0x0df32fe8,0xfb800bf9,0x3001bee7,0xb8bf10ff,0x01fff02f,0x0bf07ff1, 0x3fa2fb80,0x6ffc4ffe,0x3f69ff50,0x5c0ffcc5,0x3ffa60ff,0x05facfff, 0x09ffd710,0x45f72fe8,0x0bfa03fd,0x4fd807f5,0x03fe63fb,0x7d4037d4, 0x7f55ec06,0xf32fe80f,0x800df50d,0x01fe66fc,0x7764df50,0xeffeeeff, 0x817fa3ee,0x007d84fd,0x229f337c,0x90ff51fd,0xc85ff5ff,0x20bfe06f, 0x9f72cedb,0x80ff9000,0x7c3f91ff,0x81ff102f,0x3bf201fd,0x3f623fb2, 0x807f980d,0xf1ec06fa,0x265fd07f,0x00ff886f,0x3ff13fa0,0xfb27ec00, 0xffffffff,0x1fec9fff,0x5f70bf90,0xfc8bee00,0x27ecfee1,0xe86fffd8, 0x017f202f,0x07d93fc8,0x2203ff10,0xfd8bea7f,0xfa8df903,0xfb1be605, 0xf885fb83,0x137d400f,0xbf91ec13,0x1be65fd0,0x22d82ffc,0x37ec1ffb, 0xd82ff980,0xc817e20f,0x20ffa05f,0x8df004f8,0x6d3e60fe,0x7ffd104f, 0x7e407fd0,0x7fc03315,0x3e00df71,0x44df301f,0x261bf23f,0x03fe64ff, 0x0fec2fc8,0x0ff407fc,0x2ff9bea0,0xe84fc8f6,0x260df32f,0x77fc43ff, 0xff884ffa,0x82ff4404,0x1027cc6f,0x3ff101ff,0x3ee01ba0,0x9f507f42, 0x3a203fea,0x2fe40eff,0xdf73ff88,0xff89bea0,0x503fd403,0x3e65f89f, 0x37ffea3f,0x7403ffb8,0x740fec1f,0x402fd81f,0xd97f26fa,0x3fa0ffe3, 0x7d40df32,0x3ff220df,0x37fe606f,0x105ffa81,0x402fb89f,0x3f620efd, 0x8803f206,0x2e1fd86f,0x8877fe3f,0x20effffe,0x7e443ff9,0x985ff10f, 0x67fec0ff,0x027fdc41,0x20fd87f9,0xdcfffffb,0x802fffff,0x40fec0fe, 0x03fb81fe,0x7ff537d4,0x407fe4f6,0x80df32fe,0xfeeffffa,0x2602efff, 0xffeeffff,0x90fea05f,0xffe8801f,0x200effdd,0x07ee03fa,0x3fa237ea, 0x3b7ffee0,0x6ffa9eff,0x7ee77fdc,0x77fdc2ff,0xf902ffdc,0xffffdfff, 0x541fe807,0x96fed45f,0x220cefe8,0x6c0ff809,0x981fd81f,0x237d405f, 0xffeeeffc,0x265fd02f,0xfdb9806f,0xffbaceff,0xffb5101e,0xfc8059df, 0xf9003f41,0x8801bfff,0x40df105f,0x982ffffc,0x20cffffe,0xffe983fa, 0xf9501eff,0xda805bff,0x02dffffe,0x3fc837cc,0x077e4000,0x07f607fc, 0x0ff407f6,0xfd70bf70,0x7403dfff,0x000df32f,0x03f91013,0x29800260, 0x188002a8,0xc9815400,0x4015c401,0x10020098,0x00180033,0x6c001310, 0x033fa01f,0x01ffb100,0x1fd81ff1,0x9f302fc8,0xd102fe40,0x25fd001b, 0x800006f9,0x00000000,0x00000000,0x00000000,0x00000000,0x05f88000, 0x055fff4c,0x03dfd510,0x07f61be6,0x0fd813f2,0x2017fee4,0x3fbaa03d, 0x7ddff32f,0x00000000,0x00000000,0x00000000,0x00000000,0x40000000, 0xfd5000fc,0xdb99bfff,0x36607fff,0x81fd84ff,0xf883eff9,0x4027ffc4, 0x3ffee02b,0x9ffff32f,0x00000000,0x00000000,0x00000000,0x00000000, 0x20000000,0xdb8003f8,0xdefffffe,0x37fea00c,0xf701fd80,0x883f20bf, 0x00000009,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x880000c4,0x04c40009,0x09880310,0x00000260,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x01880000, 0x22003100,0x40000000,0x44000001,0x21ff0000,0x000006fa,0x20620000, 0xcccccccb,0x3e00c404,0x0ff9802f,0x04c000c0,0x7c40ff50,0x29fb000f, 0x10df56fa,0x9dfffd95,0x4417e001,0x1dffffdb,0x1ceec980,0x6fffed40, 0x76441fd8,0x3ee01cef,0x21ff0001,0x5c0006fa,0xffeb882f,0x7ffe403e, 0x7fffffc5,0x19f50fff,0xf03bfffd,0x1ff3005f,0x2bfffb50,0x7ff4c0fe, 0x1ff80dff,0x6c00bf70,0x3eadf54f,0x7ffffd46,0x402ffffe,0xfff983f9, 0x04ffffef,0x3fffbff2,0xf9fff502,0x7c43fddf,0x02fffeff,0x3e0003ff, 0x000df50f,0x3e617fd4,0x0effffff,0x23efffa8,0xaaaaaff9,0x3ffbea2a, 0x7c0fffce,0x0ff9802f,0x7f67ffcc,0x3fea0fee,0x42fffddf,0x05fd04fc, 0x3c9a7ec0,0x77fd4df5,0x1ffecc0a,0xff983f90,0x3ff6a0ad,0x2a1ef983, 0x5ffc41ff,0xe87ffee0,0x3ff711df,0x20003ff0,0x00df50ff,0xd0bffea0, 0x37f545bf,0x5fa82fec,0x45dff500,0x17fc6fc8,0xf107fcc0,0x0fffb87f, 0x6c41bff1,0x21fe60ff,0x7ec007f8,0x3e2df504,0x06fc805f,0x09ff31ba, 0x7f40ffe8,0x7e45fb81,0x2a3ff705,0x84fd80ff,0xf83001ff,0x0c4df50f, 0x3ffff220,0x2603fea2,0x81fec1ff,0xff5003fc,0xff8bfa05,0x20ff9802, 0x1ff905fc,0x3e203fee,0x2e17f43f,0x27ec004f,0x1ff96fa8,0x105ff100, 0x00efd89f,0xdf527fcc,0xfe83fe20,0x75c7fe01,0x7e4df705,0xda83ffff, 0x0ff8cfff,0xfffd1df5,0xafff883d,0x817f22fe,0x817f43fe,0xdf5001fd, 0x5ff27dc0,0x6c1ff300,0x21ff102f,0x13f605fd,0x01fe8bf7,0x6faa7ec0, 0x00ffadf5,0x2fa80aa8,0x1a800ffc,0x5fd027e4,0x3fd007fc,0xeb93f600, 0x7cc2eeff,0xffeffcff,0xbdffff50,0x6fcc3fff,0x0d445fd0,0x3ff67fd0, 0x47fc6fff,0xfa83dec9,0xff97ea05,0x20ff9802,0x83fe01ff,0x10ff6008, 0x01be61ff,0xb7d53f60,0x01ff8efa,0x4c1f9000,0x3a0000ff,0x44ff603f, 0x07fa00ff,0x3e0bfe60,0x0bff881f,0x7d43ffee,0x9bf622ef,0x0017f418, 0x3fb23ff3,0x3fe25eef,0x0effffff,0x6fa817ea,0x3e600bfe,0x401ff10f, 0xff3000fe,0x3f27fb03,0x54fd8003,0x3e7beadf,0xdf00000f,0x40007fb8, 0x93f203fe,0x07fe01ff,0x817ff5c4,0x05fc81ff,0x3fea1ff9,0x7405ff02, 0x1bf6002f,0x3fea0bfa,0x6ffda8ae,0x5fb817ea,0x3e600bfe,0xf807fe0f, 0x3ff9800f,0x03febf50,0x7d53f600,0x0df7df56,0x4cccccc4,0x3f21fcc1, 0x17f40005,0x17f49f90,0xf701ff88,0x3fe01bff,0xf102fd81,0xc81bea1f, 0x00bfa04f,0x7f40ffdc,0xf505c982,0xc81bea5f,0x200bfe3f,0x0bfa0ff9, 0x7cc00ff8,0x7d7fc04f,0x29fb0005,0xf9df56fa,0x7fffe40d,0x20fdc7ff, 0x7c0005fc,0xb97ee02f,0x03ff706f,0x0fffaea6,0x07fe07fe,0x0bf50ff8, 0x5fd02fdc,0x207ff700,0xff0002fe,0x7c07feab,0x200bfe2f,0x837dc7f9, 0x3e200ffb,0xfefc805f,0x29fb0002,0xf5df56fa,0x3fff201f,0x43ec7fff, 0x740007fb,0x893f202f,0xff932eff,0x3fee003f,0x3e20ffc0,0x543fa00f, 0x81bea05f,0x7fe402fe,0x000bfa03,0xeffab7e4,0xfd17f662,0x88ff5007, 0x3fea0cff,0x017f600f,0x0007ffcc,0x2df54fd8,0x01ff8efa,0x5f89fea0, 0x1000ff98,0x3603fd81,0x7fffcc3f,0x001ffdff,0x03ff0bfe,0x87fc03ff, 0x17ee05fa,0x3f602fe8,0x017f402f,0xff56fb80,0x1dffbdff,0xfb804fd8, 0xecfffa85,0x3e00ffef,0x13fa000f,0x4ffa0330,0x3adf56fa,0x9fea003f, 0x03ff02fa,0x3fc9bee0,0x3220bf60,0x01ff3dfe,0x3fe2fe40,0xf102fd81, 0xc81bea1f,0x20bfa04f,0xe801ffd8,0x203ed82f,0xd3df55fe,0xf9019fff, 0x209fb00b,0xf8dfffe9,0x00ff100f,0x3e601fe8,0x3ea5fd07,0x3ff2df56, 0x64ff5001,0x00dfd00f,0x05fb93fa,0xff0003fe,0xfe80ff61,0x7dc0ff44, 0x2a1ff705,0x2ff881ff,0xfd10bfa0,0x0bfa001d,0x7fcc1ff2,0x00c4df52, 0xf880bfea,0xf04c403f,0x0132201f,0x7c406f98,0xf51ff80f,0x7fc5bead, 0x3fec401f,0x27fcc0dd,0xf887ff20,0x646fa80f,0x64df502d,0x87ff307f, 0xcff882fe,0x543ffea0,0x3f660eff,0x3617f406,0x3fa000ef,0x4c4ff982, 0x01bea6fd,0x502bff60,0x3e000bfd,0xd100000f,0x3bfd005f,0x7d43ff62, 0x7fd4df56,0x7fdcc1bf,0xa809f15f,0x36a21cff,0x45fc83ff,0x77dc1fe8, 0xf327fc40,0x86fd987f,0x7cc3fffd,0xffefecff,0xbbffdf50,0xfe803fff, 0x266bfea2,0x74099999,0x9fff702f,0x7d41dffd,0xffe88006,0x0effffff, 0x201ff000,0x3f200cc9,0xff5006ff,0x545fffdf,0xf98df56f,0xfffeffff, 0x007ee2ef,0x3fbffff2,0xfd104fff,0x109ffb9d,0xffd9bffd,0xd9fff70b, 0xfd103fff,0xfffb30bf,0x3ea1fd1b,0x0dfffe9c,0x3fe2fe80,0xffffffff, 0x5017f44f,0x81bffffd,0x910006fa,0x19fffffb,0x807fc000,0x3ee00ffa, 0x3ea000ef,0x7d42efff,0x9510df56,0x07bffffd,0x7ed400fb,0x401effff, 0x03dfffd8,0x3bfff6e2,0x3fffaa03,0x800800df,0x00188001,0xfff897f4, 0xffffffff,0x44017f44,0x01bea009,0x000cc400,0xf500ff80,0x0009801f, 0x00002620,0x55002620,0x00666000,0x0c0004c0,0x00066200,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x7e406fc8,0x47fe203f,0xf7001ffc,0x3fffea3f,0xffffffff,0x003ff66f, 0xffff17fa,0x59bdffff,0x7fffffc0,0xfd82deef,0x4bfe2006,0xf9804ff8, 0x013ffe27,0xff8bffd4,0x07fe2001,0x2a1dff50,0x1bea006f,0x9802ff80, 0x3ffee0ff,0xffffffff,0x401ff52f,0x3ea05fff,0x201bfa27,0x3fea3ff9, 0xffffffff,0x3fe26fff,0x2077e405,0xffffffff,0xff04ffff,0xffffffff, 0x0ffd41df,0x3e27fb80,0x3fcc01ff,0x200dfff1,0x3ff17ffd,0x00ffc400, 0x6fa8bff5,0x801bea00,0xff9802ff,0x3ffffee0,0x2fffffff,0x77cc07fe, 0x317f207f,0x6fe807ff,0x64ccccc4,0x099999ef,0xfa81ffd4,0x102ff81f, 0xff09ffb7,0x93333337,0x03ff8bff,0x7fc49fd0,0x9fe600ef,0x401ffff8, 0xff17fff8,0x0ffc4003,0xfa85ffa8,0x01bea006,0xf9802ff8,0x2666620f, 0xffe99999,0x7dc0ff60,0x5fd01feb,0x2e03ff90,0xdf7000ff,0x20ffe400, 0x5ff03ff8,0xff0dfb00,0x21ffb803,0xff8806fc,0x13fffe20,0x3fe27f98, 0x77d404fd,0x003ff17f,0x7d40ffc4,0x00df505f,0xff0037d4,0x01ff3005, 0x5c2ffc80,0xf93fb05f,0x101ff107,0x7ff10dfd,0x0037dc00,0x0bfd1bfa, 0x7d4017fc,0x200ffc0f,0x3fe23ff8,0x222fdc01,0x302ffcff,0x7d7fc4ff, 0xbfdfec06,0x22001ff8,0x2ffd41ff,0x0098df50,0x7fc00df5,0x00ff9802, 0x260ffee0,0xf37f887f,0x540df50d,0x02fec3ff,0x3001bee0,0x03ff29ff, 0xf9802ff8,0x400ffc0f,0x027ec4fe,0x1ff10bfa,0xff301dfb,0x0ff47fc4, 0x17f9ef88,0x7c4003ff,0x017fea1f,0xfffb1df5,0xa86fa87d,0x00bfe2ff, 0x4c003fe6,0x07fe05ff,0x207fcbf5,0x7fe404fc,0x8001ff70,0xfb8006fb, 0x7c01ffbf,0x85fc802f,0x7fcc01ff,0xf303fd42,0xf11ff10f,0x44ff309f, 0x504fc8ff,0x3e2ff37f,0x3fe2001f,0x5009ff51,0xffbdfdff,0x2a37d45f, 0x017fc2ff,0x44007fcc,0x1fec06ff,0x42fd8bf2,0x7f4402fe,0x8002ff8d, 0xfb0006fb,0x5ff007ff,0x0bff6660,0xffb007fe,0x3205ff01,0x50ff884f, 0x27f985ff,0x06f98ff8,0x22ff31fb,0x3e2001ff,0x00fffa9f,0x220fffa8, 0xa9bea6fd,0xcdff82ff,0xdccccccc,0xffe800ff,0x3a27dc00,0xf893ee0f, 0xeffa800f,0xdf70005f,0x1ffe2000,0x7fffffc0,0x04ffffff,0x755559ff, 0x3209ffd9,0x103ff05f,0x077ec1ff,0x87fc4ff3,0x9afc41fe,0x003ff17f, 0x7ffdffc4,0x1ffa804f,0x5bea7fa8,0xfff02ffa,0xffffffff,0xfc801fff, 0x26f9801f,0x53fcc6f8,0x7fe400bf,0xdf70000f,0x3fff2000,0xfffff803, 0x01beffff,0x3ffffffe,0x2603ffff,0x837d40ff,0x3fe20ff8,0xff89fe64, 0x2fb89f90,0x07fe2ff3,0xbffff880,0x7d402ffb,0x7d43fe07,0x3e02ffae, 0xccccccdf,0x200ffdcc,0x3e003ffb,0xff09f70f,0x8800ff21,0x2e0002ff, 0xffa8006f,0x7fc01ffd,0x017fe4c2,0x37bbbbfe,0xfe800abc,0xf881fec2, 0x997fd40f,0x4c3fe27f,0xf987ec6f,0x4003ff17,0x3f63fff8,0x81bea00f, 0xffff51ff,0x017fc05f,0xf9807fcc,0x97e4005f,0xd2fc81fd,0x2ff8003f, 0x01bee000,0x3fa9ff10,0xc817fc06,0x07fe02ff,0x897ee000,0x1ff100ff, 0xff31ffb0,0x3fd07fc4,0x17f997e2,0x7c4003ff,0x037fc43f,0x8ffc0df5, 0x0ffdfffa,0xf3005ff0,0x0dff101f,0x1fe9f500,0x007fa7d4,0x20002ff8, 0x7ec006fb,0xf813fe66,0x07ff602f,0x40000ffc,0x09f70ff8,0x7c407fc4, 0x3e27f9cf,0x7dd3f20f,0x7fc5fe62,0x07fe2001,0x7d413fea,0x7d47fe06, 0x3e0bfd1f,0x0ff9802f,0x8000ffe8,0x105f9ef8,0x000bf3df,0x5c0005ff, 0x3fee006f,0xf817fe41,0x1bfe202f,0x80000ffc,0x403fd3fd,0xff700ff8, 0x07fc4ff7,0x983fadf3,0x003ff17f,0xfc80ffc4,0x206fa82f,0x4cdf51ff, 0x02ff82ff,0x7e40ff98,0x3fa0001f,0x2ffa03fc,0x2ff8002f,0x01bee000, 0xfe81ffcc,0x402ff80f,0x1ff83ffb,0x3bf50000,0x0ff880df,0x89ffff60, 0x7d7f40ff,0xff8bfcc5,0x07fe2001,0x7d40ffe8,0x7d47fe06,0x3e07fdc6, 0x0ff9802f,0x0000ffea,0x6401fff9,0xf8000fff,0x3ee0002f,0x05fe8806, 0x3fe17fe2,0x40ffd802,0x200001ff,0x4403fcfe,0x3fe200ff,0x703fe27f, 0x7f985fff,0x33335ff1,0x7fc43333,0x517fe601,0xa8ffc0df,0x7c5fe86f, 0x0ff9802f,0x3333bff3,0x01333333,0xf301bfea,0x3fe000df,0x1bee0002, 0x7003ff60,0x02ff87ff,0x7fc5ff88,0x3ee00001,0x7fc400ff,0x13ffdc00, 0x7ff981ff,0xfff17f98,0xffffffff,0x2e00ffc4,0x81bea3ff,0x30df51ff, 0x017fc5ff,0xffb87fcc,0xffffffff,0xff104fff,0x009ff009,0x8000bfe0, 0x7fdc06fb,0x43ffb002,0xff7002ff,0x0000ffc7,0x100bff10,0xffb001ff, 0x7f407fc4,0xff17f984,0xffffffff,0x400ffc4f,0x0df51ffe,0x06fa8ffc, 0x0bfe1ff9,0x7dc3fe60,0xffffffff,0x0004ffff,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x7ffc0000, 0xffffffff,0x3ffffe0f,0x7fffffff,0x7ffffffc,0xbf900cee,0x3bbbbbb2, 0xff14eeee,0x79dfffff,0x09ff5000,0x3600dfd0,0x202fec1f,0x0cc00099, 0x00033100,0x02200033,0x80600300,0x40df5008,0x804c00ff,0x3e5755fd, 0xffffffff,0x3ffe0fff,0xffffffff,0x7ffffc7f,0x84ffffff,0xffffd5fc, 0x2bffffff,0xfffffff8,0x2000dfff,0xfe807ffd,0x41ffb806,0xffea85fd, 0x36203fff,0x300dffff,0x03dffffb,0x6fffff4c,0x7ffecc00,0x4e7d40bd, 0x19f52fff,0x261dfffb,0x7d43effe,0x7d43fe06,0x3ffffd8c,0xf5fdafec, 0x3333337f,0x9bff8333,0x99999999,0x4ccdffc1,0x44ffeba9,0x555555fc, 0x27ff7555,0x9999aff8,0x1006ffba,0xe805fbdf,0x7ffcc06f,0x3f21e5c1, 0x4fffdcef,0xecdfff98,0x77fcc1ff,0xa82fffcc,0xfffedfff,0xbbfff101, 0xfdfa8bff,0xdbf51fff,0xf5dffdbf,0x549ffdbf,0x543fe06f,0xffdefedf, 0x7ecf2e3f,0xf0005ff5,0x3fe0005f,0x90ffec01,0x97f600bf,0x3e601ff8, 0xacfb800f,0x037f406f,0x2007fffa,0x7fc81ff8,0x7e40cfe8,0x7ec27e46, 0x3067fc45,0x9fd10dfb,0xf517f441,0xffa8a3df,0x33ffe60f,0x6fa9fee0, 0x7fd43fe0,0x2037ec1e,0x0005ff4c,0x3e0005ff,0x26fd801f,0xffb805fc, 0xf007fe20,0x15fd005f,0x37f403ff,0x03fd7f90,0x3e60bd70,0x403fee0f, 0x20bf62ff,0x037e42c8,0x06fb87ff,0x17fd4bf5,0xfe81ffa8,0xf50ff886, 0xfa87fc0d,0x00ff981f,0x0017fcba,0xf80017fc,0x1ff9801f,0xff880bf9, 0x200ffc42,0x7fcc01ff,0x7ec09fb0,0x3fabf505,0xff880001,0xfd813f60, 0x002fff24,0x5fb80bfa,0xf5001fe4,0x03fea01f,0x8ffc17f2,0x43fe06fa, 0x03fe07fa,0x02ff8764,0x0002ff80,0x3fe003ff,0xfd80bf92,0x201ff884, 0x5fc807fa,0x5fc81fea,0x3fd0ff88,0xedca9800,0x3bfa0fff,0xfeeeeeee, 0x3bfffa25,0x403ff01b,0x017f46fa,0x7d40ff50,0x3e09f907,0x7c0df51f, 0x7c0df50f,0xbff8301f,0x09999999,0xaaaacff8,0x7c0aaaaa,0x27fd001f, 0x3fea05fc,0xaabff880,0x01efdcaa,0x17fc2ff8,0x2fd84fc8,0x754007fa, 0xffceffff,0x3fffffe0,0x446fffff,0x0efffffc,0xf9803fe2,0x5000ffc7, 0x837d40df,0x23ff04fc,0x1ff106fa,0x1ff81bea,0xffffff00,0xff0dffff, 0xffffffff,0x01ff83ff,0x17f2bfb0,0xff105fd8,0xffffffff,0x90ff5005, 0x513ee0df,0x801fe8bf,0x221bdffa,0x00bfe0ff,0xfffd7300,0xf500ffc1, 0x2002fe8b,0x1bea06fa,0x1ff827e4,0x3fe60df5,0x7fc0df50,0x3fe57501, 0xeeeeeeee,0xeeeeff85,0x41eeeeee,0xbfb001ff,0x7fc417f2,0xdddff101, 0x09fffddd,0xff984fd8,0x3e23fb81,0x400ff40f,0x1ff304fe,0x20102ff4, 0x745ff300,0xb13ee02f,0xa866c07f,0x41bea06f,0x23ff04fc,0x1ff707f9, 0x1ff81bea,0x0bfebfb0,0x000bfe00,0xfe800ffc,0x3ee0bf94,0x807fe206, 0xff104ffa,0xff555559,0x7f47f509,0x65c1fe81,0x7dc0bfe3,0x403ff21f, 0x407fe4fe,0x817f23fe,0x837dc2fe,0x81bea7fa,0x09f906fa,0x1ffc47fe, 0x7d43ffea,0x65c7fe06,0x0bfebfb3,0x000bfe00,0xff800ffc,0x3fa0bf93, 0x007fe203,0x3fee0ff7,0xffffffff,0xfb97d40f,0xffaaaaae,0x6cbfb1ac, 0x1fffa85f,0xf9077fe2,0x4c0efb8d,0x33fe20ff,0x103bf660,0x7f4419ff, 0xfa81bea4,0x3e09f906,0x33bff21f,0xf50fedfe,0xfd8ffc0d,0x0005ff05, 0x3e0005ff,0x1ff9801f,0x1ff30bf9,0x200ffc40,0xdfe81ff8,0xfccccccc, 0xfc97cc3f,0xffffffff,0x4cbfb5ff,0xdfecbeff,0x7ffd42fe,0xe81fffcd, 0x4ffecdff,0xfddfffb8,0xfff500ef,0xfa8dffbb,0x641bea06,0xb83ff04f, 0x1fd4ffff,0x1ff81bea,0x0bfe0bfb,0x000bfe00,0x7f400ffc,0x3f217f26, 0x00ffc405,0xff307fe6,0x446fd801,0xddddd70c,0x49ddffdd,0x7fffdc4c, 0xb10bf92f,0x2039dfff,0x2effffd9,0x3bfffa60,0x7ff4c00c,0x37d40cff, 0x3f20df50,0x2203ff04,0xf037d400,0x0bfe003f,0x000bfe00,0x3ee00ffc, 0x3617f22f,0x0ffc404f,0x3f21ff20,0x01ff9805,0x3a07fa00,0x00013302, 0x99880026,0x0004c000,0x00000198,0x00000000,0x05ff0000,0x3337ff00, 0x13333333,0x4cccdffc,0x645ffda9,0x402fe85f,0x9999aff8,0xf84ffc99, 0x49fd002f,0x3fd003cb,0x00000ec8,0x00000000,0x00000000,0x00000000, 0x3fe00000,0xffff8002,0xffffffff,0x3ffffe2f,0x84ffffff,0x01ff85fc, 0x7fffffc4,0xa85fffff,0x3fee007f,0x3a00bfb0,0x00000c1f,0x00000000, 0x00000000,0x00000000,0x7fc00000,0xffff8002,0xffffffff,0x3ffffe2f, 0x901ceeff,0x807f98bf,0xfffffff8,0x9fb01def,0xd9ffc400,0x03fd005f, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x4427fc40,0x000ee4fe,0xff981bee,0xff307fb0,0x640bf505,0x7fffc01e, 0x04ffffff,0x1300e440,0x65404c00,0xcccccccc,0x369fd0cc,0x0449fb4f, 0x88166e54,0x99999912,0x33333265,0xcccccccc,0x0000000c,0x00000000, 0x3f60ffd4,0x0067fe46,0xf900ff88,0x7dc2fdc9,0x203fc84f,0x777402fd, 0x3ffeeeee,0x03ffb500,0x7c003fea,0xfffffc84,0xd1ffffff,0x7ed3fa9f, 0x7e43ff75,0x99cfffff,0xffff13eb,0x3ffea7ff,0xffffffff,0x00000fff, 0x00000000,0x2a6fd800,0x7fecc1ff,0x3fd802df,0x3fc43fd0,0x7fc37fec, 0x000bf600,0x2202ff44,0x00cfffeb,0xf0c07ffb,0x5554c227,0xaaaaaaaa, 0x53fa9fd0,0xe97f25fd,0xffffecdf,0x99913fff,0x00005999,0x00000000, 0x20000000,0x3ff8cff8,0x3bfff220,0x30df500b,0xf83fd0df,0x1be60fee, 0x20005fb0,0x3f2606fd,0x7cc02eff,0x2fbe07fe,0x0004fcce,0xb3fd9ff4, 0x1b1fd89f,0x3fffeb88,0x00000000,0x00000000,0xf9800000,0x2a005fef, 0xf81cfffe,0x641fe41f,0x3f73e64f,0xfb00ff22,0x1df90005,0x39fffd50, 0x3f2bf200,0xfffdb882,0x640002ce,0x3ee5f92f,0x8800d443,0x00000000, 0x00000000,0x40000000,0x8000effc,0x641fffc9,0x4c07fc4f,0x3eebee6f, 0xeeb83fa4,0xeeeeffee,0x07fee01e,0x002fbff2,0x0df37f88,0x4c41ffc8, 0x99999999,0x7d47ee19,0x00003f51,0x00000000,0x00000000,0x30000000, 0x54000bff,0x3fcc1ffd,0x87fc0bf5,0xf16f88fe,0xfffffc8d,0x01ffffff, 0x3f205ff5,0x7dc000cf,0x7dc07fa4,0x3ff21fda,0xffffffff,0x1144511f, 0x00000015,0x00000000,0x00000000,0xffd00000,0x75c4007f,0x5fd03eff, 0xafc80bf6,0x2e3fa6f8,0x4cccc44f,0x01999bfd,0x64407ff3,0xf002dfff, 0xe82fd41f,0x775c9f15,0xeeeeeeee,0x0000001e,0x00000000,0x00000000, 0x40000000,0x01ffaefc,0x16fffe4c,0x3fe33ee0,0x3eb7ea00,0x07f6bf24, 0x2200bf60,0xd71004ff,0x2a017dff,0x100ff85f,0x00000004,0x00000000, 0x00000000,0x00000000,0x23ff5000,0xffd506fc,0x3e20039f,0xff804fbf, 0x3f7ea1fc,0x805fb007,0x50005fe8,0xe83bfffb,0x004fc82f,0x00000000, 0x00000000,0x00000000,0x00000000,0xf88ffe20,0x5f7fe44f,0xfffd8000, 0x47ffd801,0xb004fff8,0x06fe805f,0xfffc9800,0x32209911,0x00000004, 0x00000000,0x00000000,0x00000000,0x1bf60000,0x2dc87fea,0x37fd4000, 0xe85ffb80,0x5fb001ff,0x7777fdc0,0x005eeeee,0x00007ae2,0x00000000, 0x00000000,0x00000000,0x00000000,0x80ffdc00,0x00010efd,0x8801ffc0, 0x07fc83ff,0x7ffdc000,0x7fffffff,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000, }; static signed short stb__arial_28_usascii_x[95]={ 0,2,1,0,0,1,1,1,1,1,0,1,2,0, 2,0,1,2,0,1,0,1,0,1,1,1,2,2,1,1,1,1,1,-1,1,1,1,1,2,1,2,2,0,1, 1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,1,0,0,0,-1,1,0,1,0,0,0,0,0,1,1, -2,1,1,1,1,0,1,0,1,0,0,1,0,0,0,0,0,0,2,0,1, }; static signed short stb__arial_28_usascii_y[95]={ 22,4,4,3,2,3,3,4,3,3,3,7,19,14, 19,3,3,3,3,3,4,4,3,4,3,3,9,9,7,9,7,3,3,4,4,3,4,4,4,3,4,4,4,4, 4,4,4,3,4,3,4,3,4,4,4,4,4,4,4,4,3,4,3,25,3,8,4,8,4,8,3,8,4,4, 4,4,4,8,8,8,8,8,8,8,4,9,9,9,9,9,9,3,3,3,11, }; static unsigned short stb__arial_28_usascii_w[95]={ 0,3,7,14,13,20,16,3,7,7,9,13,3,8, 3,7,12,8,13,12,13,12,13,12,12,12,3,3,13,13,13,12,24,18,15,17,16,15,13,17,15,3,11,16, 13,18,16,18,15,18,17,15,15,16,17,24,17,17,15,6,7,6,12,16,5,13,12,13,13,13,8,13,12,3, 6,12,3,19,12,14,12,13,8,12,7,12,13,18,13,13,12,8,3,8,13, }; static unsigned short stb__arial_28_usascii_h[95]={ 0,18,7,20,23,20,20,7,25,25,9,13,7,3, 3,20,20,19,19,20,18,19,20,18,20,20,13,17,13,8,13,19,25,18,18,20,18,18,18,20,18,18,19,18, 18,18,18,20,18,21,18,20,18,19,18,18,18,18,18,23,20,23,11,2,5,15,19,15,19,15,19,20,18,18, 24,18,18,14,14,15,19,19,14,15,19,14,13,13,13,19,13,25,25,25,5, }; static unsigned short stb__arial_28_usascii_s[95]={ 254,100,144,137,71,174,195,140,56,1,116, 62,251,172,251,19,45,120,129,72,104,152,152,52,212,225,247,118,89,126,15, 209,9,81,65,27,31,15,1,1,223,48,236,180,166,147,130,118,96,99,78, 238,44,178,112,1,60,26,239,92,166,85,103,181,152,122,107,178,93,136,143, 58,197,248,64,210,252,201,234,163,165,195,192,150,85,221,29,43,1,222,76, 47,43,34,158, }; static unsigned short stb__arial_28_usascii_t[95]={ 1,67,86,1,1,1,1,86,1,1,86, 86,67,86,75,27,27,27,27,27,67,27,1,67,1,1,67,67,86,86,86, 27,1,67,67,27,67,67,67,27,48,67,27,48,48,48,48,1,48,1,48, 1,48,27,48,48,48,48,48,1,1,1,86,86,86,67,27,67,27,67,27, 27,48,27,1,48,27,67,67,67,27,27,67,67,27,67,86,86,86,27,86, 1,1,1,86, }; static unsigned short stb__arial_28_usascii_a[95]={ 111,111,142,223,223,357,267,77, 134,134,156,234,111,134,111,111,223,223,223,223,223,223,223,223, 223,223,111,111,234,234,234,223,407,267,267,290,290,267,245,312, 290,111,201,267,223,334,290,312,267,312,290,267,245,290,267,378, 267,267,245,111,111,111,188,223,134,223,223,201,223,223,111,223, 223,89,89,201,89,334,223,223,223,223,134,201,111,223,201,290, 201,201,201,134,104,134,234, }; // Call this function with // font: NULL or array length // data: NULL or specified size // height: STB_FONT_arial_28_usascii_BITMAP_HEIGHT or STB_FONT_arial_28_usascii_BITMAP_HEIGHT_POW2 // return value: spacing between lines static void stb_font_arial_28_usascii(stb_fontchar font[STB_FONT_arial_28_usascii_NUM_CHARS], unsigned char data[STB_FONT_arial_28_usascii_BITMAP_HEIGHT][STB_FONT_arial_28_usascii_BITMAP_WIDTH], int height) { int i,j; if (data != 0) { unsigned int *bits = stb__arial_28_usascii_pixels; unsigned int bitpack = *bits++, numbits = 32; for (i=0; i < STB_FONT_arial_28_usascii_BITMAP_WIDTH*height; ++i) data[0][i] = 0; // zero entire bitmap for (j=1; j < STB_FONT_arial_28_usascii_BITMAP_HEIGHT-1; ++j) { for (i=1; i < STB_FONT_arial_28_usascii_BITMAP_WIDTH-1; ++i) { unsigned int value; if (numbits==0) bitpack = *bits++, numbits=32; value = bitpack & 1; bitpack >>= 1, --numbits; if (value) { if (numbits < 3) bitpack = *bits++, numbits = 32; data[j][i] = (bitpack & 7) * 0x20 + 0x1f; bitpack >>= 3, numbits -= 3; } else { data[j][i] = 0; } } } } // build font description if (font != 0) { float recip_width = 1.0f / STB_FONT_arial_28_usascii_BITMAP_WIDTH; float recip_height = 1.0f / height; for (i=0; i < STB_FONT_arial_28_usascii_NUM_CHARS; ++i) { // pad characters so they bilerp from empty space around each character font[i].s0 = (stb__arial_28_usascii_s[i]) * recip_width; font[i].t0 = (stb__arial_28_usascii_t[i]) * recip_height; font[i].s1 = (stb__arial_28_usascii_s[i] + stb__arial_28_usascii_w[i]) * recip_width; font[i].t1 = (stb__arial_28_usascii_t[i] + stb__arial_28_usascii_h[i]) * recip_height; font[i].x0 = stb__arial_28_usascii_x[i]; font[i].y0 = stb__arial_28_usascii_y[i]; font[i].x1 = stb__arial_28_usascii_x[i] + stb__arial_28_usascii_w[i]; font[i].y1 = stb__arial_28_usascii_y[i] + stb__arial_28_usascii_h[i]; font[i].advance_int = (stb__arial_28_usascii_a[i]+8)>>4; font[i].s0f = (stb__arial_28_usascii_s[i] - 0.5f) * recip_width; font[i].t0f = (stb__arial_28_usascii_t[i] - 0.5f) * recip_height; font[i].s1f = (stb__arial_28_usascii_s[i] + stb__arial_28_usascii_w[i] + 0.5f) * recip_width; font[i].t1f = (stb__arial_28_usascii_t[i] + stb__arial_28_usascii_h[i] + 0.5f) * recip_height; font[i].x0f = stb__arial_28_usascii_x[i] - 0.5f; font[i].y0f = stb__arial_28_usascii_y[i] - 0.5f; font[i].x1f = stb__arial_28_usascii_x[i] + stb__arial_28_usascii_w[i] + 0.5f; font[i].y1f = stb__arial_28_usascii_y[i] + stb__arial_28_usascii_h[i] + 0.5f; font[i].advance = stb__arial_28_usascii_a[i]/16.0f; } } } #ifndef STB_SOMEFONT_CREATE #define STB_SOMEFONT_CREATE stb_font_arial_28_usascii #define STB_SOMEFONT_BITMAP_WIDTH STB_FONT_arial_28_usascii_BITMAP_WIDTH #define STB_SOMEFONT_BITMAP_HEIGHT STB_FONT_arial_28_usascii_BITMAP_HEIGHT #define STB_SOMEFONT_BITMAP_HEIGHT_POW2 STB_FONT_arial_28_usascii_BITMAP_HEIGHT_POW2 #define STB_SOMEFONT_FIRST_CHAR STB_FONT_arial_28_usascii_FIRST_CHAR #define STB_SOMEFONT_NUM_CHARS STB_FONT_arial_28_usascii_NUM_CHARS #define STB_SOMEFONT_LINE_SPACING STB_FONT_arial_28_usascii_LINE_SPACING #endif
62.979381
117
0.775184
stetre
895c5c10f933e68ab004370d0a2fe8c883377acd
9,991
cpp
C++
extern/nbclient/src/NBEventHeaders.cpp
jychoi-hpc/pviz3
d55c84a45df0a5bf30ecb832b370e03f0c7ab4c1
[ "xpp" ]
null
null
null
extern/nbclient/src/NBEventHeaders.cpp
jychoi-hpc/pviz3
d55c84a45df0a5bf30ecb832b370e03f0c7ab4c1
[ "xpp" ]
null
null
null
extern/nbclient/src/NBEventHeaders.cpp
jychoi-hpc/pviz3
d55c84a45df0a5bf30ecb832b370e03f0c7ab4c1
[ "xpp" ]
null
null
null
/*************************************************************************** * Copyright:http://www.naradabrokering.org/index.html * Author: Jaliya Ekanayake * Email : jaliyae@gmail.com ****************************************************************************/ #ifdef WIN32 #include "StdAfx.h" #endif #include <string> #include <sstream> #include <iostream> #include "constants.h" #include "NBEventHeaders.h" #include "ServiceException.h" #include "Utils.h" using namespace std; NBEventHeaders::NBEventHeaders() { } NBEventHeaders::~NBEventHeaders() { } void NBEventHeaders::init() { containsTemplateId =false; containsTimestamp=false; containsSource =false; supressDistributionToSource=false; containsEventId=false; correlated=false; containsTimeToLive=false; secure=false; containsIntegrity=false; fragmented=false; sliced=false; containsPriorityInfo=false; containsApplicationInfo=false; persistent=false; transient=false; compressed=false; containsAssertions=false; templateId=0 ; timestamp=0; source=0; timeToLive=0; priority=0; snapshot=0; numOfHeaders=0; } NBEventHeaders::NBEventHeaders(char *) { } /** ********************************************************************** */ /** Implementation of methods in the Event Headers interface */ /** ********************************************************************** */ /** Indicates the templateId which this event conforms to */ int NBEventHeaders::getTemplateId() { return this->templateId; } void NBEventHeaders::setTemplateId(int templateId) { this->containsTemplateId=true; this->templateId=templateId; } /** * Returns the timestamp for this event. This timestamp corresponds to the * value assigned by the time service */ long long NBEventHeaders::getTimeStamp() { return this->timestamp; } void NBEventHeaders::setTimeStamp(long long timestamp) { this->timestamp=timestamp; this->containsTimestamp=true; } /** Returns the generator of this message */ int NBEventHeaders::getSource() { return this->source; } /** * Indicates that the message should not be rerouted to it source, that is * contained in the event headers */ bool NBEventHeaders::setSupressDistributionToSource() { return this->supressDistributionToSource; } void NBEventHeaders::setSourceInformation(int source,bool supressDistributionToSource) { this->source=source; this->containsSource=true; this->supressDistributionToSource=supressDistributionToSource; } /** Indicates if there is an event id associated with this message */ bool NBEventHeaders::hasEventId() { return this->containsEventId; } /** Get the event identifier */ NBEventID* NBEventHeaders::getEventId() { return this->eventId; } void NBEventHeaders::setEventId(NBEventID * eventId) { this->eventId=eventId; this->containsEventId=true; } /** * Indicates if this event is correlated with any other event. Casual * constraints may entail that the correlated event be delivered prior to the * delivery of this event. */ bool NBEventHeaders::isCorrelated() { return this->correlated; } /** Returns the correlation identifier associated with the event */ NBEventID* NBEventHeaders::getCorrelationIdentifier() { return this->correlationId; } void NBEventHeaders::setCorrelationId(NBEventID *correlationId) { this->correlationId=correlationId; this->correlated=true; } bool NBEventHeaders::hasTimeToLive(){ return this->containsTimeToLive; } /** Returns the time to live */ int NBEventHeaders::getTimeToLive() { return this->timeToLive; } void NBEventHeaders::setTimeToLive(int timeToLive) { this->timeToLive=timeToLive; this->containsTimeToLive=true; } /** Indicates if this event is a secure event */ bool NBEventHeaders::isSecure() { return this->secure; } /** Indicates if the event has integerity check information. */ bool NBEventHeaders::hasIntegrity() { return this->containsIntegrity; } /** Indicates if this event is a fragment of a larger event */ bool NBEventHeaders::isFragmented() { return this->fragmented; } /* * Indicates if this is an event slice which contains a part of the orginal * transmitted payload. These are specifically used in cases where the device * might not prefer the retransmission of the entire event */ bool NBEventHeaders::isSliced() { return this->sliced; } /** Indicates if this event includes priority information */ bool NBEventHeaders::hasPriorityInfo() { return this->containsPriorityInfo; } /** Gets the priority associated with this event */ int NBEventHeaders::getPriority() { return this->priority; } void NBEventHeaders::setPriorityInformation(int priority) { this->priority=priority; } bool NBEventHeaders::hasApplicationInfo() { return this->containsApplicationInfo; } /** Gets the application type associated with this event */ char * NBEventHeaders::getApplicationType() { return this->application; } /** * Indicates if the event is a persistent one. If it is, the event needs to * be archived on storage. It is of course assumed that the event corresponds * to a template that supports reliable delivery */ bool NBEventHeaders::isPersistent() { return this->persistent; } void NBEventHeaders::setPersistent() { this->persistent=true; } /** * Indicates if this event is a transient event. If this is a transient event * it need not be archived on any storage */ bool NBEventHeaders::isTransient() { return this->transient; } /** * Indicates if the payload has been compressed. Such events are specifically * used in cases where the device's network utilization costs might be at a * premium. */ bool NBEventHeaders::isCompressed() { return this->compressed; } /** Generate the serialized representation of the event headers */ void NBEventHeaders::getBytes(char *buff,int * length) { long long offset=0; snapshot = createHeaderSnapshot(); //cout<<"Snapshot ==== "<<snapshot<<endl; Utils::writeInt(buff+offset,snapshot,offset); //offset+=4; if (containsTemplateId) { // cout<<"Template ID = "<<templateId<<endl; Utils::writeInt(buff+offset,templateId,offset); //offset+=4; } if (containsTimestamp) { // cout<<"TimeStamp = "<<timestamp<<endl; Utils::writeLong(buff+offset,timestamp,offset); //offset+=8; } if (containsSource) { // cout<<"Source = "<<source<<endl; Utils::writeInt(buff+offset,source,offset); //offset+=4; } if (containsEventId) { int len; char temp[32]; eventId->getBytes(temp,&len); // cout<<"Length of Event ID = "<<len<<endl; Utils::writeInt(buff+offset,len,offset); // offset+=4; Utils::writeBytes(buff+offset,temp,len,offset); //offset+=len; } //cout<<"Coming to this point" <<endl; if (correlated) { int len; correlationId->getBytes(buff+offset,&len); // cout<<"Length of Correlation ID = "<<len<<endl; offset+=len; } if (containsTimeToLive) { // cout<<"containsTimeToLive = "<<timeToLive<<endl; Utils::writeInt(buff+offset,timeToLive,offset); //offset+=4; } if (secure) { throw ServiceException("Security is not supported "); } if (containsIntegrity) { throw ServiceException("Integrity checking is not supported "); } if (fragmented) { throw ServiceException("Fragmenting is not supported "); } //By default this is false. We don't support it yet. /* if (hasTotalNumOfFragmentsInfo) { } */ if (containsPriorityInfo) { // cout<<"contains Priority = "<<priority<<endl; Utils::writeInt(buff+offset,priority,offset); //offset+=4; } //By default this is false. We don't support it yet. /* if (containsApplicationInfo) { } */ //By default this is false. We don't support it yet. /* if (compressed) { } */ //ss>>str; //strncat(buff,str.c_str(),str.length()); (*length)=offset; } /** Creates a snapshot of the headers contained in the event headers */ int NBEventHeaders::createHeaderSnapshot() { snapshot = 0; numOfHeaders = 0; snapshot = updateSnapshot(snapshot, false); //Default Value snapshot = updateSnapshot(snapshot, compressed); snapshot = updateSnapshot(snapshot, persistent); snapshot = updateSnapshot(snapshot, containsApplicationInfo); snapshot = updateSnapshot(snapshot, containsPriorityInfo); snapshot = updateSnapshot(snapshot, false);//Default Value snapshot = updateSnapshot(snapshot, false);//Default Value snapshot = updateSnapshot(snapshot, fragmented); snapshot = updateSnapshot(snapshot, containsIntegrity); snapshot = updateSnapshot(snapshot, secure); snapshot = updateSnapshot(snapshot, containsTimeToLive); snapshot = updateSnapshot(snapshot, correlated); snapshot = updateSnapshot(snapshot, containsEventId); snapshot = updateSnapshot(snapshot, supressDistributionToSource); snapshot = updateSnapshot(snapshot, containsSource); snapshot = updateSnapshot(snapshot, containsTimestamp); snapshot = updateSnapshot(snapshot, containsTemplateId); return snapshot; } int NBEventHeaders::updateSnapshot(int snapshot, bool subHeader) { int orWith = 1; /** * If the widget's value is true, we need to first update the snapshot to * contain the subHeader's trace */ if (subHeader) { snapshot |= orWith; } snapshot = snapshot << 1; numOfHeaders++; if (numOfHeaders == MAX_NUM_HEADERS) { throw ServiceException("Num of headers exceeded the maximum "); } return snapshot; }
22.8627
81
0.660695
jychoi-hpc
895cbed539482619f455397ed672789054adedaf
1,801
cpp
C++
ext/types/offer.cpp
Atidot/hs-mesos
7449a31550259a231c4809d9a6fcc626892502b3
[ "MIT" ]
null
null
null
ext/types/offer.cpp
Atidot/hs-mesos
7449a31550259a231c4809d9a6fcc626892502b3
[ "MIT" ]
null
null
null
ext/types/offer.cpp
Atidot/hs-mesos
7449a31550259a231c4809d9a6fcc626892502b3
[ "MIT" ]
null
null
null
#include <iostream> #include "types.h" using namespace mesos; OfferPtr toOffer(OfferIDPtr offerID, FrameworkIDPtr frameworkID, SlaveIDPtr slaveID, char* hostname, int hostnameLen, ResourcePtr* resources, int resourcesLen, AttributePtr* attributes, int attributesLen, ExecutorIDPtr* executorIDs, int idsLen) { OfferPtr offer = new Offer(); *offer->mutable_id() = *offerID; *offer->mutable_framework_id() = *frameworkID; *offer->mutable_slave_id() = *slaveID; offer->set_hostname(hostname, hostnameLen); for (int i = 0; i < resourcesLen; ++i) *offer->add_resources() = *resources[i]; for (int i = 0; i < attributesLen; ++i) *offer->add_attributes() = *attributes[i]; for (int i = 0; i < idsLen; ++i) *offer->add_executor_ids() = *executorIDs[i]; return offer; } void fromOffer(OfferPtr offer, OfferIDPtr* offerID, FrameworkIDPtr* frameworkID, SlaveIDPtr* slaveID, char** hostname, int* hostnameLen, ResourcePtr** resources, int* resourcesLen, AttributePtr** attributes, int* attributesLen, ExecutorIDPtr** executorIDs, int* idsLen) { *offerID = offer->mutable_id(); *frameworkID = offer->mutable_framework_id(); *slaveID = offer->mutable_slave_id(); *hostname = (char*) offer->mutable_hostname()->data(); *hostnameLen = offer->mutable_hostname()->size(); *resources = offer->mutable_resources()->mutable_data(); *resourcesLen = offer->resources_size(); *attributes = offer->mutable_attributes()->mutable_data(); *attributesLen = offer->attributes_size(); *executorIDs = offer->mutable_executor_ids()->mutable_data(); *idsLen = offer->executor_ids_size(); } void destroyOffer(OfferPtr offer) { delete offer; }
22.5125
63
0.667962
Atidot
89678386c71f9f7c8a1dead073b46d650133a148
582
cpp
C++
hw4/src/lib/sema/ContextManager.cpp
idoleat/P-Language-Compiler-CourseProject
57db735b349a0a3a30d78b927953e2d44b7c7d53
[ "MIT" ]
7
2020-09-10T16:54:49.000Z
2022-03-15T12:39:23.000Z
hw4/src/lib/sema/ContextManager.cpp
idoleat/simple-P-compiler
57db735b349a0a3a30d78b927953e2d44b7c7d53
[ "MIT" ]
null
null
null
hw4/src/lib/sema/ContextManager.cpp
idoleat/simple-P-compiler
57db735b349a0a3a30d78b927953e2d44b7c7d53
[ "MIT" ]
null
null
null
#include "sema/SemanticAnalyzer.hpp" std::string SemanticAnalyzer::ContextManager::TrimDimension(const char* typeString, int amount, bool TrimWhiteSpace){ std::string type = std::string(typeString); std::size_t left, right; while(amount != 0){ left = type.find_first_of("["); right = type.find_first_of("]"); type.erase(type.begin() + left, type.begin() + right+1); amount -= 1; } if(TrimWhiteSpace){ while(type.find(" ") != std::string::npos){ type.erase(type.find(" ")); } } return type; }
29.1
117
0.594502
idoleat
8967bedf82ef7802f2c640389d5bcc1ffdc0b67b
1,198
cpp
C++
Source/10.0.18362.0/ucrt/string/strtok.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
2
2021-01-27T10:19:30.000Z
2021-02-09T06:24:30.000Z
Source/10.0.18362.0/ucrt/string/strtok.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
null
null
null
Source/10.0.18362.0/ucrt/string/strtok.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
1
2021-01-27T10:19:36.000Z
2021-01-27T10:19:36.000Z
// // strtok.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. // // Defines strtok(), which tokenizes a string via repeated calls. // // strtok() considers the string to consist of a sequence of zero or more text // tokens separated by spans of one or more control characters. The first call, // with a string specified, returns a pointer to the first character of the // first token, and will write a null character into the string immediately // following the returned token. Subsequent calls with a null string argument // will work through the string until no tokens remain. The control string // may be different from call to call. When no tokens remain in the string, a // null pointer is returned. // #include <corecrt_internal.h> #include <string.h> extern "C" char* __cdecl __acrt_strtok_s_novalidation( _Inout_opt_z_ char* string, _In_z_ char const* control, _Inout_ _Deref_prepost_opt_z_ char** context ); extern "C" char* __cdecl strtok(char* const string, char const* const control) { return __acrt_strtok_s_novalidation(string, control, &__acrt_getptd()->_strtok_token); }
35.235294
90
0.708681
825126369
89695dcb97261b08d68dac2c77b378c7da782414
145
cpp
C++
src/Redox.cpp
adityaatluri/Redox
d4e0c6fdc2fa676c038d2386c5c11766af576c07
[ "MIT" ]
null
null
null
src/Redox.cpp
adityaatluri/Redox
d4e0c6fdc2fa676c038d2386c5c11766af576c07
[ "MIT" ]
null
null
null
src/Redox.cpp
adityaatluri/Redox
d4e0c6fdc2fa676c038d2386c5c11766af576c07
[ "MIT" ]
null
null
null
// // Copyright 2018 - present @adityaatluri // #include "Redox/Redox.hpp" #include "Redox/IR.hpp" namespace Redox { } // end namespace Redox
13.181818
41
0.689655
adityaatluri
896a4c73f95f68c47644475ea4886e136439e6b8
1,225
hpp
C++
CRTPFactory/src/AddToRegistry.hpp
DLancer999/FactoryImplementation
a87b595cac1b2c082a39113b5a6cfbc2548bd8ff
[ "MIT" ]
null
null
null
CRTPFactory/src/AddToRegistry.hpp
DLancer999/FactoryImplementation
a87b595cac1b2c082a39113b5a6cfbc2548bd8ff
[ "MIT" ]
null
null
null
CRTPFactory/src/AddToRegistry.hpp
DLancer999/FactoryImplementation
a87b595cac1b2c082a39113b5a6cfbc2548bd8ff
[ "MIT" ]
null
null
null
/*************************************************************************\ License Copyright (c) 2018 Kavvadias Ioannis. This file is part of FactoryImplementation. Licensed under the MIT License. See LICENSE file in the project root for full license information. Class AddToRegistry Description Dummy class to create runTimeSelection tables at global initialization stage \************************************************************************/ #ifndef ADDTOREGISTRY_H #define ADDTOREGISTRY_H //ADDED class has to inherit from PolymorphicInheritance and from HASREGISTRY //HASREGISTRY class has to inherit from PolymorphicBase template <class ADDED, class HASREGISTRY> class AddToRegistry { using ObjectCreator = typename HASREGISTRY::ObjectCreator; public: AddToRegistry() { //track additions std::cout<<"Adding \"" <<ADDED::name <<"\" to RuntimeSelectionTable of " <<HASREGISTRY::name<<'\n'; //needed to define which polymorphicCreate instantiation we need ObjectCreator createFunc = ADDED::polymorphicCreate; //actual addition HASREGISTRY::registry()[ADDED::name] = createFunc; } }; #endif
27.840909
80
0.621224
DLancer999
89702dfc51ba464bc6da15cd2b8a948f21927687
4,454
cc
C++
krypton/crypto/rsa_fdh_blinder_test.cc
Condum/vpn-libraries
aa741f31c98f25e81e76fb5306c30233dd872598
[ "Apache-2.0" ]
163
2020-10-29T21:24:42.000Z
2022-03-28T15:42:24.000Z
krypton/crypto/rsa_fdh_blinder_test.cc
0xgpapad/vpn-libraries
aa741f31c98f25e81e76fb5306c30233dd872598
[ "Apache-2.0" ]
4
2021-02-13T20:14:53.000Z
2022-03-08T03:18:06.000Z
krypton/crypto/rsa_fdh_blinder_test.cc
0xgpapad/vpn-libraries
aa741f31c98f25e81e76fb5306c30233dd872598
[ "Apache-2.0" ]
25
2020-11-10T18:06:04.000Z
2022-03-08T03:11:32.000Z
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the ); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "privacy/net/krypton/crypto/rsa_fdh_blinder.h" #include <cstdio> #include <ostream> #include <vector> #include "testing/base/public/gmock.h" #include "testing/base/public/gunit.h" #include "third_party/absl/cleanup/cleanup.h" #include "third_party/absl/memory/memory.h" #include "third_party/openssl/base.h" #include "third_party/openssl/bio.h" #include "third_party/openssl/bn.h" #include "third_party/tink/cc/subtle/subtle_util_boringssl.h" namespace privacy { namespace krypton { namespace crypto { namespace { using ::testing::status::IsOk; using ::testing::status::StatusIs; } // namespace class RsaFdhBlinderTest : public ::testing::Test { public: RsaFdhBlinderTest() : bn_ctx_(BN_CTX_new()) { BN_CTX_start(bn_ctx_.get()); rsa_f4_ = BN_CTX_get(bn_ctx_.get()); EXPECT_TRUE(BN_set_u64(rsa_f4_, RSA_F4)); EXPECT_THAT(::crypto::tink::subtle::SubtleUtilBoringSSL::GetNewRsaKeyPair( 2048, rsa_f4_, &private_key_, &public_key_), IsOk()); BN_CTX_end(bn_ctx_.get()); } protected: void SetUp() override { // The RSA modulus and exponent are checked as part of the conversion to // bssl::UniquePtr<RSA>. ASSERT_OK_AND_ASSIGN(rsa_public_key_, ::crypto::tink::subtle::SubtleUtilBoringSSL:: BoringSslRsaFromRsaPublicKey(public_key_)); ASSERT_OK_AND_ASSIGN(rsa_private_key_, ::crypto::tink::subtle::SubtleUtilBoringSSL:: BoringSslRsaFromRsaPrivateKey(private_key_)); } bssl::UniquePtr<RSA> public_key_copy() const { bssl::UniquePtr<RSA> public_key_copy( RSAPublicKey_dup(rsa_public_key_.get())); EXPECT_THAT(public_key_copy.get(), testing::NotNull()); return public_key_copy; } bssl::UniquePtr<BN_CTX> bn_ctx_; BIGNUM* rsa_f4_; ::crypto::tink::subtle::SubtleUtilBoringSSL::RsaPrivateKey private_key_; ::crypto::tink::subtle::SubtleUtilBoringSSL::RsaPublicKey public_key_; private: // Initialized after SetUp bssl::UniquePtr<RSA> rsa_public_key_; bssl::UniquePtr<RSA> rsa_private_key_; }; TEST_F(RsaFdhBlinderTest, E2eWorks) { ASSERT_OK_AND_ASSIGN(auto verifier, RsaFdhVerifier::New(public_key_)); ASSERT_OK_AND_ASSIGN(auto signer, RsaFdhBlindSigner::New(private_key_)); const absl::string_view message = "Hello World!"; ASSERT_OK_AND_ASSIGN( auto blinded, RsaFdhBlinder::Blind(message, public_key_copy(), bn_ctx_.get())); ASSERT_OK_AND_ASSIGN(std::string blinded_signature, signer->Sign(blinded->blind())); ASSERT_OK_AND_ASSIGN(std::string signature, blinded->Unblind(blinded_signature, bn_ctx_.get())); ASSERT_OK(verifier->Verify(message, signature, bn_ctx_.get())); } TEST_F(RsaFdhBlinderTest, InvalidSignature) { ASSERT_OK_AND_ASSIGN(auto verifier, RsaFdhVerifier::New(public_key_)); ASSERT_OK_AND_ASSIGN(auto signer, RsaFdhBlindSigner::New(private_key_)); const absl::string_view message = "Hello World!"; ASSERT_OK_AND_ASSIGN( auto blinded, RsaFdhBlinder::Blind(message, public_key_copy(), bn_ctx_.get())); ASSERT_OK_AND_ASSIGN(std::string blinded_signature, signer->Sign(blinded->blind())); ASSERT_OK_AND_ASSIGN(std::string signature, blinded->Unblind(blinded_signature, bn_ctx_.get())); ASSERT_OK(verifier->Verify(message, signature, bn_ctx_.get())); // Invalidate the signature by zeroing the last 10 bytes. for (int i = 0; i < 10; i++) signature.pop_back(); for (int i = 0; i < 10; i++) signature.push_back(0); EXPECT_THAT(verifier->Verify(message, signature, bn_ctx_.get()), StatusIs(absl::StatusCode::kInvalidArgument, testing::HasSubstr("Verification"))); } } // namespace crypto } // namespace krypton } // namespace privacy
35.070866
78
0.701392
Condum
897172d3ad4713dc6ff9e70ca874f801cc893b2b
747
cpp
C++
String/First Non-repeted char in a string.cpp
Biplob68/Data-Structure-and-Algorithms
2ea7895a87ce1dfb9bd90495c678fc5d1ae133f6
[ "MIT" ]
null
null
null
String/First Non-repeted char in a string.cpp
Biplob68/Data-Structure-and-Algorithms
2ea7895a87ce1dfb9bd90495c678fc5d1ae133f6
[ "MIT" ]
null
null
null
String/First Non-repeted char in a string.cpp
Biplob68/Data-Structure-and-Algorithms
2ea7895a87ce1dfb9bd90495c678fc5d1ae133f6
[ "MIT" ]
null
null
null
#include <stdio.h> #include <string.h> int main(void) { char str[100] ; scanf("%[^\n]%c", str); int len = strlen(str); int i,j,flag; // Two loops to compare each character with other character for(i = 0; i < len; i++) { flag = 0; for(j = 0; j < len; j++) { // If it's equal and indexes is not same if((str[i] == str[j]) && (i != j)) { flag = 1; break; } } if (flag == 0) { printf("First non-repeating character is %c\n",str[i]); break; } } if (flag == 1) { printf("Didn't find any non-repeating character\n"); } return 0; }
18.675
67
0.417671
Biplob68
8973a1d5836bd39116a198ef89f47f9839decc08
780
hpp
C++
include/Pothos/serialization/impl/mpl/char_fwd.hpp
pothosware/pothos-serialization
c59130f916a3e5b833a32ba415063f9cb306a8dd
[ "BSL-1.0" ]
1
2015-05-26T11:27:22.000Z
2015-05-26T11:27:22.000Z
include/Pothos/serialization/impl/mpl/char_fwd.hpp
pothosware/pothos-serialization
c59130f916a3e5b833a32ba415063f9cb306a8dd
[ "BSL-1.0" ]
null
null
null
include/Pothos/serialization/impl/mpl/char_fwd.hpp
pothosware/pothos-serialization
c59130f916a3e5b833a32ba415063f9cb306a8dd
[ "BSL-1.0" ]
null
null
null
#ifndef POTHOS_MPL_CHAR_FWD_HPP_INCLUDED #define POTHOS_MPL_CHAR_FWD_HPP_INCLUDED // Copyright Eric Niebler 2008 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source$ // $Date: 2008-06-14 08:41:37 -0700 (Sat, 16 Jun 2008) $ // $Revision: 24874 $ #include <Pothos/serialization/impl/mpl/aux_/adl_barrier.hpp> #include <Pothos/serialization/impl/mpl/aux_/nttp_decl.hpp> POTHOS_MPL_AUX_ADL_BARRIER_NAMESPACE_OPEN template< POTHOS_MPL_AUX_NTTP_DECL(char, N) > struct char_; POTHOS_MPL_AUX_ADL_BARRIER_NAMESPACE_CLOSE POTHOS_MPL_AUX_ADL_BARRIER_DECL(char_) #endif // BOOST_MPL_CHAR_FWD_HPP_INCLUDED
27.857143
62
0.788462
pothosware
89780c9bf1eb5779c361a74d2cf56f2d76c3717d
822
cpp
C++
acm/hdu/1873.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
17
2016-01-01T12:57:25.000Z
2022-02-06T09:55:12.000Z
acm/hdu/1873.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
null
null
null
acm/hdu/1873.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
8
2018-12-27T01:31:49.000Z
2022-02-06T09:55:12.000Z
#include<bits/stdc++.h> using namespace std; #define sa(x) scanf("%d",&x) const int maxn = 1005; struct node{ int pri; int id; bool operator < (const node a) const { if(pri == a.pri)return id>a.id; return pri<a.pri; } }g; int main(){ string a; int n; while(cin>>n){ int cnt = 1; priority_queue<node> q[3]; for(int i = 0;i<n;i++){ cin>>a; if(a == "OUT"){ int d; cin>>d; d--; if(q[d].empty()){cout<<"EMPTY"<<endl;} else{ g = q[d].top(); q[d].pop(); cout<<g.id<<endl; } } else{ int d; cin>>d>>g.pri; g.id = cnt++; q[d-1].push(g); } } } }
19.116279
50
0.375912
xiaohuihuigh
897970954c73f23ff6cf5eda1abbf808f5415d5b
7,409
hpp
C++
src/operator/perturbedst2eoperator.hpp
susilehtola/aquarius
9160e73bd7e3e0d8d97b10d00d9a4860aee709d2
[ "BSD-3-Clause" ]
18
2015-02-11T15:02:39.000Z
2021-09-24T13:10:12.000Z
src/operator/perturbedst2eoperator.hpp
susilehtola/aquarius
9160e73bd7e3e0d8d97b10d00d9a4860aee709d2
[ "BSD-3-Clause" ]
21
2015-06-23T13:32:29.000Z
2022-02-15T20:14:42.000Z
src/operator/perturbedst2eoperator.hpp
susilehtola/aquarius
9160e73bd7e3e0d8d97b10d00d9a4860aee709d2
[ "BSD-3-Clause" ]
8
2016-01-09T23:36:21.000Z
2019-11-19T14:22:34.000Z
#ifndef _AQUARIUS_OPERATOR_PERTURBEDST2EOPERATOR_HPP_ #define _AQUARIUS_OPERATOR_PERTURBEDST2EOPERATOR_HPP_ #include "util/global.hpp" #include "2eoperator.hpp" #include "st2eoperator.hpp" namespace aquarius { namespace op { /* * _A -T A T _ A A T _ A * Form X = e X e + [X, T ] = (X e ) + (X T ) , up to two-electron terms * c c */ template <typename U> class PerturbedSTTwoElectronOperator : public STTwoElectronOperator<U> { protected: const STTwoElectronOperator<U>& X; const ExcitationOperator<U,2>& TA; public: template <int N> PerturbedSTTwoElectronOperator(const string& name, const STTwoElectronOperator<U>& X, const OneElectronOperator<U>& XA, const ExcitationOperator<U,N>& T, const ExcitationOperator<U,N>& TA) : STTwoElectronOperator<U>(name, XA, T), X(X), TA(TA) { OneElectronOperator<U> I("I", this->arena, this->occ, this->vrt); tensor::SpinorbitalTensor<U>& IMI = I.getIJ(); tensor::SpinorbitalTensor<U>& IAE = I.getAB(); tensor::SpinorbitalTensor<U>& IME = I.getIA(); IME["me"] = X.getIJAB()["mnef"]*TA(1)["fn"]; IMI["mi"] = X.getIJAK()["nmei"]*TA(1)["en"]; IMI["mi"] += 0.5*X.getIJAB()["mnef"]*TA(2)["efin"]; IAE["ae"] = X.getAIBC()["amef"]*TA(1)["fm"]; IAE["ae"] -= 0.5*X.getIJAB()["mnef"]*TA(2)["afmn"]; this->ia["ia"] += IME["ia"]; this->ij["ij"] += X.getIA()["ie"]*TA(1)["ej"]; this->ij["ij"] += IMI["ij"]; this->ab["ab"] -= X.getIA()["mb"]*TA(1)["am"]; this->ab["ab"] += IAE["ab"]; this->ai["ai"] += X.getAB()["ae"]*TA(1)["ei"]; this->ai["ai"] -= X.getIJ()["mi"]*TA(1)["am"]; this->ai["ai"] += X.getIA()["me"]*TA(2)["aeim"]; this->ai["ai"] -= X.getAIBJ()["amei"]*TA(1)["em"]; this->ai["ai"] -= 0.5*X.getIJAK()["nmei"]*TA(2)["aemn"]; this->ai["ai"] += 0.5*X.getAIBC()["amef"]*TA(2)["efim"]; this->getIJAK()["ijak"] += X.getIJAB()["ijae"]*TA(1)["ek"]; this->getAIBC()["aibc"] -= X.getIJAB()["mibc"]*TA(1)["am"]; this->getIJKL()["ijkl"] += X.getIJAK()["jiek"]*TA(1)["el"]; this->getIJKL()["ijkl"] += 0.5*X.getIJAB()["ijef"]*TA(2)["efkl"]; this->getABCD()["abcd"] -= X.getAIBC()["amcd"]*TA(1)["bm"]; this->getABCD()["abcd"] += 0.5*X.getIJAB()["mncd"]*TA(2)["abmn"]; this->getAIBJ()["aibj"] += X.getAIBC()["aibe"]*TA(1)["ej"]; this->getAIBJ()["aibj"] -= X.getIJAK()["mibj"]*TA(1)["am"]; this->getAIBJ()["aibj"] -= X.getIJAB()["mibe"]*TA(2)["aemj"]; this->getAIJK()["aijk"] += IME["ie"]*T(2)["aejk"]; this->getAIJK()["aijk"] += X.getAIBJ()["aiek"]*TA(1)["ej"]; this->getAIJK()["aijk"] -= X.getIJKL()["mijk"]*TA(1)["am"]; this->getAIJK()["aijk"] += X.getIJAK()["miek"]*TA(2)["aejm"]; this->getAIJK()["aijk"] += 0.5*X.getAIBC()["aief"]*TA(2)["efjk"]; this->getABCI()["abci"] -= IME["mc"]*T(2)["abmi"]; this->getABCI()["abci"] -= X.getAIBJ()["amci"]*TA(1)["bm"]; this->getABCI()["abci"] += X.getABCD()["abce"]*TA(1)["ei"]; this->getABCI()["abci"] += X.getAIBC()["amce"]*TA(2)["beim"]; this->getABCI()["abci"] += 0.5*X.getIJAK()["mnci"]*TA(2)["abmn"]; this->abij["abij"] += IAE["ae"]*T(2)["ebij"]; this->abij["abij"] -= IMI["mi"]*T(2)["abmj"]; this->abij["abij"] += X.getABCI()["abej"]*TA(1)["ei"]; this->abij["abij"] -= X.getAIJK()["bmji"]*TA(1)["am"]; this->abij["abij"] += 0.5*X.getABCD()["abef"]*TA(2)["efij"]; this->abij["abij"] += 0.5*X.getIJKL()["mnij"]*TA(2)["abmn"]; this->abij["abij"] -= X.getAIBJ()["amei"]*TA(2)["ebmj"]; } template <int N> PerturbedSTTwoElectronOperator(const string& name, const STTwoElectronOperator<U>& X, const TwoElectronOperator<U>& XA, const ExcitationOperator<U,N>& T, const ExcitationOperator<U,N>& TA) : STTwoElectronOperator<U>(name, XA, T), X(X), TA(TA) { OneElectronOperator<U> I("I", this->arena, this->occ, this->vrt); tensor::SpinorbitalTensor<U>& IMI = I.getIJ(); tensor::SpinorbitalTensor<U>& IAE = I.getAB(); tensor::SpinorbitalTensor<U>& IME = I.getIA(); IME["me"] = X.getIJAB()["mnef"]*TA(1)["fn"]; IMI["mi"] = X.getIJAK()["nmei"]*TA(1)["en"]; IMI["mi"] += 0.5*X.getIJAB()["mnef"]*TA(2)["efin"]; IAE["ae"] = X.getAIBC()["amef"]*TA(1)["fm"]; IAE["ae"] -= 0.5*X.getIJAB()["mnef"]*TA(2)["afmn"]; this->ia["ia"] += IME["ia"]; this->ij["ij"] += X.getIA()["ie"]*TA(1)["ej"]; this->ij["ij"] += IMI["ij"]; this->ab["ab"] -= X.getIA()["mb"]*TA(1)["am"]; this->ab["ab"] += IAE["ab"]; this->ai["ai"] += X.getAB()["ae"]*TA(1)["ei"]; this->ai["ai"] -= X.getIJ()["mi"]*TA(1)["am"]; this->ai["ai"] += X.getIA()["me"]*TA(2)["aeim"]; this->ai["ai"] -= X.getAIBJ()["amei"]*TA(1)["em"]; this->ai["ai"] -= 0.5*X.getIJAK()["nmei"]*TA(2)["aemn"]; this->ai["ai"] += 0.5*X.getAIBC()["amef"]*TA(2)["efim"]; this->getIJAK()["ijak"] += X.getIJAB()["ijae"]*TA(1)["ek"]; this->getAIBC()["aibc"] -= X.getIJAB()["mibc"]*TA(1)["am"]; this->getIJKL()["ijkl"] += X.getIJAK()["jiek"]*TA(1)["el"]; this->getIJKL()["ijkl"] += 0.5*X.getIJAB()["ijef"]*TA(2)["efkl"]; this->getABCD()["abcd"] -= X.getAIBC()["amcd"]*TA(1)["bm"]; this->getABCD()["abcd"] += 0.5*X.getIJAB()["mncd"]*TA(2)["abmn"]; this->getAIBJ()["aibj"] += X.getAIBC()["aibe"]*TA(1)["ej"]; this->getAIBJ()["aibj"] -= X.getIJAK()["mibj"]*TA(1)["am"]; this->getAIBJ()["aibj"] -= X.getIJAB()["mibe"]*TA(2)["aemj"]; this->getAIJK()["aijk"] += IME["ie"]*T(2)["aejk"]; this->getAIJK()["aijk"] += X.getAIBJ()["aiek"]*TA(1)["ej"]; this->getAIJK()["aijk"] -= X.getIJKL()["mijk"]*TA(1)["am"]; this->getAIJK()["aijk"] += X.getIJAK()["miek"]*TA(2)["aejm"]; this->getAIJK()["aijk"] += 0.5*X.getAIBC()["aief"]*TA(2)["efjk"]; this->getABCI()["abci"] -= IME["mc"]*T(2)["abmi"]; this->getABCI()["abci"] -= X.getAIBJ()["amci"]*TA(1)["bm"]; this->getABCI()["abci"] += X.getABCD()["abce"]*TA(1)["ei"]; this->getABCI()["abci"] += X.getAIBC()["amce"]*TA(2)["beim"]; this->getABCI()["abci"] += 0.5*X.getIJAK()["mnci"]*TA(2)["abmn"]; this->abij["abij"] += IAE["ae"]*T(2)["ebij"]; this->abij["abij"] -= IMI["mi"]*T(2)["abmj"]; this->abij["abij"] += X.getABCI()["abej"]*TA(1)["ei"]; this->abij["abij"] -= X.getAIJK()["bmji"]*TA(1)["am"]; this->abij["abij"] += 0.5*X.getABCD()["abef"]*TA(2)["efij"]; this->abij["abij"] += 0.5*X.getIJKL()["mnij"]*TA(2)["abmn"]; this->abij["abij"] -= X.getAIBJ()["amei"]*TA(2)["ebmj"]; } }; } } #endif
43.582353
127
0.460791
susilehtola
897a1fa3ff51d806bdb4e52201d22d56e844ebfc
22,050
cc
C++
elang/compiler/syntax/lexer.cc
eval1749/elang
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
[ "Apache-2.0" ]
1
2018-01-27T22:40:53.000Z
2018-01-27T22:40:53.000Z
elang/compiler/syntax/lexer.cc
eval1749/elang
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
[ "Apache-2.0" ]
1
2016-01-29T00:54:49.000Z
2016-01-29T00:54:49.000Z
elang/compiler/syntax/lexer.cc
eval1749/elang
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
[ "Apache-2.0" ]
null
null
null
// Copyright 2014-2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "elang/compiler/syntax/lexer.h" #include <cmath> #include <limits> #include <string> #include <vector> #include "base/logging.h" #include "base/strings/string_util.h" #include "elang/base/atomic_string.h" #include "elang/compiler/compilation_session.h" #include "elang/compiler/compilation_unit.h" #include "elang/compiler/public/compiler_error_code.h" #include "elang/compiler/source_code.h" #include "elang/compiler/token.h" #include "elang/compiler/token_type.h" namespace elang { namespace compiler { namespace { TokenType ComputeToken(AtomicString* name) { typedef std::unordered_map<base::StringPiece16, TokenType> KeywordMap; CR_DEFINE_STATIC_LOCAL(KeywordMap*, keyword_map, ()); if (!keyword_map) { keyword_map = new KeywordMap(); #define K(name, string, details) (*keyword_map)[L##string] = TokenType::name; FOR_EACH_TOKEN(IGNORE_TOKEN, K) #undef K } auto it = keyword_map->find(name->string()); return it == keyword_map->end() ? TokenType::SimpleName : it->second; } int DigitToInt(base::char16 char_code, int base) { auto const value = char_code - '0'; if (value >= 0 && value < base) return value; if (base <= 10) return -1; auto const alpha = char_code - 'A' + 10; if (alpha >= 10 && alpha < base) return alpha; auto const alpha2 = char_code - 'a' + 10; if (alpha2 >= 10 && alpha2 < base) return alpha2; return -1; } bool IsNameStartChar(base::char16 char_code) { if (char_code >= 'A' && char_code <= 'Z') return true; if (char_code >= 'a' && char_code <= 'z') return true; return char_code == '_'; } bool IsNameChar(base::char16 char_code) { if (IsNameStartChar(char_code)) return true; return char_code >= '0' && char_code <= '9'; } } // namespace ////////////////////////////////////////////////////////////////////// // // Lexer::CharSink // class Lexer::CharSink { public: CharSink(); ~CharSink() = default; base::StringPiece16 End(); void AddChar(base::char16 char_code); void Start(); private: std::vector<base::char16> buffer_; DISALLOW_COPY_AND_ASSIGN(CharSink); }; Lexer::CharSink::CharSink() : buffer_(200) { } void Lexer::CharSink::AddChar(base::char16 char_code) { buffer_.push_back(char_code); } base::StringPiece16 Lexer::CharSink::End() { return base::StringPiece16(buffer_.data(), buffer_.size()); } void Lexer::CharSink::Start() { buffer_.resize(0); } ////////////////////////////////////////////////////////////////////// // // Lexer::InputStream // class Lexer::InputStream { public: explicit InputStream(SourceCode* source_code); ~InputStream(); void Advance(); bool IsAtEndOfStream(); base::char16 PeekChar(); base::char16 ReadChar(); private: bool has_char_; base::char16 last_char_; int offset_; SourceCode* source_code_; CharacterStream* const stream_; DISALLOW_COPY_AND_ASSIGN(InputStream); }; Lexer::InputStream::InputStream(SourceCode* source_code) : has_char_(false), last_char_(0), offset_(0), source_code_(source_code), stream_(source_code->GetStream()) { } Lexer::InputStream::~InputStream() { } void Lexer::InputStream::Advance() { has_char_ = false; if (IsAtEndOfStream()) return; ReadChar(); } bool Lexer::InputStream::IsAtEndOfStream() { return !has_char_ && stream_->IsAtEndOfStream(); } base::char16 Lexer::InputStream::PeekChar() { if (has_char_) return last_char_; return ReadChar(); } base::char16 Lexer::InputStream::ReadChar() { DCHECK(!has_char_); DCHECK(!stream_->IsAtEndOfStream()); ++offset_; has_char_ = true; last_char_ = stream_->ReadChar(); if (last_char_ == '\n') source_code_->RememberStartOfLine(offset_ + 1); return last_char_; } ////////////////////////////////////////////////////////////////////// // // Lexer // Lexer::Lexer(CompilationSession* session, CompilationUnit* compilation_unit) : char_sink_(new CharSink()), compilation_unit_(compilation_unit), input_stream_(new InputStream(compilation_unit->source_code())), session_(session), token_end_(0), token_start_(0) { } Lexer::~Lexer() { } void Lexer::Advance() { ++token_end_; input_stream_->Advance(); } bool Lexer::AdvanceIf(base::char16 char_code) { if (IsAtEndOfStream()) return false; if (PeekChar() != char_code) return false; Advance(); return true; } bool Lexer::AdvanceIfEither(base::char16 char_code1, base::char16 char_code2) { if (IsAtEndOfStream()) return false; if (PeekChar() != char_code1 && PeekChar() != char_code2) return false; Advance(); return true; } SourceCodeRange Lexer::ComputeLocation() { return ComputeLocation(token_end_ - token_start_); } SourceCodeRange Lexer::ComputeLocation(int length) { return SourceCodeRange(compilation_unit_->source_code(), token_start_, token_start_ + length); } Token* Lexer::Error(ErrorCode error_code) { session_->AddError(ComputeLocation(), error_code); return HandleOneChar(TokenType::Illegal); } Token* Lexer::GetToken() { auto just_after_whitespace = false; for (;;) { if (IsAtEndOfStream()) return HandleOneChar(TokenType::EndOfSource); auto const char_code = PeekChar(); Advance(); if (char_code == ' ' || char_code == 0x0D || char_code == 0x0A) { just_after_whitespace = true; continue; } token_start_ = token_end_ - 1; if (char_code < ' ') return HandleOneChar(TokenType::Illegal); switch (char_code) { case '!': return HandleMayBeEq(TokenType::Ne, TokenType::Not); case '"': case '\'': return HandleStringLiteral(char_code); case '%': return HandleMayBeEq(TokenType::ModAssign, TokenType::Mod); case '&': if (AdvanceIf('&')) return NewToken(TokenType::And); return HandleMayBeEq(TokenType::BitAndAssign, TokenType::BitAnd); case '(': return HandleOneChar(TokenType::LeftParenthesis); case ')': return HandleOneChar(TokenType::RightParenthesis); case '*': return HandleMayBeEq(TokenType::MulAssign, TokenType::Mul); case '+': if (AdvanceIf('+')) return NewToken(TokenType::Increment); return HandleMayBeEq(TokenType::AddAssign, TokenType::Add); case ',': return HandleOneChar(TokenType::Comma); case '-': if (AdvanceIf('-')) return NewToken(TokenType::Decrement); return HandleMayBeEq(TokenType::SubAssign, TokenType::Sub); case '.': return HandleOneChar(TokenType::Dot); case '/': if (AdvanceIf('*')) { if (!SkipBlockComment()) return Error(ErrorCode::TokenBlockCommentUnclosed); just_after_whitespace = true; continue; } if (AdvanceIf('/')) { SkipLineComment(); just_after_whitespace = true; continue; } return HandleMayBeEq(TokenType::DivAssign, TokenType::Div); case '0': return HandleZero(); case ':': return HandleOneChar(TokenType::Colon); case ';': return HandleOneChar(TokenType::SemiColon); case '<': if (!just_after_whitespace) return HandleOneChar(TokenType::LeftAngleBracket); if (AdvanceIf('<')) return HandleMayBeEq(TokenType::ShlAssign, TokenType::Shl); return HandleMayBeEq(TokenType::Le, TokenType::Lt); case '=': if (AdvanceIf('>')) return NewToken(TokenType::Arrow); return HandleMayBeEq(TokenType::Eq, TokenType::Assign); case '>': if (!just_after_whitespace) return HandleOneChar(TokenType::RightAngleBracket); if (AdvanceIf('>')) return HandleMayBeEq(TokenType::ShrAssign, TokenType::Shr); return HandleMayBeEq(TokenType::Ge, TokenType::Gt); case '?': if (just_after_whitespace) { if (AdvanceIf('?')) return NewToken(TokenType::NullOr); return HandleOneChar(TokenType::QuestionMark); } if (AdvanceIf('.')) return NewToken(TokenType::OptionalDot); return HandleOneChar(TokenType::OptionalType); case '@': return HandleAtMark(); case '[': return HandleOneChar(TokenType::LeftSquareBracket); case ']': return HandleOneChar(TokenType::RightSquareBracket); case '^': return HandleMayBeEq(TokenType::BitXorAssign, TokenType::BitXor); case '{': return HandleOneChar(TokenType::LeftCurryBracket); case '|': if (AdvanceIf('|')) return NewToken(TokenType::Or); return HandleMayBeEq(TokenType::BitOrAssign, TokenType::BitOr); case '}': return HandleOneChar(TokenType::RightCurryBracket); case '~': return HandleOneChar(TokenType::BitNot); default: if (IsNameStartChar(char_code)) return HandleName(char_code); if (char_code >= '1' && char_code <= '9') return HandleIntegerOrReal(char_code - '0'); return HandleOneChar(TokenType::Illegal); } } } Token* Lexer::HandleAfterDecimalPoint(uint64_t u64) { auto exponent = 0; while (!IsAtEndOfStream()) { auto const char_code = PeekChar(); if (char_code >= '0' && char_code <= '9') { Advance(); if (u64 >= std::numeric_limits<uint64_t>::max() / 10) return Error(ErrorCode::TokenRealTooManyDigits); u64 *= 10; u64 += char_code - '0'; --exponent; continue; } if (AdvanceIfEither('e', 'E')) return HandleExponent(u64, exponent); if (AdvanceIfEither('f', 'F')) return NewFloatLiteral(TokenType::Float32Literal, u64, exponent); break; } return NewFloatLiteral(TokenType::Float64Literal, u64, exponent); } // Handle verbatim string or raw name // - raw string: '@' '"' (CharNotQuote | '""')* '"' // - raw name: '@' NameStartChar NameChar* // Token* Lexer::HandleAtMark() { if (IsAtEndOfStream()) return Error(ErrorCode::TokenAtMarkInvalid); if (AdvanceIf('"')) { enum class State { Normal, Quote, } state = State::Normal; char_sink_->Start(); while (!IsAtEndOfStream()) { auto const char_code = PeekChar(); switch (state) { case State::Quote: if (char_code == '"') { Advance(); char_sink_->AddChar('"'); state = State::Normal; break; } return NewToken(TokenData(session_->NewString(char_sink_->End()))); case State::Normal: Advance(); if (char_code == '"') { state = State::Quote; break; } char_sink_->AddChar(char_code); break; } } if (state == State::Quote) return NewToken(TokenData(session_->NewString(char_sink_->End()))); return Error(ErrorCode::TokenAtMarkStringUnclosed); } if (IsNameStartChar(PeekChar())) { char_sink_->Start(); while (!IsAtEndOfStream()) { auto const char_code = PeekChar(); if (!IsNameChar(char_code)) break; Advance(); char_sink_->AddChar(char_code); } auto const name = session_->NewAtomicString(char_sink_->End()); DCHECK_GE(name->string().size(), 1u); return NewToken(TokenData(TokenType::VerbatimName, name)); } return Error(ErrorCode::TokenAtMarkInvalid); } Token* Lexer::HandleExponent(uint64_t u64, int exponent_offset) { auto is_minus = false; if (AdvanceIf('-')) { is_minus = true; } else if (AdvanceIf('+')) { is_minus = false; } auto token_type = TokenType::Float64Literal; auto exponent = 0; while (!IsAtEndOfStream()) { auto const char_code = PeekChar(); if (AdvanceIfEither('f', 'F')) { token_type = TokenType::Float32Literal; break; } if (char_code < '0' || char_code > '9') break; Advance(); if (exponent > std::numeric_limits<uint64_t>::max() / 10) { return Error(ErrorCode::TokenFloatExponentOverflow); } exponent *= 10; exponent += char_code - '0'; } if (is_minus) exponent = -exponent; exponent += exponent_offset; return NewFloatLiteral(token_type, u64, exponent); } Token* Lexer::HandleInteger(int base) { uint64_t u64 = 0; auto digit_count = 0; while (!IsAtEndOfStream()) { auto const digit = DigitToInt(PeekChar(), base); if (digit < 0) { if (!digit_count) { Advance(); break; } return HandleIntegerSuffix(u64); } Advance(); if (u64 >= std::numeric_limits<uint64_t>::max() / 10) return Error(ErrorCode::TokenIntegerOverflow); u64 *= base; u64 += digit; ++digit_count; } return Error(ErrorCode::TokenIntegerInvalid); } Token* Lexer::HandleIntegerOrReal(int digit) { uint64_t u64 = digit; while (!IsAtEndOfStream()) { auto const char_code = PeekChar(); if (char_code >= '0' && char_code <= '9') { Advance(); if (u64 >= std::numeric_limits<uint64_t>::max() / 10) return Error(ErrorCode::TokenIntegerOverflow); u64 *= 10; u64 += char_code - '0'; continue; } if (char_code == '.') { Advance(); return HandleAfterDecimalPoint(u64); } if (AdvanceIfEither('e', 'E')) return HandleExponent(u64, 0); if (char_code == 'l' || char_code == 'L' || char_code == 'u' || char_code == 'U') { return HandleIntegerSuffix(u64); } break; } if (u64 >= std::numeric_limits<int32_t>::max()) return Error(ErrorCode::TokenIntegerOverflow); return NewIntLiteral(TokenType::Int32Literal, u64); } // Handle Integer Suffixes // \d+ [Ll]? [Uu]? // \d+ [Uu]? [Ll]? Token* Lexer::HandleIntegerSuffix(uint64_t u64) { if (AdvanceIfEither('l', 'L')) { if (AdvanceIfEither('u', 'U')) return NewToken(TokenData(TokenType::UInt64Literal, u64)); return NewIntLiteral(TokenType::Int64Literal, u64); } if (AdvanceIfEither('u', 'U')) { if (AdvanceIfEither('l', 'L')) return NewToken(TokenData(TokenType::UInt64Literal, u64)); if (u64 > static_cast<uint64_t>(std::numeric_limits<uint32_t>::max())) return Error(ErrorCode::TokenIntegerOverflow); return NewIntLiteral(TokenType::UInt32Literal, u64); } if (u64 > static_cast<uint64_t>(std::numeric_limits<int32_t>::max())) return Error(ErrorCode::TokenIntegerOverflow); return NewIntLiteral(TokenType::Int32Literal, u64); } Token* Lexer::HandleMayBeEq(TokenType with_eq, TokenType without_eq) { if (AdvanceIf('=')) return NewToken(with_eq); return NewToken(without_eq); } Token* Lexer::HandleName(base::char16 first_char_code) { char_sink_->Start(); char_sink_->AddChar(first_char_code); while (!IsAtEndOfStream()) { auto const char_code = PeekChar(); if (!IsNameChar(char_code)) break; Advance(); char_sink_->AddChar(char_code); } auto const name = session_->NewAtomicString(char_sink_->End()); return NewToken(TokenData(ComputeToken(name), name)); } Token* Lexer::HandleOneChar(TokenType token_type) { return session_->NewToken(ComputeLocation(1), TokenData(token_type)); } // E supports following backslash sequence: // \' \" \\ \0 \a \b \f \n \r \t \uUUUU Token* Lexer::HandleStringLiteral(base::char16 delimiter) { char_sink_->Start(); enum class State { Backslash, BackslashU, Normal, } state = State::Normal; auto accumulator = 0; auto digit_count = 0; while (!IsAtEndOfStream()) { auto char_code = PeekChar(); Advance(); switch (state) { case State::Backslash: switch (char_code) { case '"': case '\'': case '\\': break; case '0': char_code = static_cast<base::char16>(0x0000); break; case 'a': char_code = static_cast<base::char16>(0x0007); break; case 'b': char_code = static_cast<base::char16>(0x0008); break; case 'f': char_code = static_cast<base::char16>(0x000C); break; case 'n': char_code = static_cast<base::char16>(0x000A); break; case 'r': char_code = static_cast<base::char16>(0x000D); break; case 't': char_code = static_cast<base::char16>(0x0009); break; case 'u': accumulator = 0; digit_count = 0; state = State::BackslashU; continue; case 'v': char_code = static_cast<base::char16>(0x000B); break; default: return Error(ErrorCode::TokenBackslashInvalid); } char_sink_->AddChar(char_code); state = State::Normal; break; case State::BackslashU: { auto const digit = DigitToInt(char_code, 16); if (digit < 0) return Error(ErrorCode::TokenBackslashUInvalid); accumulator <<= 4; accumulator += digit; ++digit_count; if (digit_count == 4) { char_sink_->AddChar(static_cast<base::char16>(accumulator)); state = State::Normal; } break; } case State::Normal: if (char_code == '\n') return Error(ErrorCode::TokenStringHasNewline); if (char_code == '\\') { state = State::Backslash; break; } if (char_code == delimiter) { auto string = session_->NewString(char_sink_->End()); auto const token = NewToken(TokenData(string)); if (delimiter == '"') return token; if (string->size() != 1) { session_->AddError(ErrorCode::TokenCharacterInvalid, token); return NewToken(TokenType::Illegal); } return NewToken(TokenData(TokenType::CharacterLiteral, (*string)[0])); } char_sink_->AddChar(char_code); break; } } return Error(ErrorCode::TokenStringUnclosed); } // Handles following numeric literals: // '0' '.' real // '0' [Bb] binary // '0' [Ee] real // '0' [Ll][Uu]? int64/uint64 // '0' [Oo] octal // '0' [Uu][Ll]? uint64 // '0' [Xx] hexadecimal Token* Lexer::HandleZero() { const uint64_t zero = 0u; if (IsAtEndOfStream()) return NewIntLiteral(TokenType::Int32Literal, zero); if (AdvanceIf('.')) return HandleAfterDecimalPoint(0u); if (AdvanceIfEither('b', 'B')) return HandleInteger(2); if (AdvanceIfEither('e', 'E')) return HandleExponent(0u, 0); if (PeekChar() == 'l' || PeekChar() == 'L') return HandleIntegerSuffix(zero); if (AdvanceIfEither('o', 'O')) return HandleInteger(8); if (PeekChar() == 'u' || PeekChar() == 'U') return HandleIntegerSuffix(zero); if (AdvanceIfEither('x', 'X')) return HandleInteger(16); if (PeekChar() >= '0' && PeekChar() <= '9') { Advance(); return HandleIntegerOrReal(PeekChar() - '0'); } return NewIntLiteral(TokenType::Int32Literal, zero); } bool Lexer::IsAtEndOfStream() { return input_stream_->IsAtEndOfStream(); } Token* Lexer::NewFloatLiteral(TokenType token_type, uint64_t u64, int exponent) { if (token_type == TokenType::Float32Literal) { auto const int_part = static_cast<float32_t>(u64); if (exponent >= 0) { auto const f32 = int_part * std::pow(10.0f, exponent); return NewToken(TokenData(f32)); } auto const f32 = int_part / std::pow(10.0f, -exponent); return NewToken(TokenData(f32)); } DCHECK_EQ(token_type, TokenType::Float64Literal); auto const int_part = static_cast<float64_t>(u64); if (exponent >= 0) { auto const f64 = int_part * std::pow(10.0, exponent); return NewToken(TokenData(f64)); } auto const f64 = int_part / std::pow(10.0, -exponent); return NewToken(TokenData(f64)); } Token* Lexer::NewIntLiteral(TokenType type, uint64_t u64) { return NewToken(TokenData(type, u64)); } Token* Lexer::NewToken(TokenType type) { return NewToken(TokenData(type)); } Token* Lexer::NewToken(const TokenData& data) { return session_->NewToken(ComputeLocation(), data); } base::char16 Lexer::PeekChar() { return input_stream_->PeekChar(); } // Returns false when we don't get matching "*/" at end of source code. // Note: Block comments is nestable. bool Lexer::SkipBlockComment() { enum State { Asterisk, Normal, Slash, }; auto state = Normal; auto depth = 1; while (!IsAtEndOfStream()) { Advance(); auto const char_code = PeekChar(); switch (state) { case State::Asterisk: if (char_code == '/') { --depth; if (!depth) { Advance(); return true; } state = State::Normal; break; } if (char_code != '*') state = State::Normal; break; case State::Normal: if (char_code == '*') { state = State::Asterisk; break; } if (char_code == '/') { state = State::Slash; break; } break; case State::Slash: if (char_code == '*') { ++depth; state = State::Normal; break; } if (char_code != '/') state = State::Normal; break; } } return false; } // Note: Skip until unescaped newline or end of source code. void Lexer::SkipLineComment() { enum State { Backslash, Normal, } state = Normal; while (!IsAtEndOfStream()) { Advance(); auto const char_code = PeekChar(); switch (state) { case State::Backslash: state = State::Normal; break; case State::Normal: if (char_code == '\n') return; if (char_code == '\\') state = State::Backslash; break; } } } } // namespace compiler } // namespace elang
28.341902
80
0.60585
eval1749
897e903e3cd8d885a3599f107cb5c14b6bf1f674
3,803
cpp
C++
test/test_speed.cpp
barometz/ringbuf
96b49b86d88969a46df56485cfa2d005bd524d9f
[ "MIT" ]
15
2021-12-12T16:58:13.000Z
2022-03-25T09:22:06.000Z
test/test_speed.cpp
barometz/ringbuf
96b49b86d88969a46df56485cfa2d005bd524d9f
[ "MIT" ]
null
null
null
test/test_speed.cpp
barometz/ringbuf
96b49b86d88969a46df56485cfa2d005bd524d9f
[ "MIT" ]
1
2021-12-19T02:03:04.000Z
2021-12-19T02:03:04.000Z
#include "baudvine/deque_ringbuf.h" #include "baudvine/ringbuf.h" #include <gtest/gtest.h> #include <chrono> // Speed comparison between deque and standard. Standard should generally be at // least as fast as deque, but in practice we're not the only process so there's // going to be some noise. namespace std { namespace chrono { std::ostream& operator<<(std::ostream& os, system_clock::duration d) { return os << duration_cast<microseconds>(d).count() << " µs"; } } // namespace chrono } // namespace std namespace { constexpr uint64_t kTestSize = 1 << 25; std::chrono::system_clock::duration TimeIt(const std::function<void()>& fn) { const auto start = std::chrono::system_clock::now(); fn(); return std::chrono::system_clock::now() - start; } } // namespace TEST(Speed, PushBackToFull) { baudvine::RingBuf<uint64_t, kTestSize> standard; baudvine::DequeRingBuf<uint64_t, kTestSize> deque; // Preload everything once so all the memory is definitely allocated for (uint32_t i = 0; i < standard.max_size(); i++) { standard.push_back(0); } standard.clear(); for (uint32_t i = 0; i < deque.max_size(); i++) { deque.push_back(0); } deque.clear(); auto standardDuration = TimeIt([&standard] { for (uint32_t i = 0; i < standard.max_size(); i++) { standard.push_back(0); } }); auto dequeDuration = TimeIt([&deque] { for (uint32_t i = 0; i < deque.max_size(); i++) { deque.push_back(0); } }); EXPECT_LT(standardDuration, dequeDuration); std::cout << "RingBuf: " << standardDuration << std::endl; std::cout << "DequeRingBuf: " << dequeDuration << std::endl; } TEST(Speed, PushBackOverFull) { baudvine::RingBuf<uint64_t, 3> standard; baudvine::DequeRingBuf<uint64_t, 3> deque; auto standardDuration = TimeIt([&standard] { for (uint32_t i = 0; i < kTestSize; i++) { standard.push_back(0); } }); auto dequeDuration = TimeIt([&deque] { for (uint32_t i = 0; i < kTestSize; i++) { deque.push_back(0); } }); EXPECT_LT(standardDuration, dequeDuration); std::cout << "RingBuf: " << standardDuration << std::endl; std::cout << "DequeRingBuf: " << dequeDuration << std::endl; } TEST(Speed, IterateOver) { baudvine::RingBuf<uint64_t, kTestSize> standard; baudvine::DequeRingBuf<uint64_t, kTestSize> deque; for (uint32_t i = 0; i < standard.max_size(); i++) { standard.push_back(i); } for (uint32_t i = 0; i < deque.max_size(); i++) { deque.push_back(i); } // Do a little math so the compiler doesn't optimize the test away in a // release build. uint64_t acc{}; auto standardDuration = TimeIt([&standard, &acc] { for (auto& x : standard) { acc += x; } }); auto dequeDuration = TimeIt([&deque, &acc] { for (auto& x : deque) { acc += x; } }); EXPECT_LT(standardDuration, dequeDuration); std::cout << "RingBuf: " << standardDuration << std::endl; std::cout << "DequeRingBuf: " << dequeDuration << std::endl; } TEST(Speed, Copy) { // baudvine::copy should be faster than std::copy as std::copy doesn't know // that there are at most two contiguous sections. baudvine::RingBuf<int, kTestSize> underTest; std::fill_n(std::back_inserter(underTest), kTestSize, 55); std::vector<int> copy; copy.reserve(kTestSize); std::fill_n(std::back_inserter(copy), kTestSize, 44); auto customTime = TimeIt([&underTest, &copy] { baudvine::copy(underTest.begin(), underTest.end(), copy.begin()); }); auto standardTime = TimeIt([&underTest, &copy] { std::copy(underTest.begin(), underTest.end(), copy.begin()); }); EXPECT_LT(customTime, standardTime); std::cout << "baudvine::copy: " << customTime << std::endl; std::cout << "std::copy: " << standardTime << std::endl; }
27.963235
80
0.645543
barometz
897f32006cf2ae2432b186da04d9755ca44448ab
6,583
cc
C++
src/external_library/libgp/src/cg.cc
ecbaum/ugpm
3ab6ff2dbc59642e0e9739f5f4647a906f19e333
[ "MIT" ]
89
2015-02-28T12:20:07.000Z
2022-02-01T17:15:57.000Z
src/cg.cc
Bellout/libgp
f2bcfe7b5b6f02444ef98caf822717662c13fc88
[ "BSD-3-Clause" ]
212
2018-09-21T10:44:07.000Z
2022-03-22T14:33:05.000Z
src/cg.cc
Bellout/libgp
f2bcfe7b5b6f02444ef98caf822717662c13fc88
[ "BSD-3-Clause" ]
58
2015-03-08T09:22:01.000Z
2021-12-14T10:12:31.000Z
/* * cg.cpp * * Created on: Feb 22, 2013 * Author: Joao Cunha <joao.cunha@ua.pt> */ #include "cg.h" #include <iostream> #include <Eigen/Core> using namespace std; namespace libgp { CG::CG() { } CG::~CG() { } void CG::maximize(GaussianProcess* gp, size_t n, bool verbose) { const double INT = 0.1; // don't reevaluate within 0.1 of the limit of the current bracket const double EXT = 3.0; // extrapolate maximum 3 times the current step-size const int MAX = 20; // max 20 function evaluations per line search const double RATIO = 10; // maximum allowed slope ratio const double SIG = 0.1, RHO = SIG/2; /* SIG and RHO are the constants controlling the Wolfe- Powell conditions. SIG is the maximum allowed absolute ratio between previous and new slopes (derivatives in the search direction), thus setting SIG to low (positive) values forces higher precision in the line-searches. RHO is the minimum allowed fraction of the expected (from the slope at the initial point in the linesearch). Constants must satisfy 0 < RHO < SIG < 1. Tuning of SIG (depending on the nature of the function to be optimized) may speed up the minimization; it is probably not worth playing much with RHO. */ /* The code falls naturally into 3 parts, after the initial line search is started in the direction of steepest descent. 1) we first enter a while loop which uses point 1 (p1) and (p2) to compute an extrapolation (p3), until we have extrapolated far enough (Wolfe-Powell conditions). 2) if necessary, we enter the second loop which takes p2, p3 and p4 chooses the subinterval containing a (local) minimum, and interpolates it, unil an acceptable point is found (Wolfe-Powell conditions). Note, that points are always maintained in order p0 <= p1 <= p2 < p3 < p4. 3) compute a new search direction using conjugate gradients (Polack-Ribiere flavour), or revert to steepest if there was a problem in the previous line-search. Return the best value so far, if two consecutive line-searches fail, or whenever we run out of function evaluations or line-searches. During extrapolation, the "f" function may fail either with an error or returning Nan or Inf, and maxmize should handle this gracefully. */ bool ls_failed = false; //prev line-search failed double f0 = -gp->log_likelihood(); //initial negative marginal log likelihood Eigen::VectorXd df0 = -gp->log_likelihood_gradient(); //initial gradient Eigen::VectorXd X = gp->covf().get_loghyper(); //hyper parameters if(verbose) cout << f0 << endl; Eigen::VectorXd s = -df0; //initial search direction double d0 = -s.dot(s); //initial slope double x3 = 1/(1-d0); double f3 = 0; double d3 = 0; Eigen::VectorXd df3 = df0; double x2 = 0, x4 = 0; double f2 = 0, f4 = 0; double d2 = 0, d4 = 0; for (unsigned int i = 0; i < n; ++i) { //copy current values Eigen::VectorXd X0 = X; double F0 = f0; Eigen::VectorXd dF0 = df0; unsigned int M = min(MAX, (int)(n-i)); while(1) //keep extrapolating until necessary { x2 = 0; f2 = f0; d2 = d0; f3 = f0; df3 = df0; double success = false; while( !success && M>0) { M --; i++; gp->covf().set_loghyper(X+s*x3); f3 = -gp->log_likelihood(); df3 = -gp->log_likelihood_gradient(); if(verbose) cout << f3 << endl; bool nanFound = false; //test NaN and Inf's for (int j = 0; j < df3.rows(); ++j) { if(isnan(df3(j))) { nanFound = true; break; } } if(!isnan(f3) && !isinf(f3) && !nanFound) success = true; else { x3 = (x2+x3)/2; // if fail, bissect and try again } } //keep best values if(f3 < F0) { X0 = X+s*x3; F0 = f3; dF0 = df3; } d3 = df3.dot(s); // new slope if( (d3 > SIG*d0) || (f3 > f0+x3*RHO*d0) || M == 0) // are we done extrapolating? { break; } double x1 = x2; double f1 = f2; double d1 = d2; // move point 2 to point 1 x2 = x3; f2 = f3; d2 = d3; // move point 3 to point 2 double A = 6*(f1-f2) + 3*(d2+d1)*(x2-x1); // make cubic extrapolation double B = 3*(f2-f1) - (2*d1+d2)*(x2-x1); x3 = x1-d1*(x2-x1)*(x2-x1)/(B+sqrt(B*B -A*d1*(x2-x1))); if(isnan(x3) || x3 < 0 || x3 > x2*EXT) // num prob | wrong sign | beyond extrapolation limit x3 = EXT*x2; else if(x3 < x2+INT*(x2-x1)) // too close to previous point x3 = x2+INT*(x2-x1); } while( ( (abs(d3) > -SIG*d0) || (f3 > f0+x3*RHO*d0) ) && (M > 0)) // keep interpolating { if( (d3 > 0) || (f3 > f0+x3*RHO*d0) ) // choose subinterval { // move point 3 to point 4 x4 = x3; f4 = f3; d4 = d3; } else { x2 = x3; //move point 3 to point 2 f2 = f3; d2 = d3; } if(f4 > f0) x3 = x2 - (0.5*d2*(x4-x2)*(x4-x2))/(f4-f2-d2*(x4-x2)); // quadratic interpolation else { double A = 6*(f2-f4)/(x4-x2)+3*(d4+d2); double B = 3*(f4-f2)-(2*d2+d4)*(x4-x2); x3 = x2+sqrt(B*B-A*d2*(x4-x2)*(x4-x2) -B)/A; } if(isnan(x3) || isinf(x3)) x3 = (x2+x4)/2; x3 = std::max(std::min(x3, x4-INT*(x4-x2)), x2+INT*(x4-x2)); gp->covf().set_loghyper(X+s*x3); f3 = -gp->log_likelihood(); df3 = -gp->log_likelihood_gradient(); if(f3 < F0) // keep best values { X0 = X+s*x3; F0 = f3; dF0 = df3; } if(verbose) cout << F0 << endl; M--; i++; d3 = df3.dot(s); // new slope } if( (abs(d3) < -SIG*d0) && (f3 < f0+x3*RHO*d0)) { X = X+s*x3; f0 = f3; s = (df3.dot(df3)-df0.dot(df3)) / (df0.dot(df0))*s - df3; // Polack-Ribiere CG direction df0 = df3; // swap derivatives d3 = d0; d0 = df0.dot(s); if(verbose) cout << f0 << endl; if(d0 > 0) // new slope must be negative { // otherwise use steepest direction s = -df0; d0 = -s.dot(s); } x3 = x3 * std::min(RATIO, d3/(d0-std::numeric_limits< double >::min())); // slope ratio but max RATIO ls_failed = false; // this line search did not fail } else { // restore best point so far X = X0; f0 = F0; df0 = dF0; if(verbose) cout << f0 << endl; if(ls_failed || i >= n) // line search failed twice in a row break; // or we ran out of time, so we give up s = -df0; d0 = -s.dot(s); // try steepest x3 = 1/(1-d0); ls_failed = true; // this line search failed } } gp->covf().set_loghyper(X); } }
27.776371
104
0.581346
ecbaum
8982d7c06dcd2f60a1505fc2864abd29f58310be
6,511
hpp
C++
3rdparty/stlsoft/include/acestl/memory/message_block_functions.hpp
wohaaitinciu/zpublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
50
2015-01-07T01:54:54.000Z
2021-01-15T00:41:48.000Z
3rdparty/stlsoft/include/acestl/memory/message_block_functions.hpp
lib1256/zpublic
64c2be9ef1abab878288680bb58122dcc25df81d
[ "Unlicense" ]
2
2016-01-08T19:32:57.000Z
2019-10-11T03:50:34.000Z
3rdparty/stlsoft/include/acestl/memory/message_block_functions.hpp
lib1256/zpublic
64c2be9ef1abab878288680bb58122dcc25df81d
[ "Unlicense" ]
39
2015-01-07T02:03:15.000Z
2021-01-15T00:41:50.000Z
/* ///////////////////////////////////////////////////////////////////////// * File: acestl/memory/message_block_functions.hpp * * Purpose: Helper functions for ACE_Message_Block (and ACE_Data_Block) classes. * * Created: 23rd September 2004 * Updated: 10th August 2009 * * Home: http://stlsoft.org/ * * Copyright (c) 2004-2009, Matthew Wilson and Synesis Software * 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(s) of Matthew Wilson and Synesis Software nor the names of * any contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. * * ////////////////////////////////////////////////////////////////////// */ /** \file acestl/memory/message_block_functions.hpp * * \brief [C++ only] Helper functions for use with the ACE_Message_Block * and ACE_Data_Block classes * (\ref group__library__memory "Memory" Library). */ #ifndef ACESTL_INCL_ACESTL_MEMORY_HPP_MESSAGE_BLOCK_FUNCTIONS #define ACESTL_INCL_ACESTL_MEMORY_HPP_MESSAGE_BLOCK_FUNCTIONS #ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION # define ACESTL_VER_ACESTL_MEMORY_HPP_MESSAGE_BLOCK_FUNCTIONS_MAJOR 2 # define ACESTL_VER_ACESTL_MEMORY_HPP_MESSAGE_BLOCK_FUNCTIONS_MINOR 0 # define ACESTL_VER_ACESTL_MEMORY_HPP_MESSAGE_BLOCK_FUNCTIONS_REVISION 3 # define ACESTL_VER_ACESTL_MEMORY_HPP_MESSAGE_BLOCK_FUNCTIONS_EDIT 28 #endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */ /* ///////////////////////////////////////////////////////////////////////// * Includes */ #ifndef ACESTL_INCL_ACESTL_HPP_ACESTL # include <acestl/acestl.hpp> #endif /* !ACESTL_INCL_ACESTL_HPP_ACESTL */ #ifndef STLSOFT_INCL_ACE_H_MESSAGE_BLOCK # define STLSOFT_INCL_ACE_H_MESSAGE_BLOCK # include <ace/Message_Block.h> // for ACE_Message_Block #endif /* !STLSOFT_INCL_ACE_H_MESSAGE_BLOCK */ #ifndef STLSOFT_INCL_ACE_H_OS_MEMORY # define STLSOFT_INCL_ACE_H_OS_MEMORY # include <ace/OS_Memory.h> // for ACE_bad_alloc, ACE_NEW_THROWS_EXCEPTIONS #endif /* !STLSOFT_INCL_ACE_H_OS_MEMORY */ /* ///////////////////////////////////////////////////////////////////////// * Namespace */ #ifndef _ACESTL_NO_NAMESPACE # if defined(_STLSOFT_NO_NAMESPACE) || \ defined(STLSOFT_DOCUMENTATION_SKIP_SECTION) /* There is no stlsoft namespace, so must define ::acestl */ namespace acestl { # else /* Define stlsoft::acestl_project */ namespace stlsoft { namespace acestl_project { # endif /* _STLSOFT_NO_NAMESPACE */ #endif /* !_ACESTL_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////// * Functions */ /** \brief Creates a new ACE_Message_Block instance whose contents are * copied from the given memory. * * \ingroup group__library__memory * * \param p Pointer to the memory to copy into the new message block. May be * NULL, in which case the contents are not explicitly initialised. * \param n Number of bytes to copy into the new message block. If * <code>NULL == p</code>, this is the size of the initialised block. * * Usage is simple: just specify the source (pointer and length), and test * for NULL (allocation failure): * \code ACE_Message_Block *newBlock = acestl::make_copied_Message_Block("Contents", 7); if(NULL == newBlock) { std::cerr << "Allocation failed!\n"; } \endcode * * * \exception - In accordance with the non-throwing nature of * ACE, memory allocation failure is reflected by returning NULL. */ inline ACE_Message_Block *make_copied_Message_Block(char const* p, as_size_t n) { #if defined(ACE_NEW_THROWS_EXCEPTIONS) try { #endif /* ACE_NEW_THROWS_EXCEPTIONS */ ACE_Message_Block *pmb = new ACE_Message_Block(n); if(NULL == pmb) { errno = ENOMEM; } else { pmb->wr_ptr(n); if(NULL != p) { ::memcpy(pmb->base(), p, n); } } return pmb; #if defined(ACE_NEW_THROWS_EXCEPTIONS) } catch(ACE_bad_alloc) // TODO: This should be a reference, surely?? { return NULL; } #endif /* ACE_NEW_THROWS_EXCEPTIONS */ } #if defined(STLSOFT_CF_STATIC_ARRAY_SIZE_DETERMINATION_SUPPORT) template <ss_size_t N> inline ACE_Message_Block *make_copied_Message_Block(const char (&ar)[N]) { return make_copied_Message_Block(&ar[0], N); } #endif /* STLSOFT_CF_STATIC_ARRAY_SIZE_DETERMINATION_SUPPORT */ //////////////////////////////////////////////////////////////////////////// // Unit-testing #ifdef STLSOFT_UNITTEST # include "./unittest/message_block_functions_unittest_.h" #endif /* STLSOFT_UNITTEST */ /* ////////////////////////////////////////////////////////////////////// */ #ifndef _ACESTL_NO_NAMESPACE # if defined(_STLSOFT_NO_NAMESPACE) || \ defined(STLSOFT_DOCUMENTATION_SKIP_SECTION) } // namespace acestl # else } // namespace acestl_project } // namespace stlsoft # endif /* _STLSOFT_NO_NAMESPACE */ #endif /* !_ACESTL_NO_NAMESPACE */ /* ////////////////////////////////////////////////////////////////////// */ #endif /* ACESTL_INCL_ACESTL_MEMORY_HPP_MESSAGE_BLOCK_FUNCTIONS */ /* ///////////////////////////// end of file //////////////////////////// */
33.735751
84
0.664107
wohaaitinciu
89830906549049ec94bd68b5850cbaa453031e56
2,782
cpp
C++
src/Fantasma.cpp
rickylh/Medieval-Game
2e818ab09cdd6158b59133c56cfca8e31d1f8f3a
[ "MIT" ]
null
null
null
src/Fantasma.cpp
rickylh/Medieval-Game
2e818ab09cdd6158b59133c56cfca8e31d1f8f3a
[ "MIT" ]
null
null
null
src/Fantasma.cpp
rickylh/Medieval-Game
2e818ab09cdd6158b59133c56cfca8e31d1f8f3a
[ "MIT" ]
null
null
null
#include "Fantasma.hpp" #include "Fase.hpp" const float Fantasma::TEMPO_FANTASMA (0.2f); Fantasma::Fantasma(sf::Vector2f posicao) : Inimigo(2.0f, false, false) , caveira_de_fogo(1, 2, sf::Vector2f(10.0f,10.0f), this) , _tempo_ataque (0.0f) { setIdTipoObjeto(Codigos::FANTASMA); setPosicao(posicao); carregarAnimacoes(); setArea(sf::Vector2f(35, 35)); caveira_de_fogo.setVelocidade(sf::Vector2f(6.0f, 3.0f)); caveira_de_fogo.setPosicao(posicao); caveira_de_fogo.setIdTipoObjeto(Codigos::BOLA_FOGO); surgindo.atualiza(true, _corpo, TEMPO_FANTASMA); setVelocidade(sf::Vector2f(0, 0));\ setEstatico(true); _esta_nascendo = true; esta_atacando = false; } Fantasma::~Fantasma(){ } void Fantasma::mover(){ if (estaVivo() && !esta_atacando && !_esta_nascendo) { if (getJogadorMaisProximo()->getPosicao().x > getPosicao().x) { setEstaParaDireita(false); } else { setEstaParaDireita(true); } parado.atualiza(estaParaDireita(), _corpo); } else if (_esta_nascendo) { if (surgindo.terminou()) { _esta_nascendo = false; } else { surgindo.atualiza(estaParaDireita(), _corpo); } } EntidadeColidivel::mover(); } void Fantasma::carregarAnimacoes(){ soltando_caveira.setConfig("sprites/fantasma-cast.png", 4, TEMPO_FANTASMA); parado.setConfig("sprites/fantasma.png", 7, TEMPO_FANTASMA); surgindo.setConfig("sprites/fantasma-spawn.png", 6, TEMPO_FANTASMA); _morte.setConfig("sprites/fantasma-death.png", 7, TEMPO_FANTASMA); caveira_de_fogo.setAnimador("sprites/caveira-fogo_att.png", 8, 0.15f); } Projetil* Fantasma::atacar() { if (!estaVivo() || (getJogador1() == NULL && getJogador2() == NULL)) { return NULL; } Projetil* atk = NULL; _tempo_ataque += Fase::getCronometro(); if (estaVivo() && !_esta_nascendo && !esta_atacando) { if (caveira_de_fogo.recarregou()) { esta_atacando = true; soltando_caveira.reiniciar(); } } else if (esta_atacando) { if (soltando_caveira.executou(3) && _tempo_ataque > 1.0f) { _tempo_ataque = 0; atk = new Projetil (caveira_de_fogo); atk->setPosicao(getPosicao()); atk->ativar(); sf::Vector2f vel; vel.x = caveira_de_fogo.getVelocidade().x * direcaoNormalizada(getJogadorMaisProximo()).x; vel.y = caveira_de_fogo.getVelocidade().y * direcaoNormalizada(getJogadorMaisProximo()).y; atk->setVelocidade(vel); caveira_de_fogo.setTempoUltimoArtefatoAtaque(0); } if (!soltando_caveira.terminou()) { soltando_caveira.atualiza(estaParaDireita(), _corpo); } else { soltando_caveira.zerar(); parado.atualiza(estaParaDireita(), _corpo); esta_atacando = false; } } return atk; }
28.387755
94
0.668584
rickylh
898400f485fa53dc1690a4de3cf759bc7b9292f9
704
hpp
C++
state/state.hpp
B777B2056/Design-Pattern-Cpp
cb2cb72d745cc7b529ef5957dc787b7094001165
[ "MIT" ]
null
null
null
state/state.hpp
B777B2056/Design-Pattern-Cpp
cb2cb72d745cc7b529ef5957dc787b7094001165
[ "MIT" ]
null
null
null
state/state.hpp
B777B2056/Design-Pattern-Cpp
cb2cb72d745cc7b529ef5957dc787b7094001165
[ "MIT" ]
null
null
null
#ifndef STATE #define STATE #include <string> #include <memory> #include <iostream> class context; class state { public: virtual ~state() {} virtual void handle(context& c) = 0; }; class concrete_state_A : public state { private: std::string _inner_state; public: concrete_state_A(); virtual void handle(context& c) override; }; class concrete_state_B : public state { private: std::string _inner_state; public: concrete_state_B(); virtual void handle(context& c) override; }; class context { friend class concrete_state_A; friend class concrete_state_B; private: std::shared_ptr<state> _s; public: context(state* s); void request(); }; #endif
13.538462
45
0.691761
B777B2056
8985ea1530bd6c49cbf6bc9acdb1f0b71aba2087
3,039
cpp
C++
src/order_book/order_book.cpp
YileZheng/hft-system
9294d751a6906f42c6c2ebc4f180a1415c6ff12f
[ "MIT" ]
1
2022-03-03T16:15:01.000Z
2022-03-03T16:15:01.000Z
src/order_book/order_book.cpp
YileZheng/hft-system
9294d751a6906f42c6c2ebc4f180a1415c6ff12f
[ "MIT" ]
null
null
null
src/order_book/order_book.cpp
YileZheng/hft-system
9294d751a6906f42c6c2ebc4f180a1415c6ff12f
[ "MIT" ]
1
2022-03-08T00:27:51.000Z
2022-03-08T00:27:51.000Z
#include "order_book.hpp" // make sure there should up to only one empty slot each time execute this function void table_refresh( int ystart, int xstart, price_lookup price_table[LEVELS*STOCKS][2] ){ bool last_empty = False; price_lookup slot; for (int i=0; i < LEVELS; i++){ slot = price_table[ystart+i][xstart]; if (last_empty){ price_table[ystart+i][xstart] = slot; last_empty = true }else{ last_empty = slot.orderCnt == 0; } } } // insert a new data in the table and move the following data 1 step backward void table_insert( int &ystart, int &xstart, price_lookup price_table[LEVELS*STOCKS][2], price_lookup price_new, int &insert_pos // relative position to the start point ){ price_lookup bubble = price_new, bubble_tmp; for (int i=0; i < LEVELS; i++){ if (i >= insert_pos && bubble.orderCnt != 0){ // start from the insert_pos and ended at the last valid slot bubble_tmp = price_table[ystart+i][xstart]; price_table[ystart+i][xstart] = bubble; bubble = bubble_tmp; } } } void order_new( sub_order book[LEVELS*STOCKS][2*CAPACITY], price_lookup price_table[LEVELS*STOCKS][2], order order_info, ap_uint<12> bookIndex, bool bid=true ){ int book_frame_ystart = bookIndex*LEVELS; int book_frame_xstart = bid? 0: CAPACITY; int price_table_frame_xstart = bid? 0: 1; static int heap_head=0, heap_tail=0; // search existing level if (bid) { for (int i=0; i < LEVELS; i++){ price_lookup level_socket = price_table[book_frame_ystart+i][price_table_frame_xstart] level_socket.orderCnt == 0 || level_socket.price == order_info.price } } } void order_change(bool bid=true){ } void order_remove(bool bid=true){ } void suborder_book(){ } void order_book_system( stream<decoded_message> &messages_stream, stream<Time> &incoming_time, stream<metadata> &incoming_meta, stream<Time> &outgoing_time, stream<metadata> &outgoing_meta, stream<order> &top_bid, stream<order> &top_ask, orderID_t &top_bid_id, orderID_t &top_ask_id) { static sub_order book[LEVELS*STOCKS][2*CAPACITY]; static price_lookup price_map[LEVELS*STOCKS][2]; static symbol_t symbol_list[STOCKS]; // string of length 6 decoded_message msg_inbound = messages_stream.read(); order order_inbound; order_inbound.price = msg_inbound.price; order_inbound.size = msg_inbound.size; order_inbound.orderID = msg_inbound.orderID; symbol_t symbol_inbound = msg_inbound.symbol; ap_uint<3> operation = msg_inbound.operation; // symbol location searching ap_uint<12> bookIndex; // stock's correponding index in the order book, up to 4096 stocks for (int i=0; i<STOCKS; i++){ if (symbol_inbound == symbol_list[i]) bookIndex = i; } // Order book modification according to the operation type switch (operation) { case 0: // Change ASK break; case 2: // New ASK break; case 4: // Remove ASK break; case 1: // Change BID break; case 3: // New BID break; case 5: // Remove BID break; default: break; } // Order book access from master }
23.55814
115
0.71438
YileZheng
898864ee7acfbd5a1d4a0d68fccc6563d09be1c4
10,227
cc
C++
build/x86/cpu/o3/O3CPU.py.cc
billionshang/gem5
18cc4294f32315595f865d07d1f33434e92b06b2
[ "BSD-3-Clause" ]
null
null
null
build/x86/cpu/o3/O3CPU.py.cc
billionshang/gem5
18cc4294f32315595f865d07d1f33434e92b06b2
[ "BSD-3-Clause" ]
null
null
null
build/x86/cpu/o3/O3CPU.py.cc
billionshang/gem5
18cc4294f32315595f865d07d1f33434e92b06b2
[ "BSD-3-Clause" ]
null
null
null
#include "sim/init.hh" namespace { const uint8_t data_m5_objects_O3CPU[] = { 120,156,181,152,91,87,27,57,18,128,101,67,204,37,36,16, 8,201,228,222,185,59,23,226,92,38,153,36,147,153,9,24, 72,60,67,128,180,205,230,44,47,62,237,150,140,5,237,110, 167,213,77,96,207,236,83,246,109,31,118,30,246,23,236,47, 217,199,121,220,127,180,91,85,106,181,101,200,100,206,158,51, 193,208,180,62,149,74,85,186,148,74,246,89,246,51,4,127, 47,29,198,84,12,47,28,126,11,44,96,172,91,96,155,5, 86,192,114,145,5,69,214,200,222,134,244,219,16,11,134,89, 119,152,109,14,231,50,71,116,205,48,11,74,172,91,98,155, 165,188,102,4,106,142,48,49,204,218,5,198,75,236,111,140, 125,100,236,207,155,163,140,143,176,122,121,20,186,149,255,133, 159,114,1,222,18,44,182,82,25,240,165,112,87,19,124,220, 214,175,35,240,88,240,148,168,174,111,104,48,6,143,181,71, 213,142,240,119,68,156,140,67,105,81,196,114,23,208,250,134, 111,60,28,198,86,232,225,223,225,77,48,116,12,44,219,44, 162,171,155,67,104,24,88,137,86,65,145,236,4,247,178,98, 137,138,195,166,56,194,196,40,219,30,99,224,14,56,242,177, 200,54,199,13,25,97,124,148,200,81,34,19,140,3,28,39, 114,204,34,71,137,28,183,200,4,145,73,139,28,35,50,101, 52,31,103,124,146,200,9,67,166,24,63,65,100,218,144,105, 198,103,136,204,88,122,78,18,57,105,145,89,34,179,22,57, 69,228,148,69,78,19,57,109,245,254,21,145,175,44,153,51, 68,206,88,228,44,145,179,22,57,71,228,156,165,231,60,145, 243,150,204,5,34,23,12,185,200,248,37,34,23,45,25,135, 200,37,75,207,101,34,142,69,174,16,185,108,145,171,68,174, 16,185,202,196,53,92,114,252,26,193,235,150,242,235,68,110, 88,228,6,145,155,150,170,155,68,202,22,41,19,185,101,90, 221,98,252,54,145,219,150,158,59,68,238,152,86,119,25,159, 35,114,215,34,247,136,204,89,147,88,33,114,207,34,247,137, 84,12,121,192,248,67,34,247,137,60,96,226,33,227,143,136, 60,50,50,95,51,254,152,200,215,134,60,97,252,27,34,143, 45,242,148,200,19,67,224,247,25,145,111,12,121,206,248,183, 68,158,90,228,5,145,103,184,5,54,159,51,241,45,227,223, 177,51,124,131,237,148,88,28,14,137,23,108,251,41,250,118, 18,42,67,150,181,19,208,238,37,181,251,206,90,194,243,68, 190,55,100,129,241,42,145,31,44,139,22,137,188,36,50,207, 248,18,227,203,68,22,12,121,197,248,107,34,85,34,139,140, 215,24,255,145,200,146,37,243,19,145,101,75,102,133,200,43, 75,230,13,145,215,150,204,42,145,154,145,89,99,124,157,200, 143,68,126,98,98,133,241,183,76,188,97,219,32,9,225,206, 165,218,53,51,51,217,216,252,192,118,32,212,212,169,110,157, 241,6,6,147,205,183,204,173,151,255,4,129,201,197,232,164, 38,225,225,247,210,74,244,168,194,49,128,221,235,116,124,12, 112,230,175,138,225,11,37,33,100,213,203,69,120,89,77,74, 24,0,101,87,134,91,101,140,114,58,32,98,52,247,3,165, 9,62,84,21,30,149,110,152,84,58,91,109,85,169,119,188, 88,212,59,34,172,108,137,238,227,185,40,150,91,50,156,83, 137,215,10,196,220,195,251,15,30,207,61,155,123,84,81,177, 95,201,204,161,80,122,175,183,159,28,5,61,93,209,141,226, 253,102,55,226,226,22,234,70,67,88,241,211,150,38,12,44, 69,178,170,45,67,214,136,83,65,37,183,100,236,251,99,141, 60,14,122,98,241,62,149,177,104,250,158,223,17,106,238,255, 180,211,29,53,99,249,165,108,60,129,202,210,94,47,138,147, 102,226,237,136,102,180,43,226,7,125,51,37,245,118,12,30, 181,80,38,210,11,28,63,74,195,68,254,138,24,103,161,138, 142,57,235,208,94,73,52,84,205,210,185,231,195,172,56,73, 228,180,69,226,119,28,46,2,111,159,106,92,17,122,221,67, 53,55,80,191,82,169,168,44,237,9,63,77,68,229,93,44, 19,209,242,252,157,79,41,169,70,221,174,76,14,212,200,81, 99,210,50,193,15,146,39,29,249,18,225,217,28,182,210,118, 91,196,142,146,127,17,142,12,157,214,126,34,148,116,80,166, 156,203,188,79,69,42,114,145,174,244,227,104,46,234,41,167, 39,226,185,164,19,11,143,171,83,3,158,112,237,173,182,239, 230,231,93,25,144,61,53,224,203,64,213,108,110,206,193,154, 137,254,248,146,139,191,215,99,172,237,252,84,143,135,170,250, 243,54,80,53,209,119,183,223,101,95,205,111,117,174,167,5, 215,17,53,232,15,216,103,27,168,135,198,31,20,21,90,72, 87,57,101,25,38,34,14,97,21,66,85,2,235,174,182,244, 206,129,101,190,37,110,41,220,109,139,82,245,188,124,242,105, 49,104,77,186,140,129,173,223,155,102,39,113,160,211,208,79, 100,132,122,55,96,149,59,189,40,10,126,111,88,125,237,190, 54,249,226,128,123,177,136,98,8,156,102,177,245,199,48,27, 50,221,49,130,250,251,212,83,102,169,226,38,35,218,136,189, 158,19,120,137,8,253,125,53,221,95,8,22,150,71,80,248, 46,10,75,232,212,94,214,237,8,122,6,35,63,120,49,87, 100,102,26,74,223,67,255,212,237,223,106,0,127,40,127,64, 252,60,6,162,180,219,2,201,168,237,4,145,199,179,205,33, 194,36,150,66,169,11,3,2,42,137,98,49,40,33,233,64, 185,51,32,214,11,60,95,40,28,40,213,145,237,196,241,56, 7,139,69,27,27,251,152,60,171,26,14,77,39,74,3,14, 131,215,19,33,71,151,157,93,25,5,218,46,144,214,146,130, 147,245,104,153,114,110,104,3,148,3,100,59,85,73,86,148, 191,252,103,136,145,202,65,87,42,218,92,25,170,68,153,238, 113,73,65,143,78,47,22,92,250,80,15,38,146,25,45,20, 220,245,2,201,97,252,185,196,44,158,156,95,241,160,31,10, 66,96,138,86,72,65,151,70,86,157,70,63,8,42,145,56, 181,69,187,238,204,128,65,110,182,100,22,104,94,148,196,83, 65,93,27,28,182,206,190,130,137,9,28,220,3,91,192,98, 177,37,21,108,7,117,112,124,141,96,27,220,76,224,68,134, 245,12,109,250,242,116,53,105,204,187,175,150,26,205,90,125, 158,142,105,47,238,210,255,189,167,79,212,165,79,171,243,125, 171,203,171,3,50,56,136,113,74,123,232,192,252,255,27,231, 223,25,16,62,176,61,204,90,194,61,84,127,211,112,250,130, 180,236,209,254,134,142,186,9,109,25,0,129,200,200,84,214, 70,111,144,94,20,72,95,231,6,235,94,156,72,52,71,232, 96,141,66,43,245,183,14,30,148,168,113,157,68,37,71,235, 174,90,245,168,23,166,28,102,60,151,244,98,216,214,232,243, 108,38,87,59,168,70,93,233,215,124,78,129,49,196,93,91, 56,168,225,170,85,245,25,21,52,115,46,28,192,220,141,90, 48,232,39,178,102,89,96,209,202,72,40,76,187,217,24,209, 32,45,196,94,8,35,180,110,214,53,45,205,165,144,150,99, 163,190,230,188,161,92,202,193,92,42,160,204,4,163,246,152, 201,76,254,165,51,19,72,247,206,192,13,17,147,235,127,224, 181,20,175,215,5,188,156,255,21,46,231,73,17,179,240,159, 25,219,30,194,235,40,100,88,112,11,77,142,224,69,20,158, 31,217,48,84,53,75,236,231,2,166,210,40,54,194,182,71, 49,81,197,247,18,107,142,88,85,99,131,85,26,142,179,172, 56,206,194,73,188,205,190,122,13,83,141,119,88,253,213,64, 189,140,1,116,213,197,233,119,113,165,88,247,120,76,158,230, 227,110,99,101,129,174,244,31,162,120,7,67,0,45,21,177, 39,147,181,112,41,142,33,133,65,13,105,15,247,184,33,51, 40,238,197,225,90,24,236,175,133,43,208,72,115,138,107,184, 143,49,6,47,185,238,154,251,220,201,110,254,78,4,178,78, 150,84,65,88,128,217,2,56,239,190,113,96,179,93,166,36, 73,167,116,104,100,153,206,86,76,178,92,140,244,46,238,65, 23,59,77,48,194,47,123,129,18,148,4,210,183,13,126,246, 213,2,10,201,164,229,226,36,82,129,39,45,242,17,178,187, 38,156,37,195,153,91,148,155,107,83,69,208,166,14,190,64, 10,137,131,6,49,60,243,190,218,75,255,137,218,113,177,179, 194,84,97,170,56,89,40,193,103,162,112,14,62,211,67,71, 10,100,21,57,239,98,211,50,122,79,211,210,108,226,9,218, 108,210,2,110,98,98,159,6,88,164,196,120,191,39,136,251, 123,123,205,14,172,107,24,6,156,61,63,240,148,130,189,209, 137,184,139,67,228,226,162,117,199,205,0,210,206,33,229,27, 161,146,91,16,14,168,224,65,168,218,149,137,222,42,148,154, 83,2,75,99,88,221,247,3,161,18,28,44,157,119,53,34, 10,47,139,120,140,19,214,185,209,0,198,204,66,138,15,135, 68,117,150,48,128,177,75,58,49,222,225,169,79,45,169,168, 67,127,29,214,20,93,28,136,189,197,88,74,104,198,234,87, 103,105,90,219,148,233,216,134,51,86,207,54,159,54,122,7, 241,209,220,85,109,82,174,83,167,52,135,117,30,228,102,156, 108,126,52,55,184,175,212,180,135,172,173,111,189,241,42,135, 168,81,98,226,213,136,178,204,75,115,92,44,60,75,240,180, 206,113,35,169,139,56,255,31,90,250,29,103,114,121,99,29, 18,57,106,183,40,218,94,26,36,25,193,202,118,74,175,185, 175,58,132,30,54,11,34,114,223,33,237,128,238,1,203,138, 242,183,126,25,83,180,21,157,161,145,18,61,216,22,68,33, 76,206,160,183,254,76,235,220,203,32,92,192,43,111,151,244, 169,72,165,122,94,66,157,112,76,45,138,30,237,182,58,230, 79,180,61,22,192,23,29,39,142,105,17,170,199,112,165,18, 220,137,148,154,52,33,11,105,194,226,246,226,38,220,101,100, 164,247,194,202,114,189,65,29,99,161,94,175,233,194,136,62, 67,224,152,81,100,36,188,175,67,34,80,11,19,87,108,105, 67,50,180,140,89,6,65,60,32,155,92,143,244,170,174,172, 86,177,134,226,27,217,89,135,56,68,38,134,118,61,29,236, 64,106,185,163,153,8,12,190,33,168,92,117,81,175,73,11, 76,86,128,179,89,79,240,160,36,75,65,136,36,178,195,112, 66,35,24,146,12,96,188,4,55,104,227,233,138,252,192,213, 115,218,77,106,70,246,184,41,247,69,50,125,96,89,38,51, 153,131,190,80,198,244,154,178,228,244,49,156,159,194,164,172, 17,165,49,46,181,48,89,88,39,95,32,102,65,193,197,179, 157,86,120,43,111,68,83,20,10,200,105,224,204,118,47,13, 132,243,63,52,166,211,247,64,215,81,225,47,240,192,240,93, 42,78,14,227,103,186,8,159,2,124,244,19,2,122,254,94, 180,254,155,247,194,108,254,150,201,101,165,177,236,147,183,27, 42,21,166,70,166,250,172,112,224,83,156,160,186,153,194,88, 113,181,60,102,198,166,251,248,30,44,56,25,138,108,141,141, 105,214,195,176,175,104,184,176,20,71,123,251,46,157,58,47, 243,51,182,205,178,175,187,190,208,16,82,231,47,244,25,246, 61,94,21,232,130,58,85,24,135,207,148,254,43,254,15,190, 234,75,146, }; EmbeddedPython embedded_m5_objects_O3CPU( "m5/objects/O3CPU.py", "/mnt/hgfs/ShareShen/gem5-origin-stable-2015-9-3/src/cpu/o3/O3CPU.py", "m5.objects.O3CPU", data_m5_objects_O3CPU, 2563, 6391); } // anonymous namespace
57.455056
74
0.661093
billionshang
89897161239b2d66e3f45b0c4ab86ed976fa6811
14,514
cpp
C++
Source/Server/CritterManager.cpp
Marsel24/fonline
83c10c315ea6f2c5ce6a83a608f287d9c619fa9d
[ "MIT" ]
null
null
null
Source/Server/CritterManager.cpp
Marsel24/fonline
83c10c315ea6f2c5ce6a83a608f287d9c619fa9d
[ "MIT" ]
null
null
null
Source/Server/CritterManager.cpp
Marsel24/fonline
83c10c315ea6f2c5ce6a83a608f287d9c619fa9d
[ "MIT" ]
null
null
null
// __________ ___ ______ _ // / ____/ __ \____ / (_)___ ___ / ____/___ ____ _(_)___ ___ // / /_ / / / / __ \/ / / __ \/ _ \ / __/ / __ \/ __ `/ / __ \/ _ \ // / __/ / /_/ / / / / / / / / / __/ / /___/ / / / /_/ / / / / / __/ // /_/ \____/_/ /_/_/_/_/ /_/\___/ /_____/_/ /_/\__, /_/_/ /_/\___/ // /____/ // FOnline Engine // https://fonline.ru // https://github.com/cvet/fonline // // MIT License // // Copyright (c) 2006 - present, Anton Tsvetinskiy aka cvet <cvet@tut.by> // // 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 "CritterManager.h" #include "EntityManager.h" #include "GenericUtils.h" #include "ItemManager.h" #include "Log.h" #include "MapManager.h" #include "PropertiesSerializator.h" #include "ProtoManager.h" #include "Settings.h" #include "StringUtils.h" #include "Testing.h" CritterManager::CritterManager(ServerSettings& sett, ProtoManager& proto_mngr, EntityManager& entity_mngr, MapManager& map_mngr, ItemManager& item_mngr, ServerScriptSystem& script_sys, GameTimer& game_time) : settings {sett}, geomHelper(settings), protoMngr {proto_mngr}, entityMngr {entity_mngr}, mapMngr {map_mngr}, itemMngr {item_mngr}, scriptSys {script_sys}, gameTime {game_time} { } void CritterManager::AddItemToCritter(Critter* cr, Item*& item, bool send) { RUNTIME_ASSERT(cr); RUNTIME_ASSERT(item); // Add if (item->GetStackable()) { Item* item_already = cr->GetItemByPid(item->GetProtoId()); if (item_already) { uint count = item->GetCount(); itemMngr.DeleteItem(item); item = item_already; item->ChangeCount(count); return; } } item->SetSortValue(cr->invItems); cr->SetItem(item); // Send if (send) { cr->Send_AddItem(item); if (item->GetCritSlot()) cr->SendAA_MoveItem(item, ACTION_REFRESH, 0); } // Change item scriptSys.CritterMoveItemEvent(cr, item, -1); } void CritterManager::EraseItemFromCritter(Critter* cr, Item* item, bool send) { RUNTIME_ASSERT(cr); RUNTIME_ASSERT(item); auto it = std::find(cr->invItems.begin(), cr->invItems.end(), item); RUNTIME_ASSERT(it != cr->invItems.end()); cr->invItems.erase(it); item->SetAccessory(ITEM_ACCESSORY_NONE); if (send) cr->Send_EraseItem(item); if (item->GetCritSlot()) cr->SendAA_MoveItem(item, ACTION_REFRESH, 0); scriptSys.CritterMoveItemEvent(cr, item, item->GetCritSlot()); } Npc* CritterManager::CreateNpc( hash proto_id, Properties* props, Map* map, ushort hx, ushort hy, uchar dir, bool accuracy) { RUNTIME_ASSERT(map); RUNTIME_ASSERT(proto_id); RUNTIME_ASSERT(hx < map->GetWidth()); RUNTIME_ASSERT(hy < map->GetHeight()); ProtoCritter* proto = protoMngr.GetProtoCritter(proto_id); RUNTIME_ASSERT(proto); uint multihex; if (!props) multihex = proto->GetMultihex(); else multihex = props->GetValue<uint>(Critter::PropertyMultihex); if (!map->IsHexesPassed(hx, hy, multihex)) { if (accuracy) return nullptr; short hx_ = hx; short hy_ = hy; short *sx, *sy; geomHelper.GetHexOffsets(hx & 1, sx, sy); // Find in 2 hex radius int pos = -1; while (true) { pos++; if (pos >= 18) return nullptr; if (hx_ + sx[pos] < 0 || hx_ + sx[pos] >= map->GetWidth()) continue; if (hy_ + sy[pos] < 0 || hy_ + sy[pos] >= map->GetHeight()) continue; if (!map->IsHexesPassed(hx_ + sx[pos], hy_ + sy[pos], multihex)) continue; break; } hx_ += sx[pos]; hy_ += sy[pos]; hx = hx_; hy = hy_; } Npc* npc = new Npc(0, proto, settings, scriptSys, gameTime); if (props) npc->Props = *props; entityMngr.RegisterEntity(npc); npc->SetCond(COND_LIFE); Location* loc = map->GetLocation(); RUNTIME_ASSERT(loc); if (dir >= settings.MapDirCount) dir = GenericUtils::Random(0, settings.MapDirCount - 1); npc->SetWorldX(loc ? loc->GetWorldX() : 0); npc->SetWorldY(loc ? loc->GetWorldY() : 0); npc->SetHomeMapId(map->GetId()); npc->SetHomeHexX(hx); npc->SetHomeHexY(hy); npc->SetHomeDir(dir); npc->SetHexX(hx); npc->SetHexY(hy); bool can = mapMngr.CanAddCrToMap(npc, map, hx, hy, 0); RUNTIME_ASSERT(can); mapMngr.AddCrToMap(npc, map, hx, hy, dir, 0); scriptSys.CritterInitEvent(npc, true); npc->SetScript(nullptr, true); mapMngr.ProcessVisibleCritters(npc); mapMngr.ProcessVisibleItems(npc); return npc; } bool CritterManager::RestoreNpc(uint id, hash proto_id, const DataBase::Document& doc) { ProtoCritter* proto = protoMngr.GetProtoCritter(proto_id); if (!proto) { WriteLog("Proto critter '{}' is not loaded.\n", _str().parseHash(proto_id)); return false; } Npc* npc = new Npc(id, proto, settings, scriptSys, gameTime); if (!PropertiesSerializator::LoadFromDbDocument(&npc->Props, doc, scriptSys)) { WriteLog("Fail to restore properties for critter '{}' ({}).\n", _str().parseHash(proto_id), id); npc->Release(); return false; } entityMngr.RegisterEntity(npc); return true; } void CritterManager::DeleteNpc(Critter* cr) { RUNTIME_ASSERT(cr->IsNpc()); // Redundant calls if (cr->IsDestroying || cr->IsDestroyed) return; cr->IsDestroying = true; // Finish event scriptSys.CritterFinishEvent(cr); // Tear off from environment cr->LockMapTransfers++; while (cr->GetMapId() || cr->GlobalMapGroup || cr->RealCountItems()) { // Delete inventory DeleteInventory(cr); // Delete from maps Map* map = mapMngr.GetMap(cr->GetMapId()); if (map) mapMngr.EraseCrFromMap(cr, map); else if (cr->GlobalMapGroup) mapMngr.EraseCrFromMap(cr, nullptr); else if (cr->GetMapId()) cr->SetMapId(0); } cr->LockMapTransfers--; // Erase from main collection entityMngr.UnregisterEntity(cr); // Invalidate for use cr->IsDestroyed = true; cr->Release(); } void CritterManager::DeleteInventory(Critter* cr) { while (!cr->invItems.empty()) itemMngr.DeleteItem(*cr->invItems.begin()); } void CritterManager::GetCritters(CritterVec& critters) { CritterVec all_critters; entityMngr.GetCritters(all_critters); CritterVec find_critters; find_critters.reserve(all_critters.size()); for (auto it = all_critters.begin(), end = all_critters.end(); it != end; ++it) find_critters.push_back(*it); critters = find_critters; } void CritterManager::GetNpcs(NpcVec& npcs) { CritterVec all_critters; entityMngr.GetCritters(all_critters); NpcVec find_npcs; find_npcs.reserve(all_critters.size()); for (auto it = all_critters.begin(), end = all_critters.end(); it != end; ++it) { Critter* cr = *it; if (cr->IsNpc()) find_npcs.push_back((Npc*)cr); } npcs = find_npcs; } void CritterManager::GetClients(ClientVec& players, bool on_global_map /* = false */) { CritterVec all_critters; entityMngr.GetCritters(all_critters); ClientVec find_players; find_players.reserve(all_critters.size()); for (auto it = all_critters.begin(), end = all_critters.end(); it != end; ++it) { Critter* cr = *it; if (cr->IsPlayer() && (!on_global_map || !cr->GetMapId())) find_players.push_back((Client*)cr); } players = find_players; } void CritterManager::GetGlobalMapCritters(ushort wx, ushort wy, uint radius, int find_type, CritterVec& critters) { CritterVec all_critters; entityMngr.GetCritters(all_critters); CritterVec find_critters; find_critters.reserve(all_critters.size()); for (auto it = all_critters.begin(), end = all_critters.end(); it != end; ++it) { Critter* cr = *it; if (!cr->GetMapId() && GenericUtils::DistSqrt((int)cr->GetWorldX(), (int)cr->GetWorldY(), wx, wy) <= radius && cr->CheckFind(find_type)) find_critters.push_back(cr); } critters = find_critters; } Critter* CritterManager::GetCritter(uint crid) { return entityMngr.GetCritter(crid); } Client* CritterManager::GetPlayer(uint crid) { if (!IS_CLIENT_ID(crid)) return nullptr; return (Client*)entityMngr.GetEntity(crid, EntityType::Client); } Client* CritterManager::GetPlayer(const char* name) { EntityVec entities; entityMngr.GetEntities(EntityType::Client, entities); Client* cl = nullptr; for (auto it = entities.begin(); it != entities.end(); ++it) { Client* cl_ = (Client*)*it; if (_str(name).compareIgnoreCaseUtf8(cl_->GetName())) { cl = cl_; break; } } return cl; } Npc* CritterManager::GetNpc(uint crid) { if (IS_CLIENT_ID(crid)) return nullptr; return (Npc*)entityMngr.GetEntity(crid, EntityType::Npc); } Item* CritterManager::GetItemByPidInvPriority(Critter* cr, hash item_pid) { ProtoItem* proto_item = protoMngr.GetProtoItem(item_pid); if (!proto_item) return nullptr; if (proto_item->GetStackable()) { for (auto item : cr->invItems) if (item->GetProtoId() == item_pid) return item; } else { Item* another_slot = nullptr; for (auto item : cr->invItems) { if (item->GetProtoId() == item_pid) { if (!item->GetCritSlot()) return item; another_slot = item; } } return another_slot; } return nullptr; } void CritterManager::ProcessTalk(Client* cl, bool force) { if (!force && gameTime.GameTick() < cl->talkNextTick) return; cl->talkNextTick = gameTime.GameTick() + PROCESS_TALK_TICK; if (cl->Talk.TalkType == TALK_NONE) return; // Check time of talk if (cl->Talk.TalkTime && gameTime.GameTick() - cl->Talk.StartTick > cl->Talk.TalkTime) { CloseTalk(cl); return; } // Check npc Npc* npc = nullptr; if (cl->Talk.TalkType == TALK_WITH_NPC) { npc = GetNpc(cl->Talk.TalkNpc); if (!npc) { CloseTalk(cl); return; } if (!npc->IsLife()) { cl->Send_TextMsg(cl, STR_DIALOG_NPC_NOT_LIFE, SAY_NETMSG, TEXTMSG_GAME); CloseTalk(cl); return; } // Todo: don't remeber but need check (IsPlaneNoTalk) } // Check distance if (!cl->Talk.IgnoreDistance) { uint map_id = 0; ushort hx = 0, hy = 0; uint talk_distance = 0; if (cl->Talk.TalkType == TALK_WITH_NPC) { map_id = npc->GetMapId(); hx = npc->GetHexX(); hy = npc->GetHexY(); talk_distance = npc->GetTalkDistance(); talk_distance = (talk_distance ? talk_distance : settings.TalkDistance) + cl->GetMultihex(); } else if (cl->Talk.TalkType == TALK_WITH_HEX) { map_id = cl->Talk.TalkHexMap; hx = cl->Talk.TalkHexX; hy = cl->Talk.TalkHexY; talk_distance = settings.TalkDistance + cl->GetMultihex(); } if (cl->GetMapId() != map_id || !geomHelper.CheckDist(cl->GetHexX(), cl->GetHexY(), hx, hy, talk_distance)) { cl->Send_TextMsg(cl, STR_DIALOG_DIST_TOO_LONG, SAY_NETMSG, TEXTMSG_GAME); CloseTalk(cl); } } } void CritterManager::CloseTalk(Client* cl) { if (cl->Talk.TalkType != TALK_NONE) { Npc* npc = nullptr; if (cl->Talk.TalkType == TALK_WITH_NPC) { cl->Talk.TalkType = TALK_NONE; npc = GetNpc(cl->Talk.TalkNpc); if (npc) { if (cl->Talk.Barter) scriptSys.CritterBarterEvent(cl, npc, false, npc->GetBarterPlayers()); scriptSys.CritterTalkEvent(cl, npc, false, npc->GetTalkedPlayers()); } } if (cl->Talk.CurDialog.DlgScriptFunc) { cl->Talk.Locked = true; cl->Talk.CurDialog.DlgScriptFunc(cl, npc); cl->Talk.Locked = false; } } cl->Talk = Talking(); cl->Send_Talk(); } uint CritterManager::PlayersInGame() { return entityMngr.GetEntitiesCount(EntityType::Client); } uint CritterManager::NpcInGame() { return entityMngr.GetEntitiesCount(EntityType::Npc); } uint CritterManager::CrittersInGame() { return PlayersInGame() + NpcInGame(); }
28.854871
119
0.579096
Marsel24
898997678197f9d0d9bcaa468b0dc51d11207bb2
488
cpp
C++
70. Climbing Stairs/Solution.cpp
Ainevsia/Leetcode-Rust
c4f16d72f3c0d0524478b6bb90fefae9607d88be
[ "BSD-2-Clause" ]
15
2020-02-07T13:04:05.000Z
2022-03-02T14:33:21.000Z
70. Climbing Stairs/Solution.cpp
Ainevsia/Leetcode-Rust
c4f16d72f3c0d0524478b6bb90fefae9607d88be
[ "BSD-2-Clause" ]
null
null
null
70. Climbing Stairs/Solution.cpp
Ainevsia/Leetcode-Rust
c4f16d72f3c0d0524478b6bb90fefae9607d88be
[ "BSD-2-Clause" ]
3
2020-04-02T15:36:57.000Z
2021-09-14T14:13:44.000Z
#include <string> #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include <tuple> #include <deque> #include <unordered_map> #include <cmath> using namespace std; class Solution { public: int climbStairs(int n) { vector <int> fib (n+1, 1); for (int i=2; i<=n;i++) { fib[i] = fib[i-1] + fib[i-2]; } // for (int i: fib) cout << i; return fib[n]; } }; int main() { Solution a; return 0; }
16.266667
41
0.55123
Ainevsia
898bb679898fbf805691c6ef80e2e18838310e47
16,956
cc
C++
src/kafka2hdfs/log_format_impl.cc
Lanceolata/log2hdfs
1ea1b572567dbe1e65f4134849b1970f21baf741
[ "MIT" ]
null
null
null
src/kafka2hdfs/log_format_impl.cc
Lanceolata/log2hdfs
1ea1b572567dbe1e65f4134849b1970f21baf741
[ "MIT" ]
null
null
null
src/kafka2hdfs/log_format_impl.cc
Lanceolata/log2hdfs
1ea1b572567dbe1e65f4134849b1970f21baf741
[ "MIT" ]
null
null
null
// Copyright (c) 2017 Lanceolata #include "kafka2hdfs/log_format_impl.h" #include <string.h> #include "util/system_utils.h" namespace log2hdfs { namespace { bool ExtractString(const char* begin, const char* end, const char delimeter, int num, const char** rbegin, const char** rend) { if (!begin || !end || !rbegin || !rend) return false; const char* next = NULL; const char* temp = begin; int n = 0; while (temp != NULL && temp < end) { next = strchr(temp, delimeter); if (n == num) break; ++n; if (next) { temp = next + 1; } else { temp = NULL; } } if (temp == NULL || temp >= end) return false; *rbegin = temp; if (next == NULL) { *rend = end; } else { *rend = next; } return true; } } // namespace // ------------------------------------------------------------------ // LogFormat Optional<LogFormat::Type> LogFormat::ParseType(const std::string &type) { if (type == "v6") { return Optional<LogFormat::Type>(kV6); } else if (type == "v6device") { return Optional<LogFormat::Type>(kV6Device); } else if (type == "ef") { return Optional<LogFormat::Type>(kEf); } else if (type == "efdevice") { return Optional<LogFormat::Type>(kEfDevice); } else if (type == "report") { return Optional<LogFormat::Type>(kReport); } else if (type == "efic") { return Optional<LogFormat::Type>(kEfIc); } else if (type == "eficaws") { return Optional<LogFormat::Type>(kEfIcAws); } else if (type == "efimp") { return Optional<LogFormat::Type>(kEfImp); } else if (type == "efstats") { return Optional<LogFormat::Type>(kEfStats); } else if (type == "pub") { return Optional<LogFormat::Type>(kPub); } else if (type == "prebid") { return Optional<LogFormat::Type>(kPreBid); } else { return Optional<LogFormat::Type>::Invalid(); } } std::unique_ptr<LogFormat> LogFormat::Init(LogFormat::Type type) { switch (type) { case kV6: return V6LogFormat::Init(); case kV6Device: return V6DeviceLogFormat::Init(); case kEf: return EfLogFormat::Init(); case kEfDevice: return EfDeviceLogFormat::Init(); case kReport: return ReportLogFormat::Init(); case kEfIc: return EfIcLogFormat::Init(); case kEfIcAws: return EfIcAwsLogFormat::Init(); case kEfImp: return EfImpLogFormat::Init(); case kEfStats: return EfStatsLogFormat::Init(); case kPub: return PubLogFormat::Init(); case kPreBid: return PreBidLogFormat::Init(); default: return nullptr; } } // ------------------------------------------------------------------ // V6LogFormat std::unique_ptr<V6LogFormat> V6LogFormat::Init() { return std::unique_ptr<V6LogFormat>(new V6LogFormat()); } #define V6_SECTION_DELIMITER '\u0001' #define V6_OPTION_DELIMITER '\u0002' #define TIME_SECTION_INDEX 1 #define TIME_OPTION_INDEX 10 #define DEVICE_SECTION_INDEX 6 #define DEVICE_OPTION_INDEX 0 bool V6LogFormat::ExtractKeyAndTs(const char* payload, size_t len, std::string* key, time_t* ts) const { if (!payload || !key || !ts || len <= 0) return false; const char *sbegin, *send; if (!ExtractString(payload, payload + len, V6_SECTION_DELIMITER, TIME_SECTION_INDEX, &sbegin, &send)) { return false; } const char *obegin, *oend; if (!ExtractString(sbegin, send, V6_OPTION_DELIMITER, TIME_OPTION_INDEX, &obegin, &oend)) { return false; } time_t temp = atol(obegin) / 1000; if (temp <= 0) return false; *ts = temp; *key = ""; return true; } bool V6LogFormat::ParseKey(const std::string& key, std::map<char, std::string>* m) const { if (!m) return false; m->clear(); return true; } // ------------------------------------------------------------------ // V6DeviceLogFormat std::unique_ptr<V6DeviceLogFormat> V6DeviceLogFormat::Init() { return std::unique_ptr<V6DeviceLogFormat>(new V6DeviceLogFormat()); } bool V6DeviceLogFormat::ExtractKeyAndTs(const char* payload, size_t len, std::string* key, time_t* ts) const { if (!payload || !key || !ts || len <= 0) return false; const char *sbegin, *send; if (!ExtractString(payload, payload + len, V6_SECTION_DELIMITER, TIME_SECTION_INDEX, &sbegin, &send)) { return false; } const char *obegin, *oend; if (!ExtractString(sbegin, send, V6_OPTION_DELIMITER, TIME_OPTION_INDEX, &obegin, &oend)) { return false; } time_t temp = atol(obegin) / 1000; if (temp <= 0) return false; *ts = temp; // extract device if (!ExtractString(payload, payload + len, V6_SECTION_DELIMITER, DEVICE_SECTION_INDEX, &sbegin, &send)) { return false; } if (!ExtractString(sbegin, send, V6_OPTION_DELIMITER, DEVICE_OPTION_INDEX, &obegin, &oend)) { return false; } if (obegin == oend) { key->assign("pc"); } else { if (strncmp(obegin, "pc", 2) == 0 || strncmp(obegin, "na", 2) == 0) { key->assign("pc"); } else { key->assign("mobile"); } } return true; } bool V6DeviceLogFormat::ParseKey(const std::string& key, std::map<char, std::string>* m) const { if (!m || key.empty()) return false; m->clear(); if (key == "pc" || key == "mobile") { (*m)['D'] = key; } else { return false; } return true; } // ------------------------------------------------------------------ // EfLogFormat std::unique_ptr<EfLogFormat> EfLogFormat::Init() { return std::unique_ptr<EfLogFormat>(new EfLogFormat()); } #define EF_DELIMITER '\t' #define TIME_INDEX 6 #define DEVICE_INDEX 41 #define TIME_FORMAT "%Y%m%d%H%M" #define TIME_LENGTH 12 bool EfLogFormat::ExtractKeyAndTs(const char* payload, size_t len, std::string* key, time_t* ts) const { if (!payload || !key || !ts || len <= 0) return false; const char *begin, *end; if (!ExtractString(payload, payload + len, EF_DELIMITER, TIME_INDEX, &begin, &end)) { return false; } std::string time_str(begin, TIME_LENGTH); time_t time_stamp = StrToTs(time_str, TIME_FORMAT); if (time_stamp <= 0) { return false; } *ts = time_stamp; *key = ""; return true; } bool EfLogFormat::ParseKey(const std::string& key, std::map<char, std::string>* m) const { if (!m) return false; m->clear(); return true; } // ------------------------------------------------------------------ // EfDeviceLogFormat std::unique_ptr<EfDeviceLogFormat> EfDeviceLogFormat::Init() { return std::unique_ptr<EfDeviceLogFormat>(new EfDeviceLogFormat()); } bool EfDeviceLogFormat::ExtractKeyAndTs(const char* payload, size_t len, std::string* key, time_t* ts) const { if (!payload || !key || !ts || len <= 0) return false; const char *begin, *end; if (!ExtractString(payload, payload + len, EF_DELIMITER, TIME_INDEX, &begin, &end)) { return false; } std::string time_str(begin, TIME_LENGTH); time_t time_stamp = StrToTs(time_str, TIME_FORMAT); if (time_stamp <= 0) { return false; } *ts = time_stamp; if (!ExtractString(payload, payload + len, EF_DELIMITER, DEVICE_INDEX, &begin, &end)) { return false; } if (begin == end) { key->assign("pc"); } else { if (strncmp(begin, "General", 2) == 0 || strncmp(begin, "Na", 2) == 0) { key->assign("pc"); } else { key->assign("mobile"); } } return true; } bool EfDeviceLogFormat::ParseKey(const std::string& key, std::map<char, std::string>* m) const { if (!m || key.empty()) return false; m->clear(); if (key == "pc" || key == "mobile") { (*m)['D'] = key; } else { return false; } return true; } // ------------------------------------------------------------------ // ReportLogFormat std::unique_ptr<ReportLogFormat> ReportLogFormat::Init() { return std::unique_ptr<ReportLogFormat>(new ReportLogFormat()); } bool ReportLogFormat::ExtractKeyAndTs(const char* payload, size_t len, std::string* key, time_t* ts) const { if (!payload || !key || !ts || len <= 0) return false; std::string time_str(payload, TIME_LENGTH); time_t time_stamp = StrToTs(time_str, TIME_FORMAT); if (time_stamp <= 0) { return false; } *ts = time_stamp; return true; } bool ReportLogFormat::ParseKey(const std::string& key, std::map<char, std::string>* m) const { if (!m) return false; m->clear(); return true; } // ------------------------------------------------------------------ // EfIcLogFormat std::unique_ptr<EfIcLogFormat> EfIcLogFormat::Init() { return std::unique_ptr<EfIcLogFormat>(new EfIcLogFormat()); } #define ACTION_INDEX 2 bool EfIcLogFormat::ExtractKeyAndTs(const char* payload, size_t len, std::string* key, time_t* ts) const { if (!payload || !key || !ts || len <= 0) return false; const char *begin, *end; if (!ExtractString(payload, payload + len, EF_DELIMITER, TIME_INDEX, &begin, &end)) { return false; } std::string time_str(begin, TIME_LENGTH); time_t time_stamp = StrToTs(time_str, TIME_FORMAT); if (time_stamp <= 0) { return false; } *ts = time_stamp; if (!ExtractString(payload, payload + len, EF_DELIMITER, ACTION_INDEX, &begin, &end)) { return false; } if (begin == end) { return false; } int type = atoi(begin); if (type == 2) { key->assign("click"); return true; } else if (type != 1) { return false; } if (!ExtractString(payload, payload + len, EF_DELIMITER, DEVICE_INDEX, &begin, &end)) { return false; } std::string device; if (begin == end) { key->assign("imp_pc"); } else { if (strncmp(begin, "General", 2) == 0 || strncmp(begin, "Na", 2) == 0) { key->assign("imp_pc"); } else { key->assign("imp_mobile"); } } return true; } bool EfIcLogFormat::ParseKey(const std::string& key, std::map<char, std::string>* m) const { if (key.empty() || !m) return false; if (key == "click") { (*m)['k'] = "click"; } else if (key == "imp_pc") { (*m)['k'] = "imp_pc"; } else if (key == "imp_mobile") { (*m)['k'] = "imp_mobile"; } else { return false; } return true; } // ------------------------------------------------------------------ // EfIcAwsLogFormat std::unique_ptr<EfIcAwsLogFormat> EfIcAwsLogFormat::Init() { return std::unique_ptr<EfIcAwsLogFormat>(new EfIcAwsLogFormat()); } #define ACTION_INDEX 2 bool EfIcAwsLogFormat::ExtractKeyAndTs(const char* payload, size_t len, std::string* key, time_t* ts) const { if (!payload || !key || !ts || len <= 0) return false; const char *begin, *end; if (!ExtractString(payload, payload + len, EF_DELIMITER, TIME_INDEX, &begin, &end)) { return false; } std::string time_str(begin, TIME_LENGTH); time_t time_stamp = StrToTs(time_str, TIME_FORMAT); if (time_stamp <= 0) { return false; } *ts = time_stamp; if (!ExtractString(payload, payload + len, EF_DELIMITER, ACTION_INDEX, &begin, &end)) { return false; } if (begin == end) { return false; } int type = atoi(begin); if (type == 2) { key->assign("click"); return true; } else if (type != 1) { return false; } if (!ExtractString(payload, payload + len, EF_DELIMITER, DEVICE_INDEX, &begin, &end)) { return false; } std::string device; if (begin == end) { key->assign("imp_pc"); } else { if (strncmp(begin, "General", 2) == 0 || strncmp(begin, "Na", 2) == 0) { key->assign("imp_pc"); } else { key->assign("imp_mobile"); } } return true; } bool EfIcAwsLogFormat::ParseKey(const std::string& key, std::map<char, std::string>* m) const { if (key.empty() || !m) return false; if (key == "click") { (*m)['D'] = ""; (*m)['A'] = "click"; } else if (key == "imp_pc") { (*m)['D'] = "pc"; (*m)['A'] = "imp"; } else if (key == "imp_mobile") { (*m)['D'] = "mobile"; (*m)['A'] = "imp"; } else { return false; } return true; } // ------------------------------------------------------------------ // EfImpLogFormat std::unique_ptr<EfImpLogFormat> EfImpLogFormat::Init() { return std::unique_ptr<EfImpLogFormat>(new EfImpLogFormat()); } bool EfImpLogFormat::ExtractKeyAndTs(const char* payload, size_t len, std::string* key, time_t* ts) const { if (!payload || !key || !ts || len <= 0) return false; const char *begin, *end; if (!ExtractString(payload, payload + len, EF_DELIMITER, TIME_INDEX, &begin, &end)) { return false; } std::string time_str(begin, TIME_LENGTH); time_t time_stamp = StrToTs(time_str, TIME_FORMAT); if (time_stamp <= 0) { return false; } *ts = time_stamp; if (!ExtractString(payload, payload + len, EF_DELIMITER, ACTION_INDEX, &begin, &end)) { return false; } if (begin == end) { return false; } int type = atoi(begin); if (type == 1) { key->assign("imp"); } else if (type == 2) { key->assign("click"); } else { return false; } return true; } bool EfImpLogFormat::ParseKey(const std::string& key, std::map<char, std::string>* m) const { if (key.empty() || !m) return false; if (key == "click") { (*m)['A'] = "click"; } else if (key == "imp") { (*m)['A'] = "imp"; } else { return false; } return true; } // ------------------------------------------------------------------ // EfStatsLogFormat std::unique_ptr<EfStatsLogFormat> EfStatsLogFormat::Init() { return std::unique_ptr<EfStatsLogFormat>(new EfStatsLogFormat()); } bool EfStatsLogFormat::ExtractKeyAndTs(const char* payload, size_t len, std::string* key, time_t* ts) const { if (!payload || !key || !ts || len <= 0) return false; const char *begin, *end; if (!ExtractString(payload, payload + len, EF_DELIMITER, TIME_INDEX, &begin, &end)) { return false; } std::string time_str(begin, TIME_LENGTH); time_t time_stamp = StrToTs(time_str, TIME_FORMAT); if (time_stamp <= 0) { return false; } *ts = time_stamp; if (!ExtractString(payload, payload + len, EF_DELIMITER, ACTION_INDEX, &begin, &end)) { return false; } if (begin == end) { return false; } int type = atoi(begin); if (type == 11) { key->assign("imp"); } else if (type == 12) { key->assign("click"); } else { return false; } return true; } bool EfStatsLogFormat::ParseKey(const std::string& key, std::map<char, std::string>* m) const { if (key.empty() || !m) return false; if (key == "click") { (*m)['A'] = "click"; (*m)['p'] = "click"; } else if (key == "imp") { (*m)['A'] = "imp"; (*m)['p'] = "impression"; } else { return false; } return true; } // ------------------------------------------------------------------ // EfPubLogFormat std::unique_ptr<PubLogFormat> PubLogFormat::Init() { return std::unique_ptr<PubLogFormat>(new PubLogFormat()); } #define TIME_INDEX_PUB 11 bool PubLogFormat::ExtractKeyAndTs(const char* payload, size_t len, std::string* key, time_t* ts) const { if (!payload || !key || !ts || len <= 0) return false; const char *begin, *end; if (!ExtractString(payload, payload + len, EF_DELIMITER, TIME_INDEX_PUB, &begin, &end)) { return false; } std::string time_str(begin, TIME_LENGTH); time_t time_stamp = StrToTs(time_str, TIME_FORMAT); if (time_stamp <= 0) { return false; } *ts = time_stamp; *key = ""; return true; } bool PubLogFormat::ParseKey(const std::string& key, std::map<char, std::string>* m) const { if (!m) return false; m->clear(); return true; } // ------------------------------------------------------------------ // PreBidLogFormat std::unique_ptr<PreBidLogFormat> PreBidLogFormat::Init() { return std::unique_ptr<PreBidLogFormat>(new PreBidLogFormat()); } #define PREBID_DELIMITER '\t' #define PREBID_TIME_INDEX 1 #define PREBID_TIME_FORMAT "%Y%m%d%H%M" #define PREBID_TIME_LENGTH 12 bool PreBidLogFormat::ExtractKeyAndTs(const char* payload, size_t len, std::string* key, time_t* ts) const { if (!payload || !key || !ts || len <= 0) return false; const char *begin, *end; if (!ExtractString(payload, payload + len, PREBID_DELIMITER, PREBID_TIME_INDEX, &begin, &end)) { return false; } std::string time_str(begin, PREBID_TIME_LENGTH); time_t time_stamp = StrToTs(time_str, PREBID_TIME_FORMAT); if (time_stamp <= 0) { return false; } *ts = time_stamp; *key = ""; return true; } bool PreBidLogFormat::ParseKey(const std::string& key, std::map<char, std::string>* m) const { if (!m) return false; m->clear(); return true; } } // namespace log2hdfs
23.006784
76
0.579146
Lanceolata
898e34a3888c430d0f9a4123290f8c31ad0298ba
203
cpp
C++
Homework/GraphingCalculator/GraphingCalculator/src/main.cpp
benjaminmao123/PCC_CS003A
0339d83ebab7536952644517a99dc46702035b2b
[ "MIT" ]
null
null
null
Homework/GraphingCalculator/GraphingCalculator/src/main.cpp
benjaminmao123/PCC_CS003A
0339d83ebab7536952644517a99dc46702035b2b
[ "MIT" ]
null
null
null
Homework/GraphingCalculator/GraphingCalculator/src/main.cpp
benjaminmao123/PCC_CS003A
0339d83ebab7536952644517a99dc46702035b2b
[ "MIT" ]
null
null
null
/* * Author: Benjamin Mao * Project: Predator/Prey * Purpose: Entry point to the Grid class. * * Notes: None. */ #include "Animate.h" int main() { Animate game; game.Run(); return 0; }
11.277778
42
0.605911
benjaminmao123
898fda707ddac8972c1123a3f335cb80ad071a51
1,721
hpp
C++
includes/avl.hpp
viniciusmalloc/planarity
88d3f2998c6095d812614827517d26b505820dc5
[ "MIT" ]
null
null
null
includes/avl.hpp
viniciusmalloc/planarity
88d3f2998c6095d812614827517d26b505820dc5
[ "MIT" ]
null
null
null
includes/avl.hpp
viniciusmalloc/planarity
88d3f2998c6095d812614827517d26b505820dc5
[ "MIT" ]
null
null
null
struct node { int key; unsigned char height; node* left; node* right; node(int k) { key = k; left = right = 0; height = 1; } }; unsigned char height(node* p) { return p ? p->height : 0; } int b_factor(node* p) { return height(p->right) - height(p->left); } void fix_height(node* p) { unsigned char hl = height(p->left); unsigned char hr = height(p->right); p->height = ((hl > hr) ? hl : hr) + 1; } node* rotate_right(node* p) { node* q = p->left; p->left = q->right; q->right = p; fix_height(p); fix_height(q); return q; } node* rotate_left(node* q) { node* p = q->right; q->right = p->left; p->left = q; fix_height(q); fix_height(p); return p; } // balance balances a p node. node* balance(node* p) { fix_height(p); if (b_factor(p) == 2) { if (b_factor(p->right) < 0) p->right = rotate_right(p->right); return rotate_left(p); } if (b_factor(p) == -2) { if (b_factor(p->left) > 0) p->left = rotate_left(p->left); return rotate_right(p); } // balancing is not required return p; } // insert inserts k key in a tree with p root. node* insert(node* p, int k) { if (!p) return new node(k); if (k < p->key) p->left = insert(p->left, k); else p->right = insert(p->right, k); return balance(p); } // find_min finds a node with minimal key in a p tree. node* find_min(node* p) { return p->left ? find_min(p->left) : p; } bool find(node *p, int key) { if (!p) return false; if (key == p->key) return true; if (key < p->key) return find(p->left, key); else return find(p->right, key); }
19.337079
54
0.542708
viniciusmalloc
899bd53962ea646c9babfee418df07267d68983b
4,397
cpp
C++
projs/sphere_reflect/src/app.cpp
colintan95/gl_projects
ad9bcdeaaa65474f45968b26a9a565cbe34af68e
[ "MIT" ]
null
null
null
projs/sphere_reflect/src/app.cpp
colintan95/gl_projects
ad9bcdeaaa65474f45968b26a9a565cbe34af68e
[ "MIT" ]
null
null
null
projs/sphere_reflect/src/app.cpp
colintan95/gl_projects
ad9bcdeaaa65474f45968b26a9a565cbe34af68e
[ "MIT" ]
null
null
null
#include "app.h" #include <iostream> #include <cstdlib> #include <random> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/string_cast.hpp> #include "gfx_utils/primitives.h" // // Significant portion of implementation adapted from: LearnOpenGL // https://learnopengl.com/Advanced-Lighting/SSAO // static const float kPi = 3.14159265358979323846f; static const int kWindowWidth = 1920; static const int kWindowHeight = 1080; static const std::string kReflectPassVertShaderPath = "shaders/reflection.vert"; static const std::string kReflectPassFragShaderPath = "shaders/reflection.frag"; // Format of vertex - {pos_x, pos_y, pos_z, texcoord_u, texcoord_v} static const float kQuadVertices[] = { -1.f, 1.f, 0.f, 0.f, 1.f, -1.f, -1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 1.f, -1.f, 0.f, 1.f, 0.f }; void App::Run() { Startup(); MainLoop(); Cleanup(); } void App::MainLoop() { bool should_quit = false; while (!should_quit) { ReflectPass(); window_.SwapBuffers(); window_.TickMainLoop(); if (window_.ShouldQuit()) { should_quit = true; } } } void App::ReflectPass() { glUseProgram(reflect_pass_program_.GetProgramId()); glViewport(0, 0, kWindowWidth, kWindowHeight); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBindVertexArray(reflect_pass_vao_); glm::mat4 view_mat = camera_.CalcViewMatrix(); glm::mat4 proj_mat = glm::perspective(glm::radians(30.f), window_.GetAspectRatio(), 0.1f, 1000.f); const auto& entities = scene_.GetEntities(); for (auto entity_ptr : entities) { if (!entity_ptr->HasModel()) { continue; } for (auto& mesh : entity_ptr->GetModel()->GetMeshes()) { glm::mat4 model_mat = entity_ptr->ComputeTransform(); glm::mat4 mv_mat = view_mat * model_mat; glm::mat4 mvp_mat = proj_mat * view_mat * model_mat; glm::mat3 normal_mat = glm::transpose(glm::inverse(glm::mat3(mv_mat))); reflect_pass_program_.GetUniform("mv_mat").Set(mv_mat); reflect_pass_program_.GetUniform("mvp_mat").Set(mvp_mat); reflect_pass_program_.GetUniform("normal_mat").Set(normal_mat); reflect_pass_program_.GetUniform("camera_pos") .Set(camera_.GetCameraLocation()); GLuint cubemap_id = resource_manager_.GetCubemapId("skybox"); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_CUBE_MAP, cubemap_id); reflect_pass_program_.GetUniform("cubemap").Set(1); // Set vertex attributes GLuint pos_vbo_id = resource_manager_.GetMeshVboId(mesh.id, gfx_utils::kVertTypePosition); glBindBuffer(GL_ARRAY_BUFFER, pos_vbo_id); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0); GLuint normal_vbo_id = resource_manager_.GetMeshVboId(mesh.id, gfx_utils::kVertTypeNormal); glBindBuffer(GL_ARRAY_BUFFER, normal_vbo_id); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0); glDrawArrays(GL_TRIANGLES, 0, mesh.num_verts); } } glBindVertexArray(0); glUseProgram(0); } void App::Startup() { if (!window_.Inititalize(kWindowWidth, kWindowHeight, "Shadow Map")) { std::cerr << "Failed to initialize gfx window" << std::endl; exit(1); } if (!camera_.Initialize(&window_)) { std::cerr << "Failed to initialize camera" << std::endl; exit(1); } scene_.LoadSceneFromJson("scene/scene.json"); resource_manager_.SetScene(&scene_); resource_manager_.CreateGLResources(); glEnable(GL_TEXTURE_2D); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); SetupReflectPass(); } void App::SetupReflectPass() { if (!reflect_pass_program_.CreateFromFiles(kReflectPassVertShaderPath, kReflectPassFragShaderPath)) { std::cerr << "Could not create reflect pass program." << std::endl; exit(1); } glGenVertexArrays(1, &reflect_pass_vao_); } void App::Cleanup() { glDeleteVertexArrays(1, &reflect_pass_vao_); resource_manager_.Cleanup(); window_.Destroy(); }
26.810976
80
0.654992
colintan95
899c0b78a6e02e4b8fb767c9b055e1c7303c4706
1,702
cpp
C++
src/Look.cpp
FellowRoboticists/myRobotScan
f87c73937d1a26a273479c6747bd7d4731bf31e3
[ "MIT" ]
null
null
null
src/Look.cpp
FellowRoboticists/myRobotScan
f87c73937d1a26a273479c6747bd7d4731bf31e3
[ "MIT" ]
null
null
null
src/Look.cpp
FellowRoboticists/myRobotScan
f87c73937d1a26a273479c6747bd7d4731bf31e3
[ "MIT" ]
null
null
null
// Look Arduino library // // Copyright 2013 Dave Sieh // See LICENSE.txt for details. #include <Arduino.h> #include "Look.h" #include "SoftServo.h" #include "IrSensors.h" #include "PingSensor.h" #include "pspc_support.h" Look::Look(SoftServo *sweepServo, IrSensors *sensors, PingSensor *pingSensor) { servo = sweepServo; irSensors = sensors; ping = pingSensor; } void Look::begin() { if (servo) { servo->begin(); } if (irSensors) { irSensors->begin(); } if (ping) { ping->begin(); } } boolean Look::irEdgeDetect(IrSensor sensor) { boolean detected = false; if (irSensors) { detected = irSensors->lowReflectionDetected(sensor); } return detected; } boolean Look::sensesObstacle(ObstacleType obstacle, int minDistance) { switch(obstacle) { case OBST_FRONT_EDGE: return irEdgeDetect(IrLeft) && irEdgeDetect(IrRight); case OBST_LEFT_EDGE: return irEdgeDetect(IrLeft); case OBST_RIGHT_EDGE: return irEdgeDetect(IrRight); case OBST_FRONT: return lookAt(DIR_CENTER) <= minDistance; } return false; } int Look::lookAt(LookDirection direction) { int angle = servoAngles[direction]; // wait for servo to get into position servo->write(angle, servoDelay); int distance = (ping) ? ping->getAverageDistance(4) : 0; // distaceToObstacle(); if (angle != servoAngles[DIR_CENTER]) { #ifdef LOOK_DEBUG // Print only if looking right/left Serial.print(P("looking at dir ")); Serial.print(angle), Serial.print(P(" distance= ")); Serial.println(distance); #endif // Re-center the servo servo->write(servoAngles[DIR_CENTER], servoDelay / 2); } return distance; }
22.394737
82
0.672738
FellowRoboticists
89a64aaf723287c92770b3b3227e323d7298bea2
1,483
cpp
C++
03-Ejemplo basico de Qt/main.cpp
vialrogo/TutorialCPP
f0b44dcc0f58eb54ce5d48a069923f5963eb545f
[ "CC0-1.0" ]
null
null
null
03-Ejemplo basico de Qt/main.cpp
vialrogo/TutorialCPP
f0b44dcc0f58eb54ce5d48a069923f5963eb545f
[ "CC0-1.0" ]
null
null
null
03-Ejemplo basico de Qt/main.cpp
vialrogo/TutorialCPP
f0b44dcc0f58eb54ce5d48a069923f5963eb545f
[ "CC0-1.0" ]
null
null
null
/* +---------------------------------------+ | Ejemplos-Tutorial C++ con Qt | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | Creado por: Victor Alberto Romero | | e-mail: vialrogo@gmail.com | +---------------------------------------+ Archivo main de ejemplo de qt básico En esta clase podemos ver como usamos la clase BasicoQT para hacer la suma de unas cadenas. Estas clases usan la clase QString de QT, por lo cual se compilan diferentes. Primero de seclara el objeto miBasicoQT, luego los datos con los que se va a trabajar. Es importante ver que se usa el método cin para el ingreso de caracteres por consola. El método data() de string permite convertir un "string" en un "const char * ". El metodo qPrintable permite convertir un QString en un char* Podemos compilar este ejemplo con: qmake -project qmake -makefile make y podemos correrlo con: ./<nombre de la carpeta donde se encuentra> */ #include <iostream> #include <QString> #include "BasicoQT.h" using namespace std; //Es para poder usar directamente cin, cout y endl. int main() { BasicoQT* miBasicoQT = new BasicoQT(); char* Cabecera = "La cadena sumada fue: "; string parteA; string parteB; cout<<"Introduzca la parte A: "<<endl; cin>>parteA; cout<<"Introduzca la parte B: "<<endl; cin>>parteB; miBasicoQT->calcularCadena(parteA.data(), parteB.data()); QString* cadenaSumada = miBasicoQT->devolverCadena(); cout<<Cabecera<<qPrintable(*cadenaSumada)<<endl; return 0; }
26.482143
119
0.664194
vialrogo
89a6ad9f44e2b3661a8cbab41b0e722e79153c56
842
cpp
C++
code_blocks/check_fft/main.cpp
rafald/xtechnical_analysis
7686c16241e9e53fb5a5548354531b533f983b54
[ "MIT" ]
12
2020-01-20T14:22:18.000Z
2022-01-26T04:41:36.000Z
code_blocks/check_fft/main.cpp
rafald/xtechnical_analysis
7686c16241e9e53fb5a5548354531b533f983b54
[ "MIT" ]
1
2020-05-23T07:35:03.000Z
2020-05-23T07:35:03.000Z
code_blocks/check_fft/main.cpp
rafald/xtechnical_analysis
7686c16241e9e53fb5a5548354531b533f983b54
[ "MIT" ]
9
2019-11-02T19:01:55.000Z
2021-07-08T21:51:44.000Z
#include <iostream> #include "xtechnical_indicators.hpp" using namespace std; int main() { cout << "Hello world!" << endl; xtechnical_indicators::FreqHist<double> iFreqHist(100, xtechnical_dft::RECTANGULAR_WINDOW); const double MATH_PI = 3.14159265358979323846264338327950288; for(size_t i = 0; i < 1000; ++i) { double temp = std::cos(3 * MATH_PI * 2 * (double)i / 100.0); std::vector<double> amplitude; std::vector<double> frequencies; iFreqHist.update(temp, amplitude, frequencies, 100); std::cout << "step: " << i << " temp " << temp << std::endl; for(size_t i = 0; i < frequencies.size(); ++i) { std::cout << "freq " << frequencies[i] << " " << amplitude[i] << std::endl; } std::cout << std::endl << std::endl; } return 0; }
31.185185
87
0.58076
rafald
89a93f9d49fa304f09791a1595ca12b48e44ebdc
1,952
cpp
C++
src/Gen/Builders/DoLoopBuilder.cpp
albeva/LightBASIC
489bcc81bed268798874d6675054e594ffc8eb07
[ "MIT" ]
6
2021-05-24T15:43:58.000Z
2022-03-21T12:50:05.000Z
src/Gen/Builders/DoLoopBuilder.cpp
albeva/LightBASIC
489bcc81bed268798874d6675054e594ffc8eb07
[ "MIT" ]
15
2022-02-23T23:24:36.000Z
2022-03-05T13:44:27.000Z
src/Gen/Builders/DoLoopBuilder.cpp
albeva/LightBASIC
489bcc81bed268798874d6675054e594ffc8eb07
[ "MIT" ]
1
2017-04-13T13:13:29.000Z
2017-04-13T13:13:29.000Z
// // Created by Albert Varaksin on 28/05/2021. // #include "DoLoopBuilder.hpp" #include "Driver/Context.hpp" using namespace lbc; using namespace Gen; DoLoopBuilder::DoLoopBuilder(CodeGen& gen, AstDoLoopStmt& ast) : Builder{ gen, ast }, m_bodyBlock{ llvm::BasicBlock::Create(m_llvmContext, "do_loop.body") }, m_condBlock{ (m_ast.condition == AstDoLoopStmt::Condition::None) ? nullptr : llvm::BasicBlock::Create(m_llvmContext, "do_loop.cond") }, m_exitBlock{ llvm::BasicBlock::Create(m_llvmContext, "do_loop.end") }, m_continueBlock{ m_condBlock } { build(); } void DoLoopBuilder::build() { for (const auto& decl : m_ast.decls) { m_gen.visit(*decl); } // pre makeCondition switch (m_ast.condition) { case AstDoLoopStmt::Condition::None: m_continueBlock = m_bodyBlock; break; case AstDoLoopStmt::Condition::PreUntil: makeCondition(true); break; case AstDoLoopStmt::Condition::PreWhile: makeCondition(false); break; default: break; } // body m_gen.switchBlock(m_bodyBlock); m_gen.getControlStack().push(ControlFlowStatement::Do, { m_continueBlock, m_exitBlock }); m_gen.visit(*m_ast.stmt); m_gen.getControlStack().pop(); // post makeCondition switch (m_ast.condition) { case AstDoLoopStmt::Condition::PostUntil: makeCondition(true); break; case AstDoLoopStmt::Condition::PostWhile: makeCondition(false); break; default: m_gen.terminateBlock(m_continueBlock); break; } // exit m_gen.switchBlock(m_exitBlock); } void DoLoopBuilder::makeCondition(bool isUntil) { m_gen.switchBlock(m_condBlock); auto value = m_gen.visit(*m_ast.expr).load(); if (isUntil) { m_builder.CreateCondBr(value, m_exitBlock, m_bodyBlock); } else { m_builder.CreateCondBr(value, m_bodyBlock, m_exitBlock); } }
27.492958
93
0.659324
albeva
89abb05926deed25d1ff77e99d404144658e1642
9,666
cpp
C++
spa/plugins/aec/aec-webrtc.cpp
neonkingfr/pipewire
43fec3ee3bc8bd07b67e56279f1b437e05461449
[ "MIT" ]
null
null
null
spa/plugins/aec/aec-webrtc.cpp
neonkingfr/pipewire
43fec3ee3bc8bd07b67e56279f1b437e05461449
[ "MIT" ]
null
null
null
spa/plugins/aec/aec-webrtc.cpp
neonkingfr/pipewire
43fec3ee3bc8bd07b67e56279f1b437e05461449
[ "MIT" ]
null
null
null
/* PipeWire * * Copyright © 2021 Wim Taymans <wim.taymans@gmail.com> * © 2021 Arun Raghavan <arun@asymptotic.io> * * 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 (including the next * paragraph) 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 <memory> #include <utility> #include <spa/interfaces/audio/aec.h> #include <spa/support/log.h> #include <spa/utils/string.h> #include <spa/utils/names.h> #include <spa/support/plugin.h> #include <webrtc/modules/audio_processing/include/audio_processing.h> #include <webrtc/modules/interface/module_common_types.h> #include <webrtc/system_wrappers/include/trace.h> struct impl_data { struct spa_handle handle; struct spa_audio_aec aec; struct spa_log *log; std::unique_ptr<webrtc::AudioProcessing> apm; spa_audio_info_raw info; std::unique_ptr<float *[]> play_buffer, rec_buffer, out_buffer; }; static struct spa_log_topic log_topic = SPA_LOG_TOPIC(0, "spa.eac.webrtc"); #undef SPA_LOG_TOPIC_DEFAULT #define SPA_LOG_TOPIC_DEFAULT &log_topic static bool webrtc_get_spa_bool(const struct spa_dict *args, const char *key, bool default_value) { const char *str_val; bool value = default_value; str_val = spa_dict_lookup(args, key); if (str_val != NULL) value =spa_atob(str_val); return value; } static int webrtc_init(void *data, const struct spa_dict *args, const struct spa_audio_info_raw *info) { auto impl = reinterpret_cast<struct impl_data*>(data); bool extended_filter = webrtc_get_spa_bool(args, "webrtc.extended_filter", true); bool delay_agnostic = webrtc_get_spa_bool(args, "webrtc.delay_agnostic", true); bool high_pass_filter = webrtc_get_spa_bool(args, "webrtc.high_pass_filter", true); bool noise_suppression = webrtc_get_spa_bool(args, "webrtc.noise_suppression", true); bool voice_detection = webrtc_get_spa_bool(args, "webrtc.voice_detection", true); // Note: AGC seems to mess up with Agnostic Delay Detection, especially with speech, // result in very poor performance, disable by default bool gain_control = webrtc_get_spa_bool(args, "webrtc.gain_control", false); // Disable experimental flags by default bool experimental_agc = webrtc_get_spa_bool(args, "webrtc.experimental_agc", false); bool experimental_ns = webrtc_get_spa_bool(args, "webrtc.experimental_ns", false); // FIXME: Intelligibility enhancer is not currently supported // This filter will modify playback buffer (when calling ProcessReverseStream), but now // playback buffer modifications are discarded. webrtc::Config config; config.Set<webrtc::ExtendedFilter>(new webrtc::ExtendedFilter(extended_filter)); config.Set<webrtc::DelayAgnostic>(new webrtc::DelayAgnostic(delay_agnostic)); config.Set<webrtc::ExperimentalAgc>(new webrtc::ExperimentalAgc(experimental_agc)); config.Set<webrtc::ExperimentalNs>(new webrtc::ExperimentalNs(experimental_ns)); webrtc::ProcessingConfig pconfig = {{ webrtc::StreamConfig(info->rate, info->channels, false), /* input stream */ webrtc::StreamConfig(info->rate, info->channels, false), /* output stream */ webrtc::StreamConfig(info->rate, info->channels, false), /* reverse input stream */ webrtc::StreamConfig(info->rate, info->channels, false), /* reverse output stream */ }}; auto apm = std::unique_ptr<webrtc::AudioProcessing>(webrtc::AudioProcessing::Create(config)); if (apm->Initialize(pconfig) != webrtc::AudioProcessing::kNoError) { spa_log_error(impl->log, "Error initialising webrtc audio processing module"); return -1; } apm->high_pass_filter()->Enable(high_pass_filter); // Always disable drift compensation since it requires drift sampling apm->echo_cancellation()->enable_drift_compensation(false); apm->echo_cancellation()->Enable(true); // TODO: wire up supression levels to args apm->echo_cancellation()->set_suppression_level(webrtc::EchoCancellation::kHighSuppression); apm->noise_suppression()->set_level(webrtc::NoiseSuppression::kHigh); apm->noise_suppression()->Enable(noise_suppression); apm->voice_detection()->Enable(voice_detection); // TODO: wire up AGC parameters to args apm->gain_control()->set_analog_level_limits(0, 255); apm->gain_control()->set_mode(webrtc::GainControl::kAdaptiveDigital); apm->gain_control()->Enable(gain_control); impl->apm = std::move(apm); impl->info = *info; impl->play_buffer = std::make_unique<float *[]>(info->channels); impl->rec_buffer = std::make_unique<float *[]>(info->channels); impl->out_buffer = std::make_unique<float *[]>(info->channels); return 0; } static int webrtc_run(void *data, const float *rec[], const float *play[], float *out[], uint32_t n_samples) { auto impl = reinterpret_cast<struct impl_data*>(data); webrtc::StreamConfig config = webrtc::StreamConfig(impl->info.rate, impl->info.channels, false); unsigned int num_blocks = n_samples * 1000 / impl->info.rate / 10; if (n_samples * 1000 / impl->info.rate % 10 != 0) { spa_log_error(impl->log, "Buffers must be multiples of 10ms in length (currently %u samples)", n_samples); return -1; } for (size_t i = 0; i < num_blocks; i ++) { for (size_t j = 0; j < impl->info.channels; j++) { impl->play_buffer[j] = const_cast<float *>(play[j]) + config.num_frames() * i; impl->rec_buffer[j] = const_cast<float *>(rec[j]) + config.num_frames() * i; impl->out_buffer[j] = out[j] + config.num_frames() * i; } /* FIXME: ProcessReverseStream may change the playback buffer, in which * case we should use that, if we ever expose the intelligibility * enhancer */ if (impl->apm->ProcessReverseStream(impl->play_buffer.get(), config, config, impl->play_buffer.get()) != webrtc::AudioProcessing::kNoError) { spa_log_error(impl->log, "Processing reverse stream failed"); } // Extra delay introduced by multiple frames impl->apm->set_stream_delay_ms((num_blocks - 1) * 10); if (impl->apm->ProcessStream(impl->rec_buffer.get(), config, config, impl->out_buffer.get()) != webrtc::AudioProcessing::kNoError) { spa_log_error(impl->log, "Processing stream failed"); } } return 0; } static struct spa_audio_aec_methods impl_aec = { SPA_VERSION_AUDIO_AEC_METHODS, .add_listener = NULL, .init = webrtc_init, .run = webrtc_run, }; static int impl_get_interface(struct spa_handle *handle, const char *type, void **interface) { auto impl = reinterpret_cast<struct impl_data*>(handle); spa_return_val_if_fail(handle != NULL, -EINVAL); spa_return_val_if_fail(interface != NULL, -EINVAL); if (spa_streq(type, SPA_TYPE_INTERFACE_AUDIO_AEC)) *interface = &impl->aec; else return -ENOENT; return 0; } static int impl_clear(struct spa_handle *handle) { spa_return_val_if_fail(handle != NULL, -EINVAL); auto impl = reinterpret_cast<struct impl_data*>(handle); impl->~impl_data(); return 0; } static size_t impl_get_size(const struct spa_handle_factory *factory, const struct spa_dict *params) { return sizeof(struct impl_data); } static int impl_init(const struct spa_handle_factory *factory, struct spa_handle *handle, const struct spa_dict *info, const struct spa_support *support, uint32_t n_support) { spa_return_val_if_fail(factory != NULL, -EINVAL); spa_return_val_if_fail(handle != NULL, -EINVAL); auto impl = new (handle) impl_data(); impl->handle.get_interface = impl_get_interface; impl->handle.clear = impl_clear; impl->aec.iface = SPA_INTERFACE_INIT( SPA_TYPE_INTERFACE_AUDIO_AEC, SPA_VERSION_AUDIO_AEC, &impl_aec, impl); impl->aec.name = "webrtc", impl->aec.info = NULL; impl->aec.latency = "480/48000", impl->log = (struct spa_log*)spa_support_find(support, n_support, SPA_TYPE_INTERFACE_Log); spa_log_topic_init(impl->log, &log_topic); return 0; } static const struct spa_interface_info impl_interfaces[] = { {SPA_TYPE_INTERFACE_AUDIO_AEC,}, }; static int impl_enum_interface_info(const struct spa_handle_factory *factory, const struct spa_interface_info **info, uint32_t *index) { spa_return_val_if_fail(factory != NULL, -EINVAL); spa_return_val_if_fail(info != NULL, -EINVAL); spa_return_val_if_fail(index != NULL, -EINVAL); switch (*index) { case 0: *info = &impl_interfaces[*index]; break; default: return 0; } (*index)++; return 1; } const struct spa_handle_factory spa_aec_webrtc_factory = { SPA_VERSION_HANDLE_FACTORY, SPA_NAME_AEC, NULL, impl_get_size, impl_init, impl_enum_interface_info, }; SPA_EXPORT int spa_handle_factory_enum(const struct spa_handle_factory **factory, uint32_t *index) { spa_return_val_if_fail(factory != NULL, -EINVAL); spa_return_val_if_fail(index != NULL, -EINVAL); switch (*index) { case 0: *factory = &spa_aec_webrtc_factory; break; default: return 0; } (*index)++; return 1; }
34.645161
108
0.747155
neonkingfr
89af705ee09cb1cb533cbad81ee8eaa74e2c01a7
413
hpp
C++
header/Connector.hpp
Sdc97/Rshell
37c0dd264799d199e6c0dc1f13ae1e25f9368620
[ "MIT" ]
1
2020-06-28T20:40:57.000Z
2020-06-28T20:40:57.000Z
header/Connector.hpp
Sdc97/Rshell
37c0dd264799d199e6c0dc1f13ae1e25f9368620
[ "MIT" ]
null
null
null
header/Connector.hpp
Sdc97/Rshell
37c0dd264799d199e6c0dc1f13ae1e25f9368620
[ "MIT" ]
1
2021-04-02T21:47:58.000Z
2021-04-02T21:47:58.000Z
#ifndef CONNECTOR #define CONNECTOR #include "Executable.hpp" #include "Cmnd.hpp" class Connector : public Executable { protected: Executable* left; Executable* right; public: virtual bool run_command() =0; virtual char** get_command() {} virtual void set_left(Executable*) =0; virtual void set_right(Executable*) =0; virtual Executable* get_left() =0; virtual Executable* get_right() =0; }; #endif
18.772727
40
0.731235
Sdc97
89af7544e15c04b34f0c1e40b22d5ca5ef17f78e
1,953
cpp
C++
src/display/display.cpp
passinglink/passinglink
d1bc70cc8bf2c32a9dfea412fc37a44c6dbf09c1
[ "MIT" ]
76
2020-03-09T20:30:59.000Z
2022-03-29T13:39:47.000Z
src/display/display.cpp
Project-Alpaca/passinglink
f259466d2e8aafca6c8511df3b1259156954e907
[ "MIT" ]
24
2020-08-08T23:07:12.000Z
2022-03-31T20:38:07.000Z
src/display/display.cpp
Project-Alpaca/passinglink
f259466d2e8aafca6c8511df3b1259156954e907
[ "MIT" ]
18
2020-07-31T01:23:44.000Z
2022-03-23T01:14:45.000Z
#include "display/display.h" #include <stdio.h> #include "arch.h" #include "display/menu.h" #include "display/ssd1306.h" #include "types.h" #include "util.h" #include <logging/log.h> #define LOG_LEVEL LOG_LEVEL_INF LOG_MODULE_REGISTER(display); static bool status_locked; static bool status_probing; static optional<uint32_t> status_latency; static ProbeType status_probe_type; static void display_draw_status_line() { char buf[DISPLAY_WIDTH + 1]; static_assert(DISPLAY_WIDTH == 21); char* p = buf; memset(buf, ' ', sizeof(buf) - 1); switch (status_probe_type) { case ProbeType::NX: p += copy_text(buf, "Switch"); break; case ProbeType::PS3: p += copy_text(buf, "PS3"); break; case ProbeType::PS4: p += copy_text(buf, "PS4"); break; } if (status_probing) { p[0] = '?'; } if (status_probe_type == ProbeType::NX) { p = buf + 8; if (!status_probing) { ++p; } } else { p = buf + 7; } if (status_locked) { memcpy(p, "LOCKED", strlen("LOCKED")); } if (!status_latency) { snprintf(buf + 15, 7, " ???us"); } else { snprintf(buf + 15, 7, "%4uus", *status_latency); } buf[DISPLAY_WIDTH] = '\0'; display_set_line(DISPLAY_ROWS, buf); } void display_update_latency(uint32_t us) { status_latency.reset(us); display_draw_status_line(); display_blit(); } void display_set_locked(bool locked) { status_locked = locked; display_draw_status_line(); display_blit(); } void display_set_connection_type(bool probing, ProbeType type) { LOG_INF("display_set_connection_type: probing = %d", probing); status_probing = probing; status_probe_type = type; display_draw_status_line(); display_blit(); } void display_init() { status_locked = false; status_probing = true; status_probe_type = ProbeType::NX; ssd1306_init(); menu_init(); display_draw_logo(); display_draw_status_line(); display_blit(); }
19.53
64
0.664107
passinglink
89b1e599fb58b3c8a56de15849e4ac017124cd1b
673
cpp
C++
src/common/transformations/src/transformations/rt_info/decompression.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/common/transformations/src/transformations/rt_info/decompression.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/common/transformations/src/transformations/rt_info/decompression.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "transformations/rt_info/decompression.hpp" void ov::mark_as_decompression(const std::shared_ptr<Node>& node) { auto& rt_info = node->get_rt_info(); rt_info[Decompression::get_type_info_static()] = Decompression(); } void ov::unmark_as_decompression(const std::shared_ptr<Node>& node) { auto& rt_info = node->get_rt_info(); rt_info.erase(Decompression::get_type_info_static()); } bool ov::is_decompression(const std::shared_ptr<Node>& node) { const auto& rt_info = node->get_rt_info(); return rt_info.count(Decompression::get_type_info_static()); }
32.047619
69
0.736999
ryanloney
89b26cad6b4973354e3a987f86dc420785c82d81
5,375
hpp
C++
src/libpanacea/kernels/median_kernel_wrapper.hpp
lanl/PANACEA
9779bdb6dcc3be41ea7b286ae55a21bb269e0339
[ "BSD-3-Clause" ]
null
null
null
src/libpanacea/kernels/median_kernel_wrapper.hpp
lanl/PANACEA
9779bdb6dcc3be41ea7b286ae55a21bb269e0339
[ "BSD-3-Clause" ]
null
null
null
src/libpanacea/kernels/median_kernel_wrapper.hpp
lanl/PANACEA
9779bdb6dcc3be41ea7b286ae55a21bb269e0339
[ "BSD-3-Clause" ]
null
null
null
#ifndef PANACEA_PRIVATE_MEDIANKERNELWRAPPER_H #define PANACEA_PRIVATE_MEDIANKERNELWRAPPER_H #pragma once // Local private PANACEA includes #include "base_kernel_wrapper.hpp" #include "data_point_template.hpp" #include "error.hpp" // Local public PANACEA includes #include "panacea/passkey.hpp" // Standard includes #include <any> #include <cstddef> #include <deque> #include <memory> #include <typeindex> #include <vector> namespace panacea { class BaseDescriptorWrapper; class KernelWrapperFactory; namespace test { class Test; } class MedianKernelWrapper : public BaseKernelWrapper { private: DataPointTemplate<std::vector<double>> data_wrapper_; /** * Number of points to track to watch to keep an up to date median **/ int number_pts_store_ = 100; std::vector<std::deque<double>> points_near_median_; /** * Will alternate if an odd number of points need to be remove * alternate between removing an extra element from the front and back **/ bool remove_from_front_ = true; int number_pts_median_; // Number of points used to calculate the median virtual BaseKernelWrapper::ReadFunction getReadFunction_() final; virtual BaseKernelWrapper::WriteFunction getWriteFunction_() const final; /** * Private constructors **/ explicit MedianKernelWrapper(const BaseDescriptorWrapper &desc_wrapper); explicit MedianKernelWrapper(const std::vector<double> &); public: explicit MedianKernelWrapper(const PassKey<test::Test> &){}; MedianKernelWrapper(const PassKey<KernelWrapperFactory> &, const BaseDescriptorWrapper &desc_wrapper) : MedianKernelWrapper(desc_wrapper){}; MedianKernelWrapper(const PassKey<test::Test> &, const BaseDescriptorWrapper &desc_wrapper) : MedianKernelWrapper(desc_wrapper){}; /** * If initialized with a single vector the median is assumed to be the * vector passed in. **/ MedianKernelWrapper(const PassKey<KernelWrapperFactory> &, const std::vector<double> &data) : MedianKernelWrapper(data){}; MedianKernelWrapper(const PassKey<test::Test> &, const std::vector<double> &data) : MedianKernelWrapper(data){}; virtual const settings::KernelCenterCalculation center() const noexcept final; virtual const settings::KernelCount count() const noexcept final; virtual double &at(const int row, const int col) final; virtual double at(const int row, const int col) const final; virtual void resize(const int rows, const int cols) final; virtual int rows() const final; virtual int cols() const final; virtual int getNumberDimensions() const final; virtual int getNumberPoints() const final; virtual const Arrangement &arrangement() const noexcept final; virtual void set(const Arrangement arrangement) final; virtual void update(const BaseDescriptorWrapper &) final; virtual const std::any getPointerToRawData() const noexcept final; virtual std::type_index getTypeIndex() const noexcept final; virtual void print() const final; // Standard any should not be a reference because the underlying type should // be a pointer static std::unique_ptr<BaseKernelWrapper> create(const PassKey<KernelWrapperFactory> &, std::any data, const int rows, const int cols); static std::istream &read(BaseKernelWrapper &, std::istream &); static std::ostream &write(const BaseKernelWrapper &, std::ostream &); }; inline std::unique_ptr<BaseKernelWrapper> MedianKernelWrapper::create(const PassKey<KernelWrapperFactory> &key, std::any data, const int rows, const int cols) { if (std::type_index(data.type()) == std::type_index(typeid(const BaseDescriptorWrapper *))) { return std::make_unique<MedianKernelWrapper>( key, *std::any_cast<const BaseDescriptorWrapper *>(data)); } else if (std::type_index(data.type()) == std::type_index(typeid(BaseDescriptorWrapper *))) { return std::make_unique<MedianKernelWrapper>( key, *const_cast<const BaseDescriptorWrapper *>( std::any_cast<BaseDescriptorWrapper *>(data))); } else if (std::type_index(data.type()) == std::type_index(typeid(const BaseDescriptorWrapper &))) { return std::make_unique<MedianKernelWrapper>( key, std::any_cast<const BaseDescriptorWrapper &>(data)); } else if (std::type_index(data.type()) == std::type_index(typeid(BaseDescriptorWrapper &))) { return std::make_unique<MedianKernelWrapper>( key, const_cast<const BaseDescriptorWrapper &>( std::any_cast<BaseDescriptorWrapper &>(data))); } else if (std::type_index(data.type()) == std::type_index(typeid(const std::vector<double>))) { return std::make_unique<MedianKernelWrapper>( key, std::any_cast<const std::vector<double>>(data)); } else if (std::type_index(data.type()) == std::type_index(typeid(std::vector<double>))) { return std::make_unique<MedianKernelWrapper>( key, std::any_cast<std::vector<double>>(data)); } else { std::string error_msg = "Unsupported data type encountered while "; error_msg += "attempting to create Kernel center median"; PANACEA_FAIL(error_msg); } return nullptr; } } // namespace panacea #endif // PANACEA_PRIVATE_MEDIANKERNELWRAPPER_H
35.130719
80
0.71107
lanl
89b786614913a2a02561549873a2de4534c62c9d
10,368
cpp
C++
src/D3dsurf.cpp
rbwsok/3dfx-OpenGL-ICD-update
4e0846d6569bf5d7ec8b22918f33fc7701df6e73
[ "Unlicense" ]
null
null
null
src/D3dsurf.cpp
rbwsok/3dfx-OpenGL-ICD-update
4e0846d6569bf5d7ec8b22918f33fc7701df6e73
[ "Unlicense" ]
null
null
null
src/D3dsurf.cpp
rbwsok/3dfx-OpenGL-ICD-update
4e0846d6569bf5d7ec8b22918f33fc7701df6e73
[ "Unlicense" ]
null
null
null
// // d3dsurf.cpp : You *really* don't want to know // #include "stdafx.h" #define INITGUID #include <Guiddef.h> // {1F2069EB-6D07-4f75-9409-AFEABA279E6A} //DEFINE_GUID(IID_IGXP_D3DSurface8, //0x1f2069eb, 0x6d07, 0x4f75, 0x94, 0x9, 0xaf, 0xea, 0xba, 0x27, 0x9e, 0x6a); #define PRINTF while(0) printf #define IS_2_POW_N(X) (((X)&(X-1)) == 0) void * _fastcall _aligned_malloc(size_t size,size_t alignment) { size_t ptr, r_ptr; size_t *reptr; if (!IS_2_POW_N(alignment)) { return NULL; } alignment = (alignment > sizeof(void *) ? alignment : sizeof(void *)); if ((ptr = (size_t)GlobalAllocPtr(GPTR,size + alignment + sizeof(void *))) == (size_t)NULL) return NULL; r_ptr = (ptr + alignment + sizeof(void *)) & ~(alignment -1); reptr = (size_t *)(r_ptr - sizeof(void *)); *reptr = ptr; return (void *)r_ptr; } void _fastcall _aligned_free(void *memblock) { size_t ptr; if (memblock == NULL) return; ptr = (size_t)memblock; /* ptr points to the pointer to starting of the memory block */ ptr = (ptr & ~(sizeof(void *) -1)) - sizeof(void *); /* ptr is the pointer to the start of memory block*/ ptr = *((size_t *)ptr); GlobalFree((void *)ptr); } int IGXP_D3DSurface8::GetSizeForFormat(D3DFORMAT format) { switch (format) { case D3DFMT_A8R8G8B8: case D3DFMT_X8R8G8B8: return 32; case D3DFMT_R8G8B8: return 24; case D3DFMT_R5G6B5: case D3DFMT_X1R5G5B5: case D3DFMT_A1R5G5B5: case D3DFMT_A4R4G4B4: case D3DFMT_A8R3G3B2: case D3DFMT_X4R4G4B4: case D3DFMT_A8P8: case D3DFMT_A8L8: return 16; case D3DFMT_R3G3B2: case D3DFMT_A8: case D3DFMT_P8: case D3DFMT_L8: case D3DFMT_A4L4: case D3DFMT_DXT2: case D3DFMT_DXT3: case D3DFMT_DXT4: case D3DFMT_DXT5: return 8; case D3DFMT_DXT1: return 4; default: return 0; } } // // operator new // //void *IGXP_D3DSurface8::operator new (size_t s) //{ // PRINTF("void *IGXP_D3DSurface8::operator new (size_t s)\n"); // return CoTaskMemAlloc(s); //} // // operator delete // //void IGXP_D3DSurface8::operator delete (void *b) //{ // PRINTF("void IGXP_D3DSurface8::operator delete (void *b)\n"); // CoTaskMemFree(b); //} // // Constructor // IGXP_D3DSurface8::IGXP_D3DSurface8(D3DFORMAT format, int w, int h, BYTE *_buffer) : m_cRef(1), lock_count(0) { // PRINTF("IGXP_D3DSurface8::IGXP_D3DSurface8(D3DFORMAT format = %i, int w = %i, int h = %i)\n", format, w, h); bpp = GetSizeForFormat(format); // Do these first surf_desc.Format = format; surf_desc.Type = D3DRTYPE_SURFACE; surf_desc.Usage = 0; surf_desc.Pool = D3DPOOL_MANAGED; surf_desc.MultiSampleType = D3DMULTISAMPLE_NONE; surf_desc.Width = w; surf_desc.Height = h; // Now what we need to do is clamp the w and h values if we are using S3TC if (surf_desc.Format >= D3DFMT_DXT1 && surf_desc.Format <= D3DFMT_DXT5) { w = max(w,4); h = max(h,4); } surf_desc.Size = (w * h * bpp) / 8; if (_buffer) { nodel = TRUE; buffer = _buffer; allocated = 0; allocated_size = 0; } else { nodel = FALSE; allocated = buffer = (BYTE*) _aligned_malloc(allocated_size = max(surf_desc.Size,16), 8); } } // // Destructor // IGXP_D3DSurface8::~IGXP_D3DSurface8() { // PRINTF("IGXP_D3DSurface8::~IGXP_D3DSurface8()\n"); if (allocated) _aligned_free(allocated); } // // IUnknown::AddRef implementation // ULONG IGXP_D3DSurface8::AddRef(void) { // PRINTF("ULONG IGXP_D3DSurface8::AddRef(void)\n"); return ++m_cRef; } // // IUnknown::Release implementation // ULONG IGXP_D3DSurface8::Release(void) { // PRINTF("ULONG IGXP_D3DSurface8::Release(void)\n"); --m_cRef; if (!m_cRef) { delete this; return 0; } return m_cRef; } // // IUnknown::QueryInterface implementation // HRESULT IGXP_D3DSurface8::QueryInterface(REFIID riid, void** ppvObj) { // PRINTF("HRESULT IGXP_D3DSurface8::QueryInterface(REFIID riid, void** ppvObj)\n"); if (IsEqualGUID(riid, IID_IUnknown)) { *ppvObj = (IUnknown*)this; return S_OK; } if (IsEqualGUID(riid, IID_IDirect3DSurface8)) { *ppvObj = (IDirect3DSurface8*)this; return S_OK; } if (IsEqualGUID(riid, IID_IGXP_D3DSurface8)) { *ppvObj = (IGXP_D3DSurface8*)this; return S_OK; } *ppvObj = 0; return E_NOINTERFACE; } // // IDirect3DSurface8::GetDevice implementation // HRESULT IGXP_D3DSurface8::GetDevice(IDirect3DDevice8** ppDevice) { // PRINTF("HRESULT IGXP_D3DSurface8::GetDevice(IDirect3DDevice8** ppDevice)\n"); lpD3DDevice->AddRef(); *ppDevice = lpD3DDevice; return D3D_OK; } // // IDirect3DSurface8::SetPrivateData implementation // HRESULT IGXP_D3DSurface8::SetPrivateData(REFGUID refguid,CONST void* pData,DWORD SizeOfData,DWORD Flags) { // PRINTF("HRESULT IGXP_D3DSurface8::SetPrivateData(REFGUID refguid,CONST void* pData,DWORD SizeOfData,DWORD Flags)\n"); return D3DERR_INVALIDCALL; } // // IDirect3DSurface8::GetPrivateData implementation // HRESULT IGXP_D3DSurface8::GetPrivateData(REFGUID refguid,void* pData,DWORD* pSizeOfData) { // PRINTF("HRESULT IGXP_D3DSurface8::GetPrivateData(REFGUID refguid,void* pData,DWORD* pSizeOfData)\n"); return D3DERR_INVALIDCALL; } // // IDirect3DSurface8::FreePrivateData implementation // HRESULT IGXP_D3DSurface8::FreePrivateData(REFGUID refguid) { // PRINTF("HRESULT IGXP_D3DSurface8::FreePrivateData(REFGUID refguid)\n"); return D3DERR_INVALIDCALL; } // // IDirect3DSurface8::GetContainer implementation // HRESULT IGXP_D3DSurface8::GetContainer(REFIID riid,void** ppContainer) { // PRINTF("HRESULT IGXP_D3DSurface8::GetContainer(REFIID riid,void** ppContainer)\n"); return D3DERR_INVALIDCALL; } // // IDirect3DSurface8::GetDesc implementation // HRESULT IGXP_D3DSurface8::GetDesc(D3DSURFACE_DESC *pDesc) { // PRINTF("HRESULT IGXP_D3DSurface8::GetDesc(D3DSURFACE_DESC *pDesc = %X)\n", pDesc); *pDesc = surf_desc; return D3D_OK; } // // IDirect3DSurface8::LockRect implementation // HRESULT IGXP_D3DSurface8::LockRect(D3DLOCKED_RECT* pLockedRect,CONST RECT* pRect,DWORD Flags) { // PRINTF("HRESULT IGXP_D3DSurface8::LockRect(D3DLOCKED_RECT* pLockedRect = %X,CONST RECT* pRect = %X,DWORD Flags = %X)\n", pLockedRect, pRect, Flags); lock_count++; pLockedRect->pBits = buffer; if (surf_desc.Format >= D3DFMT_DXT1 && surf_desc.Format <= D3DFMT_DXT5) { // Pitch will 'screw up' on surfaces smaller than 4 pixels if (surf_desc.Width <= 4) pLockedRect->Pitch = bpp*2; else pLockedRect->Pitch = (surf_desc.Width*bpp)/2; // If we have a rectangle and we are using S3TC, then we must be // aligned to the 4x4 blocks if (pRect) { // Never Valid if ((pRect->left&3) || (pRect->top&3)) return D3DERR_INVALIDCALL; // It's valid to lock non multiples of 4, IF the surface is smaller than 4 pixels if ((pRect->right != (LONG) surf_desc.Width && (pRect->right&3)) || (pRect->bottom != (LONG) surf_desc.Height && (pRect->bottom&3))) { return D3DERR_INVALIDCALL; } int x = pRect->left/4; int y = pRect->top /4; pLockedRect->pBits = buffer + (pLockedRect->Pitch * y) + (x * bpp)/2; } } else { pLockedRect->Pitch = (surf_desc.Width*bpp)/8; if (pRect) pLockedRect->pBits = buffer + (surf_desc.Width*pRect->top+pRect->left)*bpp/8; } return D3D_OK; } // // IDirect3DSurface8::UnlockRect implementation // HRESULT IGXP_D3DSurface8::UnlockRect() { // PRINTF("HRESULT IGXP_D3DSurface8::UnlockRect()\n"); if (lock_count == 0) return D3DERR_INVALIDCALL; lock_count--; return D3D_OK; } // // IGXP_D3DSurface8::CopyFromOpenGL implementation // HRESULT IGXP_D3DSurface8::CopyFromOpenGL (GLenum format, const GLvoid *pixels) { BYTE *dest = buffer; BYTE *end = dest+surf_desc.Size; BYTE *source = (BYTE *)pixels; if (format == GL_RGBA) { if (bpp == 32) while (dest < end) { *(dest+0) = *(source+2); *(dest+1) = *(source+1); *(dest+2) = *(source+0); *(dest+3) = *(source+3); dest+= 4; source+= 4; } else if (bpp == 24) while (dest < end) { *(dest+0) = *(source+2); *(dest+1) = *(source+1); *(dest+2) = *(source+0); dest+= 3; source+= 4; } } else if (format == GL_RGB) { if (bpp == 32) while (dest < end) { *(dest+0) = *(source+2); *(dest+1) = *(source+1); *(dest+2) = *(source+0); *(dest+3) = 0xFF; dest+= 4; source+= 3; } else if (bpp == 24) while (dest < end) { *(dest+0) = *(source+2); *(dest+1) = *(source+1); *(dest+2) = *(source+0); dest+= 3; source+= 3; } } else if (format == GL_BGRA_EXT) { if (bpp == 32) while (dest < end) { *(DWORD*)dest = *(DWORD*)source; dest+= 4; source+= 4; } else if (bpp == 24) while (dest < end) { *(dest+0) = *(source+0); *(dest+1) = *(source+1); *(dest+2) = *(source+2); dest+= 3; source+= 4; } } else if (format == GL_BGR_EXT) { if (bpp == 32) while (dest < end) { *(dest+0) = *(source+0); *(dest+1) = *(source+1); *(dest+2) = *(source+2); *(dest+3) = 0xFF; dest+= 4; source+= 3; } else if (bpp == 24) while (dest < end) { *(dest+0) = *(source+0); *(dest+1) = *(source+1); *(dest+2) = *(source+2); dest+= 3; source+= 3; } } return D3D_OK; } // // IGXP_D3DSurface8::ReallocSurface implementation // HRESULT IGXP_D3DSurface8::ReallocSurface(D3DFORMAT format, int w, int h, BYTE *_buffer) { // PRINTF("IGXP_D3DSurface8::ReallocSurface(D3DFORMAT format = %i, int w = %i, int h = %i)\n", format, w, h); if (lock_count) D3DERR_INVALIDCALL; bpp = GetSizeForFormat(format); // Do these first surf_desc.Format = format; surf_desc.Type = D3DRTYPE_SURFACE; surf_desc.Usage = 0; surf_desc.Pool = D3DPOOL_MANAGED; surf_desc.MultiSampleType = D3DMULTISAMPLE_NONE; surf_desc.Width = w; surf_desc.Height = h; // Now what we need to do is clamp the w and h values if we are using S3TC if (surf_desc.Format >= D3DFMT_DXT1 && surf_desc.Format <= D3DFMT_DXT5) { w = max(w,4); h = max(h,4); } surf_desc.Size = (w * h * bpp) / 8; if (_buffer) { // Don't care about the allocated surface nodel = TRUE; buffer = _buffer; } else { // Only realloc IF real_size is less than the size we want if (allocated_size < surf_desc.Size) { if (allocated) _aligned_free(allocated); allocated = (BYTE*) _aligned_malloc(allocated_size = max(surf_desc.Size,16), 8); } buffer = allocated; nodel = FALSE; } return D3D_OK; }
21.6
151
0.66088
rbwsok
89b8c660bb355f90968b76344c6b893124347574
2,301
cpp
C++
src/omwmm/modmanager.cpp
luluco250/omwmm
ee9cd11e4876515c84ad4f2c97372ba23616ac2b
[ "MIT" ]
null
null
null
src/omwmm/modmanager.cpp
luluco250/omwmm
ee9cd11e4876515c84ad4f2c97372ba23616ac2b
[ "MIT" ]
null
null
null
src/omwmm/modmanager.cpp
luluco250/omwmm
ee9cd11e4876515c84ad4f2c97372ba23616ac2b
[ "MIT" ]
null
null
null
#include <omwmm/modmanager.hpp> #include <filesystem> #include <utility> #include <functional> #include <unordered_set> #include <string> #include <string_view> #include <omwmm/config.hpp> #include <omwmm/exceptions.hpp> #include <7zpp/7zpp.h> using Path = std::filesystem::path; using DirectoryIterator = std::filesystem::directory_iterator; template<class T> using Function = std::function<T>; template<class T> using UnorderedSet = std::unordered_set<T>; using String = std::string; using StringView = std::string_view; namespace omwmm { using namespace exceptions; ModManager::ModManager(const Config& cfg) { config(cfg); } const Config& ModManager::config() const { return _config; } void ModManager::config(const Config& cfg) { if (!cfg.data_files_path || cfg.data_files_path->empty()) throw ModManagerSetupException("Data files path is empty"); if (!cfg.downloaded_mods_path || cfg.downloaded_mods_path->empty()) throw ModManagerSetupException("Downloaded mods path is empty"); if (!cfg.extracted_mods_path || cfg.extracted_mods_path->empty()) throw ModManagerSetupException("Extracted mods path is empty"); _config = cfg; } static const UnorderedSet<StringView> download_exts{ ".7z", ".zip", ".rar" }; void ModManager::query_downloads( const Function<void(StringView)>& func ) { for (auto p : DirectoryIterator(downloaded_mods_path())) if (download_exts.find(p.path().extension().string()) != download_exts.end()) func(p.path().filename().string()); } void ModManager::extract_mod(StringView filename) { auto source = downloaded_mods_path() / filename; auto dest = extracted_mods_path() / source.filename().replace_extension(""); _extractor.extract(source, dest); } #define GET_SET(NAME, PRETTY_NAME) \ Path ModManager::NAME() const { \ return *_config.NAME; \ } \ void ModManager::NAME(const Path& path) { \ if (path.empty()) \ throw InvalidArgumentException(PRETTY_NAME " cannot be empty"); \ \ _config.NAME = path; \ } \ void ModManager::NAME(Path&& path) { \ if (path.empty()) \ throw InvalidArgumentException(PRETTY_NAME " cannot be empty"); \ \ _config.NAME = std::move(path); \ } GET_SET(data_files_path, "Data files path") GET_SET(downloaded_mods_path, "Downloaded mods path") GET_SET(extracted_mods_path, "Extracted mods path") }
26.755814
79
0.734463
luluco250
89bb3ef38d4be053ae48489bb26769638fa3bb0d
641
hpp
C++
src/Mechanics/ForceField/Branching/BranchingDihedralQuadratic.hpp
allen-cell-animated/medyan
0b5ef64fb338c3961673361e5632980617937ee6
[ "BSD-4-Clause-UC" ]
null
null
null
src/Mechanics/ForceField/Branching/BranchingDihedralQuadratic.hpp
allen-cell-animated/medyan
0b5ef64fb338c3961673361e5632980617937ee6
[ "BSD-4-Clause-UC" ]
null
null
null
src/Mechanics/ForceField/Branching/BranchingDihedralQuadratic.hpp
allen-cell-animated/medyan
0b5ef64fb338c3961673361e5632980617937ee6
[ "BSD-4-Clause-UC" ]
null
null
null
#ifndef MEDYAN_Mechanics_ForceField_Branching_BranchingDihedralQuadratic_Hpp #define MEDYAN_Mechanics_ForceField_Branching_BranchingDihedralQuadratic_Hpp #include "common.h" // floatingpoint struct BranchingDihedralQuadratic { floatingpoint energy( const floatingpoint *coord, size_t nint, const unsigned int *beadSet, const floatingpoint *kdih, const floatingpoint *pos ) const; void forces( const floatingpoint *coord, floatingpoint *f, size_t nint, const unsigned int *beadSet, const floatingpoint *kdih, const floatingpoint *pos, floatingpoint *stretchforce ) const; }; #endif
32.05
89
0.76131
allen-cell-animated
89bc5aecef0da213a33adbe7fcd3462897651c6d
10,443
cpp
C++
src/libtsduck/dtv/descriptors/tsEventGroupDescriptor.cpp
manuelmann/tsduck-test
13760d34bd6f522c2ff813a996371a7cb30e1835
[ "BSD-2-Clause" ]
null
null
null
src/libtsduck/dtv/descriptors/tsEventGroupDescriptor.cpp
manuelmann/tsduck-test
13760d34bd6f522c2ff813a996371a7cb30e1835
[ "BSD-2-Clause" ]
null
null
null
src/libtsduck/dtv/descriptors/tsEventGroupDescriptor.cpp
manuelmann/tsduck-test
13760d34bd6f522c2ff813a996371a7cb30e1835
[ "BSD-2-Clause" ]
null
null
null
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2020, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------- #include "tsEventGroupDescriptor.h" #include "tsDescriptor.h" #include "tsNames.h" #include "tsTablesDisplay.h" #include "tsPSIRepository.h" #include "tsDuckContext.h" #include "tsxmlElement.h" #include "tsMJD.h" TSDUCK_SOURCE; #define MY_XML_NAME u"event_group_descriptor" #define MY_CLASS ts::EventGroupDescriptor #define MY_DID ts::DID_ISDB_EVENT_GROUP #define MY_PDS ts::PDS_ISDB #define MY_STD ts::Standards::ISDB TS_REGISTER_DESCRIPTOR(MY_CLASS, ts::EDID::Private(MY_DID, MY_PDS), MY_XML_NAME, MY_CLASS::DisplayDescriptor); //---------------------------------------------------------------------------- // Constructors //---------------------------------------------------------------------------- ts::EventGroupDescriptor::EventGroupDescriptor() : AbstractDescriptor(MY_DID, MY_XML_NAME, MY_STD, 0), group_type(0), actual_events(), other_events(), private_data() { } ts::EventGroupDescriptor::EventGroupDescriptor(DuckContext& duck, const Descriptor& desc) : EventGroupDescriptor() { deserialize(duck, desc); } void ts::EventGroupDescriptor::clearContent() { group_type = 0; actual_events.clear(); other_events.clear(); private_data.clear(); } ts::EventGroupDescriptor::ActualEvent::ActualEvent() : service_id(0), event_id(0) { } ts::EventGroupDescriptor::OtherEvent::OtherEvent() : original_network_id(0), transport_stream_id(0), service_id(0), event_id(0) { } //---------------------------------------------------------------------------- // Serialization //---------------------------------------------------------------------------- void ts::EventGroupDescriptor::serialize(DuckContext& duck, Descriptor& desc) const { ByteBlockPtr bbp(serializeStart()); bbp->appendUInt8(uint8_t(group_type << 4) | uint8_t(actual_events.size() & 0x0F)); for (auto it = actual_events.begin(); it != actual_events.end(); ++it) { bbp->appendUInt16(it->service_id); bbp->appendUInt16(it->event_id); } if (group_type == 4 || group_type == 5) { for (auto it = other_events.begin(); it != other_events.end(); ++it) { bbp->appendUInt16(it->original_network_id); bbp->appendUInt16(it->transport_stream_id); bbp->appendUInt16(it->service_id); bbp->appendUInt16(it->event_id); } } else { bbp->append(private_data); } serializeEnd(desc, bbp); } //---------------------------------------------------------------------------- // Deserialization //---------------------------------------------------------------------------- void ts::EventGroupDescriptor::deserialize(DuckContext& duck, const Descriptor& desc) { const uint8_t* data = desc.payload(); size_t size = desc.payloadSize(); _is_valid = desc.isValid() && desc.tag() == tag() && size >= 1; actual_events.clear(); other_events.clear(); private_data.clear(); if (_is_valid) { group_type = (data[0] >> 4) & 0x0F; size_t count = data[0] & 0x0F; data++; size--; while (count > 0 && size >= 4) { ActualEvent ev; ev.service_id = GetUInt16(data); ev.event_id = GetUInt16(data + 2); actual_events.push_back(ev); data += 4; size -= 4; count--; } _is_valid = count == 0; if (_is_valid) { if (group_type == 4 || group_type == 5) { while (size >= 8) { OtherEvent ev; ev.original_network_id = GetUInt16(data); ev.transport_stream_id = GetUInt16(data + 2); ev.service_id = GetUInt16(data + 4); ev.event_id = GetUInt16(data + 6); other_events.push_back(ev); data += 8; size -= 8; } _is_valid = size == 0; } else { private_data.copy(data, size); } } } } //---------------------------------------------------------------------------- // Static method to display a descriptor. //---------------------------------------------------------------------------- void ts::EventGroupDescriptor::DisplayDescriptor(TablesDisplay& display, DID did, const uint8_t* data, size_t size, int indent, TID tid, PDS pds) { DuckContext& duck(display.duck()); std::ostream& strm(duck.out()); const std::string margin(indent, ' '); if (size >= 1) { const uint8_t type = (data[0] >> 4) & 0x0F; size_t count = data[0] & 0x0F; data++; size--; strm << margin << "Group type: " << NameFromSection(u"ISDBEventGroupType", type, names::DECIMAL_FIRST) << std::endl; strm << margin << "Actual events:" << (count == 0 ? " none" : "") << std::endl; while (count > 0 && size >= 4) { strm << margin << UString::Format(u"- Service id: 0x%X (%d)", {GetUInt16(data), GetUInt16(data)}) << std::endl << margin << UString::Format(u" Event id: 0x%X (%d)", {GetUInt16(data + 2), GetUInt16(data + 2)}) << std::endl; data += 4; size -= 4; count--; } if (type == 4 || type == 5) { strm << margin << "Other networks events:" << (size < 8 ? " none" : "") << std::endl; while (size >= 8) { strm << margin << UString::Format(u"- Original network id: 0x%X (%d)", {GetUInt16(data), GetUInt16(data)}) << std::endl << margin << UString::Format(u" Transport stream id: 0x%X (%d)", {GetUInt16(data + 2), GetUInt16(data + 2)}) << std::endl << margin << UString::Format(u" Service id: 0x%X (%d)", {GetUInt16(data + 4), GetUInt16(data + 4)}) << std::endl << margin << UString::Format(u" Event id: 0x%X (%d)", {GetUInt16(data + 6), GetUInt16(data + 6)}) << std::endl; data += 8; size -= 8; } display.displayExtraData(data, size, indent); } else { display.displayPrivateData(u"Private data", data, size, indent); } } } //---------------------------------------------------------------------------- // XML serialization //---------------------------------------------------------------------------- void ts::EventGroupDescriptor::buildXML(DuckContext& duck, xml::Element* root) const { root->setIntAttribute(u"group_type", group_type); for (auto it = actual_events.begin(); it != actual_events.end(); ++it) { xml::Element* e = root->addElement(u"actual"); e->setIntAttribute(u"service_id", it->service_id, true); e->setIntAttribute(u"event_id", it->event_id, true); } if (group_type == 4 || group_type == 5) { for (auto it = other_events.begin(); it != other_events.end(); ++it) { xml::Element* e = root->addElement(u"other"); e->setIntAttribute(u"original_network_id", it->original_network_id, true); e->setIntAttribute(u"transport_stream_id", it->transport_stream_id, true); e->setIntAttribute(u"service_id", it->service_id, true); e->setIntAttribute(u"event_id", it->event_id, true); } } else { root->addHexaTextChild(u"private_data", private_data, true); } } //---------------------------------------------------------------------------- // XML deserialization //---------------------------------------------------------------------------- bool ts::EventGroupDescriptor::analyzeXML(DuckContext& duck, const xml::Element* element) { xml::ElementVector xactual; xml::ElementVector xother; bool ok = element->getIntAttribute<uint8_t>(group_type, u"group_type", true, 0, 0, 15) && element->getChildren(xactual, u"actual", 0, 15) && element->getChildren(xother, u"other", 0, group_type == 4 || group_type == 5 ? 31 : 0) && element->getHexaTextChild(private_data, u"private_data", false, 0, group_type == 4 || group_type == 5 ? 0 : 254); for (auto it = xactual.begin(); ok && it != xactual.end(); ++it) { ActualEvent ev; ok = (*it)->getIntAttribute<uint16_t>(ev.service_id, u"service_id", true) && (*it)->getIntAttribute<uint16_t>(ev.event_id, u"event_id", true); actual_events.push_back(ev); } for (auto it = xother.begin(); ok && it != xother.end(); ++it) { OtherEvent ev; ok = (*it)->getIntAttribute<uint16_t>(ev.original_network_id, u"original_network_id", true) && (*it)->getIntAttribute<uint16_t>(ev.transport_stream_id, u"transport_stream_id", true) && (*it)->getIntAttribute<uint16_t>(ev.service_id, u"service_id", true) && (*it)->getIntAttribute<uint16_t>(ev.event_id, u"event_id", true); other_events.push_back(ev); } return ok; }
39.259398
145
0.551566
manuelmann
89c30d095e454b52779a31d7e31efe1f00ba13c0
3,746
cc
C++
storageServer/saveFile_2/src/Loop.cc
HenryKing96/MiniDistributedStorage
7da8b7fb72baca4a04cfde9ce27eec3bb207e056
[ "Apache-2.0" ]
null
null
null
storageServer/saveFile_2/src/Loop.cc
HenryKing96/MiniDistributedStorage
7da8b7fb72baca4a04cfde9ce27eec3bb207e056
[ "Apache-2.0" ]
null
null
null
storageServer/saveFile_2/src/Loop.cc
HenryKing96/MiniDistributedStorage
7da8b7fb72baca4a04cfde9ce27eec3bb207e056
[ "Apache-2.0" ]
null
null
null
#include "Loop.h" #include "EpollEvent.h" #include "EPoller.h" #include <boost/bind.hpp> #include <iostream> #include <assert.h> #include <signal.h> #include <sys/eventfd.h> using namespace Reactor; Loop* t_loopInThisThread = 0; const int kPollTimeMs = 10000; static int createEventfd() { return ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); } Loop::Loop() : looping_(false), quit_(false), callFunctors_(false), threadId_(std::this_thread::get_id()), wakeupFd_(createEventfd()), epoller_(new EPoller(this)), wakeupEvent_(new EpollEvent(this, wakeupFd_)) { printf("thread id: %lu created success\n", threadId_); t_loopInThisThread = this; wakeupEvent_->setReadCallback(boost::bind(&Loop::handleRead, this)); wakeupEvent_->enableReading(); } Loop::~Loop() { ::close(wakeupFd_); t_loopInThisThread = NULL; } void Loop::loop() { looping_ = true; quit_ = false; while (!quit_) { activeEvents_.clear(); epoller_->epoll(kPollTimeMs, &activeEvents_); for (EventlList::iterator it = activeEvents_.begin(); it != activeEvents_.end(); ++it) { (*it)->handleEvent(); } doFunctors(); } looping_ = false; } void Loop::quit() { quit_ = true; if (!isInLoopThread()) { wakeup(); } } void Loop::runInLoop(const Functor& cb) { if (isInLoopThread()) { cb(); } else { queueInLoop(cb); } } void Loop::queueInLoop(const Functor& cb) { { std::lock_guard<std::mutex> guard(mutex_); Functors_.push_back(cb); } if (!isInLoopThread() || callFunctors_) { wakeup(); } } void Loop::updateEvent(EpollEvent* epollEvent) { epoller_->updateEvent(epollEvent); } void Loop::removeEvent(EpollEvent* epollEvent) { epoller_->removeEvent(epollEvent); } void Loop::wakeup() { uint64_t one = 1; ::write(wakeupFd_, &one, sizeof one); } void Loop::handleRead() { uint64_t one = 1; ::read(wakeupFd_, &one, sizeof one); } void Loop::doFunctors() { std::vector<Functor> functors; callFunctors_ = true; { std::lock_guard<std::mutex> guard(mutex_); functors.swap(Functors_); } for (size_t i = 0; i < functors.size(); ++i) { functors[i](); } callFunctors_ = false; }
27.955224
1,532
0.381474
HenryKing96
89c37b76a49283607c174aa28f43ff946d88690b
5,710
cpp
C++
test_gcc/test.cpp
KnicKnic/native-powershell
add37eff76c47fc0e782c22a8460bff3f3327dca
[ "Apache-2.0" ]
21
2019-06-27T06:29:11.000Z
2021-12-29T05:08:37.000Z
test_gcc/test.cpp
KnicKnic/native-powershell
add37eff76c47fc0e782c22a8460bff3f3327dca
[ "Apache-2.0" ]
5
2019-08-17T01:34:11.000Z
2019-11-06T21:52:15.000Z
test_gcc/test.cpp
KnicKnic/native-powershell
add37eff76c47fc0e782c22a8460bff3f3327dca
[ "Apache-2.0" ]
1
2021-03-13T20:58:48.000Z
2021-03-13T20:58:48.000Z
// test.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <algorithm> #include <vector> #include "host.h" #include "utils/macros.hpp" #include "utils/zero_resetable.hpp" #include "utils/cpp_wrappers.hpp" using namespace std; using namespace native_powershell; struct SomeContext { std::wstring LoggerContext; std::wstring CommandContext; NativePowerShell_RunspaceHandle runspace; std::optional<NativePowerShell_PowerShellHandle> powershell; }; extern "C" { void Logger(void* context, const wchar_t* s) { auto realContext = (SomeContext*)context; std::wcout << realContext->LoggerContext << std::wstring(s); } void Command(void* context, const wchar_t* s, NativePowerShell_PowerShellObject* input, unsigned long long inputCount, NativePowerShell_JsonReturnValues* returnValues) { input; inputCount; auto realContext = (SomeContext*)context; std::wcout << realContext->CommandContext << std::wstring(s) << L'\n'; for (size_t i = 0; i < inputCount; ++i) { // test nested creation RunScript(realContext->runspace, realContext->powershell, L"[int]11", true); auto& v = input[i]; std::wcout << L"In data processing got " << GetToString(v) << L" of type " << GetType(v) << L'\n'; } // allocate return object holders returnValues->count = 1 + inputCount; returnValues->objects = (NativePowerShell_GenericPowerShellObject*)NativePowerShell_DefaultAlloc(sizeof(*(returnValues->objects)) * returnValues->count); if (returnValues->objects == nullptr) { throw "memory allocation failed for return values in command"; } // allocate and fill out each object auto& object = returnValues->objects[0]; object.releaseObject = char(1); object.type = NativePowerShell_PowerShellObjectTypeString; object.instance.string = MallocCopy(s); for (size_t i = 0; i < inputCount; ++i) { auto& v = returnValues->objects[1 + i]; v.releaseObject = char(0); v.type = NativePowerShell_PowerShellObjectHandle; v.instance.psObject = input[i]; } return; } } int main() { SomeContext context{ L"MyLoggerContext: ", L"MyCommandContext: ", NativePowerShell_InvalidHandleValue, std::nullopt }; NativePowerShell_LogString_Holder logHolder = { 0 }; logHolder.Log = Logger; auto runspace = NativePowerShell_CreateRunspace(&context, Command, &logHolder); context.runspace = runspace; RunScript(runspace, std::nullopt, L"[int12", true); auto powershell = NativePowerShell_CreatePowerShell(runspace); //AddScriptSpecifyScope(powershell, L"c:\\code\\psh_host\\script.ps1", 1); //AddCommand(powershell, L"c:\\code\\go-net\\t3.ps1"); //AddScriptSpecifyScope(powershell, L"write-host $pwd", 0); NativePowerShell_AddScriptSpecifyScope(powershell, L"0;1;$null;dir c:\\", 1); //AddCommandSpecifyScope(powershell, L"..\\..\\go-net\\t3.ps1", 0); //AddScriptSpecifyScope(powershell, L"$a = \"asdf\"", 0); //AddArgument(powershell, L"c:\\ddddddd"); { Invoker invoke(powershell); wcout << L"examining returned objects\n"; for (unsigned int i = 0; i < invoke.count; ++i) { wcout << L"Got type: " << GetType(invoke[i]) << L"with value: " << GetToString(invoke[i]) << L'\n'; } auto powershell2 = NativePowerShell_CreatePowerShell(runspace); // note below will write to output, not return objects NativePowerShell_AddScriptSpecifyScope(powershell2, L"write-host 'about to enumerate directory';" L"write-host $args; $len = $args.length; write-host \"arg count $len\";" L"$args | ft | out-string | write-host;" L"@(1,'asdf',$null,$false) | send-hostcommand -message 'I sent the host a command' | write-host;" L"send-hostcommand -message 'I sent the host a command' | write-host", 0); NativePowerShell_AddArgument(powershell2, L"String to start"); NativePowerShell_AddPSObjectArguments(powershell2, invoke.objects, invoke.count); NativePowerShell_AddArgument(powershell2, L"String to end"); context.powershell = powershell2; Invoker invoke2(powershell2); context.powershell = std::nullopt; } NativePowerShell_DeletePowershell(powershell); powershell = NativePowerShell_CreatePowerShell(runspace); //AddScriptSpecifyScope(powershell, L"c:\\code\\psh_host\\script.ps1", 1); NativePowerShell_AddCommandSpecifyScope(powershell, L"..\\..\\go-net\\t3.ps1", 0); //AddScriptSpecifyScope(powershell, L"write-host $a", 0); //AddCommand(powershell, L"c:\\code\\go-net\\t3.ps1"); //AddArgument(powershell, L"c:\\ddddddd"); { Invoker invoke(powershell); } NativePowerShell_DeletePowershell(powershell); NativePowerShell_DeleteRunspace(runspace); std::cout << "Hello World!\n"; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
41.376812
171
0.670228
KnicKnic
89c4f250960e689e775d7455b8916b7e1d65acdf
14
inl
C++
modules/aho/inl/ja_regex/lexrep/OneStateMap.inl
JosDenysGitHub/iknow
e6a142253513ad4365d7998e36c569d4174e8248
[ "MIT" ]
49
2020-02-05T15:54:24.000Z
2022-03-03T20:10:39.000Z
modules/aho/inl/ja_regex/lexrep/OneStateMap.inl
makorin0315/iknow
3043030d2ac83b8719471bacaabd204ebdf94be6
[ "MIT" ]
84
2020-02-06T13:09:16.000Z
2022-03-22T19:36:00.000Z
modules/aho/inl/ja_regex/lexrep/OneStateMap.inl
makorin0315/iknow
3043030d2ac83b8719471bacaabd204ebdf94be6
[ "MIT" ]
20
2020-02-04T21:38:57.000Z
2022-02-23T20:30:13.000Z
0, 0,Symbol()
4.666667
10
0.571429
JosDenysGitHub
89c562a87b5acce423f54442a803bd258039f8f2
1,036
hpp
C++
codegen.hpp
kwQt/dummyscope
160010342e87fb1578f707b97812af9d34814d76
[ "MIT" ]
1
2020-07-17T05:17:07.000Z
2020-07-17T05:17:07.000Z
codegen.hpp
kwQt/dummyscope
160010342e87fb1578f707b97812af9d34814d76
[ "MIT" ]
null
null
null
codegen.hpp
kwQt/dummyscope
160010342e87fb1578f707b97812af9d34814d76
[ "MIT" ]
null
null
null
#pragma once #include <llvm/IR/IRBuilder.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/IR/Value.h> #include <memory> #include "ast.hpp" class ExprAST; class CodeGen { private: std::unique_ptr<llvm::LLVMContext> context; std::unique_ptr<llvm::Module> module; std::unique_ptr<llvm::IRBuilder<>> builder; std::map<std::string, llvm::Value*> named_values; public: CodeGen(); ~CodeGen(){}; bool generate(TranslationUnitAST* ast); llvm::Module* getModule() { return module.get(); } private: llvm::Function* generateFunction(FunctionAST* ast); llvm::Value* generateNumber(NumberAST* ast); llvm::Function* generateProtoType(PrototypeAST* ast); llvm::Value* generateExpr(ExprAST* ast); llvm::Value* generateBinaryExpr(BinaryExprAST* ast); llvm::Value* generateCallExpr(CallExprAST* ast); llvm::Value* generateVariable(VariableAST* ast); void setNamedValue(const std::string& name, llvm::Value* value); void clearNamedValue(); void addBuiltinFunction(); };
21.142857
66
0.718147
kwQt
89c668a24249d00c648bf3d9099505d397572bf2
484
cpp
C++
Sesame/src/Sesame/Core/Log.cpp
yook00627/Sesame-Engine
1adf6227afcfc582697203cb9ccf0e2d56c9d5eb
[ "MIT" ]
3
2020-06-06T23:07:55.000Z
2020-07-31T17:13:29.000Z
Sesame/src/Sesame/Core/Log.cpp
yook00627/Sesame-Engine
1adf6227afcfc582697203cb9ccf0e2d56c9d5eb
[ "MIT" ]
1
2020-08-09T17:43:03.000Z
2021-03-25T02:22:23.000Z
Sesame/src/Sesame/Core/Log.cpp
yook00627/Sesame-Engine
1adf6227afcfc582697203cb9ccf0e2d56c9d5eb
[ "MIT" ]
null
null
null
#include "ssmpch.h" #include "Log.h" namespace Sesame { std::shared_ptr<spdlog::logger> Log::s_CoreLogger; std::shared_ptr<spdlog::logger> Log::s_ClientLogger; void Log::Init() { spdlog::set_pattern("%t-%^[%T] %n: %v%$"); s_CoreLogger = spdlog::stdout_color_mt("SESAME"); s_CoreLogger->set_level(spdlog::level::trace); s_ClientLogger = spdlog::stdout_color_mt("APP"); s_ClientLogger->set_level(spdlog::level::trace); } }
26.888889
57
0.634298
yook00627
89c7c9bdd0b58f4151ed3099002373f24e5497f8
4,337
cpp
C++
apps/Stencil2D_InPlace_ASYN_Tps/Stencil2DKernel.cpp
randres2011/DARTS
d3a0d28926b15796661783f91451dcd313905582
[ "BSD-2-Clause" ]
3
2020-02-21T01:34:36.000Z
2021-11-13T06:24:40.000Z
apps/Stencil2D_InPlace_ASYN_Tps/Stencil2DKernel.cpp
randres2011/DARTS
d3a0d28926b15796661783f91451dcd313905582
[ "BSD-2-Clause" ]
1
2021-01-25T06:57:45.000Z
2022-02-02T11:44:04.000Z
apps/Stencil2D_InPlace_ASYN_Tps/Stencil2DKernel.cpp
randres2011/DARTS
d3a0d28926b15796661783f91451dcd313905582
[ "BSD-2-Clause" ]
4
2016-12-12T05:46:58.000Z
2022-01-01T16:08:56.000Z
#include <stdint.h> #include <stdlib.h> #include "Stencil2DKernel.h" /** * Naive 4pt stencil for 2D array */ void stencil2d_seq(double *dst,double *src,const uint64_t n_rows,const uint64_t n_cols,uint64_t n_tsteps){ typedef double (*Array2D)[n_cols]; Array2D DST = (Array2D) dst, SRC = (Array2D) src; for (size_t ts = 0; ts < n_tsteps; ++ts) { for (size_t i = 1; i < n_rows-1; ++i) { for (size_t j = 1; j < n_cols-1; ++j) { DST[i][j] = (SRC[i-1][j] + SRC[i+1][j] + SRC[i][j-1] + SRC[i][j+1]) / 4; } } SWAP_PTR(&DST,&SRC); } } /* //compute inner blocks for no sub cut void computeInner_stencil2d(uint64_t BlockPosition,double *Initial,double *share,uint64_t BlockM,const uint64_t InitialM, const uint64_t InitialN){ double *upper = new double[InitialN];//upper is used to store current line which can be used for next line computing double *lower = new double[InitialN]; double *current=new double[InitialN]; if(BlockM > InitialM){ std::cout << "Inner error \n"<<std::endl; return; } memcpy(current,share,sizeof(double)*InitialN); memcpy(lower,Initial+BlockPosition-1,sizeof(double)*InitialN); for(uint64_t i=0;i<BlockM;++i){ memcpy(upper,current,sizeof(double)*InitialN); memcpy(current,lower,sizeof(double)*InitialN); //memcpy(lower,Initial+BlockPosition+i*InitialN-1,sizeof(double)*(BlockNPlus2)); double *LOWER = (i==(BlockM-1))? (share+InitialN):(Initial+BlockPosition+(i+1)*InitialN-1); memcpy(lower,LOWER,sizeof(double)*(InitialN)); for(uint64_t j=0;j<InitialN-2;++j){ Initial[BlockPosition+i*InitialN+j]=(upper[j+1]+current[j]+current[j+2]+lower[j+1])/4; } } delete [] upper; delete [] lower; delete [] current; return; } */ //compute inner blocks void computeInner_stencil2d(uint64_t BlockPosition,double *Initial,double *share,uint64_t BlockM,uint64_t BlockN,const uint64_t InitialM, const uint64_t InitialN){ uint64_t BlockNPlus2=BlockN+2; double *upper = new double[BlockNPlus2];//upper is used to store current line which can be used for next line computing double *lower = new double[BlockNPlus2]; double *current=new double[BlockNPlus2]; if(BlockM > InitialM){ std::cout << "Inner error \n"<<std::endl; return; } memcpy(current,share,sizeof(double)*(BlockNPlus2)); memcpy(lower,Initial+BlockPosition-1,sizeof(double)*(BlockNPlus2)); for(uint64_t i=0;i<BlockM;++i){ memcpy(upper,current,sizeof(double)*(BlockNPlus2)); memcpy(current,lower,sizeof(double)*(BlockNPlus2)); //memcpy(lower,Initial+BlockPosition+i*InitialN-1,sizeof(double)*(BlockNPlus2)); double *LOWER = (i==(BlockM-1))? (share+BlockNPlus2):(Initial+BlockPosition+(i+1)*InitialN-1); memcpy(lower,LOWER,sizeof(double)*(BlockNPlus2)); for(uint64_t j=0;j<BlockN;++j){ Initial[BlockPosition+i*InitialN+j]=(upper[j+1]+current[j]+current[j+2]+lower[j+1])/4; } } delete [] upper; delete [] lower; delete [] current; return; } /* // when we compute inner matrix, we first should copy the block to the inner of codelet void copyMatrix_stencil2d(uint64_t BlockPosition, uint64_t BlockM, uint64_t BlockN,double *InitialMatrix,double *CopyMatrix,const uint64_t InitialM, const uint64_t InitialN){ uint64_t i,j,k,l; uint64_t i_begin = BlockPosition/InitialN; uint64_t j_begin = BlockPosition%InitialN; uint64_t i_end = i_begin + BlockM-1; uint64_t j_end = j_begin + BlockN-1; if(i_end > InitialM){ std::cout << "Inner error \n"<<std::endl; return; } for(i=i_begin,k=0;i<=i_end;++i,++k) for(j=j_begin,l=0;j<=j_end;++j,++l){ CopyMatrix[k*BlockN+l]=InitialMatrix[i*InitialN+j]; } return; } */ /* //copy RowDecomposition block share lines (up+lower lines) void copyShareLines_stencil2d(uint64_t BlockPosition,double *InitialMatrix,double *CopyMatrix,uint64_t StepM,const uint64_t InitialM, const uint64_t InitialN){ uint64_t i = BlockPosition/InitialN; if((i+StepM) > InitialM){ std::cout << "Inner error \n"<<std::endl; return; } for(uint64_t j=0;j<InitialN;++j){ CopyMatrix[j]=InitialMatrix[i*InitialN+j]; CopyMatrix[InitialN+j]=InitialMatrix[(i+StepM+1)*InitialN+j]; } return; } */ void copyLine_stencil2d(uint64_t BlockPosition,double *Initial,double *Copy,const uint64_t InitialN){ uint64_t i = BlockPosition/InitialN; memcpy(Copy,Initial+i*InitialN,sizeof(double)*InitialN); return; }
31.889706
174
0.709477
randres2011
89c9c38e01658b9f9f35f37518c62387db41fdf2
11,634
cpp
C++
src/QtComponents/Traditions/nComboBox.cpp
Vladimir-Lin/QtComponents
e7f0a6abcf0504cc9144dcf59f3f14a52d08092c
[ "MIT" ]
null
null
null
src/QtComponents/Traditions/nComboBox.cpp
Vladimir-Lin/QtComponents
e7f0a6abcf0504cc9144dcf59f3f14a52d08092c
[ "MIT" ]
null
null
null
src/QtComponents/Traditions/nComboBox.cpp
Vladimir-Lin/QtComponents
e7f0a6abcf0504cc9144dcf59f3f14a52d08092c
[ "MIT" ]
null
null
null
#include <qtcomponents.h> N::ComboBox:: ComboBox ( QWidget * parent , Plan * p ) : QComboBox ( parent ) , VirtualGui ( this , p ) , Thread ( 0 , false ) { WidgetClass ; Configure ( ) ; } N::ComboBox::~ComboBox(void) { } SUID N::ComboBox::toUuid(void) { return toUuid ( currentIndex ( ) ) ; } SUID N::ComboBox::toUuid(int index) { return itemData ( index ) . toULongLong ( ) ; } void N::ComboBox::Configure(void) { setAttribute ( Qt::WA_InputMethodEnabled ) ; setAcceptDrops ( true ) ; setDropFlag ( DropFont , true ) ; setDropFlag ( DropPen , true ) ; setDropFlag ( DropBrush , true ) ; addConnector ( "AssignName" , this , SIGNAL(assignNames(NAMEs&)) , this , SLOT (appendNames(NAMEs&)) ) ; addConnector ( "Commando" , Commando , SIGNAL ( timeout ( ) ) , this , SLOT ( DropCommands ( ) ) ) ; onlyConnector ( "AssignName" ) ; onlyConnector ( "Commando" ) ; //////////////////////////////////////////////// if ( NotNull ( plan ) ) { Data . Controller = & ( plan->canContinue ) ; } ; } void N::ComboBox::paintEvent(QPaintEvent * event) { nIsolatePainter ( QComboBox ) ; } void N::ComboBox::focusInEvent(QFocusEvent * event) { if (!focusIn (event)) QComboBox::focusInEvent (event) ; } void N::ComboBox::focusOutEvent(QFocusEvent * event) { if (!focusOut(event)) QComboBox::focusOutEvent(event) ; } void N::ComboBox::resizeEvent(QResizeEvent * event) { QComboBox :: resizeEvent ( event ) ; } void N::ComboBox::dragEnterEvent(QDragEnterEvent * event) { if (dragEnter(event)) event->acceptProposedAction() ; else { if (PassDragDrop) QComboBox::dragEnterEvent(event) ; else event->ignore() ; } ; } void N::ComboBox::dragLeaveEvent(QDragLeaveEvent * event) { if (removeDrop()) event->accept() ; else { if (PassDragDrop) QComboBox::dragLeaveEvent(event) ; else event->ignore() ; } ; } void N::ComboBox::dragMoveEvent(QDragMoveEvent * event) { if (dragMove(event)) event->acceptProposedAction() ; else { if (PassDragDrop) QComboBox::dragMoveEvent(event) ; else event->ignore() ; } ; } void N::ComboBox::dropEvent(QDropEvent * event) { if (drop(event)) event->acceptProposedAction() ; else { if (PassDragDrop) QComboBox::dropEvent(event) ; else event->ignore() ; } ; } bool N::ComboBox::acceptDrop(QWidget * source,const QMimeData * mime) { Q_UNUSED ( source ) ; Q_UNUSED ( mime ) ; return false ; } bool N::ComboBox::dropNew(QWidget * source,const QMimeData * mime,QPoint pos) { Q_UNUSED ( source ) ; Q_UNUSED ( mime ) ; Q_UNUSED ( pos ) ; return true ; } bool N::ComboBox::dropMoving(QWidget * source,const QMimeData * mime,QPoint pos) { Q_UNUSED ( source ) ; Q_UNUSED ( mime ) ; Q_UNUSED ( pos ) ; return true ; } bool N::ComboBox::dropAppend(QWidget * source,const QMimeData * mime,QPoint pos) { return dropItems ( source , mime , pos ) ; } bool N::ComboBox::dropFont(QWidget * source,QPointF pos,const SUID font) { Q_UNUSED ( source ) ; Q_UNUSED ( pos ) ; nKickOut ( IsNull(plan) , false ) ; Font f ; GraphicsManager GM ( plan ) ; EnterSQL ( SC , plan->sql ) ; f = GM.GetFont ( SC , font ) ; LeaveSQL ( SC , plan->sql ) ; assignFont ( f ) ; return true ; } bool N::ComboBox::dropPen(QWidget * source,QPointF pos,const SUID pen) { Q_UNUSED ( source ) ; Q_UNUSED ( pos ) ; nKickOut ( IsNull(plan) , false ) ; Pen p ; GraphicsManager GM ( plan ) ; EnterSQL ( SC , plan->sql ) ; p = GM.GetPen ( SC , pen ) ; LeaveSQL ( SC , plan->sql ) ; assignPen ( p ) ; return true ; } bool N::ComboBox::dropBrush(QWidget * source,QPointF pos,const SUID brush) { Q_UNUSED ( source ) ; Q_UNUSED ( pos ) ; nKickOut ( IsNull(plan) , false ) ; Brush b ; GraphicsManager GM ( plan ) ; EnterSQL ( SC , plan->sql ) ; b = GM.GetBrush ( SC , brush ) ; LeaveSQL ( SC , plan->sql ) ; assignBrush ( b ) ; return true ; } void N::ComboBox::DropCommands(void) { LaunchCommands ( ) ; } void N::ComboBox::assignFont(Font & f) { QComboBox::setFont ( f ) ; } void N::ComboBox::assignPen(Pen & p) { Q_UNUSED ( p ) ; } void N::ComboBox::assignBrush(Brush & b) { QBrush B = b ; QPalette P = palette ( ) ; P . setBrush ( QPalette::Base , B ) ; setPalette ( P ) ; } void N::ComboBox::appendNames(NAMEs & names) { N :: AddItems ( ME , names ) ; } void N::ComboBox::appendNames(UUIDs & uuids,NAMEs & names) { SUID u ; foreach ( u , uuids ) { addItem ( names[u] , u ) ; } ; } void N::ComboBox::addItems(SqlConnection & SC,UUIDs & Uuids) { SUID uuid ; foreach (uuid,Uuids) { QString name = SC.getName(PlanTable(Names),"uuid",vLanguageId,uuid) ; addItem ( name , uuid ) ; } ; } void N::ComboBox::addItems(UUIDs Uuids) { SqlConnection SC(plan->sql) ; if (SC.open("ComboBox","addItems")) { addItems ( SC , Uuids ) ; SC.close ( ) ; } ; SC.remove() ; } void N::ComboBox::addItems(QString table,enum Qt::SortOrder sorting) { SqlConnection SC(plan->sql) ; if (SC.open("ComboBox","addItems")) { UUIDs Uuids = SC.Uuids ( table , "uuid" , SC.OrderBy("id",sorting) ) ; addItems ( SC , Uuids ) ; SC.close ( ) ; } ; SC.remove() ; } void N::ComboBox::addGroups ( SUID group , int t1 , int t2 , int relation , enum Qt::SortOrder sorting ) { GroupItems GI ( plan ) ; SqlConnection SC ( plan -> sql ) ; if (SC.open("ComboBox","addGroups")) { UUIDs U ; U = GI . Subordination ( SC , group , t1 , t2 , relation , SC.OrderBy("position",sorting) ) ; addItems ( SC , U ) ; SC.close ( ) ; } ; SC.remove() ; } void N::ComboBox::addDivision(int type,enum Qt::SortOrder sorting) { GroupItems GI ( plan ) ; SqlConnection SC ( plan -> sql ) ; if (SC.open("ComboBox","addDivision")) { UUIDs U ; U = GI . Groups ( SC , (Types::ObjectTypes)type , SC.OrderBy("id",sorting) ) ; addItems ( SC , U ) ; SC.close ( ) ; } ; SC.remove() ; } void N::ComboBox::pendItems(UUIDs U) { VarArgs V ; V << U.count() ; toVariants ( U , V ) ; start ( 10001 , V ) ; } void N::ComboBox::pendItems(QString table,enum Qt::SortOrder sorting) { VarArgs V ; V << table ; V << (int)sorting ; start ( 10002 , V ) ; } void N::ComboBox::pendGroups ( SUID group , int t1 , int t2 , int relation , enum Qt::SortOrder sorting ) { VarArgs V ; V << group ; V << t1 ; V << t2 ; V << relation ; V << (int)sorting ; start ( 10003 , V ) ; } void N::ComboBox::pendDivision(int type,enum Qt::SortOrder sorting) { VarArgs V ; V << type ; V << (int)sorting ; start ( 10004 , V ) ; } void N::ComboBox::run(int Type,ThreadData * data) { UUIDs U ; VarArgs V = data->Arguments ; int t ; switch ( Type ) { case 10001 : startLoading ( ) ; t = V [ 0 ] . toInt ( ) ; for (int i=1;i<=t;i++) { U << V [ i ] . toULongLong ( ) ; } ; addItems ( U ) ; stopLoading ( ) ; break ; case 10002 : startLoading ( ) ; t = V [ 1 ] .toInt() ; addItems ( V [ 0 ] .toString() , (enum Qt::SortOrder)t ) ; stopLoading ( ) ; break ; case 10003 : startLoading ( ) ; t = V [ 4 ] .toInt() ; addGroups ( V [ 0 ] . toULongLong ( ) , V [ 1 ] . toInt ( ) , V [ 2 ] . toInt ( ) , V [ 3 ] . toInt ( ) , (enum Qt::SortOrder)t ) ; stopLoading ( ) ; break ; case 10004 : startLoading ( ) ; t = V [ 1 ] .toInt() ; addDivision ( V[0].toInt() , (enum Qt::SortOrder)t ) ; stopLoading ( ) ; break ; } ; }
32.406685
80
0.381382
Vladimir-Lin
89cd26664f503d7a4c4d04bf69a6ccc3ecc4f4e5
10,555
cc
C++
GUI/Master/NotesWindow.cc
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
GUI/Master/NotesWindow.cc
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
GUI/Master/NotesWindow.cc
jwillemsen/sidecar
941d9f3b84d05ca405df1444d4d9fd0bde03887f
[ "MIT" ]
null
null
null
#include "QtCore/QByteArray" #include "QtCore/QDir" #include "QtCore/QFile" #include "QtCore/QSettings" #include "QtGui/QCursor" #include "QtGui/QTextDocument" #include "QtWidgets/QApplication" #include "QtWidgets/QMessageBox" #include "GUI/LogUtils.h" #include "App.h" #include "NotesWindow.h" #include "RadarSettings.h" #include "RecordingController.h" #include "RecordingInfo.h" #include "ui_NotesWindow.h" using namespace SideCar::GUI; using namespace SideCar::GUI::Master; Logger::Log& NotesWindow::Log() { static Logger::Log& log_ = Logger::Log::Find("master.NotesWindow"); return log_; } NotesWindow::NotesWindow(RecordingController& controller, RecordingInfo& info) : Super(), gui_(new Ui::NotesWindow), controller_(controller), info_(info) { Logger::ProcLog log("NotesWindow", Log()); LOGINFO << std::endl; gui_->setupUi(this); setVisibleAfterRestore(false); connect(getApp(), SIGNAL(closingAuxillaryWindows()), SLOT(close())); connect(gui_->recordingStop_, SIGNAL(clicked()), &controller, SLOT(startStop())); connect(gui_->actionStop_Recording, SIGNAL(triggered()), &controller, SLOT(startStop())); connect(gui_->actionUndo, SIGNAL(triggered()), gui_->notes_, SLOT(undo())); connect(gui_->actionRedo, SIGNAL(triggered()), gui_->notes_, SLOT(redo())); connect(gui_->actionCut, SIGNAL(triggered()), gui_->notes_, SLOT(cut())); connect(gui_->actionCopy, SIGNAL(triggered()), gui_->notes_, SLOT(copy())); connect(gui_->actionPaste, SIGNAL(triggered()), gui_->notes_, SLOT(paste())); connect(gui_->actionInsert_Time, SIGNAL(triggered()), SLOT(on_insertNow__clicked())); connect(gui_->actionInsert_Elapsed, SIGNAL(triggered()), SLOT(on_insertElapsed__clicked())); connect(gui_->notes_, SIGNAL(copyAvailable(bool)), gui_->actionCut, SLOT(setEnabled(bool))); connect(gui_->notes_, SIGNAL(copyAvailable(bool)), gui_->actionCopy, SLOT(setEnabled(bool))); connect(gui_->notes_, SIGNAL(undoAvailable(bool)), gui_->actionUndo, SLOT(setEnabled(bool))); connect(gui_->notes_, SIGNAL(redoAvailable(bool)), gui_->actionRedo, SLOT(setEnabled(bool))); gui_->actionCut->setEnabled(false); gui_->actionCopy->setEnabled(false); gui_->actionUndo->setEnabled(false); gui_->actionRedo->setEnabled(false); RadarSettings& radarSettings(App::GetApp()->getRadarSettings()); gui_->radarTransmitting_->setChecked(radarSettings.isTransmitting()); gui_->radarFrequency_->setValue(radarSettings.getFrequency()); gui_->radarRotating_->setChecked(radarSettings.isRotating()); gui_->radarRotationRate_->setValue(radarSettings.getRotationRate()); gui_->drfmOn_->setChecked(radarSettings.isDRFMOn()); gui_->drfmConfig_->setText(radarSettings.getDRFMConfig()); statsChanged(); connect(gui_->radarTransmitting_, SIGNAL(clicked()), SLOT(radarTransmittingChanged())); connect(gui_->radarFrequency_, SIGNAL(valueChanged(double)), &info, SLOT(infoChanged())); radarTransmittingChanged(); connect(gui_->radarRotating_, SIGNAL(clicked()), SLOT(radarRotatingChanged())); connect(gui_->radarRotationRate_, SIGNAL(valueChanged(double)), &info, SLOT(infoChanged())); radarRotatingChanged(); connect(gui_->drfmOn_, SIGNAL(clicked()), SLOT(drfmOnChanged())); connect(gui_->drfmConfig_, SIGNAL(editingFinished()), &info, SLOT(infoChanged())); drfmOnChanged(); connect(&info, SIGNAL(statsChanged()), SLOT(statsChanged())); gui_->insertNow_->setEnabled(true); gui_->recordingStop_->setEnabled(true); setWindowTitle(QString("%1 Notes").arg(info.getName())); gui_->now_->setText(controller.getNow()); gui_->elapsed_->setText(info_.getFormattedElapsedTime()); QAction* insertNow = new QAction("Insert Now", this); connect(insertNow, SIGNAL(triggered()), SLOT(on_insertNow__clicked())); QAction* insertElapsed = new QAction("Insert Elapsed", this); connect(insertElapsed, SIGNAL(triggered()), SLOT(on_insertElapsed__clicked())); } void NotesWindow::makeMenuBar() { App* app = App::GetApp(); QMenuBar* mb = menuBar(); mb->insertMenu(mb->actions().front(), app->makeApplicationMenu(this)); setWindowMenu(app->makeWindowMenu(this)); mb->addMenu(getWindowMenu()); mb->addMenu(app->makeLoggingMenu(this)); mb->addMenu(app->makeHelpMenu(this)); } void NotesWindow::radarTransmittingChanged() { gui_->radarFrequency_->setEnabled(gui_->radarTransmitting_->isChecked()); info_.infoChanged(); } void NotesWindow::radarRotatingChanged() { gui_->radarRotationRate_->setEnabled(gui_->radarRotating_->isChecked()); info_.infoChanged(); } void NotesWindow::drfmOnChanged() { gui_->drfmConfig_->setEnabled(gui_->drfmOn_->isChecked()); gui_->drfmConfigLabel_->setEnabled(gui_->drfmOn_->isChecked()); info_.infoChanged(); } void NotesWindow::recordingStopped() { gui_->recordingInfo_->setVisible(false); gui_->actionStop_Recording->setEnabled(false); addTimeStampedEntry("*** STOPPED ***"); saveToFile(); } void NotesWindow::recordingTick(const QString& now) { gui_->now_->setText(now); gui_->elapsed_->setText(info_.getFormattedElapsedTime()); } void NotesWindow::on_insertNow__clicked() { gui_->notes_->insertPlainText(QString("%1 ").arg(gui_->now_->text())); gui_->notes_->setFocus(Qt::OtherFocusReason); } void NotesWindow::on_insertElapsed__clicked() { gui_->notes_->insertPlainText(QString("%1 ").arg(gui_->elapsed_->text())); gui_->notes_->setFocus(Qt::OtherFocusReason); } void NotesWindow::addTimeStampedEntry(const QString& text) { gui_->notes_->moveCursor(QTextCursor::End); gui_->notes_->textCursor().insertText(QString("%1 %2\n").arg(gui_->now_->text()).arg(text)); gui_->notes_->moveCursor(QTextCursor::End); } void NotesWindow::closeEvent(QCloseEvent* event) { Logger::ProcLog log("closeEvent", Log()); LOGINFO << std::endl; saveToFile(); Super::closeEvent(event); } void NotesWindow::loadFromFile(QFile& file) { Logger::ProcLog log("loadFromFile", Log()); gui_->recordingInfo_->setVisible(false); gui_->actionStop_Recording->setEnabled(false); // Radar Transmitting // QByteArray data = file.readLine().trimmed(); QList<QByteArray> bits = data.split(' '); if (bits.count() == 7) { gui_->radarTransmitting_->setChecked(true); gui_->radarFrequency_->setValue(bits[5].toDouble()); } else { gui_->radarTransmitting_->setChecked(false); } // Radar Rotating // data = file.readLine().trimmed(); bits = data.split(' '); if (bits.count() == 7) { gui_->radarRotating_->setChecked(true); gui_->radarRotationRate_->setValue(bits[5].toDouble()); } else { gui_->radarRotating_->setChecked(false); } // Using DRFM // data = file.readLine().trimmed(); bits = data.split(' '); gui_->drfmOn_->setChecked(false); if (bits.count() > 3) { gui_->drfmOn_->setChecked(true); QString tmp(bits[5]); for (int index = 6; index < bits.size(); ++index) { tmp.append(' '); tmp.append(bits[index]); } gui_->drfmConfig_->setText(tmp.trimmed()); } else { gui_->drfmOn_->setChecked(false); } auto _ = file.readLine().trimmed(); gui_->notes_->document()->setPlainText(file.readAll()); statsChanged(); } void NotesWindow::saveToFile() { Logger::ProcLog log("saveToFile", Log()); LOGINFO << std::endl; QApplication::setOverrideCursor(Qt::WaitCursor); QByteArray data; data.append("Configurations: ") .append(info_.getConfigurationNames().join(" ")) .append("\nDuration: ") .append(info_.getElapsedTime()) .append("\nDropped Messages: ") .append(gui_->drops_->text()) .append("\nDuplicate Messages: ") .append(gui_->duplicates_->text()); data.append("\nRadar Transmitting: ").append(gui_->radarTransmitting_->isChecked() ? "YES" : "NO"); if (gui_->radarTransmitting_->isChecked()) data.append(" - Frequency: ").append(QString::number(gui_->radarFrequency_->value())).append(" MHz"); data.append("\nRadar Rotating: ").append(gui_->radarRotating_->isChecked() ? "YES" : "NO"); if (gui_->radarRotating_->isChecked()) data.append(" - Rate: ").append(QString::number(gui_->radarRotationRate_->value())).append(" rpm"); data.append("\nUsing DRFM: ").append(gui_->drfmOn_->isChecked() ? "YES" : "NO"); if (gui_->drfmOn_->isChecked()) data.append(" - Configuration: ").append(gui_->drfmConfig_->text()); data.append("\n\n"); data.append(gui_->notes_->document()->toPlainText().toLatin1()); foreach (QString path, info_.getRecordingDirectories()) { QDir dir(path); QFile file(dir.filePath("notes.txt")); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { file.write(data); file.close(); } } gui_->notes_->document()->setModified(false); QApplication::restoreOverrideCursor(); LOGDEBUG << "done" << std::endl; } void NotesWindow::statsChanged() { gui_->drops_->setNum(info_.getDropCount()); } bool NotesWindow::wasRadarTransmitting() const { return gui_->radarTransmitting_->isChecked(); } double NotesWindow::getRadarFrequency() const { return gui_->radarFrequency_->value(); } bool NotesWindow::wasRadarRotating() const { return gui_->radarRotating_->isChecked(); } double NotesWindow::getRadarRotationRate() const { return gui_->radarRotationRate_->value(); } bool NotesWindow::wasDRFMOn() const { return gui_->drfmOn_->isChecked(); } QString NotesWindow::getDRFMConfig() const { return wasDRFMOn() ? gui_->drfmConfig_->text() : QString(""); } void NotesWindow::start(const QStringList& changes) { if (!changes.isEmpty()) { addAlert("*** Parameter(s) Changed from Configuration:\n"); addAlerts(changes); } addTimeStampedEntry("*** STARTED ***"); } void NotesWindow::addChangedParameters(const QStringList& changes) { if (!changes.isEmpty()) { addTimeStampedEntry("*** Parameter(s) Changed:"); addAlerts(changes); } } void NotesWindow::addAlerts(const QStringList& alerts) { foreach (QString alert, alerts) addAlert(alert); } void NotesWindow::addAlert(const QString& alert) { gui_->notes_->moveCursor(QTextCursor::End); gui_->notes_->textCursor().insertText(alert); gui_->notes_->moveCursor(QTextCursor::End); }
29.48324
109
0.678351
jwillemsen
89ce426f74a24b73142fd46265afa8a66c571523
697
cpp
C++
4 course/parallel_programming/lab12/lab12_4/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
4 course/parallel_programming/lab12/lab12_4/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
4 course/parallel_programming/lab12/lab12_4/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
// Программа с пользовательской обработкой сигнала SIGINT. #include <signal.h> #include <iostream> using namespace std; // Функция my_handler - пользовательский обработчик сигнала. void my_handler(int nsig) { if (nsig == SIGINT) { cout << "Receive signal " << nsig << ", CTRL-C pressed" << endl; } else if (nsig == SIGQUIT) { cout << "Receive signal " << nsig << ", CTRL+4 pressed" << endl; } } int main() { // Выставляем реакцию процесса на сигнал SIGINT. signal(SIGINT, my_handler); signal(SIGQUIT, my_handler); // Начиная с этого места, процесс будет печатать сообщение о возникновении сигнала SIGINT. while(1); return 0; }
21.78125
94
0.64132
SgAkErRu
89cf4ebdef576fc7f831ef9da261df21c1dc87fc
5,703
cc
C++
camera/features/hdrnet/tests/hdrnet_processor_impl_test.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
camera/features/hdrnet/tests/hdrnet_processor_impl_test.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
camera/features/hdrnet/tests/hdrnet_processor_impl_test.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2021 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <memory> #include <string> #include <base/at_exit.h> #include <base/command_line.h> #include <base/files/file_util.h> #include <base/strings/string_number_conversions.h> #include <base/strings/string_split.h> #include <base/test/test_timeouts.h> #pragma push_macro("None") #pragma push_macro("Bool") #undef None #undef Bool // gtest's internal typedef of None and Bool conflicts with the None and Bool // macros in X11/X.h (https://github.com/google/googletest/issues/371). // X11/X.h is pulled in by the GL headers we include. #include <gtest/gtest.h> #pragma pop_macro("None") #pragma pop_macro("Bool") #include <hardware/gralloc.h> #include <sync/sync.h> #include <system/graphics.h> #include "cros-camera/common.h" #include "features/hdrnet/tests/hdrnet_processor_test_fixture.h" namespace cros { struct Options { static constexpr const char kBenchmarkIterationsSwitch[] = "iterations"; static constexpr const char kInputSizeSwitch[] = "input-size"; static constexpr const char kOutputSizeSwitch[] = "output-sizes"; static constexpr const char kDumpBufferSwitch[] = "dump-buffer"; static constexpr const char kInputFile[] = "input-file"; static constexpr const char kInputFormat[] = "input-format"; // Use the default device processor to measure the latency of the core HDRnet // linear RGB pipeline. static constexpr const char kUseDefaulProcessorDeviceAdapter[] = "use-default-processor-device-adapter"; int iterations = 1000; Size input_size{1920, 1080}; std::vector<Size> output_sizes{{1920, 1080}, {1280, 720}}; bool dump_buffer = false; base::Optional<base::FilePath> input_file; bool use_default_processor_device_adapter = false; uint32_t input_format = HAL_PIXEL_FORMAT_YCbCr_420_888; }; Options g_args; void ParseCommandLine(int argc, char** argv) { base::CommandLine command_line(argc, argv); { std::string arg = command_line.GetSwitchValueASCII(Options::kBenchmarkIterationsSwitch); if (!arg.empty()) { CHECK(base::StringToInt(arg, &g_args.iterations)); } } { std::string arg = command_line.GetSwitchValueASCII(Options::kInputSizeSwitch); if (!arg.empty()) { std::vector<std::string> arg_split = base::SplitString( arg, "x", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); CHECK_EQ(arg_split.size(), 2); CHECK(base::StringToUint(arg_split[0], &g_args.input_size.width)); CHECK(base::StringToUint(arg_split[1], &g_args.input_size.height)); } } { std::string arg = command_line.GetSwitchValueASCII(Options::kOutputSizeSwitch); if (!arg.empty()) { g_args.output_sizes.clear(); for (auto size : base::SplitString(arg, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) { std::vector<std::string> arg_split = base::SplitString( size, "x", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); CHECK_EQ(arg_split.size(), 2); uint32_t width, height; CHECK(base::StringToUint(arg_split[0], &width)); CHECK(base::StringToUint(arg_split[1], &height)); g_args.output_sizes.push_back({width, height}); } } } if (command_line.HasSwitch(Options::kDumpBufferSwitch)) { g_args.dump_buffer = true; } { std::string arg = command_line.GetSwitchValueASCII(Options::kInputFile); if (!arg.empty()) { base::FilePath path(arg); CHECK(base::PathExists(path)) << ": Input file does not exist"; g_args.input_file = path; } } { std::string arg = command_line.GetSwitchValueASCII(Options::kInputFormat); if (!arg.empty()) { CHECK(arg == "nv12" || arg == "p010") << "Unrecognized input format: " << arg; if (arg == "nv12") { g_args.input_format = HAL_PIXEL_FORMAT_YCBCR_420_888; } else { // arg == "p010" g_args.input_format = HAL_PIXEL_FORMAT_YCBCR_P010; } } } if (command_line.HasSwitch(Options::kUseDefaulProcessorDeviceAdapter)) { g_args.use_default_processor_device_adapter = true; } } class HdrNetProcessorTest : public testing::Test { public: HdrNetProcessorTest() : fixture_(g_args.input_size, g_args.input_format, g_args.output_sizes, g_args.use_default_processor_device_adapter) {} ~HdrNetProcessorTest() = default; protected: HdrNetProcessorTestFixture fixture_; }; TEST_F(HdrNetProcessorTest, FullPipelineTest) { if (g_args.input_file) { fixture_.LoadInputFile(*g_args.input_file); } HdrnetMetrics metrics; for (int i = 0; i < g_args.iterations; ++i) { Camera3CaptureDescriptor result = fixture_.ProduceFakeCaptureResult(); fixture_.processor()->ProcessResultMetadata(&result); base::ScopedFD fence = fixture_.processor()->Run( i, HdrNetConfig::Options(), fixture_.input_image(), base::ScopedFD(), fixture_.output_buffers(), &metrics); constexpr int kFenceWaitTimeoutMs = 300; ASSERT_EQ(sync_wait(fence.get(), kFenceWaitTimeoutMs), 0); } if (g_args.dump_buffer) { fixture_.DumpBuffers(testing::UnitTest::GetInstance() ->current_test_info() ->test_case_name()); } } } // namespace cros int main(int argc, char** argv) { base::AtExitManager exit_manager; base::CommandLine::Init(argc, argv); TestTimeouts::Initialize(); cros::ParseCommandLine(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
33.745562
79
0.682272
Toromino
89d190c4b043c886e75f81bca3cfbd3773c2488b
3,867
cpp
C++
posix/subsystem/src/inotify.cpp
avdgrinten/managarm
4c4478cbde21675ca31e65566f10e1846b268bd5
[ "MIT" ]
13
2017-02-13T23:29:44.000Z
2021-09-30T05:41:21.000Z
posix/subsystem/src/inotify.cpp
avdgrinten/managarm
4c4478cbde21675ca31e65566f10e1846b268bd5
[ "MIT" ]
12
2016-12-03T13:06:13.000Z
2018-05-04T15:49:17.000Z
posix/subsystem/src/inotify.cpp
avdgrinten/managarm
4c4478cbde21675ca31e65566f10e1846b268bd5
[ "MIT" ]
1
2021-12-01T19:01:53.000Z
2021-12-01T19:01:53.000Z
#include <string.h> #include <sys/epoll.h> #include <sys/inotify.h> #include <iostream> #include <async/doorbell.hpp> #include <helix/ipc.hpp> #include "fs.hpp" #include "inotify.hpp" #include "process.hpp" #include "vfs.hpp" namespace inotify { namespace { struct OpenFile : File { public: struct Packet { int descriptor; uint32_t events; std::string name; uint32_t cookie; }; struct Watch final : FsObserver { Watch(OpenFile *file_, int descriptor, uint32_t mask) : file{file_}, descriptor{descriptor}, mask{mask} { } void observeNotification(uint32_t events, const std::string &name, uint32_t cookie) override { uint32_t inotifyEvents = 0; if(events & FsObserver::deleteEvent) inotifyEvents |= IN_DELETE; if(!(inotifyEvents & mask)) return; file->_queue.push_back(Packet{descriptor, inotifyEvents & mask, name, cookie}); file->_inSeq = ++file->_currentSeq; file->_statusBell.ring(); } OpenFile *file; int descriptor; uint32_t mask; }; static void serve(smarter::shared_ptr<OpenFile> file) { helix::UniqueLane lane; std::tie(lane, file->_passthrough) = helix::createStream(); async::detach(protocols::fs::servePassthrough(std::move(lane), smarter::shared_ptr<File>{file}, &File::fileOperations)); } OpenFile() : File{StructName::get("inotify")} { } ~OpenFile() { // TODO: Properly keep track of watches. std::cout << "\e[31m" "posix: Destruction of inotify leaks watches" "\e[39m" << std::endl; } expected<size_t> readSome(Process *, void *data, size_t maxLength) override { // TODO: As an optimization, we could return multiple events at the same time. Packet packet = std::move(_queue.front()); _queue.pop_front(); if(maxLength < sizeof(inotify_event) + packet.name.size() + 1) co_return Error::illegalArguments; inotify_event e; memset(&e, 0, sizeof(inotify_event)); e.wd = packet.descriptor; e.mask = packet.events; e.cookie = packet.cookie; e.len = packet.name.size(); memcpy(data, &e, sizeof(inotify_event)); memcpy(reinterpret_cast<char *>(data) + sizeof(inotify_event), packet.name.c_str(), packet.name.size() + 1); co_return sizeof(inotify_event) + packet.name.size() + 1; } expected<PollResult> poll(Process *, uint64_t sequence, async::cancellation_token cancellation) override { // TODO: Return Error::fileClosed as appropriate. assert(sequence <= _currentSeq); while(sequence == _currentSeq && !cancellation.is_cancellation_requested()) co_await _statusBell.async_wait(cancellation); int edges = 0; if(_inSeq > sequence) edges |= EPOLLIN; int events = 0; if(!_queue.empty()) events |= EPOLLIN; co_return PollResult(_currentSeq, edges, events); } helix::BorrowedDescriptor getPassthroughLane() override { return _passthrough; } int addWatch(std::shared_ptr<FsNode> node, uint32_t mask) { // TODO: Coalesce watch descriptors for the same inode. if(mask & ~(IN_DELETE)) std::cout << "posix: inotify mask " << mask << " is partially ignored" << std::endl; auto descriptor = _nextDescriptor++; auto watch = std::make_shared<Watch>(this, descriptor, mask); node->addObserver(watch); return descriptor; } private: helix::UniqueLane _passthrough; std::deque<Packet> _queue; // TODO: Use a proper ID allocator to allocate watch descriptor IDs. int _nextDescriptor = 1; async::doorbell _statusBell; uint64_t _currentSeq = 1; uint64_t _inSeq = 0; }; } // anonymous namespace smarter::shared_ptr<File, FileHandle> createFile() { auto file = smarter::make_shared<OpenFile>(); file->setupWeakFile(file); OpenFile::serve(file); return File::constructHandle(std::move(file)); } int addWatch(File *base, std::shared_ptr<FsNode> node, uint32_t mask) { auto file = static_cast<OpenFile *>(base); return file->addWatch(std::move(node), mask); } } // namespace inotify
27.041958
107
0.703905
avdgrinten
89d215bb4b949c5521664a49866c9d9546559c13
8,518
cc
C++
chrome/browser/chromeos/login/web_kiosk_controller_browsertest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chromeos/login/web_kiosk_controller_browsertest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chromeos/login/web_kiosk_controller_browsertest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/app_mode/web_app/mock_web_kiosk_app_launcher.h" #include "chrome/browser/chromeos/login/session/user_session_manager.h" #include "chrome/browser/chromeos/login/web_kiosk_controller.h" #include "chrome/browser/ui/ash/keyboard/chrome_keyboard_controller_client_test_helper.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/webui/chromeos/login/fake_app_launch_splash_screen_handler.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_profile.h" #include "components/account_id/account_id.h" #include "components/session_manager/core/session_manager.h" #include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; namespace chromeos { class WebKioskControllerTest : public InProcessBrowserTest { public: using AppState = WebKioskController::AppState; using NetworkUIState = WebKioskController::NetworkUIState; WebKioskControllerTest() = default; WebKioskControllerTest(const WebKioskControllerTest&) = delete; WebKioskControllerTest& operator=(const WebKioskControllerTest&) = delete; void SetUpOnMainThread() override { InProcessBrowserTest::SetUpOnMainThread(); auto app_launcher = std::make_unique<MockWebKioskAppLauncher>(); view_ = std::make_unique<FakeAppLaunchSplashScreenHandler>(); app_launcher_ = app_launcher.get(); controller_ = WebKioskController::CreateForTesting(view_.get(), std::move(app_launcher)); } WebKioskController* controller() { return controller_.get(); } WebKioskAppLauncher::Delegate* launch_controls() { return static_cast<WebKioskAppLauncher::Delegate*>(controller_.get()); } UserSessionManagerDelegate* session_controls() { return static_cast<UserSessionManagerDelegate*>(controller_.get()); } AppLaunchSplashScreenView::Delegate* view_controls() { return static_cast<AppLaunchSplashScreenView::Delegate*>(controller_.get()); } MockWebKioskAppLauncher* launcher() { return app_launcher_; } void ExpectState(AppState app_state, NetworkUIState network_state) { EXPECT_EQ(app_state, controller_->app_state_); EXPECT_EQ(network_state, controller_->network_ui_state_); } void FireSplashScreenTimer() { controller_->OnTimerFire(); } void SetOnline(bool online) { view_->SetNetworkReady(online); static_cast<AppLaunchSplashScreenView::Delegate*>(controller_.get()) ->OnNetworkStateChanged(online); } Profile* profile() { return browser()->profile(); } FakeAppLaunchSplashScreenHandler* view() { return view_.get(); } private: std::unique_ptr<FakeAppLaunchSplashScreenHandler> view_; MockWebKioskAppLauncher* app_launcher_; // owned by |controller_|. std::unique_ptr<WebKioskController> controller_; }; IN_PROC_BROWSER_TEST_F(WebKioskControllerTest, RegularFlow) { controller()->StartWebKiosk(EmptyAccountId()); ExpectState(AppState::CREATING_PROFILE, NetworkUIState::NOT_SHOWING); EXPECT_CALL(*launcher(), Initialize(_)).Times(1); session_controls()->OnProfilePrepared(profile(), false); launch_controls()->InitializeNetwork(); ExpectState(AppState::INIT_NETWORK, NetworkUIState::NOT_SHOWING); EXPECT_CALL(*launcher(), ContinueWithNetworkReady()).Times(1); SetOnline(true); launch_controls()->OnAppStartedInstalling(); launch_controls()->OnAppPrepared(); ExpectState(AppState::INSTALLED, NetworkUIState::NOT_SHOWING); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::LAUNCHED, NetworkUIState::NOT_SHOWING); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } IN_PROC_BROWSER_TEST_F(WebKioskControllerTest, AlreadyInstalled) { controller()->StartWebKiosk(EmptyAccountId()); ExpectState(AppState::CREATING_PROFILE, NetworkUIState::NOT_SHOWING); EXPECT_CALL(*launcher(), Initialize(_)).Times(1); session_controls()->OnProfilePrepared(profile(), false); launch_controls()->OnAppPrepared(); ExpectState(AppState::INSTALLED, NetworkUIState::NOT_SHOWING); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::LAUNCHED, NetworkUIState::NOT_SHOWING); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } IN_PROC_BROWSER_TEST_F(WebKioskControllerTest, ConfigureNetworkBeforeProfile) { controller()->StartWebKiosk(EmptyAccountId()); ExpectState(AppState::CREATING_PROFILE, NetworkUIState::NOT_SHOWING); // User presses the hotkey. view_controls()->OnNetworkConfigRequested(); ExpectState(AppState::CREATING_PROFILE, NetworkUIState::NEED_TO_SHOW); EXPECT_CALL(*launcher(), Initialize(_)).Times(1); session_controls()->OnProfilePrepared(profile(), false); // WebKioskAppLauncher::Initialize call is synchronous, we have to call the // response now. launch_controls()->InitializeNetwork(); ExpectState(AppState::INIT_NETWORK, NetworkUIState::SHOWING); EXPECT_CALL(*launcher(), ContinueWithNetworkReady()).Times(1); view_controls()->OnNetworkConfigFinished(); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); launch_controls()->OnAppPrepared(); // Skipping INSTALLED state since there splash screen timer is stopped when // network configure ui was shown. launch_controls()->OnAppLaunched(); ExpectState(AppState::LAUNCHED, NetworkUIState::NOT_SHOWING); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } IN_PROC_BROWSER_TEST_F(WebKioskControllerTest, ConfigureNetworkDuringInstallation) { controller()->StartWebKiosk(EmptyAccountId()); ExpectState(AppState::CREATING_PROFILE, NetworkUIState::NOT_SHOWING); EXPECT_CALL(*launcher(), Initialize(_)).Times(1); session_controls()->OnProfilePrepared(profile(), false); launch_controls()->InitializeNetwork(); ExpectState(AppState::INIT_NETWORK, NetworkUIState::NOT_SHOWING); EXPECT_CALL(*launcher(), ContinueWithNetworkReady()).Times(1); SetOnline(true); launch_controls()->OnAppStartedInstalling(); // User presses the hotkey, current installation is canceled. EXPECT_CALL(*launcher(), CancelCurrentInstallation()).Times(1); view_controls()->OnNetworkConfigRequested(); ExpectState(AppState::INIT_NETWORK, NetworkUIState::SHOWING); EXPECT_CALL(*launcher(), ContinueWithNetworkReady()).Times(1); view_controls()->OnNetworkConfigFinished(); launch_controls()->OnAppStartedInstalling(); ExpectState(AppState::INSTALLING, NetworkUIState::NOT_SHOWING); launch_controls()->OnAppPrepared(); ExpectState(AppState::INSTALLED, NetworkUIState::NOT_SHOWING); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::LAUNCHED, NetworkUIState::NOT_SHOWING); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } IN_PROC_BROWSER_TEST_F(WebKioskControllerTest, ConnectionLostDuringInstallation) { controller()->StartWebKiosk(EmptyAccountId()); ExpectState(AppState::CREATING_PROFILE, NetworkUIState::NOT_SHOWING); EXPECT_CALL(*launcher(), Initialize(_)).Times(1); session_controls()->OnProfilePrepared(profile(), false); launch_controls()->InitializeNetwork(); ExpectState(AppState::INIT_NETWORK, NetworkUIState::NOT_SHOWING); EXPECT_CALL(*launcher(), ContinueWithNetworkReady()).Times(1); SetOnline(true); launch_controls()->OnAppStartedInstalling(); EXPECT_CALL(*launcher(), CancelCurrentInstallation()).Times(1); SetOnline(false); ExpectState(AppState::INIT_NETWORK, NetworkUIState::SHOWING); EXPECT_CALL(*launcher(), ContinueWithNetworkReady()).Times(1); view_controls()->OnNetworkConfigFinished(); launch_controls()->OnAppStartedInstalling(); ExpectState(AppState::INSTALLING, NetworkUIState::NOT_SHOWING); launch_controls()->OnAppPrepared(); ExpectState(AppState::INSTALLED, NetworkUIState::NOT_SHOWING); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::LAUNCHED, NetworkUIState::NOT_SHOWING); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } } // namespace chromeos
37.690265
89
0.767668
sarang-apps
89d71df45db0d567d681e5286bf650ef2dc12542
2,078
cpp
C++
Settings.cpp
mariosbikos/Augmented_Reality_Chess_Game_RGB-D
aa22b722a9f7b6f94891c6015166e39d1570c27c
[ "MIT" ]
6
2016-05-29T01:10:33.000Z
2019-12-04T13:34:05.000Z
Settings.cpp
mariosbikos/Augmented_Reality_Chess_Game_RGB-D
aa22b722a9f7b6f94891c6015166e39d1570c27c
[ "MIT" ]
null
null
null
Settings.cpp
mariosbikos/Augmented_Reality_Chess_Game_RGB-D
aa22b722a9f7b6f94891c6015166e39d1570c27c
[ "MIT" ]
5
2015-11-22T14:36:29.000Z
2021-03-31T06:52:21.000Z
#include "Settings.h" void SetCameraParameters(std::string TheIntrinsicFile) { TheDistCameraParameters.readFromXMLFile(TheIntrinsicFile); TheDistCameraParameters.resize( cv::Size(constants::COLOR_WIDTH,constants::COLOR_HEIGHT) ); TheCameraParameters=TheDistCameraParameters; //The cv::Mat Distortion of TheCameraParameters become all-0 TheCameraParameters.Distorsion.setTo( cv::Scalar::all(0) ); } void SetDictionary(aruco::Dictionary &D) { if (!D.fromFile(TheDictionaryFile)) { cerr<<"Could not open dictionary file"<<endl; exit(1); } } void SetBoardDetectorParameters(BoardConfiguration& TheBoardConfig, CameraParameters& TheCameraParameters,float TheMarkerSize,Dictionary& D) { //Set the properties of aruco-BoardDetector TheBoardDetector.setYPerperdicular(false); TheBoardDetector.setParams(TheBoardConfig,TheCameraParameters,TheMarkerSize); //Set the parameters of the INTERNAL Marker Detector //Threhold parameters //1)Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on. //2)The constant subtracted from the mean or weighted mean TheBoardDetector.getMarkerDetector().setThresholdParams( constants::THRESHOLD_PARAMETER_1,constants::THRESHOLD_PARAMETER_2); // for blue-green markers, the window size has to be larger TheBoardDetector.getMarkerDetector().setMakerDetectorFunction(aruco::HighlyReliableMarkers::detect); TheBoardDetector.getMarkerDetector().setCornerRefinementMethod(aruco::MarkerDetector::LINES); TheBoardDetector.getMarkerDetector().setWarpSize( (D[0].n() + 2) * 8 ); TheBoardDetector.getMarkerDetector().setMinMaxSize(0.005, 0.5); } void SetOffsetValuesBasedOnMarkerSize() { //Set offset for rendering in the lower left corner of chessboard(center of marker 0,0) //3.5 is 3 cells and a half to go to (0,0) marker of chessboard Offset_X_M=(-3.5 * TheMarkerSize - 3.5 * constants::SPACE_BETWEEN_CELLS); Offset_Y_M=(-3.5 * TheMarkerSize - 3.5 * constants::SPACE_BETWEEN_CELLS); Offset_Pieces_M= TheMarkerSize + constants::SPACE_BETWEEN_CELLS; }
42.408163
185
0.786814
mariosbikos
89d8347c92b8a2e321d3484e482702ff32661d41
1,091
ipp
C++
include/External/stlib/packages/numerical/random/gamma/GammaGeneratorMarsagliaTsang.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
include/External/stlib/packages/numerical/random/gamma/GammaGeneratorMarsagliaTsang.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
include/External/stlib/packages/numerical/random/gamma/GammaGeneratorMarsagliaTsang.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
// -*- C++ -*- #if !defined(__numerical_random_GammaGeneratorMarsagliaTsang_ipp__) #error This file is an implementation detail of GammaGeneratorMarsagliaTsang. #endif namespace numerical { template < typename T, class Uniform, template<class> class Normal > inline typename GammaGeneratorMarsagliaTsang<T, Uniform, Normal>::result_type GammaGeneratorMarsagliaTsang<T, Uniform, Normal>:: operator()(const Number a) { #ifdef DEBUG_stlib assert(a >= 1); #endif const Number d = a - 1. / 3.; const Number c = 1 / std::sqrt(9 * d); Number x, v, u; for (;;) { do { x = ((*_normalGenerator)()); v = 1 + c * x; } while (v <= 0); v = v * v * v; u = transformDiscreteDeviateToContinuousDeviateOpen<Number> ((*_normalGenerator->getDiscreteUniformGenerator())()); if (u < 1 - 0.331 * x * x * x * x) { return d * v; } if (std::log(u) < 0.5 * x * x + d *(1 - v + std::log(v))) { return d * v; } } } } // namespace numerical
26.609756
78
0.56187
bxl295
89dbf4bcc8fd03715f0ec2ef881dda474025b745
7,308
cpp
C++
ControlX/wk.cpp
bikashtudu/Interfacing-and-Data-Acquisition-from-Scientific-Instruments
e2da91b2a9a8a7bf19aac75334925ae30b2c10e9
[ "MIT" ]
null
null
null
ControlX/wk.cpp
bikashtudu/Interfacing-and-Data-Acquisition-from-Scientific-Instruments
e2da91b2a9a8a7bf19aac75334925ae30b2c10e9
[ "MIT" ]
null
null
null
ControlX/wk.cpp
bikashtudu/Interfacing-and-Data-Acquisition-from-Scientific-Instruments
e2da91b2a9a8a7bf19aac75334925ae30b2c10e9
[ "MIT" ]
1
2018-08-04T14:12:15.000Z
2018-08-04T14:12:15.000Z
#include "wk.h" #include "ui_wk.h" #include "measureset.h" #include "traceset.h" #include "wkmeter.h" #include "QFile" #include "QTextStream" #include <QDebug> #include "allfun4.h" #include <QPixmap> #define sta sta4 #define sto sto4 #define read read4 #define write write4 #define delay delay1 #include <QTime> #include <wk.h> QString props[12]={"L","C","Q","D","R","X","Z","Y","Angle","B","G","L"}; QString propy[11]={"Inductance","Capacitance","Q-factor","D-factor","Resistance","Reactance","Impedance","Admittance","Angle","Susceptance","Conductance"}; QVector< QString > vec; int j; int pt; qreal mi,Ma; QFile fi("/home/dell/build-CTC100-Desktop_Qt_5_8_0_GCC_64bit-Debug/check.txt"); QTextStream foo(&fi); void delay1( int millisecondsToWait ) { millisecondsToWait*=1000; QTime dieTime = QTime::currentTime().addMSecs( millisecondsToWait ); while( QTime::currentTime() < dieTime ) { QCoreApplication::processEvents( QEventLoop::AllEvents, 100 ); } } void readfile() { QFile file("/home/dell/build-CTC100-Desktop_Qt_5_8_0_GCC_64bit-Debug/wk.txt"); vec.clear(); file.open(QIODevice::ReadOnly); while(!file.atEnd()) { char a[1025]; file.readLine(a,sizeof(a)); if(a[0]=='r' and a[1]=='e') { QString temp; int x=strlen(a); for(int i=18;i<x-2;i++) { temp=temp+a[i]; } vec.push_back(temp); //qDebug()<<temp; } } } void wk::writelog() { sta(); read("ANA:POINTS?"); sto(); readfile(); QFile file1("/home/dell/build-CTC100-Desktop_Qt_5_8_0_GCC_64bit-Debug/Graphs/"+props[j]+"~Freq"+".txt"); QFile file2("/home/dell/build-CTC100-Desktop_Qt_5_8_0_GCC_64bit-Debug/Graphs/"+props[j+1]+"~Freq"+".txt"); file1.open(QFile::WriteOnly |QFile::Text); file2.open(QFile::WriteOnly |QFile::Text); QTextStream out1(&file1); QTextStream out2(&file2); int tot=vec[0].toInt(); //qDebug()<<vec[0]; sta(); for(int i=0;i<tot;i++) { read("ANA:POINT? "+QString::number(i)); } sto(); readfile(); out1<<"Frquency(Hz)"<<" "<<props[j]<<endl<<endl; out2<<"Frquency(Hz)"<<" "<<props[j+1]<<endl<<endl; for(int i=0;i<tot;i++) { QStringList my = vec[i].split(','); out1<<my[0]<<" "<<my[1]<<endl; out2<<my[0]<<" "<<my[2]<<endl; } //delay(ui->spinBox_3->value()); for(int i=0;i<11;i++) {int temp=250; sta(); write("ANA:PROP1 "+props[i]); write("ANA:FIT 3"); sto(); QFile file1("/home/dell/build-CTC100-Desktop_Qt_5_8_0_GCC_64bit-Debug/Graphs/"+props[i]+"~Freq"+".txt"); file1.open(QFile::ReadWrite); QTextStream out(&file1); out<<temp<<" "; sta(); for(int i=0;i<=tot;i++) { read("ANA:POINT? "+QString::number(i)); } sto(); readfile(); for(int i=0;i<11;i++) { QStringList my = vec[i].split(','); out<<my[1]<<" "; } } } bool biasm=0; wk::wk(QWidget *parent) : QMainWindow(parent), ui(new Ui::wk) { ui->setupUi(this); fi.open(QIODevice::ReadOnly); this->setWindowTitle("Analysis Mode"); sta(); read("ANA:BIAS-STAT?"); sto(); readfile(); if(vec[0][0]=="0") { QPixmap pixmap(":/on.jpg"); QIcon ButtonIcon(pixmap); ui->pushButton->setIcon(ButtonIcon); ui->pushButton->setIconSize(QSize(61,31)); biasm=1; } else { QPixmap pixmap(":/on-off.jpg"); QIcon ButtonIcon(pixmap); ui->pushButton->setIcon(ButtonIcon); ui->pushButton->setIconSize(QSize(61,31)); biasm=0; } //Graphs...1 for(int i=0;i<11;i++){ series[i] = new QLineSeries(); chart[i] = new QChart(); axisX[i] = new QValueAxis(); axisY[i] = new QValueAxis(); series[i]->setName(propy[i]+" Vs Temperature"); series[i]->setPointsVisible(true); chart[i]->addSeries(series[i]); chart[i]->addAxis(axisY[i], Qt::AlignLeft); chart[i]->setAxisX(axisX[i], series[i]); series[i]->attachAxis(axisY[i]); //series[i]->attachAxis(axisX[i]); axisX[i]->setTitleText("Temperature"); axisY[i]->setTitleText(propy[i]); axisY[i]->setLabelFormat("%0.4E"); series[i]->setPointsVisible(true); // axisY[i]->setTickCount(10); //axisX[i]->setRange(); //axisY[i]->setRange(0,250); chartView[i] = new QChartView(chart[i]); } ui->gridLayout_4->addWidget(chartView[0]); ui->gridLayout_5->addWidget(chartView[1]); ui->gridLayout_6->addWidget(chartView[2]); ui->gridLayout_7->addWidget(chartView[3]); ui->gridLayout_8->addWidget(chartView[4]); ui->gridLayout_9->addWidget(chartView[5]); ui->gridLayout_10->addWidget(chartView[6]); ui->gridLayout_11->addWidget(chartView[7]); ui->gridLayout_12->addWidget(chartView[8]); ui->gridLayout_13->addWidget(chartView[9]); ui->gridLayout_14->addWidget(chartView[10]); } wk::~wk() { delete ui; } void wk::on_pushButton_2_clicked() { wkmeter* ptr=new wkmeter; ptr->show(); hide(); } void wk::on_meas_setup_clicked() { measureset* ptr; ptr= new measureset; ptr->show(); } void wk::on_trace_setup_clicked() { traceset* ptr; ptr=new traceset; ptr->show(); } void wk::on_pushButton_clicked() { if(biasm==1) { QPixmap pixmap(":/on-off.jpg"); QIcon ButtonIcon(pixmap); ui->pushButton->setIcon(ButtonIcon); ui->pushButton->setIconSize(QSize(61,31)); biasm=0; sta(); write("ANA:BIAS-STAT OFF"); sto(); } else { QPixmap pixmap(":/on.jpg"); QIcon ButtonIcon(pixmap); ui->pushButton->setIcon(ButtonIcon); ui->pushButton->setIconSize(QSize(61,31)); biasm=1; sta(); write("ANA:BIAS-STAT ON"); sto(); } } void wk::on_trig_clicked() { sta(); write("ANA:TRIG"); sto(); delay(50); for( j=0;j<11;j+=2) { sta(); write("ANA:PROP1 "+props[j]); write("ANA:PROP2 "+props[j+1]); write("ANA:FIT 3"); sto(); writelog(); } //writelog(); } /*void wk::on_add_clicked() { // fi.open(QIODevice::ReadOnly); char a[1025]; fi.readLine(a,sizeof(a)); QString cur=a; double yt=cur.toDouble(); fi.readLine(a,sizeof(a)); cur=a; double xt=cur.toDouble(); qreal y=qreal(yt); qreal x=qreal(xt); series[3]->append(x,y); if(pt==0) { if(y>0) {mi=y-y/50; Ma=y+y/50;} else {mi=y+y/50; Ma=y-y/50;} axisX[3]->setRange(x-5,x+5); } else { if(y<mi) mi=y-(mi-y); else if(y>Ma) Ma=y+(y-Ma); axisX[3]->setMax(x+5); } axisY[3]->setRange(mi,Ma); pt++; foo<<y<<" "<<mi<<" "<<Ma<<endl; //series[0]->attachAxis(axisY[0]); }*/
20.132231
155
0.532704
bikashtudu
89e25d3362cd03cd30ac65a747e3a353fea83e1f
7,427
cpp
C++
SDKs/CryCode/3.6.15/CryEngine/CryAction/GameRulesSystem.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
4
2017-12-18T20:10:16.000Z
2021-02-07T21:21:24.000Z
SDKs/CryCode/3.8.1/CryEngine/CryAction/GameRulesSystem.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
null
null
null
SDKs/CryCode/3.8.1/CryEngine/CryAction/GameRulesSystem.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
3
2019-03-11T21:36:15.000Z
2021-02-07T21:21:26.000Z
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2004. ------------------------------------------------------------------------- $Id$ $DateTime$ Description: ------------------------------------------------------------------------- History: - 15:9:2004 10:30 : Created by Mathieu Pinard *************************************************************************/ #include "StdAfx.h" #include "GameObjects/GameObjectSystem.h" #include "GameObjects/GameObject.h" #include "GameRulesSystem.h" #include "Network/GameServerNub.h" #include <list> #ifdef WIN64 #pragma warning ( disable : 4244 ) #endif #define GAMERULES_GLOBAL_VARIABLE ("g_gameRules") #define GAMERULESID_GLOBAL_VARIABLE ("g_gameRulesId") //------------------------------------------------------------------------ CGameRulesSystem::CGameRulesSystem( ISystem *pSystem, IGameFramework *pGameFW ) : m_pGameFW(pGameFW), m_pGameRules(0), m_currentGameRules(0) { } //------------------------------------------------------------------------ CGameRulesSystem::~CGameRulesSystem() { } //------------------------------------------------------------------------ bool CGameRulesSystem::RegisterGameRules( const char *rulesName, const char *extensionName ) { IEntityClassRegistry::SEntityClassDesc ruleClass; char scriptName[1024]; sprintf(scriptName, "Scripts/GameRules/%s.lua", rulesName); ruleClass.sName = rulesName; ruleClass.sScriptFile = scriptName; ruleClass.pUserProxyCreateFunc = CreateGameObject; ruleClass.pUserProxyData = this; ruleClass.flags |= ECLF_INVISIBLE; if (!gEnv->pEntitySystem->GetClassRegistry()->RegisterStdClass(ruleClass)) { CRY_ASSERT(0); return false; } std::pair<TGameRulesMap::iterator, bool> rit=m_GameRules.insert(TGameRulesMap::value_type(rulesName, SGameRulesDef())); rit.first->second.extension=extensionName; return true; } //------------------------------------------------------------------------ bool CGameRulesSystem::CreateGameRules( const char *rulesName) { const char *name=GetGameRulesName(rulesName); TGameRulesMap::iterator it=m_GameRules.find(name); if (it==m_GameRules.end()) return false; // If a rule is currently being used, ask the entity system to remove it DestroyGameRules(); SEntitySpawnParams params; params.sName = "GameRules"; params.pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass( name ); params.nFlags |= ENTITY_FLAG_NO_PROXIMITY|ENTITY_FLAG_UNREMOVABLE; params.id = 1; IEntity* pEntity = gEnv->pEntitySystem->SpawnEntity( params ); CRY_ASSERT(pEntity); if (pEntity == NULL) return false; pEntity->Activate(true); if (pEntity->GetScriptTable()) { IScriptSystem *pSS = gEnv->pScriptSystem; pSS->SetGlobalValue(GAMERULES_GLOBAL_VARIABLE, pEntity->GetScriptTable()); pSS->SetGlobalValue(GAMERULESID_GLOBAL_VARIABLE, ScriptHandle((UINT_PTR)m_currentGameRules)); } //since we re-instantiating game rules, let's get rid of everything related to previous match if(IGameplayRecorder *pGameplayRecorder = CCryAction::GetCryAction()->GetIGameplayRecorder()) pGameplayRecorder->Event(pEntity, GameplayEvent(eGE_GameReset)); if(gEnv->bServer) { if (CGameServerNub* pGameServerNub = CCryAction::GetCryAction()->GetGameServerNub()) pGameServerNub->ResetOnHoldChannels(); } return true; } //------------------------------------------------------------------------ bool CGameRulesSystem::DestroyGameRules() { // If a rule is currently being used, ask the entity system to remove it if ( m_currentGameRules ) { IEntity* pEntity = gEnv->pEntitySystem->GetEntity(m_currentGameRules); if (pEntity) pEntity->ClearFlags(ENTITY_FLAG_UNREMOVABLE); gEnv->pEntitySystem->RemoveEntity( m_currentGameRules, true ); SetCurrentGameRules(0); IScriptSystem *pSS = gEnv->pScriptSystem; pSS->SetGlobalToNull(GAMERULES_GLOBAL_VARIABLE); pSS->SetGlobalToNull(GAMERULESID_GLOBAL_VARIABLE); } return true; } //------------------------------------------------------------------------ bool CGameRulesSystem::HaveGameRules( const char *rulesName ) { const char *name=GetGameRulesName(rulesName); if (!name || !gEnv->pEntitySystem->GetClassRegistry()->FindClass( name )) return false; if (m_GameRules.find(name) == m_GameRules.end() ) return false; return true; } //------------------------------------------------------------------------ void CGameRulesSystem::AddGameRulesAlias(const char *gamerules, const char *alias) { if (SGameRulesDef *def=GetGameRulesDef(gamerules)) def->aliases.push_back(alias); } //------------------------------------------------------------------------ void CGameRulesSystem::AddGameRulesLevelLocation(const char *gamerules, const char *mapLocation) { if (SGameRulesDef *def=GetGameRulesDef(gamerules)) def->maplocs.push_back(mapLocation); } //------------------------------------------------------------------------ const char *CGameRulesSystem::GetGameRulesLevelLocation(const char *gamerules, int i) { if (SGameRulesDef *def=GetGameRulesDef(GetGameRulesName(gamerules))) { if (i>=0 && i<def->maplocs.size()) return def->maplocs[i].c_str(); } return 0; } //------------------------------------------------------------------------ void CGameRulesSystem::SetCurrentGameRules(IGameRules *pGameRules) { m_pGameRules = pGameRules; m_currentGameRules = m_pGameRules ? m_pGameRules->GetEntityId() : 0; } //------------------------------------------------------------------------ IGameRules * CGameRulesSystem::GetCurrentGameRules() const { return m_pGameRules; } //------------------------------------------------------------------------ const char *CGameRulesSystem::GetGameRulesName(const char *alias) const { for (TGameRulesMap::const_iterator it=m_GameRules.begin(); it!=m_GameRules.end(); ++it) { if (!stricmp(it->first.c_str(), alias)) return it->first.c_str(); for (std::vector<string>::const_iterator ait=it->second.aliases.begin();ait!=it->second.aliases.end(); ++ait) { if (!stricmp(ait->c_str(), alias)) return it->first.c_str(); } } return 0; } //------------------------------------------------------------------------ /* string& CGameRulesSystem::GetCurrentGameRules() { return } */ CGameRulesSystem::SGameRulesDef *CGameRulesSystem::GetGameRulesDef(const char *name) { TGameRulesMap::iterator it = m_GameRules.find(name); if (it==m_GameRules.end()) return 0; return &it->second; } //------------------------------------------------------------------------ IEntityProxyPtr CGameRulesSystem::CreateGameObject(IEntity *pEntity, SEntitySpawnParams &params, void *pUserData) { CGameRulesSystem *pThis = static_cast<CGameRulesSystem *>(pUserData); CRY_ASSERT(pThis); TGameRulesMap::iterator it = pThis->m_GameRules.find(params.pClass->GetName()); CRY_ASSERT(it != pThis->m_GameRules.end()); CGameObjectPtr pGameObject = ComponentCreateAndRegister_DeleteWithRelease<CGameObject>( IComponent::SComponentInitializer(pEntity), IComponent::EComponentFlags_LazyRegistration ); if (!it->second.extension.empty()) { if (!pGameObject->ActivateExtension(it->second.extension.c_str())) { pEntity->RegisterComponent( pGameObject, false ); pGameObject.reset(); } } return pGameObject; } void CGameRulesSystem::GetMemoryStatistics(ICrySizer * s) { s->Add(*this); s->AddContainer(m_GameRules); }
29.240157
181
0.616534
amrhead
89e47d188b3e6af0bb150c137ccdfd5a4a456159
586
hpp
C++
main/config.hpp
brianinnes/waterMonitor
fa5d21fa511b2d763c26c2807056b65d513a05d1
[ "Apache-2.0" ]
6
2019-06-09T11:57:40.000Z
2021-11-11T19:40:46.000Z
main/config.hpp
brianinnes/waterMonitor
fa5d21fa511b2d763c26c2807056b65d513a05d1
[ "Apache-2.0" ]
null
null
null
main/config.hpp
brianinnes/waterMonitor
fa5d21fa511b2d763c26c2807056b65d513a05d1
[ "Apache-2.0" ]
4
2019-06-09T11:57:43.000Z
2021-12-18T14:36:59.000Z
#pragma once #ifndef WATER_MONITOR_CONFIG_H #define WATER_MONITOR_CONFIG_H #include <string> namespace waterMonitor { class waterMonitorConfig { public: std::string getMqttHost() const; std::string getMqttUser() const; std::string getMqttPassword() const; std::string getMqttCARootCert() const; void loadConfig(); void saveConfig() const; private: std::string mqttHost; std::string mqttUser; std::string mqttPassword; std::string mqttCARootCert; }; } #endif // WATER_MONITOR_CONFIG_H
20.206897
46
0.65529
brianinnes
89e644052dd68012cdb4039d8972a40e186d0b90
2,977
cpp
C++
ALight-RayCPU-Reference/mesh.cpp
Asixa/ALight-Renderer-Complex
30b1ac19053ee89f38ee5b10e85387c92309e5bc
[ "FTL" ]
1
2020-07-28T09:25:51.000Z
2020-07-28T09:25:51.000Z
ALight-RayCPU-Reference/mesh.cpp
Asixa/ALight-Renderer-Complex
30b1ac19053ee89f38ee5b10e85387c92309e5bc
[ "FTL" ]
null
null
null
ALight-RayCPU-Reference/mesh.cpp
Asixa/ALight-Renderer-Complex
30b1ac19053ee89f38ee5b10e85387c92309e5bc
[ "FTL" ]
null
null
null
#include "mesh.h" Mesh::Mesh(const char *fileName, Material material) { m_fileName = fileName; m_material = material; if (loadObj() != 0) { std::cerr << "Mesh: Error loading " << m_fileName << std::endl; std::exit(1); } std::cout << "Mesh: " << m_fileName << " has been loaded succesfully." << std::endl; } int Mesh::loadObj() { std::vector<vec3> vertices; std::vector<vec3> normals; std::vector<face> indices; std::ifstream file; std::string line; file.open(m_fileName); if (file.is_open()) { while (file.good()) { std::getline(file, line); if (line.substr(0, 2) == "v ") { std::istringstream s(line.substr(2)); vec3 v; s >> v.x; s >> v.y; s >> v.z; vertices.push_back(v); } else if (line.substr(0, 2) == "vn ") { std::istringstream s(line.substr(2)); vec3 n; s >> n.x; s >> n.y; s >> n.z; normals.push_back(n); } else if (line.substr(0, 2) == "f ") { if (line.find("//") == std::string::npos) { std::istringstream s(line.substr(2)); face f; s >> f.va; s >> f.vb; s >> f.vc; f.va--; f.vb--; f.vc--; indices.push_back(f); } else { std::replace(line.begin(), line.end(), '/', ' '); std::istringstream s(line.substr(2)); face f; s >> f.va; s >> f.na; s >> f.vb; s >> f.nb; s >> f.vc; s >> f.nc; f.va--; f.na--; f.vb--; f.nb--; f.vc--; f.nc--; indices.push_back(f); } } else { continue; } } } else { return 1; } for (size_t i = 0; i < indices.size(); i++) { vec3 v0 = vertices[indices[i].va]; vec3 v1 = vertices[indices[i].vb]; vec3 v2 = vertices[indices[i].vc]; if (normals.size() > 0) { vec3 n0 = normals[indices[i].na]; vec3 n1 = normals[indices[i].nb]; vec3 n2 = normals[indices[i].nc]; m_triangles.push_back(Triangle(v0, v1, v2, n0, n1, n2, m_material)); } else { m_triangles.push_back(Triangle(v0, v1, v2, m_material)); } } return 0; }
25.444444
88
0.356063
Asixa
89eae73ba1a6b81299a89893c8f328a496874954
287
cpp
C++
core/src/cubos/core/io/cursor.cpp
GameDevTecnico/cubos
51f89c9f3afc8afe502d167dadecab7dfe5b1c7b
[ "MIT" ]
2
2021-09-28T14:13:27.000Z
2022-03-26T11:36:48.000Z
core/src/cubos/core/io/cursor.cpp
GameDevTecnico/cubos
51f89c9f3afc8afe502d167dadecab7dfe5b1c7b
[ "MIT" ]
72
2021-09-29T08:55:26.000Z
2022-03-29T21:21:00.000Z
core/src/cubos/core/io/cursor.cpp
GameDevTecnico/cubos
51f89c9f3afc8afe502d167dadecab7dfe5b1c7b
[ "MIT" ]
null
null
null
#include <cubos/core/io/cursor.hpp> using namespace cubos::core; #ifdef WITH_GLFW io::Cursor::Cursor(GLFWcursor* handle) { this->glfwHandle = handle; } #endif io::Cursor::~Cursor() { #ifdef WITH_GLFW if (this->glfwHandle) glfwDestroyCursor(this->glfwHandle); #endif }
15.105263
44
0.69338
GameDevTecnico
89ebe60d08ae3001c8121d40f733a4b8ffc18a03
675
cpp
C++
Data Structures and Algorithms CPP/09 Linked List 1/Assignment/02AppendLtoF.cpp
shivamaggarwal513/Coding-Ninjas
b445f4caf09730cc0a6cc7d2ab10fda3e9188111
[ "MIT" ]
null
null
null
Data Structures and Algorithms CPP/09 Linked List 1/Assignment/02AppendLtoF.cpp
shivamaggarwal513/Coding-Ninjas
b445f4caf09730cc0a6cc7d2ab10fda3e9188111
[ "MIT" ]
null
null
null
Data Structures and Algorithms CPP/09 Linked List 1/Assignment/02AppendLtoF.cpp
shivamaggarwal513/Coding-Ninjas
b445f4caf09730cc0a6cc7d2ab10fda3e9188111
[ "MIT" ]
null
null
null
#include <iostream> #include "..\01LinkedList.h" using namespace std; Node *appendLtoF(Node *head, int n) { if (n == 0) return head; int size = lengthLL(head); int i = 0; Node *temp = head; while (i < size - n - 1) { temp = temp->next; i++; } Node *newTail = temp, *newHead = temp->next; while (temp->next) temp = temp->next; newTail->next = nullptr; temp->next = head; return newHead; } int main() { int t, n; Node *head; cin >> t; while (t--) { head = takeInput(); cin >> n; head = appendLtoF(head, n); printLL(head); } return 0; }
17.763158
48
0.496296
shivamaggarwal513
8851eb91b640daf6f65521884f718c6b6d402a14
41,327
cpp
C++
belatedly/src/belatedly.cpp
Ahziu/Delayed-Hits
39e062a34ce7d3bb693dceff0a7e68ea1ee6864b
[ "BSD-3-Clause-Clear" ]
15
2020-09-04T18:32:14.000Z
2022-03-31T08:29:05.000Z
belatedly/src/belatedly.cpp
Ahziu/Delayed-Hits
39e062a34ce7d3bb693dceff0a7e68ea1ee6864b
[ "BSD-3-Clause-Clear" ]
1
2021-02-18T08:14:29.000Z
2021-02-18T08:14:29.000Z
belatedly/src/belatedly.cpp
Ahziu/Delayed-Hits
39e062a34ce7d3bb693dceff0a7e68ea1ee6864b
[ "BSD-3-Clause-Clear" ]
4
2020-10-17T21:39:38.000Z
2021-06-04T14:29:27.000Z
// STD headers #include <assert.h> #include <fstream> #include <functional> #include <iomanip> #include <iostream> #include <list> #include <string> #include <thread> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // Boost headers #include <boost/bimap.hpp> #include <boost/program_options.hpp> // Cereal headers #include <cereal/archives/binary.hpp> #include <cereal/types/vector.hpp> // Gurobi headers #include <gurobi_c++.h> // Custom headers #include "flow_dict.hpp" #include "simulator.hpp" #include "utils.hpp" // Typedefs namespace bopt = boost::program_options; typedef std::tuple<std::string, bool, std::string, std::string, double> Edge; // Format: (flow_id, in_cache, src, dst, cost) // Constant hyperparameters constexpr unsigned int kNumThreads = 24; /** * Implements a Multi-Commodity Min-Cost Flow-based * solver for the Delayed Hits caching problem. */ class MCMCFSolver { private: typedef std::vector<size_t> Indices; // Trace and cache parameters const uint z_; const uint c_; const bool is_forced_; const size_t trace_len_; const std::string trace_file_path_; const std::string model_file_prefix_; const std::string packets_file_path_; const std::vector<std::string> trace_; // Housekeeping std::vector<double> solution_; std::unordered_set<size_t> cache_node_idxs_; std::unordered_map<std::string, Indices> indices_; boost::bimap<size_t, std::string> idx_to_nodename_; std::unordered_map<size_t, double> idx_to_miss_cost_; std::unordered_map<std::string, std::string> sink_nodes_; std::unordered_map<std::string, Indices> cache_interval_start_idxs_; // "Split nodes" are used to enforce forced admission, if required. // We detect nodes where the forced admission constraint *might* be // violated (i.e. an object doesn't remain in the cache for atleast // one timestep), and add manually a constraint that enforces this. std::unordered_set<size_t> split_node_idxs_; // Internal helper methods double getMissCostStartingAt(const size_t idx) const; const std::string& cchNodeForMemAt(const size_t idx) const; size_t getNextMemNodeIdx(const size_t idx, const std::string& flow_id, std::unordered_map<std::string, size_t>& next_idxs_map) const; // Thread-safe, concurrent helper methods void populateOutOfCchEdgesConcurrent( const std::list<std::string>& flow_ids, std::list<Edge>& edges, std::unordered_set<size_t>& cache_node_idxs); void populateCchCapacityConstraintsConcurrent( const std::pair<size_t, size_t> range, const belatedly::FlowDict& flows, std::list<GRBLinExpr>& exprs) const; // Setup and checkpointing void setup(); bool loadOptimizedModelSolution(belatedly::FlowDict& flows); void saveOptimizedModelSolution(const belatedly::FlowDict& flows) const; // Model creation void populateOutOfCchEdges(std::list<Edge>& all_edges); void createFlowVariables(GRBModel& model, belatedly::FlowDict& flows, const std::list<Edge>& edges) const; void populateCchCapacityConstraints( GRBModel& model, const belatedly::FlowDict& flows) const; void populateSplitNodeFlowConstraints( GRBModel& model, const belatedly::FlowDict& flows) const; void populateFlowConservationConstraints( GRBModel& model, const belatedly::FlowDict& flows) const; void addMissCostStartingAt(const size_t start_idx, const double coefficient, std::vector<utils::Packet>& packets) const; // Cost computation and validation double getCostLowerBound(const belatedly::FlowDict& flows, const std::list<Edge>& edges) const; double getCostUpperBoundAndValidateSolution( const belatedly::FlowDict& flows, const std::list<Edge>& edges) const; public: MCMCFSolver(const std::string& trace_fp, const std::string& model_fp, const std::string& packets_fp, const bool forced, const uint z, const uint c, const std::vector<std::string>& trace) : z_(z), c_(c), is_forced_(forced), trace_len_(trace.size()), trace_file_path_(trace_fp), model_file_prefix_(model_fp), packets_file_path_(packets_fp), trace_(trace) {} void solve(); }; /** * Given an index, returns the corresponding cache node. * * Thread-safe. */ const std::string& MCMCFSolver::cchNodeForMemAt(const size_t idx) const { return idx_to_nodename_.left.at(idx); } /** * Returns the cost of a cache miss starting at idx. * * Thread-safe. */ double MCMCFSolver::getMissCostStartingAt(const size_t idx) const { const std::string& flow_id = trace_[idx]; double miss_cost = z_; // Iterate over the next z timesteps, and add the // latency cost corresponding to each subsequent // packet of the same flow. for (size_t offset = 1; offset < z_; offset++) { if (idx + offset >= trace_len_) { break; } else if (trace_[idx + offset] == flow_id) { miss_cost += (z_ - offset); } } return miss_cost; } /** * Returns the index of the first mem node corresponding to the given * flow ID occuring after idx. If no reference to this flow is found * in (idx, trace_len_), returns maxval. * * The state for each flow is cached in next_idxs_map. This dict must * be cleared before starting a new operation (that is, when indices * are no longer expected to continue increasing monotonically). * * Thread-safe. */ size_t MCMCFSolver::getNextMemNodeIdx( const size_t idx, const std::string& flow_id, std::unordered_map<std::string, size_t>& next_idxs_map) const { const std::vector<size_t>& indices = indices_.at(flow_id); size_t indices_len = indices.size(); while ((next_idxs_map[flow_id] < indices_len) && (indices[next_idxs_map[flow_id]] <= idx)) { next_idxs_map[flow_id]++; } // If the next index is beyond the idxs list for // this flow, return the corresponding sink node. size_t next_idx = next_idxs_map[flow_id]; if (next_idx == indices_len) { return std::numeric_limits<size_t>::max(); } else { size_t next_mem_idx = indices[next_idx]; assert(trace_[next_mem_idx] == flow_id); return next_mem_idx; } } /** * Attempts to load the optimal solution and the flow mappings * for the given model. Returns true if successful, else false. */ bool MCMCFSolver::loadOptimizedModelSolution(belatedly::FlowDict& flows) { if (model_file_prefix_.empty()) { return false; } std::ifstream solution_ifs(model_file_prefix_ + ".sol"); const std::string flows_fp = model_file_prefix_ + ".flows"; // Either of the required model files is missing, indicating failure if (!solution_ifs.good() || !std::ifstream(flows_fp).good()) { return false; } // Load the solutions vector { cereal::BinaryInputArchive ar(solution_ifs); ar(solution_); } // Load the flow mappings flows.loadFlowMappings(flows_fp); // Sanity check: The number of decision variables should // be equal to the number of entries in the flows map. assert(solution_.size() == flows.numVariables()); return true; } /** * Saves the optimal solution and flow mappings to disk. */ void MCMCFSolver::saveOptimizedModelSolution( const belatedly::FlowDict& flows) const { if (model_file_prefix_.empty()) { return; } std::ofstream solution_ofs(model_file_prefix_ + ".sol"); const std::string flows_fp = model_file_prefix_ + ".flows"; // Save the solutions vector cereal::BinaryOutputArchive oarchive(solution_ofs); oarchive(solution_); // Save the flow mappings flows.saveFlowMappings(flows_fp); } /** * Populate the indices map and internal data structures. */ void MCMCFSolver::setup() { size_t num_nonempty_packets = 0; for (size_t idx = 0; idx < trace_len_; idx++) { const std::string& flow_id = trace_[idx]; // If the packet is non-empty, append the idx to // the corresponding flow's idxs. Also, populate // the miss-costs map. if (!flow_id.empty()) { num_nonempty_packets++; indices_[flow_id].push_back(idx); idx_to_miss_cost_[idx] = getMissCostStartingAt(idx); } // Found a possible violation of forced admission; track this as a split node if (is_forced_ && !flow_id.empty() && (idx > 0) && (idx < trace_len_ - z_) && (flow_id == trace_[idx - 1]) && (flow_id == trace_[idx + z_])) { split_node_idxs_.insert(idx); } // Populate the nodenames map idx_to_nodename_.insert(boost::bimap<size_t, std::string>::value_type( idx, "cch_t" + std::to_string(idx + z_ - 1) + "_" + flow_id)); } // Populate the sink nodes map and // prime the cache intervals map. for (const auto& iter : indices_) { const std::string& flow_id = iter.first; sink_nodes_[flow_id] = ("x_" + flow_id); cache_interval_start_idxs_[flow_id]; } // Debug std::cout << "Finished setup with " << trace_len_ << " packets (" << num_nonempty_packets << " nonempty), " << indices_.size() << " flows." << std::endl; } /** * Helper method. Populates the out-of-cache edges (mem->cch/admittance, * and cch->mem/eviction) for the given flow IDs in a thread-safe manner. * * Important note: This method relies on the fact that separate threads * operate on disjoint sets of flow IDs (and only ever access different * STL containers concurrently), precluding the need for mutexes. * * Thread-safe. */ void MCMCFSolver::populateOutOfCchEdgesConcurrent( const std::list<std::string>& flow_ids, std::list<Edge>& edges, std::unordered_set<size_t>& local_cache_node_idxs) { // Iterate over the given flow IDs to populate the edges list std::unordered_map<std::string, size_t> next_idxs_map; for (const std::string& flow_id : flow_ids) { std::string evicted_reference = std::string(); bool has_flow_started = false; // Iterate over each timestep and fetch the next mem reference for (size_t idx = 0; idx < trace_len_; idx++) { const std::string& trace_flow_id = trace_[idx]; bool is_same_flow = (!trace_flow_id.empty() && (trace_flow_id == flow_id)); if (has_flow_started) { // Fetch the next mem reference corresponding to this flow const size_t next_reference_idx = getNextMemNodeIdx( idx + z_ - 1, flow_id, next_idxs_map); const bool is_dst_sink_node = (next_reference_idx == std::numeric_limits<size_t>::max()); // Fetch the dst node for this out-of-cache edge const std::string& next_reference = is_dst_sink_node ? sink_nodes_.at(flow_id) : cchNodeForMemAt(next_reference_idx); if (is_same_flow) { // In optional admission, unconditionally create an // outedge from this node to the next mem reference. if (!is_forced_) { evicted_reference = next_reference; edges.push_back(std::make_tuple( flow_id, false, cchNodeForMemAt(idx), next_reference, (is_dst_sink_node ? 0.0 : idx_to_miss_cost_.at(next_reference_idx))) ); } // The following node in the trace (mem_t{idx + z}) maps to // this flow, but the previous node in the caching sequence // (cch_t{idx + z - 1}) also maps to it. Thus, this is the // final opportunity to reach mem_t{idx + z}, and we create // an edge to it. else if (split_node_idxs_.find(idx) != split_node_idxs_.end()) { assert(!is_dst_sink_node); edges.push_back(std::make_tuple( flow_id, false, cchNodeForMemAt(idx), next_reference, idx_to_miss_cost_.at(next_reference_idx)) ); } // Discard the next mem reference for this flow else { evicted_reference.clear(); } // Mark this idx as the start of a new interval for this flow local_cache_node_idxs.insert(idx); cache_interval_start_idxs_.at(flow_id).push_back(idx); } // If we did not already created an eviction edge to the // next mem reference for this flow, create one to it. else if (evicted_reference != next_reference) { evicted_reference = next_reference; edges.push_back(std::make_tuple( flow_id, false, cchNodeForMemAt(idx), next_reference, (is_dst_sink_node ? 0.0 : idx_to_miss_cost_.at(next_reference_idx))) ); // Mark this idx as the start of a new interval for this flow local_cache_node_idxs.insert(idx); cache_interval_start_idxs_.at(flow_id).push_back(idx); } } // The flow has not yet started and the packet at this timestep // belongs to this flow, indicating that this is the first ever // request to it. else if (is_same_flow) { has_flow_started = true; // In optional admission, unconditionally create an // outedge from this node to the next mem reference. if (!is_forced_) { // Fetch the next mem reference corresponding to this flow const size_t next_reference_idx = getNextMemNodeIdx( idx + z_ - 1, flow_id, next_idxs_map); const bool is_dst_sink_node = (next_reference_idx == std::numeric_limits<size_t>::max()); // Fetch the dst node for this out-of-cache edge const std::string& next_reference = is_dst_sink_node ? sink_nodes_.at(flow_id) : cchNodeForMemAt(next_reference_idx); evicted_reference = next_reference; edges.push_back(std::make_tuple( flow_id, false, cchNodeForMemAt(idx), next_reference, (is_dst_sink_node ? 0.0 : idx_to_miss_cost_.at(next_reference_idx))) ); } // Mark this idx as the start of a new interval for this flow local_cache_node_idxs.insert(idx); cache_interval_start_idxs_.at(flow_id).push_back(idx); } } } } /** * Populates the out-of-cache (eviction and admittance) edges. */ void MCMCFSolver::populateOutOfCchEdges(std::list<Edge>& all_edges) { size_t num_out_of_cch_edges = 0; size_t num_total_flows = indices_.size(); size_t num_flows_per_thread = int(ceil(num_total_flows / static_cast<double>(kNumThreads))); // Temporary containers for each thread size_t num_flows_allotted = 0; std::array<std::list<Edge>, kNumThreads> edges; std::array<std::list<std::string>, kNumThreads> flow_ids; std::array<std::unordered_set<size_t>, kNumThreads> local_cache_node_idxs; // Partition the entire set of flow IDs into kNumThreads disjoint sets auto iter = indices_.begin(); for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) { for (size_t i = 0; (i < num_flows_per_thread) && (iter != indices_.end()); i++, iter++) { num_flows_allotted++; flow_ids[t_idx].push_back(iter->first); } } // Sanity check assert(num_flows_allotted == num_total_flows); // Launch kNumThreads on the corresponding sets of flow IDs std::thread workers[kNumThreads]; for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) { workers[t_idx] = std::thread(&MCMCFSolver::populateOutOfCchEdgesConcurrent, this, std::ref(flow_ids[t_idx]), std::ref(edges[t_idx]), std::ref(local_cache_node_idxs[t_idx])); } // Wait for all the worker threads to finish execution for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) { workers[t_idx].join(); } // Then, combine their results for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) { num_out_of_cch_edges += edges[t_idx].size(); all_edges.splice(all_edges.end(), edges[t_idx]); cache_node_idxs_.insert(local_cache_node_idxs[t_idx].begin(), local_cache_node_idxs[t_idx].end()); } // Next, sort the cache intervals for each flow in-place for (auto& iter : cache_interval_start_idxs_) { std::vector<size_t>& start_idxs = iter.second; std::sort(start_idxs.begin(), start_idxs.end()); } // Finally, for the last packet in the trace, unconditionally // create an outedge to the corresponding flow's sink node. size_t idx = (trace_len_ - 1); const std::string& flow_id = trace_[idx]; if (is_forced_ && !flow_id.empty()) { num_out_of_cch_edges++; all_edges.push_back(std::make_tuple(flow_id, false, cchNodeForMemAt(idx), sink_nodes_.at(flow_id), 0.0)); } // Debug std::cout << "Finished populating " << num_out_of_cch_edges << " out-of-cache edges concurrently, using " << kNumThreads << " threads." << std::endl; } /** * Given a list of edges, populates the flow tupledict. */ void MCMCFSolver:: createFlowVariables(GRBModel& model, belatedly::FlowDict& flows, const std::list<Edge>& edges) const { size_t num_total_cache_intervals = 0; // First, create variables representing mem->cch and cch->mem edges for (const Edge& edge : edges) { flows.addVariable(std::get<0>(edge), std::get<1>(edge), std::get<2>(edge), std::get<3>(edge), std::get<4>(edge)); } // Next, for every flow, create decision variables // corresponding to each possible caching interval. for (const auto& iter : cache_interval_start_idxs_) { const std::string& flow_id = iter.first; const std::vector<size_t>& start_idxs = iter.second; const size_t num_intervals = (start_idxs.size() - 1); // Iterate over each interval for (size_t i = 0; i < num_intervals; i++) { size_t idx = start_idxs[i]; size_t next_idx = start_idxs[i + 1]; // Sanity check: Both indices should be in the nodes set assert((cache_node_idxs_.find(idx) != cache_node_idxs_.end()) && (cache_node_idxs_.find(next_idx) != cache_node_idxs_.end())); // Create a decision variable corresponding to cch_{idx}->cch_{next_idx} num_total_cache_intervals++; flows.addVariable(flow_id, true, cchNodeForMemAt(idx), cchNodeForMemAt(next_idx), 0.0); } } // Finally, update the model model.update(); // Debug std::cout << "Finished creating " << flows.numVariables() << " flow variables (for " << edges.size() << " edges, plus " << num_total_cache_intervals << " caching intervals)." << std::endl; } /** * Helper method. Populates the cache capacity constraints for * the given range of trace indices in a thread-safe manner. * * Thread-safe. */ void MCMCFSolver::populateCchCapacityConstraintsConcurrent( const std::pair<size_t, size_t> range, const belatedly:: FlowDict& flows, std::list<GRBLinExpr>& exprs) const { std::unordered_map<std::string, GRBVar> decision_variables; std::unordered_map<std::string, size_t> current_idxs; // Starting index is out-of-bounds, do nothing if (range.first >= trace_len_) { return; } // First, for each flow ID, forward its current iterator idx // to point to the appropriate location in its indices list. for (const auto& iter : cache_interval_start_idxs_) { const std::vector<size_t>& intervals = iter.second; const std::string& flow_id = iter.first; size_t i = 0; while (i < (intervals.size() - 1) && range.first > intervals[i + 1]) { i++; } // Update the current iterator idx current_idxs[flow_id] = i; } // Next, generate a linear-expression corresponding to the sum of // all flow decision variables at every timestep, and impose that // it is LEQ the cache size as a constraint. for (size_t idx = range.first; idx < range.second; idx++) { if (cache_node_idxs_.find(idx) == cache_node_idxs_.end()) { continue; } bool is_split_node = (split_node_idxs_.find(idx) != split_node_idxs_.end()); GRBLinExpr node_capacity_expr; bool is_expr_changed = false; // Update the current decision variable for each // flow and add it to the LHS of the constraints. for (const auto& iter : cache_interval_start_idxs_) { const std::string& flow_id = iter.first; const std::vector<size_t>& intervals = iter.second; bool is_split_node_for_flow = (is_split_node && (trace_[idx] == flow_id)); // If this trace index either precedes the first decision // variable, or is either at or beyond the last decision // variable for this flow, do nothing. size_t i = current_idxs[flow_id]; if (idx < intervals[0] || idx >= intervals.back()) { continue; } // Reached the first interval or the end // of the current interval for this flow. else if ((decision_variables.find(flow_id) == decision_variables.end()) || (idx == intervals[i + 1])) { // If this is the end of the current // interval, update the idx iterator. if (idx == intervals[i + 1]) { current_idxs[flow_id] = ++i; } // Fetch the current interval size_t start_idx = intervals[i]; size_t end_idx = intervals[i + 1]; // This is a regular node GRBVar decision_variable = ( flows.getVariable(flow_id, true, cchNodeForMemAt(start_idx), cchNodeForMemAt(end_idx))); // Update the decision variable for this flow decision_variables[flow_id] = decision_variable; node_capacity_expr += decision_variable; is_expr_changed = true; } // Else, add the current decision variable to the expression else { GRBVar decision_variable = decision_variables.at(flow_id); node_capacity_expr += decision_variable; assert(!is_split_node_for_flow); } } // Finally, add the expression as a cache constraints if (is_expr_changed) { exprs.push_back(node_capacity_expr); } } } /** * Populates the cache capacity constraints for the given flow variables. */ void MCMCFSolver::populateCchCapacityConstraints( GRBModel& model, const belatedly::FlowDict& flows) const { std::array<std::list<GRBLinExpr>, kNumThreads> exprs; std::thread workers[kNumThreads]; size_t num_constraints = 0; // Partition the trace into kNumThreads disjoint sets size_t start_idx = 0; size_t idxs_per_thread = int(ceil(trace_len_ / static_cast<double>(kNumThreads))); // Launch kNumThreads on the corresponding range of indices for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) { size_t end_idx = std::min(trace_len_, start_idx + idxs_per_thread); workers[t_idx] = std::thread( &MCMCFSolver::populateCchCapacityConstraintsConcurrent, this, std::make_pair(start_idx, end_idx), std::ref(flows), std::ref(exprs[t_idx])); // Update the starting idx start_idx = end_idx; } // Wait for all the worker threads to finish execution for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) { workers[t_idx].join(); } // Populate the model constraints for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) { for (auto& expr : exprs[t_idx]) { num_constraints++; model.addConstr(expr, GRB_LESS_EQUAL, c_, ""); } exprs[t_idx].clear(); } // Debug std::cout << "Finished adding " << num_constraints << " arc-capacity" << " constraints for cch->cch edges concurrently, using " << kNumThreads << " threads." << std::endl; } /** * Populates flow constraints for split nodes. These ensure that once * flow enters the cache, it remains there for at least one timestep. */ void MCMCFSolver::populateSplitNodeFlowConstraints( GRBModel& model, const belatedly::FlowDict& flows) const { size_t num_split_node_constraints = 0; for (const size_t idx : split_node_idxs_) { const std::string& flow_id = trace_[idx]; num_split_node_constraints++; // Fetch the decision variable corresponding // to the cch_{idx}->next_mem_node edge. const GRBVar outflow = flows.getVariable( flow_id, false, cchNodeForMemAt(idx), cchNodeForMemAt(idx + z_)); // Fetch the expression corresponding // to the mem_{idx}->cch_{idx} edge. const GRBLinExpr inflow = ( flows.sumAcrossSrcNodes(flow_id, false, cchNodeForMemAt(idx))); // Ensure that the outflow is LEQ (1 - inflow) model.addConstr(outflow + inflow, GRB_LESS_EQUAL, 1, ""); } // Debug std::cout << "Finished populating " << num_split_node_constraints << " flow constraints for split nodes." << std::endl; } /** * Populates the flow conservation constraints for all nodes. */ void MCMCFSolver::populateFlowConservationConstraints( GRBModel& model, const belatedly::FlowDict& flows) const { // Flow-conservation constraints for sink nodes size_t num_sink_node_constraints = 0; for (const auto& iter : indices_) { num_sink_node_constraints++; const std::string& flow_id = iter.first; const std::string& node = sink_nodes_.at(flow_id); model.addConstr(flows.sumAcrossSrcNodes(flow_id, node), GRB_EQUAL, 1, ""); } // Debug std::cout << "Finished adding " << num_sink_node_constraints << " flow-conservation constraints for sink nodes." << std::endl; // Flow-conservation constraints for cache nodes size_t num_cache_node_constraints = 0; for (const auto& iter : cache_interval_start_idxs_) { const std::string& flow_id = iter.first; const std::vector<size_t>& start_idxs = iter.second; for (size_t idx : start_idxs) { num_cache_node_constraints++; const std::string& node = cchNodeForMemAt(idx); assert(cache_node_idxs_.find(idx) != cache_node_idxs_.end()); // This is the source node for this flow if (idx == start_idxs.front()) { model.addConstr(flows.sumAcrossDstNodes(flow_id, node), GRB_EQUAL, 1, ""); } // Else, this is a regular node else { model.addConstr(flows.sumAcrossSrcNodes(flow_id, node), GRB_EQUAL, flows.sumAcrossDstNodes(flow_id, node), ""); } } } // Debug std::cout << "Finished adding " << num_cache_node_constraints << " flow-conservation constraints for cache nodes." << std::endl; } /** * Helper method. Given a start idx and cost coefficient (flow fraction), * updates latencies of subsequent same-flow packets that occur within z * timesteps of start_idx. */ void MCMCFSolver:: addMissCostStartingAt(const size_t start_idx, const double coefficient, std::vector<utils::Packet>& packets) const { if (utils::DoubleApproxEqual(coefficient, 0.)) { return; } // Iterate over the next z timesteps, and add the weighted // latency cost to each subsequent packet of the same flow. const std::string& flow_id = trace_[start_idx]; for (size_t offset = 0; offset < z_; offset++) { const size_t idx = start_idx + offset; if (idx >= trace_len_) { break; } else if (trace_[idx] == flow_id) { packets[idx].addLatency((z_ - offset) * coefficient); } } } /** * Returns a (tight) lower-bound on the cost of the LP solution. */ double MCMCFSolver::getCostLowerBound(const belatedly::FlowDict& flows, const std::list<Edge>& edges) const { // Create packets corresponding to each timestep std::vector<utils::Packet> processed_packets; for (const std::string& flow_id : trace_) { processed_packets.push_back(utils::Packet(flow_id)); } // Update the packet latency corresponding // to the first occurence of each flow. for (const auto& elem : indices_) { const size_t src_idx = elem.second.front(); addMissCostStartingAt(src_idx, 1., processed_packets); } // Next, add the latency cost of flow // routed through out-of-cch edges. for (const auto& edge : edges) { const bool in_cache = std::get<1>(edge); const std::string& src = std::get<2>(edge); const std::string& dst = std::get<3>(edge); const std::string& flow_id = std::get<0>(edge); // This is an out-of-cch edge and dst is not a sink node if (!in_cache && dst != sink_nodes_.at(flow_id)) { double flow_fraction = solution_[ flows.getVariableIdx(flow_id, in_cache, src, dst)]; size_t dst_idx = idx_to_nodename_.right.at(dst); addMissCostStartingAt(dst_idx, flow_fraction, processed_packets); } } // Compute the total latency for this solution double total_latency = 0; for (const utils::Packet& packet : processed_packets) { const std::string& flow_id = packet.getFlowId(); const double latency = packet.getTotalLatency(); if (!flow_id.empty()) { // Sanity check: For non-empty packets, latency should be in [0, z] assert(utils::DoubleApproxGreaterThanOrEqual(latency, 0.) && utils::DoubleApproxGreaterThanOrEqual(z_, latency)); total_latency += latency; } // Else, for empty packets, do nothing else { assert(latency == 0.); } } return total_latency; } /** * Validates the computed LP solution. */ double MCMCFSolver::getCostUpperBoundAndValidateSolution( const belatedly::FlowDict& flows, const std::list<Edge>& edges) const { std::vector<std::tuple<size_t, std::string, double>> evictions; std::vector<std::tuple<size_t, std::string, double>> inductions; // Parse the eviction schedule from the computed LP solution bool is_solution_integral = true; size_t num_fractional_vars = 0; for (const auto& edge : edges) { const bool in_cache = std::get<1>(edge); const std::string& flow_id = std::get<0>(edge); // If this is an out-of-cch edge, fetch the // decision variable corresponding to it. if (!in_cache) { const size_t src_idx = idx_to_nodename_.right.at( std::get<2>(edge)) + z_ - 1; const size_t dst_idx = (std::get<3>(edge) == sink_nodes_.at(flow_id)) ? std::numeric_limits<size_t>::max() : idx_to_nodename_.right.at(std::get<3>(edge)) + z_ - 1; double value = solution_[flows.getVariableIdx( flow_id, in_cache, std::get<2>(edge), std::get<3>(edge))]; // The solution has non-integral variables if (!utils::DoubleApproxEqual(value, 1.) && !utils::DoubleApproxEqual(value, 0.)) { is_solution_integral = false; num_fractional_vars++; } // Perform an eviction at this node if (value > 0.) { evictions.push_back(std::make_tuple(src_idx, flow_id, value)); if (dst_idx != std::numeric_limits<size_t>::max()) { inductions.push_back(std::make_tuple(dst_idx, flow_id, value)); } } } } // Populate the inductions list for source nodes for (const auto& item : indices_) { const std::string& flow_id = item.first; const size_t src_idx = item.second.front() + z_ - 1; inductions.push_back(std::make_tuple(src_idx, flow_id, 1.)); } // Sort the eviction schedule std::sort(evictions.begin(), evictions.end(), []( const std::tuple<size_t, std::string, double>& a, const std::tuple<size_t, std::string, double>& b) { return (std::get<0>(a) < std::get<0>(b)); }); // Sort the induction schedule std::sort(inductions.begin(), inductions.end(), []( const std::tuple<size_t, std::string, double>& a, const std::tuple<size_t, std::string, double>& b) { return (std::get<0>(a) < std::get<0>(b)); }); // Debug std::cout << "Solution is " << (is_solution_integral ? "INTEGRAL." : "FRACTIONAL.") << std::endl; // For fractional solutions, output the fraction of non-integer decision variables if (!is_solution_integral) { double percentage_fractional = (num_fractional_vars * 100.) / flows.numVariables(); std::cout << "Warning: Solution has " << num_fractional_vars << " fractional " << "decision variables (" << flows.numVariables() << " in total => " << std::fixed << std::setprecision(2) << percentage_fractional << "%)." << std::endl; } // Finally, run the cache simulator and validate the computed LP solution belatedly::CacheSimulator simulator(packets_file_path_, is_solution_integral, is_forced_, z_, c_, trace_, evictions, inductions); return simulator.run(); } /** * Solve the MCMCF instance for the given trace. */ void MCMCFSolver::solve() { // Populate the internal structs setup(); std::list<Edge> edges; populateOutOfCchEdges(edges); // Create optimization model GRBEnv env = GRBEnv(); GRBModel model = GRBModel(env); belatedly::FlowDict flows = belatedly::FlowDict(model); // If the solution does not already exist, re-run the optimizer bool is_loaded_from_file = loadOptimizedModelSolution(flows); double opt_cost = std::numeric_limits<double>::max(); if (!is_loaded_from_file) { // Create variables, populate constraints createFlowVariables(model, flows, edges); populateCchCapacityConstraints(model, flows); populateSplitNodeFlowConstraints(model, flows); populateFlowConservationConstraints(model, flows); // Compute the optimal solution model.set(GRB_IntAttr_ModelSense, GRB_MINIMIZE); model.set(GRB_DoubleParam_NodefileStart, 5); model.set(GRB_IntParam_Threads, 1); model.set(GRB_IntParam_Method, 1); model.optimize(); // Populate the solution vector int status = model.get(GRB_IntAttr_Status); assert(status == GRB_OPTIMAL); // Sanity check for (size_t idx = 0; idx < flows.numVariables(); idx++) { solution_.push_back(flows.getVariableAt(idx).get(GRB_DoubleAttr_X)); } // Save the optimal solution saveOptimizedModelSolution(flows); // Fetch the optimal cost opt_cost = model.get(GRB_DoubleAttr_ObjVal); for (const auto& iter : indices_) { size_t first_idx = iter.second.front(); opt_cost += idx_to_miss_cost_.at(first_idx); } // Print the cost corresponding to the optimal solution std::cout << "Optimal cost is: " << std::fixed << std::setprecision(3) << opt_cost << std::endl << std::endl; } // Note: This point onwards, we cannot assume that the Gurobi model parameters are // available (since the solution may have been loaded from file). Instead, we use // the flow mappings and the solutions vector in the remainder of the pipeline. double lower_bound = getCostLowerBound(flows, edges); double upper_bound = getCostUpperBoundAndValidateSolution(flows, edges); double delta_percent = ((upper_bound - lower_bound) / lower_bound) * 100; // Debug std::cout << "Lower-bound (LB) on the total latency cost is: " << std::fixed << std::setprecision(3) << lower_bound << "." << std::endl; std::cout << "Upper-bound (UB) on the total latency cost is: " << std::fixed << std::setprecision(3) << upper_bound << " (" << delta_percent << "% worse than LB)." << std::endl << std::endl; // If the model was solved in this instance, also validate the opt_cost if (!is_loaded_from_file) { assert(utils::DoubleApproxEqual(opt_cost, lower_bound, 1e-2)); } } int main(int argc, char **argv) { // Parameters uint z; double c_scale; std::string trace_fp; std::string model_fp; std::string packets_fp; // Program options bopt::variables_map variables; bopt::options_description desc{"BELATEDLY's MCMCF-based solver for" " the Delayed Hits caching problem"}; try { // Command-line arguments desc.add_options() ("help", "Prints this message") ("trace", bopt::value<std::string>(&trace_fp)->required(), "Input trace file path") ("cscale", bopt::value<double>(&c_scale)->required(), "Parameter: Cache size (%Concurrent Flows)") ("zfactor", bopt::value<uint>(&z)->required(), "Parameter: Z") ("model", bopt::value<std::string>(&model_fp)->default_value(""), "[Optional] Output model file prefix (for checkpointing)") ("packets", bopt::value<std::string>(&packets_fp)->default_value(""), "[Optional] Output packets file path") ("forced,f", "[Optional] Use forced admission"); // Parse model parameters bopt::store(bopt::parse_command_line(argc, argv, desc), variables); // Handle help flag if (variables.count("help")) { std::cout << desc << std::endl; return 0; } bopt::notify(variables); } // Flag argument errors catch(const bopt::required_option& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } catch(...) { std::cerr << "Unknown Error." << std::endl; return 1; } // Use forced admission? bool is_forced = (variables.count("forced") != 0); // Parse the trace file, and compute the absolute cache size std::vector<std::string> trace = utils::parseTrace(trace_fp); size_t num_cfs = utils::getFlowCounts(trace).num_concurrent_flows; uint c = std::max(1u, static_cast<uint>(round((num_cfs * c_scale) / 100.))); // Debug std::cout << "Optimizing trace: " << trace_fp << " (with " << num_cfs << " concurrent flows) using z = " << z << ", c = " << c << ", and " << (is_forced ? "forced" : "optional") << " admission." << std::endl; // Instantiate the solver and optimize MCMCFSolver solver(trace_fp, model_fp, packets_fp, is_forced, z, c, trace); solver.solve(); }
40.397849
146
0.599753
Ahziu
8854a0a68e45517775ec1b5583cbcd9b4fed60c5
830
cpp
C++
test/verify/test_clip.cpp
raramakr/AMDMIGraphX
83e7425367f6ce850ec28fe716fe7c23ce34c79f
[ "MIT" ]
72
2018-12-06T18:31:17.000Z
2022-03-30T15:01:02.000Z
test/verify/test_clip.cpp
raramakr/AMDMIGraphX
83e7425367f6ce850ec28fe716fe7c23ce34c79f
[ "MIT" ]
1,006
2018-11-30T16:32:33.000Z
2022-03-31T22:43:39.000Z
test/verify/test_clip.cpp
raramakr/AMDMIGraphX
83e7425367f6ce850ec28fe716fe7c23ce34c79f
[ "MIT" ]
36
2019-05-07T10:41:46.000Z
2022-03-28T15:59:56.000Z
#include "verify_program.hpp" #include <migraphx/program.hpp> #include <migraphx/generate.hpp> #include <migraphx/make_op.hpp> struct test_clip : verify_program<test_clip> { migraphx::program create_program() const { migraphx::program p; auto* mm = p.get_main_module(); auto x = mm->add_parameter("x", migraphx::shape{migraphx::shape::float_type, {3}}); auto min_val = mm->add_literal(0.0f); auto max_val = mm->add_literal(6.0f); min_val = mm->add_instruction(migraphx::make_op("multibroadcast", {{"out_lens", {3}}}), min_val); max_val = mm->add_instruction(migraphx::make_op("multibroadcast", {{"out_lens", {3}}}), max_val); mm->add_instruction(migraphx::make_op("clip"), x, min_val, max_val); return p; } };
34.583333
99
0.624096
raramakr
885723fee25f1b0e86d62aea222192c1febd6e59
36,952
cpp
C++
src/fred2/briefingeditordlg.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
1
2020-07-14T07:29:18.000Z
2020-07-14T07:29:18.000Z
src/fred2/briefingeditordlg.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
2
2019-01-01T22:35:56.000Z
2022-03-14T07:34:00.000Z
src/fred2/briefingeditordlg.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
2
2021-03-07T11:40:42.000Z
2021-12-26T21:40:39.000Z
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on * the source. */ /* * $Logfile: /Freespace2/code/Fred2/BriefingEditorDlg.cpp $ * $Revision: 110 $ * $Date: 2002-06-09 06:41:30 +0200 (Sun, 09 Jun 2002) $ * $Author: relnev $ * * Briefing editor dialog box class. * * $Log$ * Revision 1.3 2002/06/09 04:41:16 relnev * added copyright header * * Revision 1.2 2002/05/07 03:16:43 theoddone33 * The Great Newline Fix * * Revision 1.1.1.1 2002/05/03 03:28:08 root * Initial import. * * * 9 7/19/99 3:01p Dave * Fixed icons. Added single transport icon. * * 8 7/18/99 5:19p Dave * Jump node icon. Fixed debris fogging. Framerate warning stuff. * * 7 7/09/99 5:54p Dave * Seperated cruiser types into individual types. Added tons of new * briefing icons. Campaign screen. * * 6 5/20/99 1:46p Andsager * Add briefing view copy and paste between stages * * 5 4/23/99 12:01p Johnson * Added SIF_HUGE_SHIP * * 4 11/30/98 5:32p Dave * Fixed up Fred support for software mode. * * 3 10/16/98 4:28p Andsager * Fix fred dependency * * 2 10/07/98 6:28p Dave * Initial checkin. Renamed all relevant stuff to be Fred2 instead of * Fred. Globalized mission and campaign file extensions. Removed Silent * Threat specific code. * * 1 10/07/98 3:02p Dave * * 1 10/07/98 3:00p Dave * * 63 5/21/98 4:20p Dave * Fixed bug with briefing editor when no current stage selected. * * 62 5/21/98 12:58a Hoffoss * Fixed warnings optimized build turned up. * * 61 5/14/98 4:47p Hoffoss * Made it so when you switch to a new team's debriefing (via menu), it * updates the camera position to what it should be for new briefing * stage. * * 60 4/30/98 8:23p John * Fixed some bugs with Fred caused by my new cfile code. * * 59 4/22/98 9:56a Sandeep * * 58 4/20/98 4:40p Hoffoss * Added a button to 4 editors to play the chosen wave file. * * 57 4/16/98 2:49p Johnson * Fixed initialization for new icons in briefing. * * 56 4/07/98 6:32p Dave * Fixed function I forget to change back. * * 55 4/07/98 6:27p Dave * Implemented a more boiler-plate solution to the multiple team briefing * problem in this editor. * * 54 4/07/98 4:51p Dave * (Hoffoss) Fixed a boat load of bugs caused by the new change to * multiple briefings. Allender's code changed to support this in the * briefing editor wasn't quite correct. * * 53 4/06/98 5:37p Hoffoss * Added sexp tree support to briefings in Fred. * * 52 4/06/98 10:43a John * Fixed bugs with inserting/deleting stages * * 51 4/03/98 12:39p Hoffoss * Changed starting directory for browse buttons in several editors. * * 50 4/03/98 11:34a John * Fixed the stuff I broke in Fred from the new breifing * * 49 3/26/98 6:40p Lawrance * Don't store icon text for briefings * * 48 3/21/98 7:36p Lawrance * Move jump nodes to own lib. * * 47 3/19/98 4:24p Hoffoss * Added remaining support for command brief screen (ANI and WAVE file * playing). * * 46 3/17/98 2:00p Hoffoss * Added ability to make an icon from a jump node in briefing editor. * * 45 2/18/98 6:44p Hoffoss * Added support for lines between icons in briefings for Fred. * * 44 2/09/98 9:25p Allender * team v team support. multiple pools and breifings * * 43 2/04/98 4:31p Allender * support for multiple briefings and debriefings. Changes to mission * type (now a bitfield). Bitfield defs for multiplayer modes * * 42 1/28/98 7:19p Lawrance * Get fading/highlighting animations working * * 41 12/28/97 5:52p Lawrance * Add support for debriefing success/fail music. * * 40 11/04/97 4:33p Hoffoss * Made saving keep the current briefing state intact. * * 39 11/04/97 11:31a Duncan * Made make icon button gray if at max icons already. * * 38 11/03/97 4:07p Jasen * Fixed bug in briefing editor caused by changes in TEAM_* defines in the * past and whoever made these changes failed to update this editor along * with it. * * 37 10/19/97 11:32p Hoffoss * Added support for briefing cuts in Fred. * * 36 10/12/97 11:23p Mike * About ten fixes/changes in the docking system. * Also, renamed SIF_REARM_REPAIR to SIF_SUPPORT. * * 35 9/30/97 5:56p Hoffoss * Added music selection combo boxes to Fred. * * $NoKeywords: $ */ #include "stdafx.h" #include <mmsystem.h> #include "fred.h" #include "briefingeditordlg.h" #include "freddoc.h" #include "missionbriefcommon.h" #include "missionparse.h" #include "fredrender.h" #include "management.h" #include "linklist.h" #include "mainfrm.h" #include "bmpman.h" #include "eventmusic.h" #include "starfield.h" #include "jumpnode.h" #include "cfile.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define ID_MENU 9000 #define NAVBUOY_NAME "Terran NavBuoy" static int Max_icons_for_lines; ///////////////////////////////////////////////////////////////////////////// // briefing_editor_dlg dialog briefing_editor_dlg::briefing_editor_dlg(CWnd* pParent /*=NULL*/) : CDialog(briefing_editor_dlg::IDD, pParent) { int i, z; // figure out max icons we can have with lines to each other less than max allowed lines. // Basically, # lines = (# icons - 1) factorial Max_icons_for_lines = 0; do { i = ++Max_icons_for_lines + 1; z = 0; while (--i) z += i; } while (z < MAX_BRIEF_STAGE_LINES); //{{AFX_DATA_INIT(briefing_editor_dlg) m_hilight = FALSE; m_icon_image = -1; m_icon_label = _T(""); m_stage_title = _T(""); m_text = _T(""); m_time = _T(""); m_voice = _T(""); m_icon_text = _T(""); m_icon_team = -1; m_ship_type = -1; m_change_local = FALSE; m_id = 0; m_briefing_music = -1; m_cut_next = FALSE; m_cut_prev = FALSE; m_current_briefing = -1; //}}AFX_DATA_INIT m_cur_stage = 0; m_last_stage = m_cur_icon = m_last_icon = -1; m_tree.link_modified(&modified); // provide way to indicate trees are modified in dialog // copy view initialization m_copy_view_set = 0; } void briefing_editor_dlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(briefing_editor_dlg) DDX_Control(pDX, IDC_TREE, m_tree); DDX_Control(pDX, IDC_LINES, m_lines); DDX_Check(pDX, IDC_HILIGHT, m_hilight); DDX_CBIndex(pDX, IDC_ICON_IMAGE, m_icon_image); DDX_Text(pDX, IDC_ICON_LABEL, m_icon_label); DDX_Text(pDX, IDC_STAGE_TITLE, m_stage_title); DDX_Text(pDX, IDC_TEXT, m_text); DDX_Text(pDX, IDC_TIME, m_time); DDX_Text(pDX, IDC_VOICE, m_voice); DDX_Text(pDX, IDC_ICON_TEXT, m_icon_text); DDX_CBIndex(pDX, IDC_TEAM, m_icon_team); DDX_CBIndex(pDX, IDC_SHIP_TYPE, m_ship_type); DDX_Check(pDX, IDC_LOCAL, m_change_local); DDX_Text(pDX, IDC_ID, m_id); DDX_CBIndex(pDX, IDC_BRIEFING_MUSIC, m_briefing_music); DDX_Check(pDX, IDC_CUT_NEXT, m_cut_next); DDX_Check(pDX, IDC_CUT_PREV, m_cut_prev); //}}AFX_DATA_MAP DDV_MaxChars(pDX, m_text, MAX_BRIEF_LEN - 1); DDV_MaxChars(pDX, m_voice, MAX_FILENAME_LEN - 1); DDV_MaxChars(pDX, m_icon_label, MAX_LABEL_LEN - 1); DDV_MaxChars(pDX, m_icon_text, MAX_ICON_TEXT_LEN - 1); } BEGIN_MESSAGE_MAP(briefing_editor_dlg, CDialog) //{{AFX_MSG_MAP(briefing_editor_dlg) ON_WM_CLOSE() ON_BN_CLICKED(IDC_NEXT, OnNext) ON_BN_CLICKED(IDC_PREV, OnPrev) ON_BN_CLICKED(IDC_BROWSE, OnBrowse) ON_BN_CLICKED(IDC_ADD_STAGE, OnAddStage) ON_BN_CLICKED(IDC_DELETE_STAGE, OnDeleteStage) ON_BN_CLICKED(IDC_INSERT_STAGE, OnInsertStage) ON_BN_CLICKED(IDC_MAKE_ICON, OnMakeIcon) ON_BN_CLICKED(IDC_DELETE_ICON, OnDeleteIcon) ON_BN_CLICKED(IDC_GOTO_VIEW, OnGotoView) ON_BN_CLICKED(IDC_SAVE_VIEW, OnSaveView) ON_CBN_SELCHANGE(IDC_ICON_IMAGE, OnSelchangeIconImage) ON_CBN_SELCHANGE(IDC_TEAM, OnSelchangeTeam) ON_BN_CLICKED(IDC_PROPAGATE_ICONS, OnPropagateIcons) ON_WM_INITMENU() ON_BN_CLICKED(IDC_LINES, OnLines) ON_NOTIFY(NM_RCLICK, IDC_TREE, OnRclickTree) ON_NOTIFY(TVN_BEGINLABELEDIT, IDC_TREE, OnBeginlabeleditTree) ON_NOTIFY(TVN_ENDLABELEDIT, IDC_TREE, OnEndlabeleditTree) ON_BN_CLICKED(IDC_PLAY, OnPlay) ON_BN_CLICKED(IDC_COPY_VIEW, OnCopyView) ON_BN_CLICKED(IDC_PASTE_VIEW, OnPasteView) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // briefing_editor_dlg message handlers void briefing_editor_dlg::OnInitMenu(CMenu* pMenu) { int i; CMenu *m; // disable any items we should disable m = pMenu->GetSubMenu(0); // uncheck all menu items for (i=0; i<Num_teams; i++) m->CheckMenuItem(i, MF_BYPOSITION | MF_UNCHECKED); for (i=Num_teams; i<MAX_TEAMS; i++) m->EnableMenuItem(i, MF_BYPOSITION | MF_GRAYED); // put a check next to the currently selected item m->CheckMenuItem(m_current_briefing, MF_BYPOSITION | MF_CHECKED ); CDialog::OnInitMenu(pMenu); } void briefing_editor_dlg::create() { int i; CComboBox *box; CDialog::Create(IDD); theApp.init_window(&Briefing_wnd_data, this); box = (CComboBox *) GetDlgItem(IDC_ICON_IMAGE); for (i=0; i<MAX_BRIEF_ICONS; i++) box->AddString(Icon_names[i]); box = (CComboBox *) GetDlgItem(IDC_TEAM); for (i=0; i<Num_team_names; i++) box->AddString(Team_names[i]); box = (CComboBox *) GetDlgItem(IDC_SHIP_TYPE); for (i=0; i<Num_ship_types; i++) box->AddString(Ship_info[i].name); box = (CComboBox *) GetDlgItem(IDC_BRIEFING_MUSIC); box->AddString("None"); for (i=0; i<Num_music_files; i++) box->AddString(Spooled_music[i].name); m_play_bm.LoadBitmap(IDB_PLAY); ((CButton *) GetDlgItem(IDC_PLAY)) -> SetBitmap(m_play_bm); m_current_briefing = 0; Briefing = &Briefings[m_current_briefing]; m_briefing_music = Mission_music[SCORE_BRIEFING] + 1; UpdateData(FALSE); update_data(); OnGotoView(); update_map_window(); } void briefing_editor_dlg::focus_sexp(int select_sexp_node) { int i, n; n = m_tree.select_sexp_node = select_sexp_node; if (n != -1) { for (i=0; i<Briefing->num_stages; i++) if (query_node_in_sexp(n, Briefing->stages[i].formula)) break; if (i < Briefing->num_stages) { m_cur_stage = i; update_data(); GetDlgItem(IDC_TREE) -> SetFocus(); m_tree.hilite_item(m_tree.select_sexp_node); } } } void briefing_editor_dlg::OnOK() { } void briefing_editor_dlg::OnCancel() { OnClose(); } void briefing_editor_dlg::OnClose() { int bs, i, j, s, t, dup = 0; briefing_editor_dlg *ptr; brief_stage *sp; m_cur_stage = -1; update_data(1); for ( bs = 0; bs < Num_teams; bs++ ) { for (s=0; s<Briefing[bs].num_stages; s++) { sp = &Briefing[bs].stages[s]; t = sp->num_icons; for (i=0; i<t-1; i++) for (j=i+1; j<t; j++) { if ((sp->icons[i].id >= 0) && (sp->icons[i].id == sp->icons[j].id)) dup = 1; } } } if (dup) MessageBox("You have duplicate icons names. You should resolve these.", "Warning"); theApp.record_window_data(&Briefing_wnd_data, this); ptr = Briefing_dialog; Briefing_dialog = NULL; delete ptr; } void briefing_editor_dlg::reset_editor() { m_cur_stage = -1; update_data(0); } // some kind of hackish code to get around the problem if saving (which implicitly loads, // which implicitly clears all mission info) not affecting the editor's state at save. void briefing_editor_dlg::save_editor_state() { stage_saved = m_cur_stage; icon_saved = m_cur_icon; } void briefing_editor_dlg::restore_editor_state() { m_cur_stage = stage_saved; m_cur_icon = icon_saved; } void briefing_editor_dlg::update_data(int update) { char buf[MAX_LABEL_LEN], buf2[MAX_ICON_TEXT_LEN], buf3[MAX_BRIEF_LEN]; int i, j, l, lines, count, enable = TRUE, valid = 0, invalid = 0; object *objp; brief_stage *ptr = NULL; if (update) UpdateData(TRUE); // save off current data before we update over it with new briefing stage/team stuff Briefing = save_briefing; Mission_music[SCORE_BRIEFING] = m_briefing_music - 1; if (m_last_stage >= 0) { ptr = &Briefing->stages[m_last_stage]; deconvert_multiline_string(buf3, m_text, MAX_BRIEF_LEN); if (stricmp(ptr->new_text, buf3)) set_modified(); strcpy(ptr->new_text, buf3); MODIFY(ptr->camera_time, atoi(m_time)); string_copy(ptr->voice, m_voice, MAX_FILENAME_LEN, 1); i = ptr->flags; if (m_cut_prev) i |= BS_BACKWARD_CUT; else i &= ~BS_BACKWARD_CUT; if (m_cut_next) i |= BS_FORWARD_CUT; else i &= ~BS_FORWARD_CUT; MODIFY(ptr->flags, i); ptr->formula = m_tree.save_tree(); switch (m_lines.GetCheck()) { case 1: // add lines between every pair of 2 marked icons if there isn't one already. for (i=0; i<ptr->num_icons - 1; i++) for (j=i+1; j<ptr->num_icons; j++) { if ( icon_marked[i] && icon_marked[j] ) { for (l=0; l<ptr->num_lines; l++) if ( ((ptr->lines[l].start_icon == i) && (ptr->lines[l].end_icon == j)) || ((ptr->lines[l].start_icon == j) && (ptr->lines[l].end_icon == i)) ) break; if ((l == ptr->num_lines) && (l < MAX_BRIEF_STAGE_LINES)) { ptr->lines[l].start_icon = i; ptr->lines[l].end_icon = j; ptr->num_lines++; } } } break; case 0: // remove all existing lines between any 2 marked icons i = ptr->num_lines; while (i--) if ( icon_marked[ptr->lines[i].start_icon] && icon_marked[ptr->lines[i].end_icon] ) { ptr->num_lines--; for (l=i; l<ptr->num_lines; l++) ptr->lines[l] = ptr->lines[l + 1]; } break; } if (m_last_icon >= 0) { valid = (m_id != ptr->icons[m_last_icon].id); if (m_id >= 0) { if (valid && !m_change_local) { for (i=m_last_stage+1; i<Briefing->num_stages; i++) { if (find_icon(m_id, i) >= 0) { char msg[1024]; valid = 0; sprintf(msg, "Icon ID #%d is already used in a later stage. You can only\n" "change to that ID locally. Icon ID has been reset back to %d", m_id, ptr->icons[m_last_icon].id); m_id = ptr->icons[m_last_icon].id; MessageBox(msg); break; } } } for (i=0; i<ptr->num_icons; i++) if ((i != m_last_icon) && (ptr->icons[i].id == m_id)) { char msg[1024]; sprintf(msg, "Icon ID #%d is already used in this stage. Icon ID has been reset back to %d", m_id, ptr->icons[m_last_icon].id); m_id = ptr->icons[m_last_icon].id; MessageBox(msg); break; } if (valid && !m_change_local) { set_modified(); reset_icon_loop(m_last_stage); while (get_next_icon(ptr->icons[m_last_icon].id)) iconp->id = m_id; } } ptr->icons[m_last_icon].id = m_id; string_copy(buf, m_icon_label, MAX_LABEL_LEN); if (stricmp(ptr->icons[m_last_icon].label, buf) && !m_change_local) { set_modified(); reset_icon_loop(m_last_stage); while (get_next_icon(m_id)) strcpy(iconp->label, buf); } strcpy(ptr->icons[m_last_icon].label, buf); if ( m_hilight ) ptr->icons[m_last_icon].flags |= BI_HIGHLIGHT; else ptr->icons[m_last_icon].flags &= ~BI_HIGHLIGHT; if ((ptr->icons[m_last_icon].type != m_icon_image) && !m_change_local) { set_modified(); reset_icon_loop(m_last_stage); while (get_next_icon(m_id)) iconp->type = m_icon_image; } ptr->icons[m_last_icon].type = m_icon_image; if ((ptr->icons[m_last_icon].team != (1 << m_icon_team)) && !m_change_local) { set_modified(); reset_icon_loop(m_last_stage); while (get_next_icon(m_id)) iconp->team = (1 << m_icon_team); } ptr->icons[m_last_icon].team = (1 << m_icon_team); if ((ptr->icons[m_last_icon].ship_class != m_ship_type) && !m_change_local) { set_modified(); reset_icon_loop(m_last_stage); while (get_next_icon(m_id)) iconp->ship_class = m_ship_type; } MODIFY(ptr->icons[m_last_icon].ship_class, m_ship_type); deconvert_multiline_string(buf2, m_icon_text, MAX_ICON_TEXT_LEN); /* if (stricmp(ptr->icons[m_last_icon].text, buf2) && !m_change_local) { set_modified(); reset_icon_loop(m_last_stage); while (get_next_icon(m_id)) strcpy(iconp->text, buf2); } strcpy(ptr->icons[m_last_icon].text, buf2); */ } } if (!::IsWindow(m_hWnd)) return; // set briefing pointer to correct team Briefing = &Briefings[m_current_briefing]; if ((m_cur_stage >= 0) && (m_cur_stage < Briefing->num_stages)) { ptr = &Briefing->stages[m_cur_stage]; m_stage_title.Format("Stage %d of %d", m_cur_stage + 1, Briefing->num_stages); m_text = convert_multiline_string(ptr->new_text); m_time.Format("%d", ptr->camera_time); m_voice = ptr->voice; m_cut_prev = (ptr->flags & BS_BACKWARD_CUT) ? 1 : 0; m_cut_next = (ptr->flags & BS_FORWARD_CUT) ? 1 : 0; m_tree.load_tree(ptr->formula); } else { m_stage_title = _T("No stages"); m_text = _T(""); m_time = _T(""); m_voice = _T(""); m_cut_prev = m_cut_next = 0; m_tree.clear_tree(); enable = FALSE; m_cur_stage = -1; } if (m_cur_stage == Briefing->num_stages - 1) GetDlgItem(IDC_NEXT) -> EnableWindow(FALSE); else GetDlgItem(IDC_NEXT) -> EnableWindow(enable); if (m_cur_stage) GetDlgItem(IDC_PREV) -> EnableWindow(enable); else GetDlgItem(IDC_PREV) -> EnableWindow(FALSE); if (Briefing->num_stages >= MAX_BRIEF_STAGES) GetDlgItem(IDC_ADD_STAGE) -> EnableWindow(FALSE); else GetDlgItem(IDC_ADD_STAGE) -> EnableWindow(TRUE); if (Briefing->num_stages) { GetDlgItem(IDC_DELETE_STAGE) -> EnableWindow(enable); GetDlgItem(IDC_INSERT_STAGE) -> EnableWindow(enable); } else { GetDlgItem(IDC_DELETE_STAGE) -> EnableWindow(FALSE); GetDlgItem(IDC_INSERT_STAGE) -> EnableWindow(FALSE); } GetDlgItem(IDC_TIME) -> EnableWindow(enable); GetDlgItem(IDC_VOICE) -> EnableWindow(enable); GetDlgItem(IDC_BROWSE) -> EnableWindow(enable); GetDlgItem(IDC_TEXT) -> EnableWindow(enable); GetDlgItem(IDC_SAVE_VIEW) -> EnableWindow(enable); GetDlgItem(IDC_GOTO_VIEW) -> EnableWindow(enable); GetDlgItem(IDC_CUT_PREV) -> EnableWindow(enable); GetDlgItem(IDC_CUT_NEXT) -> EnableWindow(enable); GetDlgItem(IDC_TREE) -> EnableWindow(enable); GetDlgItem(IDC_PLAY) -> EnableWindow(enable); if ((m_cur_stage >= 0) && (m_cur_icon >= 0) && (m_cur_icon < ptr->num_icons)) { m_hilight = (ptr->icons[m_cur_icon].flags & BI_HIGHLIGHT)?1:0; m_icon_image = ptr->icons[m_cur_icon].type; m_icon_team = bitmask_2_bitnum(ptr->icons[m_cur_icon].team); m_icon_label = ptr->icons[m_cur_icon].label; m_ship_type = ptr->icons[m_cur_icon].ship_class; // m_icon_text = convert_multiline_string(ptr->icons[m_cur_icon].text); m_id = ptr->icons[m_cur_icon].id; enable = TRUE; } else { m_hilight = FALSE; m_icon_image = -1; m_icon_team = -1; m_ship_type = -1; m_icon_label = _T(""); m_cur_icon = -1; m_id = 0; enable = FALSE; } GetDlgItem(IDC_ICON_TEXT) -> EnableWindow(enable); GetDlgItem(IDC_ICON_LABEL) -> EnableWindow(enable); GetDlgItem(IDC_ICON_IMAGE) -> EnableWindow(enable); GetDlgItem(IDC_SHIP_TYPE) -> EnableWindow(enable); GetDlgItem(IDC_HILIGHT) -> EnableWindow(enable); GetDlgItem(IDC_TEAM) -> EnableWindow(enable); GetDlgItem(IDC_ID) -> EnableWindow(enable); GetDlgItem(IDC_DELETE_ICON) -> EnableWindow(enable); valid = invalid = 0; objp = GET_FIRST(&obj_used_list); while (objp != END_OF_LIST(&obj_used_list)) { if (objp->flags & OF_MARKED) { if ((objp->type == OBJ_SHIP) || (objp->type == OBJ_START) || (objp->type == OBJ_WAYPOINT) || (objp->type == OBJ_JUMP_NODE)) valid = 1; else invalid = 1; } objp = GET_NEXT(objp); } if (m_cur_stage >= 0) ptr = &Briefing->stages[m_cur_stage]; if (valid && !invalid && (m_cur_stage >= 0) && (ptr->num_icons < MAX_STAGE_ICONS)) GetDlgItem(IDC_MAKE_ICON) -> EnableWindow(TRUE); else GetDlgItem(IDC_MAKE_ICON) -> EnableWindow(FALSE); if (m_cur_stage >= 0) for (i=0; i<ptr->num_icons; i++) icon_marked[i] = 0; valid = invalid = 0; objp = GET_FIRST(&obj_used_list); while (objp != END_OF_LIST(&obj_used_list)) { if (objp->flags & OF_MARKED) { if (objp->type == OBJ_POINT) { valid++; icon_marked[objp->instance] = 1; } else invalid++; } objp = GET_NEXT(objp); } if (valid && !invalid && (m_cur_stage >= 0)) GetDlgItem(IDC_PROPAGATE_ICONS) -> EnableWindow(TRUE); else GetDlgItem(IDC_PROPAGATE_ICONS) -> EnableWindow(FALSE); count = 0; lines = 1; // default lines checkbox to checked if (m_cur_stage >= 0) { for (i=0; i<ptr->num_lines; i++) line_marked[i] = 0; // go through and locate all lines between marked icons for (i=0; i<ptr->num_icons - 1; i++) for (j=i+1; j<ptr->num_icons; j++) { if ( icon_marked[i] && icon_marked[j] ) { for (l=0; l<ptr->num_lines; l++) if ( ((ptr->lines[l].start_icon == i) && (ptr->lines[l].end_icon == j)) || ((ptr->lines[l].start_icon == j) && (ptr->lines[l].end_icon == i)) ) { line_marked[l] = 1; count++; // track number of marked lines (lines between 2 icons that are both marked) break; } // at least 1 line missing between 2 marked icons, so use mixed state if (l == ptr->num_lines) lines = 2; } } } // not even 1 line between any 2 marked icons? Set checkbox to unchecked. if (!count) lines = 0; i = 0; if (m_cur_stage >= 0){ i = calc_num_lines_for_icons(valid) + ptr->num_lines - count; } if ((valid > 1) && !invalid && (m_cur_stage >= 0) && (i <= MAX_BRIEF_STAGE_LINES)) GetDlgItem(IDC_LINES) -> EnableWindow(TRUE); else GetDlgItem(IDC_LINES) -> EnableWindow(FALSE); m_lines.SetCheck(lines); UpdateData(FALSE); if ((m_last_stage != m_cur_stage) || (Briefing != save_briefing)) { if (m_last_stage >= 0) { for (i=0; i<save_briefing->stages[m_last_stage].num_icons; i++) { // save positions of all icons, in case they have moved save_briefing->stages[m_last_stage].icons[i].pos = Objects[icon_obj[i]].pos; // release objects being used by last stage obj_delete(icon_obj[i]); } } if (m_cur_stage >= 0) { for (i=0; i<ptr->num_icons; i++) { // create an object for each icon for display/manipulation purposes icon_obj[i] = obj_create(OBJ_POINT, -1, i, NULL, &ptr->icons[i].pos, 0.0f, OF_RENDERS); } obj_merge_created_list(); } m_last_stage = m_cur_stage; } m_last_icon = m_cur_icon; Update_window = 1; save_briefing = Briefing; } // Given a number of icons, figure out how many lines would be required to connect each one // with all of the others. // int briefing_editor_dlg::calc_num_lines_for_icons(int num) { int lines = 0; if (num < 2) return 0; // Basically, this is # lines = (# icons - 1) factorial while (--num) lines += num; return lines; } void briefing_editor_dlg::OnNext() { m_cur_stage++; m_cur_icon = -1; update_data(); OnGotoView(); } void briefing_editor_dlg::OnPrev() { m_cur_stage--; m_cur_icon = -1; update_data(); OnGotoView(); } void briefing_editor_dlg::OnBrowse() { int z; CString name; UpdateData(TRUE); if (The_mission.game_type & MISSION_TYPE_TRAINING) z = cfile_push_chdir(CF_TYPE_VOICE_TRAINING); else z = cfile_push_chdir(CF_TYPE_VOICE_BRIEFINGS); CFileDialog dlg(TRUE, "wav", NULL, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR, "Wave Files (*.wav)|*.wav||"); if (dlg.DoModal() == IDOK) { m_voice = dlg.GetFileName(); UpdateData(FALSE); } if (!z) cfile_pop_dir(); } void briefing_editor_dlg::OnAddStage() { int i; if (Briefing->num_stages >= MAX_BRIEF_STAGES) return; m_cur_stage = i = Briefing->num_stages++; copy_stage(i - 1, i); update_data(1); } void briefing_editor_dlg::OnDeleteStage() { int i, z; if (m_cur_stage < 0) return; Assert(Briefing->num_stages); z = m_cur_stage; m_cur_stage = -1; update_data(1); for (i=z+1; i<Briefing->num_stages; i++) { copy_stage(i, i-1); } Briefing->num_stages--; m_cur_stage = z; if (m_cur_stage >= Briefing->num_stages) m_cur_stage = Briefing->num_stages - 1; update_data(0); } void briefing_editor_dlg::draw_icon(object *objp) { if (m_cur_stage < 0) return; brief_render_icon(m_cur_stage, objp->instance, 1.0f/30.0f, objp->flags & OF_MARKED, (float) True_rw / BRIEF_GRID_W, (float) True_rh / BRIEF_GRID_H); } void briefing_editor_dlg::batch_render() { int i, num_lines; if (m_cur_stage < 0) return; num_lines = Briefing->stages[m_cur_stage].num_lines; for (i=0; i<num_lines; i++) brief_render_icon_line(m_cur_stage, i); } void briefing_editor_dlg::icon_select(int num) { m_cur_icon = num; update_data(1); } void briefing_editor_dlg::OnInsertStage() { int i, z; if (Briefing->num_stages >= MAX_BRIEF_STAGES) return; if (!Briefing->num_stages) { OnAddStage(); return; } z = m_cur_stage; m_cur_stage = -1; update_data(1); for (i=Briefing->num_stages; i>z; i--) { copy_stage(i-1, i); } Briefing->num_stages++; copy_stage(z, z + 1); m_cur_stage = z; update_data(0); } void briefing_editor_dlg::copy_stage(int from, int to) { if ((from < 0) || (from >= Briefing->num_stages)) { strcpy(Briefing->stages[to].new_text, "<Text here>"); strcpy(Briefing->stages[to].voice, "none.wav"); Briefing->stages[to].camera_pos = view_pos; Briefing->stages[to].camera_orient = view_orient; Briefing->stages[to].camera_time = 500; Briefing->stages[to].num_icons = 0; Briefing->stages[to].formula = Locked_sexp_true; return; } // Copy all the data in the stage structure. strcpy( Briefing->stages[to].new_text, Briefing->stages[from].new_text ); strcpy( Briefing->stages[to].voice, Briefing->stages[from].voice ); Briefing->stages[to].camera_pos = Briefing->stages[from].camera_pos; Briefing->stages[to].camera_orient = Briefing->stages[from].camera_orient; Briefing->stages[to].camera_time = Briefing->stages[from].camera_time; Briefing->stages[to].flags = Briefing->stages[from].flags; Briefing->stages[to].num_icons = Briefing->stages[from].num_icons; Briefing->stages[to].num_lines = Briefing->stages[from].num_lines; Briefing->stages[to].formula = Briefing->stages[from].formula; memmove( Briefing->stages[to].icons, Briefing->stages[from].icons, sizeof(brief_icon)*MAX_STAGE_ICONS ); memmove( Briefing->stages[to].lines, Briefing->stages[from].lines, sizeof(brief_line)*MAX_BRIEF_STAGE_LINES ); } void briefing_editor_dlg::update_positions() { int i, s, z; vector v1, v2; if (m_cur_stage < 0) return; for (i=0; i<Briefing->stages[m_cur_stage].num_icons; i++) { v1 = Briefing->stages[m_cur_stage].icons[i].pos; v2 = Objects[icon_obj[i]].pos; if ((v1.x != v2.x) || (v1.y != v2.y) || (v1.z != v2.z)) { Briefing->stages[m_cur_stage].icons[i].pos = Objects[icon_obj[i]].pos; if (!m_change_local) // propagate changes through rest of stages.. for (s=m_cur_stage+1; s<Briefing->num_stages; s++) { z = find_icon(Briefing->stages[m_cur_stage].icons[i].id, s); if (z >= 0) Briefing->stages[s].icons[z].pos = Objects[icon_obj[i]].pos; } } } } void briefing_editor_dlg::OnMakeIcon() { char *name; int z, len, team, ship, waypoint, jump_node, count = -1; int cargo = 0, cargo_count = 0, freighter_count = 0; object *ptr; vector min, max, pos; brief_icon *iconp; if (Briefing->stages[m_cur_stage].num_icons >= MAX_STAGE_ICONS) return; m_cur_icon = Briefing->stages[m_cur_stage].num_icons++; iconp = &Briefing->stages[m_cur_stage].icons[m_cur_icon]; ship = waypoint = jump_node = -1; team = TEAM_FRIENDLY; vm_vec_make(&min, 9e19f, 9e19f, 9e19f); vm_vec_make(&max, -9e19f, -9e19f, -9e19f); ptr = GET_FIRST(&obj_used_list); while (ptr != END_OF_LIST(&obj_used_list)) { if (ptr->flags & OF_MARKED) { if (ptr->pos.x < min.x) min.x = ptr->pos.x; if (ptr->pos.x > max.x) max.x = ptr->pos.x; if (ptr->pos.y < min.y) min.y = ptr->pos.y; if (ptr->pos.y > max.y) max.y = ptr->pos.y; if (ptr->pos.z < min.z) min.z = ptr->pos.z; if (ptr->pos.z > max.z) max.z = ptr->pos.z; switch (ptr->type) { case OBJ_SHIP: case OBJ_START: ship = ptr->instance; break; case OBJ_WAYPOINT: waypoint = ptr->instance; break; case OBJ_JUMP_NODE: jump_node = ptr->instance; break; default: Int3(); } if (ship >= 0) { team = Ships[ship].team; z = ship_query_general_type(ship); if (z == SHIP_TYPE_CARGO) cargo_count++; if (z == SHIP_TYPE_FREIGHTER) { z = Ai_info[Ships[ship].ai_index].dock_objnum; if (z) { // docked with anything? if ((Objects[z].flags & OF_MARKED) && (Objects[z].type == OBJ_SHIP)) { if (ship_query_general_type(Objects[z].instance) == SHIP_TYPE_CARGO) freighter_count++; } } } } count++; } ptr = GET_NEXT(ptr); } if (cargo_count && cargo_count == freighter_count) cargo = 1; vm_vec_avg(&pos, &min, &max); if (ship >= 0) name = Ships[ship].ship_name; else if (waypoint >= 0) name = Waypoint_lists[waypoint / 65536].name; else if (jump_node >= 0) name = Jump_nodes[jump_node].name; else return; len = strlen(name); if (len >= MAX_LABEL_LEN - 1) len = MAX_LABEL_LEN - 1; strncpy(iconp->label, name, len); iconp->label[len] = 0; // iconp->text[0] = 0; iconp->type = 0; iconp->team = team; iconp->pos = pos; iconp->flags = 0; iconp->id = Cur_brief_id++; if (ship >= 0) { iconp->ship_class = Ships[ship].ship_info_index; switch (Ship_info[Ships[ship].ship_info_index].flags & SIF_ALL_SHIP_TYPES) { case SIF_KNOSSOS_DEVICE: iconp->type = ICON_KNOSSOS_DEVICE; break; case SIF_CORVETTE: iconp->type = ICON_CORVETTE; break; case SIF_GAS_MINER: iconp->type = ICON_GAS_MINER; break; case SIF_SUPERCAP: iconp->type = ICON_SUPERCAP; break; case SIF_SENTRYGUN: iconp->type = ICON_SENTRYGUN; break; case SIF_AWACS: iconp->type = ICON_AWACS; break; case SIF_CARGO: if (cargo) iconp->type = (count == 1) ? ICON_FREIGHTER_WITH_CARGO : ICON_FREIGHTER_WING_WITH_CARGO; else iconp->type = count ? ICON_CARGO_WING : ICON_CARGO; break; case SIF_SUPPORT: iconp->type = ICON_SUPPORT_SHIP; break; case SIF_FIGHTER: iconp->type = count ? ICON_FIGHTER_WING : ICON_FIGHTER; break; case SIF_BOMBER: iconp->type = count ? ICON_BOMBER_WING : ICON_BOMBER; break; case SIF_FREIGHTER: if (cargo) iconp->type = (count == 1) ? ICON_FREIGHTER_WITH_CARGO : ICON_FREIGHTER_WING_WITH_CARGO; else iconp->type = count ? ICON_FREIGHTER_WING_NO_CARGO : ICON_FREIGHTER_NO_CARGO; break; case SIF_CRUISER: iconp->type = count ? ICON_CRUISER_WING : ICON_CRUISER; break; case SIF_TRANSPORT: iconp->type = count ? ICON_TRANSPORT_WING : ICON_TRANSPORT; break; case SIF_CAPITAL: case SIF_DRYDOCK: iconp->type = ICON_CAPITAL; break; default: if (Ships[ship].ship_info_index == ship_info_lookup(NAVBUOY_NAME)) iconp->type = ICON_WAYPOINT; else iconp->type = ICON_ASTEROID_FIELD; break; } } // jumpnodes else if(jump_node >= 0){ iconp->ship_class = ship_info_lookup(NAVBUOY_NAME); iconp->type = ICON_JUMP_NODE; } // everything else else { iconp->ship_class = ship_info_lookup(NAVBUOY_NAME); iconp->type = ICON_WAYPOINT; } if (!m_change_local){ propagate_icon(m_cur_icon); } icon_obj[m_cur_icon] = obj_create(OBJ_POINT, -1, m_cur_icon, NULL, &pos, 0.0f, OF_RENDERS); Assert(icon_obj[m_cur_icon] >= 0); obj_merge_created_list(); unmark_all(); set_cur_object_index(icon_obj[m_cur_icon]); GetDlgItem(IDC_MAKE_ICON) -> EnableWindow(FALSE); GetDlgItem(IDC_PROPAGATE_ICONS) -> EnableWindow(TRUE); update_data(1); } void briefing_editor_dlg::OnDeleteIcon() { delete_icon(m_cur_icon); } void briefing_editor_dlg::delete_icon(int num) { int i, z; if (num < 0) num = m_cur_icon; if (num < 0) return; Assert(m_cur_stage >= 0); Assert(Briefing->stages[m_cur_stage].num_icons); z = m_cur_icon; if (z == num) z = -1; if (z > num) z--; m_cur_icon = -1; update_data(1); obj_delete(icon_obj[num]); for (i=num+1; i<Briefing->stages[m_cur_stage].num_icons; i++) { Briefing->stages[m_cur_stage].icons[i-1] = Briefing->stages[m_cur_stage].icons[i]; icon_obj[i-1] = icon_obj[i]; Objects[icon_obj[i-1]].instance = i - 1; } Briefing->stages[m_cur_stage].num_icons--; if (z >= 0) { m_cur_icon = z; update_data(0); } } void briefing_editor_dlg::OnGotoView() { if (m_cur_stage < 0) return; view_pos = Briefing->stages[m_cur_stage].camera_pos; view_orient = Briefing->stages[m_cur_stage].camera_orient; Update_window = 1; } void briefing_editor_dlg::OnSaveView() { if (m_cur_stage < 0) return; Briefing->stages[m_cur_stage].camera_pos = view_pos; Briefing->stages[m_cur_stage].camera_orient = view_orient; } void briefing_editor_dlg::OnSelchangeIconImage() { update_data(1); } void briefing_editor_dlg::OnSelchangeTeam() { update_data(1); } int briefing_editor_dlg::check_mouse_hit(int x, int y) { int i; brief_icon *ptr; if (m_cur_stage < 0) return -1; for (i=0; i<Briefing->stages[m_cur_stage].num_icons; i++) { ptr = &Briefing->stages[m_cur_stage].icons[i]; if ((x > ptr->x) && (x < ptr->x + ptr->w) && (y > ptr->y) && (y < ptr->y + ptr->h)) { return icon_obj[i]; } } return -1; } void briefing_editor_dlg::OnPropagateIcons() { object *ptr; ptr = GET_FIRST(&obj_used_list); while (ptr != END_OF_LIST(&obj_used_list)) { if ((ptr->type == OBJ_POINT) && (ptr->flags & OF_MARKED)) { propagate_icon(ptr->instance); } ptr = GET_NEXT(ptr); } } void briefing_editor_dlg::propagate_icon(int num) { int i, s; for (s=m_cur_stage+1; s<Briefing->num_stages; s++) { i = Briefing->stages[s].num_icons; if (i >= MAX_STAGE_ICONS) continue; if (find_icon(Briefing->stages[m_cur_stage].icons[num].id, s) >= 0) continue; // don't change if icon exists here already. Briefing->stages[s].icons[i] = Briefing->stages[m_cur_stage].icons[num]; Briefing->stages[s].num_icons++; } } int briefing_editor_dlg::find_icon(int id, int stage) { int i; if (id >= 0) for (i=0; i<Briefing->stages[stage].num_icons; i++) if (Briefing->stages[stage].icons[i].id == id) return i; return -1; } void briefing_editor_dlg::reset_icon_loop(int stage) { stage_loop = stage + 1; icon_loop = -1; } int briefing_editor_dlg::get_next_icon(int id) { while (1) { icon_loop++; if (icon_loop >= Briefing->stages[stage_loop].num_icons) { stage_loop++; if (stage_loop > Briefing->num_stages) return 0; icon_loop = -1; continue; } iconp = &Briefing->stages[stage_loop].icons[icon_loop]; if ((id >= 0) && (iconp->id == id)) return 1; } } BOOL briefing_editor_dlg::OnCommand(WPARAM wParam, LPARAM lParam) { int id; // deal with figuring out menu stuff id = LOWORD(wParam); if ( (id >= ID_TEAM_1) && (id < ID_TEAM_3) ) { m_current_briefing = id - ID_TEAM_1; // put user back at first stage for this team (or no current stage is there are none). Briefing = &Briefings[m_current_briefing]; if ( Briefing->num_stages > 0 ) m_cur_stage = 0; else m_cur_stage = -1; update_data(1); OnGotoView(); return 1; } return CDialog::OnCommand(wParam, lParam); } void briefing_editor_dlg::OnLines() { if (m_lines.GetCheck() == 1) m_lines.SetCheck(0); else m_lines.SetCheck(1); update_data(1); } void briefing_editor_dlg::OnRclickTree(NMHDR* pNMHDR, LRESULT* pResult) { m_tree.right_clicked(); *pResult = 0; } void briefing_editor_dlg::OnBeginlabeleditTree(NMHDR* pNMHDR, LRESULT* pResult) { TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR; if (m_tree.edit_label(pTVDispInfo->item.hItem) == 1) { *pResult = 0; modified = 1; } else *pResult = 1; } void briefing_editor_dlg::OnEndlabeleditTree(NMHDR* pNMHDR, LRESULT* pResult) { TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR; *pResult = m_tree.end_label_edit(pTVDispInfo->item.hItem, pTVDispInfo->item.pszText); } BOOL briefing_editor_dlg::DestroyWindow() { m_play_bm.DeleteObject(); return CDialog::DestroyWindow(); } void briefing_editor_dlg::OnPlay() { char path[MAX_PATH_LEN + 1]; GetDlgItem(IDC_VOICE)->GetWindowText(m_voice); int size, offset; cf_find_file_location((char *) (LPCSTR) m_voice, CF_TYPE_ANY, path, &size, &offset ); PlaySound(path, NULL, SND_ASYNC | SND_FILENAME); } void briefing_editor_dlg::OnCopyView() { // TODO: Add your control notification handler code here m_copy_view_set = 1; m_copy_view_pos = view_pos; m_copy_view_orient = view_orient; } void briefing_editor_dlg::OnPasteView() { // TODO: Add your control notification handler code here if (m_cur_stage < 0) return; if (m_copy_view_set == 0) { MessageBox("No view set", "Unable to copy view"); } else { Briefing->stages[m_cur_stage].camera_pos = m_copy_view_pos; Briefing->stages[m_cur_stage].camera_orient = m_copy_view_orient; update_data(1); OnGotoView(); } }
25.519337
151
0.675227
ptitSeb
885bdd8f24f9cf110c18e19bc0a14729e5c27e67
2,127
cpp
C++
src/apps/tests/tests/LinearMatrix_tests.cpp
Adnn/Math
017e7c42bfdd665c78557109b0b379567bfe8e7c
[ "MIT" ]
null
null
null
src/apps/tests/tests/LinearMatrix_tests.cpp
Adnn/Math
017e7c42bfdd665c78557109b0b379567bfe8e7c
[ "MIT" ]
11
2021-08-02T18:59:37.000Z
2021-08-12T16:18:07.000Z
src/apps/tests/tests/LinearMatrix_tests.cpp
Adnn/math
017e7c42bfdd665c78557109b0b379567bfe8e7c
[ "MIT" ]
1
2021-03-18T10:56:44.000Z
2021-03-18T10:56:44.000Z
#include "catch.hpp" #include "detection.h" #include "operation_detectors.h" #include <math/LinearMatrix.h> using namespace ad; using namespace ad::math; SCENARIO("Linear matrix construction") { THEN("An Linear matrix can be constructed by specifying each element.") { LinearMatrix<2, 2> linear{ 1.f, 2.f, 3.f, 4.f }; double expected = 0.f; for (auto element : linear) { REQUIRE(element == ++expected); } } THEN("An identity Linear matrix can be constructed.") { LinearMatrix<4, 4> identity = LinearMatrix<4, 4>::Identity(); REQUIRE(identity == Matrix<4, 4>::Identity()); } } SCENARIO("LinearMatrix available operations") { using Linear4 = LinearMatrix<4, 4>; THEN("A 'plain' matrix cannot be converted to a Linear matrix") { REQUIRE_FALSE(is_detected_v<is_staticcastable_t, Matrix<4, 4>, Linear4>); } THEN("A Linar matrix is implicitly convertible to a 'plain' matrix") { REQUIRE(std::is_convertible_v<Linear4, Matrix<4, 4>>); } THEN("Two square matrices of same dimension can be compound multiplied") { REQUIRE(is_detected_v<is_multiplicative_assignable_t, Linear4, Linear4>); REQUIRE(std::is_same_v<decltype(std::declval<Linear4>() * std::declval<Linear4>()), Linear4>); } THEN("Two square matrices of different dimension cannot be compound multiplied") { REQUIRE_FALSE(is_detected_v<is_multiplicative_assignable_t, LinearMatrix<3,3>, LinearMatrix<4, 4>>); } THEN("Two multipliable matrices of different size cannot be compound multiplied") { REQUIRE(is_detected_v<is_multiplicative_t, LinearMatrix<3,3>, LinearMatrix<3, 4>>); REQUIRE_FALSE(is_detected_v<is_multiplicative_assignable_t, LinearMatrix<3,3>, LinearMatrix<3, 4>>); } THEN("Two non-square matrices of same dimension cannot be compound multiplied") { REQUIRE_FALSE(is_detected_v<is_multiplicative_assignable_t, LinearMatrix<3,4>, LinearMatrix<3, 4>>); } }
30.385714
108
0.652562
Adnn
885db3a357a5541728e0317ee40afc8f1be1533a
911
cpp
C++
test/2048/tes.cpp
6923403/C
d365021759e6d9078254b4b7b6455e0408e4b691
[ "MIT" ]
1
2020-10-01T14:52:45.000Z
2020-10-01T14:52:45.000Z
test/2048/tes.cpp
6923403/C
d365021759e6d9078254b4b7b6455e0408e4b691
[ "MIT" ]
3
2020-06-19T01:24:51.000Z
2020-07-16T14:00:30.000Z
test/2048/tes.cpp
6923403/C
d365021759e6d9078254b4b7b6455e0408e4b691
[ "MIT" ]
null
null
null
#include <iostream> #include <stdlib.h> #include <unistd.h> #include <ctime> #include <termios.h> using namespace std; #define max_x 8 #define max_y 4 int map_size[max_x][max_y]; void drawline() { int x, y; system("clear"); for(x = 0; x < max_x; ++x) { for(y = 0; y < max_y; ++y) { if(map_size[x][y] == 1) { cout << " ———"; } else if(map_size[x][y] == 2) { cout << " | "; } } cout << endl; } } int main() { int i, j; int con = 4; for(i = 0; i < max_x; ++i) { for(j = 0; j < max_y; ++j) { if(i % 2 == 0) { map_size[i][j] = 1; } else if(i %2 == 1) { map_size[i][j] = 2; } } } drawline(); }
16.267857
42
0.347969
6923403
885de00c45ededb4aef602920d57ebefdf333fbd
768
hpp
C++
Jackal/Source/RenderDevice/Public/RenderDevice/TextureCubeMap.hpp
CheezBoiger/Jackal
6c87bf19f6c1cd63f53c815820b32fc71b48bf77
[ "MIT" ]
null
null
null
Jackal/Source/RenderDevice/Public/RenderDevice/TextureCubeMap.hpp
CheezBoiger/Jackal
6c87bf19f6c1cd63f53c815820b32fc71b48bf77
[ "MIT" ]
null
null
null
Jackal/Source/RenderDevice/Public/RenderDevice/TextureCubeMap.hpp
CheezBoiger/Jackal
6c87bf19f6c1cd63f53c815820b32fc71b48bf77
[ "MIT" ]
null
null
null
// Copyright (c) 2017 Jackal Engine, MIT License. #pragma once #include "Core/Platform/JTypes.hpp" #include "Core/Structure/JString.hpp" #include "Core/Utility/TextureLoader.hpp" #include "RenderDeviceTypes.hpp" #include "RenderObject.hpp" namespace jackal { // CubeMap Texture object. class CubeMap : public RenderObject { protected: CubeMap() { } public: virtual ~CubeMap() { } TextureT TextureType() { static const TextureT type = TEXTURE_CUBE; return type; } // Load textures into this texture object, for use in the rendering // api. Must load 6 faces, or texture handles. // The order of the handles must be: // virtual void Load(TextureInfoT &info, TextureHandle *textures) = 0; virtual void CleanUp() = 0; }; } // jackal
20.210526
69
0.705729
CheezBoiger