blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
f98b345c527bf86eeb275ef436899648ecc3c65f
664f183c7614289bb829f034996a0d940cc1f165
/win9x/soundmng.cpp
273d49a04cb305f6a87969f011195053e6664002
[ "MIT", "GPL-1.0-or-later" ]
permissive
orbea/NP2kai
fe1e146cbc16163d47580bd9493faa6e7cb4780a
6ff798b76bd2d13793cf9e1703738114193db5a9
refs/heads/master
2020-03-27T08:01:39.757680
2018-08-22T16:16:41
2018-08-22T16:16:41
146,213,884
0
0
MIT
2018-08-26T20:26:06
2018-08-26T20:26:06
null
SHIFT_JIS
C++
false
false
9,362
cpp
/** * @file soundmng.cpp * @brief サウンド マネージャ クラスの動作の定義を行います */ #include "compiler.h" #include "soundmng.h" #include "np2.h" #if defined(SUPPORT_ROMEO) #include "ext\externalchipmanager.h" #endif #if defined(MT32SOUND_DLL) #include "ext\mt32snd.h" #endif #if defined(SUPPORT_ASIO) #include "soundmng\sdasio.h" #endif // defined(SUPPORT_ASIO) #include "soundmng\sddsound3.h" #if defined(SUPPORT_WASAPI) #include "soundmng\sdwasapi.h" #endif // defined(SUPPORT_WASAPI) #include "common\parts.h" #include "sound\sound.h" #if defined(VERMOUTH_LIB) #include "sound\vermouth\vermouth.h" #endif #if !defined(_WIN64) #ifdef __cplusplus extern "C" { #endif /** * satuation * @param[out] dst 出力バッファ * @param[in] src 入力バッファ * @param[in] size サイズ */ void __fastcall satuation_s16mmx(SINT16 *dst, const SINT32 *src, UINT size); #ifdef __cplusplus } #endif #endif #if defined(VERMOUTH_LIB) MIDIMOD vermouth_module = NULL; #endif //! 唯一のインスタンスです CSoundMng CSoundMng::sm_instance; /** * 初期化 */ void CSoundMng::Initialize() { #if defined(SUPPORT_ASIO) || defined(SUPPORT_WASAPI) ::CoInitializeEx(NULL, COINIT_MULTITHREADED); #endif // defined(SUPPORT_ASIO) || defined(SUPPORT_WASAPI) CSoundDeviceDSound3::Initialize(); #if defined(SUPPORT_WASAPI) CSoundDeviceWasapi::Initialize(); #endif // defined(SUPPORT_WASAPI) #if defined(SUPPORT_ASIO) CSoundDeviceAsio::Initialize(); #endif // defined(SUPPORT_ASIO) #if defined(SUPPORT_ROMEO) CExternalChipManager::GetInstance()->Initialize(); #endif // defined(SUPPORT_ROMEO) } /** * 解放 */ void CSoundMng::Deinitialize() { #if defined(SUPPORT_ROMEO) CExternalChipManager::GetInstance()->Deinitialize(); #endif // defined(SUPPORT_ROMEO) #if defined(SUPPORT_WASAPI) CSoundDeviceWasapi::Deinitialize(); #endif // defined(SUPPORT_WASAPI) #if defined(SUPPORT_ASIO) || defined(SUPPORT_WASAPI) ::CoUninitialize(); #endif // defined(SUPPORT_ASIO) || defined(SUPPORT_WASAPI) } /** * コンストラクタ */ CSoundMng::CSoundMng() : m_pSoundDevice(NULL) , m_nMute(0) { SetReverse(false); } /** * オープン * @param[in] nType デバイス タイプ * @param[in] lpName デバイス名 * @param[in] hWnd ウィンドウ ハンドル * @retval true 成功 * @retval false 失敗 */ bool CSoundMng::Open(DeviceType nType, LPCTSTR lpName, HWND hWnd) { Close(); CSoundDeviceBase* pSoundDevice = NULL; switch (nType) { case kDefault: pSoundDevice = new CSoundDeviceDSound3; lpName = NULL; break; case kDSound3: pSoundDevice = new CSoundDeviceDSound3; break; #if defined(SUPPORT_WASAPI) case kWasapi: pSoundDevice = new CSoundDeviceWasapi; break; #endif // defined(SUPPORT_WASAPI) #if defined(SUPPORT_ASIO) case kAsio: pSoundDevice = new CSoundDeviceAsio; break; #endif // defined(SUPPORT_ASIO) } if (pSoundDevice) { if (!pSoundDevice->Open(lpName, hWnd)) { delete pSoundDevice; pSoundDevice = NULL; } } if (pSoundDevice == NULL) { return false; } m_pSoundDevice = pSoundDevice; #if defined(MT32SOUND_DLL) MT32Sound::GetInstance()->Initialize(); #endif return true; } /** * クローズ */ void CSoundMng::Close() { if (m_pSoundDevice) { m_pSoundDevice->Close(); delete m_pSoundDevice; m_pSoundDevice = NULL; } #if defined(MT32SOUND_DLL) MT32Sound::GetInstance()->Deinitialize(); #endif } /** * サウンド有効 * @param[in] nProc プロシージャ */ void CSoundMng::Enable(SoundProc nProc) { const UINT nBit = 1 << nProc; if (!(m_nMute & nBit)) { return; } m_nMute &= ~nBit; if (!m_nMute) { if (m_pSoundDevice) { m_pSoundDevice->PlayStream(); } #if defined(SUPPORT_ROMEO) CExternalChipManager::GetInstance()->Mute(false); #endif // defined(SUPPORT_ROMEO) } } /** * サウンド無効 * @param[in] nProc プロシージャ */ void CSoundMng::Disable(SoundProc nProc) { if (!m_nMute) { if (m_pSoundDevice) { m_pSoundDevice->StopStream(); m_pSoundDevice->StopAllPCM(); } #if defined(SUPPORT_ROMEO) CExternalChipManager::GetInstance()->Mute(true); #endif // defined(SUPPORT_ROMEO) } m_nMute |= (1 << nProc); } /** * ストリームを作成 * @param[in] nSamplingRate サンプリング レート * @param[in] ms バッファ長(ミリ秒) * @return バッファ数 */ UINT CSoundMng::CreateStream(UINT nSamplingRate, UINT ms) { if (m_pSoundDevice == NULL) { return 0; } if (ms < 40) { ms = 40; } else if (ms > 1000) { ms = 1000; } UINT nBuffer = (nSamplingRate * ms) / 2000; nBuffer = (nBuffer + 1) & (~1); nBuffer = m_pSoundDevice->CreateStream(nSamplingRate, 2, nBuffer); if (nBuffer == 0) { return 0; } m_pSoundDevice->SetStreamData(this); #if defined(VERMOUTH_LIB) vermouth_module = midimod_create(nSamplingRate); midimod_loadall(vermouth_module); #endif #if defined(MT32SOUND_DLL) MT32Sound::GetInstance()->SetRate(nSamplingRate); #endif return nBuffer; } /** * ストリームを破棄 */ inline void CSoundMng::DestroyStream() { if (m_pSoundDevice) { m_pSoundDevice->DestroyStream(); } #if defined(VERMOUTH_LIB) midimod_destroy(vermouth_module); vermouth_module = NULL; #endif #if defined(MT32SOUND_DLL) MT32Sound::GetInstance()->SetRate(0); #endif } /** * ストリームのリセット */ inline void CSoundMng::ResetStream() { if (m_pSoundDevice) { m_pSoundDevice->ResetStream(); } } /** * ストリームの再生 */ inline void CSoundMng::PlayStream() { if (!m_nMute) { if (m_pSoundDevice) { m_pSoundDevice->PlayStream(); } } } /** * ストリームの停止 */ inline void CSoundMng::StopStream() { if (!m_nMute) { if (m_pSoundDevice) { m_pSoundDevice->StopStream(); } } } /** * ストリームを得る * @param[out] lpBuffer バッファ * @param[in] nBufferCount バッファ カウント * @return サンプル数 */ UINT CSoundMng::Get16(SINT16* lpBuffer, UINT nBufferCount) { const SINT32* lpSource = ::sound_pcmlock(); if (lpSource) { (*m_fnMix)(lpBuffer, lpSource, nBufferCount * 4); ::sound_pcmunlock(lpSource); return nBufferCount; } else { return 0; } } /** * パン反転を設定する * @param[in] bReverse 反転フラグ */ inline void CSoundMng::SetReverse(bool bReverse) { if (!bReverse) { #if !defined(_WIN64) if (mmxflag) { m_fnMix = satuation_s16; } else { m_fnMix = satuation_s16mmx; } #else m_fnMix = satuation_s16; #endif } else { m_fnMix = satuation_s16x; } } /** * PCM データ読み込み * @param[in] nNum PCM 番号 * @param[in] lpFilename ファイル名 */ void CSoundMng::LoadPCM(SoundPCMNumber nNum, LPCTSTR lpFilename) { if (m_pSoundDevice) { m_pSoundDevice->LoadPCM(nNum, lpFilename); } } /** * PCM ヴォリューム設定 * @param[in] nNum PCM 番号 * @param[in] nVolume ヴォリューム */ void CSoundMng::SetPCMVolume(SoundPCMNumber nNum, int nVolume) { if (m_pSoundDevice) { m_pSoundDevice->SetPCMVolume(nNum, nVolume); } } /** * PCM 再生 * @param[in] nNum PCM 番号 * @param[in] bLoop ループ フラグ * @retval true 成功 * @retval false 失敗 */ inline bool CSoundMng::PlayPCM(SoundPCMNumber nNum, BOOL bLoop) { if (!m_nMute) { if (m_pSoundDevice) { return m_pSoundDevice->PlayPCM(nNum, bLoop); } } return false; } /** * PCM 停止 * @param[in] nNum PCM 番号 */ inline void CSoundMng::StopPCM(SoundPCMNumber nNum) { if (m_pSoundDevice) { m_pSoundDevice->StopPCM(nNum); } } // ---- C ラッパー /** * ストリーム作成 * @param[in] rate サンプリング レート * @param[in] ms バッファ長(ミリ秒) * @return バッファ サイズ */ UINT soundmng_create(UINT rate, UINT ms) { return CSoundMng::GetInstance()->CreateStream(rate, ms); } /** * ストリーム破棄 */ void soundmng_destroy(void) { CSoundMng::GetInstance()->DestroyStream(); } /** * ストリーム リセット */ void soundmng_reset(void) { CSoundMng::GetInstance()->ResetStream(); } /** * ストリーム開始 */ void soundmng_play(void) { CSoundMng::GetInstance()->PlayStream(); } /** * ストリーム停止 */ void soundmng_stop(void) { CSoundMng::GetInstance()->StopStream(); } /** * ストリーム パン反転設定 * @param[in] bReverse 反転 */ void soundmng_setreverse(BOOL bReverse) { CSoundMng::GetInstance()->SetReverse((bReverse) ? true : false); } /** * PCM 再生 * @param[in] nNum PCM 番号 * @param[in] bLoop ループ * @retval SUCCESS 成功 * @retval FAILURE 失敗 */ BRESULT soundmng_pcmplay(enum SoundPCMNumber nNum, BOOL bLoop) { return (CSoundMng::GetInstance()->PlayPCM(nNum, bLoop)) ? SUCCESS : FAILURE; } /** * PCM 停止 * @param[in] nNum PCM 番号 */ void soundmng_pcmstop(enum SoundPCMNumber nNum) { CSoundMng::GetInstance()->StopPCM(nNum); }
[ "sylph23k@gmail.com" ]
sylph23k@gmail.com
d692a1f13d157ca85a7cb6ded89f474e5cd7e98d
b72890d0e6503b4528bef2b09743f6df72cb01d2
/capabilities/DavsClient/acsdkAssetsCommon/src/JitterUtil.cpp
fb632c433513012652b05a39e5096fae062a1640
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-pml-2020", "LicenseRef-.amazon.com.-AmznSL-1.0" ]
permissive
shivasiddharth/avs-device-sdk
b1375db55f204f1baaa9a4825e31f944a6e6d13c
c7ca5a12f65ce95f99d56fc7a1ab79cc96147ed8
refs/heads/master
2021-12-01T17:21:42.067397
2021-11-28T09:34:42
2021-11-28T09:34:42
152,394,898
0
2
Apache-2.0
2021-11-26T09:17:25
2018-10-10T09:09:11
C++
UTF-8
C++
false
false
1,980
cpp
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "acsdkAssetsCommon/JitterUtil.h" #include <AVSCommon/Utils/Logger/Logger.h> #include <mutex> #include <random> namespace alexaClientSDK { namespace acsdkAssets { namespace common { namespace jitterUtil { using namespace std; using namespace chrono; /// String to identify log entries originating from this file. static const std::string TAG{"JitterUtil"}; /** * Create a LogEntry using this file's TAG and the specified event string. * * @param The event string for this @c LogEntry. */ #define LX(event) alexaClientSDK::avsCommon::utils::logger::LogEntry(TAG, event) milliseconds jitter(milliseconds baseValue, float jitterFactor) { std::random_device rd; std::mt19937 mt{rd()}; if (jitterFactor <= 0 || jitterFactor >= 1) { ACSDK_ERROR(LX("jitter").m("Returning without jitter").d("bad jitter", jitterFactor)); return baseValue; } // jitter between +/- JITTER_FACTOR of current time auto jitterSize = static_cast<int64_t>(jitterFactor * baseValue.count()); auto jitterRand = std::uniform_int_distribution<int64_t>(-jitterSize, jitterSize); return baseValue + milliseconds(jitterRand(mt)); } milliseconds expJitter(milliseconds baseValue, float jitterFactor) { return baseValue + jitter(baseValue, jitterFactor); } } // namespace jitterUtil } // namespace common } // namespace acsdkAssets } // namespace alexaClientSDK
[ "womw@amazon.com" ]
womw@amazon.com
73c3348b0af3b4d7680d5a7b4ebd165a85fef235
94e5a9e157d3520374d95c43fe6fec97f1fc3c9b
/Codeforces/409 2/B.cpp
f66f9188fcc938212d8eaa37523cac3e43eb6757
[ "MIT" ]
permissive
dipta007/Competitive-Programming
0127c550ad523884a84eb3ea333d08de8b4ba528
998d47f08984703c5b415b98365ddbc84ad289c4
refs/heads/master
2021-01-21T14:06:40.082553
2020-07-06T17:40:46
2020-07-06T17:40:46
54,851,014
8
4
null
2020-05-02T13:14:41
2016-03-27T22:30:02
C++
UTF-8
C++
false
false
3,796
cpp
#pragma comment(linker, "/stack:640000000") #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <iomanip> #include <iterator> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <utility> #include <vector> using namespace std; const double EPS = 1e-9; const int INF = 0x7f7f7f7f; const double PI=acos(-1.0); #define READ(f) freopen(f, "r", stdin) #define WRITE(f) freopen(f, "w", stdout) #define MP(x, y) make_pair(x, y) #define PB(x) push_back(x) #define rep(i,n) for(int i = 1 ; i<=(n) ; i++) #define repI(i,n) for(int i = 0 ; i<(n) ; i++) #define FOR(i,L,R) for (int i = (int)(L); i <= (int)(R); i++) #define ROF(i,L,R) for (int i = (int)(L); i >= (int)(R); i--) #define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++) #define ALL(p) p.begin(),p.end() #define ALLR(p) p.rbegin(),p.rend() #define SET(p) memset(p, -1, sizeof(p)) #define CLR(p) memset(p, 0, sizeof(p)) #define MEM(p, v) memset(p, v, sizeof(p)) #define getI(a) scanf("%d", &a) #define getII(a,b) scanf("%d%d", &a, &b) #define getIII(a,b,c) scanf("%d%d%d", &a, &b, &c) #define getL(a) scanf("%lld",&a) #define getLL(a,b) scanf("%lld%lld",&a,&b) #define getLLL(a,b,c) scanf("%lld%lld%lld",&a,&b,&c) #define getC(n) scanf("%c",&n) #define getF(n) scanf("%lf",&n) #define getS(n) scanf("%s",n) #define bitCheck(N,in) ((bool)(N&(1<<(in)))) #define bitOff(N,in) (N&(~(1<<(in)))) #define bitOn(N,in) (N|(1<<(in))) #define bitCount(a) __builtin_popcount(a) #define iseq(a,b) (fabs(a-b)<EPS) #define UNIQUE(V) (V).erase(unique((V).begin(),(V).end()),(V).end()) #define vi vector < int > #define vii vector < vector < int > > #define pii pair< int, int > #define ff first #define ss second #define ll long long #define ull unsigned long long template< class T > inline T _abs(T n) { return ((n) < 0 ? -(n) : (n)); } template< class T > inline T _max(T a, T b) { return (!((a)<(b))?(a):(b)); } template< class T > inline T _min(T a, T b) { return (((a)<(b))?(a):(b)); } template< class T > inline T _swap(T &a, T &b) { a=a^b;b=a^b;a=a^b;} template< class T > inline T gcd(T a, T b) { return (b) == 0 ? (a) : gcd((b), ((a) % (b))); } template< class T > inline T lcm(T a, T b) { return ((a) / gcd((a), (b)) * (b)); } template <typename T> string NumberToString ( T Number ) { ostringstream ss; ss << Number; return ss.str(); } #ifdef dipta007 #define debug(args...) {cerr<<"Debug: "; dbg,args; cerr<<endl;} #else #define debug(args...) // Just strip off all debug tokens #endif struct debugger{ template<typename T> debugger& operator , (const T& v){ cerr<<v<<" "; return *this; } }dbg; int main() { #ifdef dipta007 //READ("in.txt"); // WRITE("in.txt"); #endif // dipta007 ios_base::sync_with_stdio(0);cin.tie(0); string x,z; while(getline(cin,x)) { string res = x; int flg=1; getline(cin,z); FOR(i,0,(int)x.size()-1) { if(x[i]<z[i]) { flg=0; break; } res[i] = z[i]; } if(flg==0) { cout << "-1" <<endl; continue; } cout << res << endl; } return 0; }
[ "iamdipta@gmail.com" ]
iamdipta@gmail.com
139ad75a275dd35b1314f5aab87b7ec3e968e39c
ee7abb27d5473a43f8853936df4533abb94de62a
/src/lib/Host_Base.cpp
ee971ea42962f622d890180fb1b084790619a8d9
[]
no_license
catid/ssbot
845027b000f4b9c78b05d5d3cdf419e0aa4762da
8c90ae19587afe154f31d3de58516fc7a11d98c4
refs/heads/master
2020-03-28T03:11:13.185434
2014-02-18T04:43:20
2014-02-18T04:43:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
335
cpp
#include "Host_Base.h" #include "player.h" Host_Base:: Host_Base(BOT_INFO & info) { botInfo = info; } Player *Host_Base::findPlayer(const char *name) { _listnode <Player> *parse = playerlist.head; while (parse) { Player *p = parse->item; if (CMPSTR(p->name, name)) return p; parse = parse->next; } return NULL; }
[ "adam.j.lewis@gmail.com" ]
adam.j.lewis@gmail.com
042f0d28f3683210bc8eaac5156f66e2e11ae10e
3310d7fa7364f8fe23136508d8fee3200901da35
/ThinkingInCPP/C16Templates/excercises/ShapeHierarchy.h
5e4f996a9b430d80522684c11f02d393b90f59d2
[]
no_license
D000M/Games
f239919a0bd7bf2326f318e1902b38ecd323e05e
90ac1172a7383f30944a1137f349fe3ca5255536
refs/heads/master
2021-07-11T21:43:54.625976
2020-05-28T07:15:23
2020-05-28T07:15:23
142,460,210
0
0
null
null
null
null
UTF-8
C++
false
false
865
h
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: ShapeHierarchy.h * Author: default * * Created on December 21, 2019, 4:21 PM */ #ifndef SHAPEHIERARCHY_H #define SHAPEHIERARCHY_H class IObject { public: }; class IShapeEx { public: }; class OShapeEx : public IObject, IShapeEx { public: }; class CircleEx : public IShapeEx { public: }; class SquareEx : public IShapeEx { public: }; class TriangleEx : public IShapeEx { public: }; class OCircleEx : public CircleEx, public OShapeEx { public: }; class OSquareEx : public SquareEx, public OShapeEx { public: }; class OTriangleEx : public TriangleEx, public OShapeEx { public: }; #endif /* SHAPEHIERARCHY_H */
[ "georgi.slavov@egt-bg.com" ]
georgi.slavov@egt-bg.com
0d239440e0c2f0deeaa31288839621c756537c35
a1ec4f96118acf65ae421682c41279d4165746b9
/11.04.2018/klarkowski - trojkaty .cpp
1dad317a0b9e1b56ef23dff442ff4151981d9bbf
[]
no_license
Klarys/Algorithms
f32aabb72f4d8ba35f68869c56c139e51393ba55
4587b19edecd0d5591445559f252f893c60dea28
refs/heads/master
2020-05-15T08:32:35.371788
2019-04-18T21:40:12
2019-04-18T21:40:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
822
cpp
#include <iostream> #include <vector> using namespace std; bool sprawdzanie(vector <int> tab) { int n=tab.size(); bool spr; for(int i=0; i<n-2; i++) { for(int j=i+1; j<n-1; j++) { for(int k=j+1; k<n; k++) { spr=1; if(tab[i]+tab[j]<=tab[k] || tab[j]+tab[k]<=tab[i] || tab[i]+tab[k]<=tab[j]) spr=0; if(spr==1) { cout<<tab[i]<<" "<<tab[j]<<" "<<tab[k]<<endl; return 1; } } } } if(spr==0) return 0; } main() { int temp; vector <int> tab; while(tab.size()<=45) { cin>>temp; if(temp==0) break; tab.push_back(temp); } if(!sprawdzanie(tab)) cout<<"NIE"<<endl; return 0; }
[ "44509197+Klarys@users.noreply.github.com" ]
44509197+Klarys@users.noreply.github.com
a51ce4ce2a34804c3023ea2836da53f9264d366c
60d50f087d6600698729247db018a7a7d30d1cd0
/SourceParametersDialog.cpp
1d4e2ff0267bd7041ba5febd72cae72d5244667b
[]
no_license
AleksandraRuzic/RS012-data-mining-toolbox
38660a09eab1d6d9aac7ca8cafa744a3208d224e
6b12a52a81cec89505650c54059e1e4e2e21ce69
refs/heads/master
2022-03-30T19:32:41.695753
2020-01-20T12:47:16
2020-01-20T12:47:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
844
cpp
#include "SourceParametersDialog.hpp" #include "ui_SourceParametersDialog.h" SourceParametersDialog::SourceParametersDialog(SourceNode* cvor, QWidget *parent) : QDialog(parent), ui(new Ui::SourceParametersDialog), UlazniCvor(cvor) { ui->setupUi(this); } SourceParametersDialog::~SourceParametersDialog() { delete ui; } void SourceParametersDialog::on_OdaberiCvor_clicked() { QString fileName = QFileDialog::getOpenFileName( this, tr("Odaberite CSV Fajl"), "/home", "CSV Files (*.csv)" ); ui->NazivFajla->setText(fileName); } void SourceParametersDialog::on_Potvrdi_clicked() { QString nazivFjla = ui->NazivFajla->toPlainText(); UlazniCvor->setFilename(nazivFjla.toStdString()); UlazniCvor->read(); this->close(); }
[ "nikola.peric303@gmail.com" ]
nikola.peric303@gmail.com
ed7b6943ab2d5281e96b645c532ba2f3d2c843dc
78d31f7946dac510ef230316d1a174275b06b4c6
/Lobelia/Input/RawInput(old)/DeviceList/DeviceManager.hpp
10ffd78ac1e3f1c03a89a537144f17f25f6841c3
[]
no_license
LobeliaSnow/LobeliaEngine
10b25746b3d02fdb9c26286e15124f7fd7b764ba
8121e83998da656a047cc14eb6bd029ae8c2d63d
refs/heads/master
2021-05-02T17:27:55.403882
2018-07-29T17:40:53
2018-07-29T17:40:53
120,646,038
1
0
null
null
null
null
UTF-8
C++
false
false
1,507
hpp
#pragma once namespace Lobelia::Input { class DeviceManager { private: static std::vector<MouseData> mouseData; static std::vector<KeyboardData> keyboardData; static std::vector<DualShock4Data> dualShock4Data; private: static std::unique_ptr<RAWINPUTDEVICELIST[]> deviceList; static UINT deviceCount; static std::vector<std::pair<HANDLE, std::shared_ptr<Mouse>>> mouses; static UINT mouseCount; static std::vector<std::pair<HANDLE, std::shared_ptr<Keyboard>>> keyboards; static UINT keyboardCount; static std::vector<std::pair<HANDLE, std::shared_ptr<DualShock4>>> dualShock4s; static UINT dualShock4Count; private: static void UpdateMouse(RAWINPUT* raw); static void UpdateKeyboard(RAWINPUT* raw); static void UpdateDualShock4(RAWINPUT* raw); static void AddDualShock4(HANDLE device); public: static void TakeDevices(HWND hwnd); static void Clear(); static LRESULT UpdateProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp); static void Update(); static int GetMouseCount(); static Mouse* GetMouse(int i); static int GetKeyboardCount(); static Keyboard* GetKeyboard(int i); static int GetDualShock4Count(); static DualShock4* GetDualShock4(int i); template<class T> static BYTE GetKey(int key_code); static BYTE GetKeyboardKey(int key_code); static BYTE GetMouseKey(int key_code); static BYTE GetDualShock4Key(DualShock4::KeyCode key_code); }; BYTE GetKeyboardKey(int key_code); BYTE GetMouseKey(int key_code); } #include "DeviceManager.inl"
[ "lobelia.snow@gmail.com" ]
lobelia.snow@gmail.com
168215a7f0920b61e3583f897bbcb4c9e7116bc6
ad273708d98b1f73b3855cc4317bca2e56456d15
/aws-cpp-sdk-iot/source/model/DimensionType.cpp
c4de69d4bd9a06839cd42651d98dfa8fded35f5a
[ "MIT", "Apache-2.0", "JSON" ]
permissive
novaquark/aws-sdk-cpp
b390f2e29f86f629f9efcf41c4990169b91f4f47
a0969508545bec9ae2864c9e1e2bb9aff109f90c
refs/heads/master
2022-08-28T18:28:12.742810
2020-05-27T15:46:18
2020-05-27T15:46:18
267,351,721
1
0
Apache-2.0
2020-05-27T15:08:16
2020-05-27T15:08:15
null
UTF-8
C++
false
false
2,164
cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/iot/model/DimensionType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace IoT { namespace Model { namespace DimensionTypeMapper { static const int TOPIC_FILTER_HASH = HashingUtils::HashString("TOPIC_FILTER"); DimensionType GetDimensionTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == TOPIC_FILTER_HASH) { return DimensionType::TOPIC_FILTER; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<DimensionType>(hashCode); } return DimensionType::NOT_SET; } Aws::String GetNameForDimensionType(DimensionType enumValue) { switch(enumValue) { case DimensionType::TOPIC_FILTER: return "TOPIC_FILTER"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace DimensionTypeMapper } // namespace Model } // namespace IoT } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
9eba154c8b8bc286372f39343e519210e255cfef
b9a754d09984634d2f88e91241c47583d8ce1b15
/src/ElectroMagnBC/ElectroMagnBC3D_refl.cpp
846a0db295d6b47a8b9624128db30ecc72d00354
[]
no_license
iouatu/mySmilei
9aa97d3fb1f9e5ddf477e4bc4eff22d7667b8f8f
41c2496d21ac03d0dd9b9d8ec41d60cdbf13bf1b
refs/heads/main
2023-07-23T01:42:48.705778
2021-08-18T18:13:01
2021-08-18T18:13:01
397,676,095
1
0
null
null
null
null
UTF-8
C++
false
false
6,556
cpp
#include "ElectroMagnBC3D_refl.h" #include <cstdlib> #include <iostream> #include <string> #include "Params.h" #include "Patch.h" #include "ElectroMagn.h" #include "Field3D.h" #include "Tools.h" using namespace std; ElectroMagnBC3D_refl::ElectroMagnBC3D_refl( Params &params, Patch *patch, unsigned int _min_max ) : ElectroMagnBC3D( params, patch, _min_max ) { // oversize if (!params.uncoupled_grids) { oversize_x = params.oversize[0]; oversize_y = params.oversize[1]; oversize_z = params.oversize[2]; } else { oversize_x = params.region_oversize[0]; oversize_y = params.region_oversize[1]; oversize_z = params.region_oversize[2]; } } // --------------------------------------------------------------------------------------------------------------------- // Apply Boundary Conditions // --------------------------------------------------------------------------------------------------------------------- void ElectroMagnBC3D_refl::apply( ElectroMagn *EMfields, double time_dual, Patch *patch ) { if( min_max == 0 && patch->isXmin() ) { // APPLICATION OF BCs OVER THE FULL GHOST CELL REGION // Static cast of the fields Field3D *By3D = static_cast<Field3D *>( EMfields->By_ ); Field3D *Bz3D = static_cast<Field3D *>( EMfields->Bz_ ); // FORCE CONSTANT MAGNETIC FIELDS // for By^(d,p,d) for( unsigned int i=oversize_x; i>0; i-- ) { for( unsigned int j=0 ; j<ny_p ; j++ ) { for( unsigned int k=0 ; k<nz_d ; k++ ) { ( *By3D )( i-1, j, k ) = ( *By3D )( i, j, k ); } } } // for Bz^(d,d,p) for( unsigned int i=oversize_x; i>0; i-- ) { for( unsigned int j=0 ; j<ny_d ; j++ ) { for( unsigned int k=0 ; k<nz_p ; k++ ) { ( *Bz3D )( i-1, j, k ) = ( *Bz3D )( i, j, k ); } } } } else if( min_max == 1 && patch->isXmax() ) { // Static cast of the fields Field3D *By3D = static_cast<Field3D *>( EMfields->By_ ); Field3D *Bz3D = static_cast<Field3D *>( EMfields->Bz_ ); // FORCE CONSTANT MAGNETIC FIELDS // for By^(d,p,d) for( unsigned int i=nx_d-oversize_x; i<nx_d; i++ ) { for( unsigned int j=0 ; j<ny_p ; j++ ) { for( unsigned int k=0 ; k<nz_d ; k++ ) { ( *By3D )( i, j, k ) = ( *By3D )( i-1, j, k ); } } } // for Bz^(d,d,p) for( unsigned int i=nx_d-oversize_x; i<nx_d; i++ ) { for( unsigned int j=0 ; j<ny_d ; j++ ) { for( unsigned int k=0 ; k<nz_p ; k++ ) { ( *Bz3D )( i, j, k ) = ( *Bz3D )( i-1, j, k ); } } } } else if( min_max == 2 && patch->isYmin() ) { // Static cast of the fields Field3D *Bx3D = static_cast<Field3D *>( EMfields->Bx_ ); Field3D *Bz3D = static_cast<Field3D *>( EMfields->Bz_ ); // FORCE CONSTANT MAGNETIC FIELDS // for Bx^(p,d,d) for( unsigned int i=0; i<nx_p; i++ ) { for( unsigned int j=oversize_y ; j>0 ; j-- ) { for( unsigned int k=0; k<nz_d ; k++ ) { ( *Bx3D )( i, j-1, k ) = ( *Bx3D )( i, j, k ); } } } // for Bz^(d,d,p) for( unsigned int i=0; i<nx_d; i++ ) { for( unsigned int j=oversize_y ; j>0 ; j-- ) { for( unsigned int k=0; k<nz_p ; k++ ) { ( *Bz3D )( i, j-1, k ) = ( *Bz3D )( i, j, k ); } } } } else if( min_max == 3 && patch->isYmax() ) { // Static cast of the fields Field3D *Bx3D = static_cast<Field3D *>( EMfields->Bx_ ); Field3D *Bz3D = static_cast<Field3D *>( EMfields->Bz_ ); // FORCE CONSTANT MAGNETIC FIELDS // for Bx^(p,d,d) for( unsigned int i=0; i<nx_p; i++ ) { for( unsigned int j=ny_d-oversize_y; j<ny_d ; j++ ) { for( unsigned int k=0; k<nz_d ; k++ ) { ( *Bx3D )( i, j, k ) = ( *Bx3D )( i, j-1, k ); } } } // for Bz^(d,d,p) for( unsigned int i=0; i<nx_d; i++ ) { for( unsigned int j=ny_d-oversize_y; j<ny_d ; j++ ) { for( unsigned int k=0; k<nz_p ; k++ ) { ( *Bz3D )( i, j, k ) = ( *Bz3D )( i, j-1, k ); } } } } else if( min_max==4 && patch->isZmin() ) { // Static cast of the fields Field3D *Bx3D = static_cast<Field3D *>( EMfields->Bx_ ); Field3D *By3D = static_cast<Field3D *>( EMfields->By_ ); // FORCE CONSTANT MAGNETIC FIELDS // for Bx^(p,d,d) for( unsigned int i=0; i<nx_p; i++ ) { for( unsigned int j=0 ; j<ny_d ; j++ ) { for( unsigned int k=oversize_z ; k>0 ; k-- ) { ( *Bx3D )( i, j, k-1 ) = ( *Bx3D )( i, j, k ); } } } // for By^(d,p,d) for( unsigned int i=0; i<nx_d; i++ ) { for( unsigned int j=0 ; j<ny_p ; j++ ) { for( unsigned int k=oversize_z ; k>0 ; k-- ) { ( *By3D )( i, j, k-1 ) = ( *By3D )( i, j, k ); } } } } else if( min_max==5 && patch->isZmax() ) { // Static cast of the fields Field3D *Bx3D = static_cast<Field3D *>( EMfields->Bx_ ); Field3D *By3D = static_cast<Field3D *>( EMfields->By_ ); // FORCE CONSTANT MAGNETIC FIELDS // for Bx^(p,d,d) for( unsigned int i=0; i<nx_p; i++ ) { for( unsigned int j=0 ; j<ny_d ; j++ ) { for( unsigned int k=nz_d-oversize_z; k<nz_d ; k++ ) { ( *Bx3D )( i, j, k ) = ( *Bx3D )( i, j, k-1 ); } } } // for By^(d,p,d) for( unsigned int i=0; i<nx_d; i++ ) { for( unsigned int j=0 ; j<ny_p ; j++ ) { for( unsigned int k=nz_d-oversize_z; k<nz_d ; k++ ) { ( *By3D )( i, j, k ) = ( *By3D )( i, j, k-1 ); } } } } }
[ "iustin.ouatu@physics.ox.ac.uk" ]
iustin.ouatu@physics.ox.ac.uk
669665c614c6b2673a957f70e0503ed3a73732ae
4bb3decfbaad417efd6f62ccc3b4c1de6fcbb4c4
/bvh_node.h
1da5820d0677ef78a5b530e28fc0206013128b5e
[]
no_license
alexshen/raytracinginoneweekend
55594e305d952579a0410605dc8c7f2289f8d11b
344098eb842ae57093edfe5d1d922e56856f7fec
refs/heads/master
2021-08-16T09:46:49.212876
2017-11-19T14:27:20
2017-11-19T14:29:25
105,617,666
0
0
null
null
null
null
UTF-8
C++
false
false
635
h
#ifndef BVH_NODE_H #define BVH_NODE_H #include "aabb.h" #include "partition.h" #include <memory> #include <vector> class bvh_node : public spatial_partition { public: bvh_node(object** objs, int n); void raycast(const ray3& r, std::vector<object*>& objs) const override; const aabb3& get_aabb() const { return m_volume; } bool is_leaf() const { return !m_left; } private: static constexpr int max_objects = 2; static constexpr int bin_num = 1024; std::unique_ptr<bvh_node> m_left; std::unique_ptr<bvh_node> m_right; std::vector<object*> m_objects; aabb3 m_volume; }; #endif // BVH_NODE_H
[ "swlsww@hotmail.com" ]
swlsww@hotmail.com
da6b0181808588eda4ed808cb79b6133e8eea4aa
95a43c10c75b16595c30bdf6db4a1c2af2e4765d
/codecrawler/_code/hdu2161/10282904.cpp
385fb61c7403f51379f2a3065f099097c8675185
[]
no_license
kunhuicho/crawl-tools
945e8c40261dfa51fb13088163f0a7bece85fc9d
8eb8c4192d39919c64b84e0a817c65da0effad2d
refs/heads/master
2021-01-21T01:05:54.638395
2016-08-28T17:01:37
2016-08-28T17:01:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
506
cpp
#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <cmath> using namespace std; bool is_prime(int n) { if(n<=2) return false; if(n%2==0) return false; for(int i=3; i<=sqrt(n); i +=2) if(n % i == 0) return false; return true; } int main() { int n; int cas = 1; while(scanf("%d",&n)&&n>0) { printf("%d: ",cas++); if(is_prime(n)) printf("yes"); else printf("no"); printf("\n"); } return 0; }
[ "zhouhai02@meituan.com" ]
zhouhai02@meituan.com
b969bf31e698891151f9e842df22df58ba9946fc
b9490d33df74ee1dcd87cc04e10e85e9de416e7a
/LCS2/LCS2.cpp
a37aed4dce86b06b615751bdecd37bc5ab0ba753
[]
no_license
t-feng/algorithm
d2753e719127b08b123af5b5bbe69322656d8111
339cd922c9ba6b58e364d50b1709ea1283c15784
refs/heads/master
2022-03-26T10:48:32.999547
2019-12-25T15:24:29
2019-12-25T15:24:29
null
0
0
null
null
null
null
GB18030
C++
false
false
1,310
cpp
/* 题目描述 题目标题: 计算两个字符串的最大公共字串的长度,字符不区分大小写 详细描述: 接口说明 原型: int getCommonStrLength(char * pFirstStr, char * pSecondStr); 输入参数: char * pFirstStr //第一个字符串 char * pSecondStr//第二个字符串 输入描述: 输入两个字符串 输出描述: 输出一个整数 */ #include <iostream> #include <string> #include <vector> using namespace std; void preProcess(string &str) { for (int i = 0; i < str.size(); i++) { if (str[i] < 'a') { str[i] += 32; } } } void LCS(string str1, string str2) { preProcess(str1); preProcess(str2); int len1 = str1.size(); int len2 = str2.size(); vector<vector<int>> dp(len1 + 1, vector<int>(len2 + 1, 0)); for (int i = 1; i <= len1; i++) { dp[i][0] = 0; } for (int i = 1; i <= len2; i++) { dp[0][i] = 0; } int res = 0; int index = 0; for (int i = 1; i <= len1; i++) { for (int j = 1; j <= len2; j++) { if (str1[i - 1] == str2[j - 1]) { dp[i][j] = dp[i - 1][j - 1] + 1; if (dp[i][j] > res) { res = dp[i][j]; index = i; } } else { dp[i][j] = 0; } } } cout << res << endl; } int main() { string str1, str2; while (cin >> str1 >> str2) { LCS(str1, str2); } }
[ "t.feng94@foxmail.com" ]
t.feng94@foxmail.com
7ca5ee91fbfd531981a947617c6370035fb047bb
be59c390795966476e777e8b75e27b5999640ee0
/src/common/i18n.h
cac02f2632ab10506a015ba07e2582e3f6e5cc47
[ "BSD-3-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
BRTChain/BRT-Chain
cdefbb1ab54c186b1f66e01c4bc5cf97b830f45a
e4bfc027bc82eb79940331f9d334ab31708d4202
refs/heads/master
2022-12-21T15:57:45.359810
2020-09-26T08:02:12
2020-09-26T08:02:12
298,766,400
1
0
null
null
null
null
UTF-8
C++
false
false
2,063
h
// Copyright (c) 2014-2020, The BRT Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once #define QT_TRANSLATE_NOOP(context,str) i18n_translate(str,context) std::string i18n_get_language(); int i18n_set_language(const char *directory, const char *base, std::string language = std::string()); const char *i18n_translate(const char *str, const std::string &context); static inline std::string get_default_i18n_context() { return std::string(); } static inline const char *tr(const char *str) { return i18n_translate(str,get_default_i18n_context()); }
[ "blockchainServ01@gmail.com" ]
blockchainServ01@gmail.com
55ec1ba6627ef218962d4070a53b895dce552565
3f1ca10cae3766896f1d8e743e8e5245b771bfe3
/mysql_audit_logger/plugin_audit.h
42d95f0fa1ed3c4f1c8330e072c0995a0f351d7d
[]
no_license
skyeskie/vanderbilt-gencrawler
c135be55b8df2e3b3a6380a5b7ff0166efff73b4
df299c50d65b06b5252d29b40e2d4a871831f18d
refs/heads/master
2021-05-26T18:31:44.447022
2012-09-08T04:02:39
2012-09-08T04:02:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,002
h
/* Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. 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; version 2 of the License. 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, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _my_audit_h #define _my_audit_h /************************************************************************* API for Audit plugin. (MYSQL_AUDIT_PLUGIN) */ #include <mysql/plugin.h> #define MYSQL_AUDIT_CLASS_MASK_SIZE 1 #define MYSQL_AUDIT_INTERFACE_VERSION 0x0300 /************************************************************************* AUDIT CLASS : GENERAL LOG events occurs before emitting to the general query log. ERROR events occur before transmitting errors to the user. RESULT events occur after transmitting a resultset to the user. STATUS events occur after transmitting a resultset or errors to the user. */ #define MYSQL_AUDIT_GENERAL_CLASS 0 #define MYSQL_AUDIT_GENERAL_CLASSMASK (1 << MYSQL_AUDIT_GENERAL_CLASS) #define MYSQL_AUDIT_GENERAL_LOG 0 #define MYSQL_AUDIT_GENERAL_ERROR 1 #define MYSQL_AUDIT_GENERAL_RESULT 2 #define MYSQL_AUDIT_GENERAL_STATUS 3 struct mysql_event_general { unsigned int event_subclass; int general_error_code; unsigned long general_thread_id; const char *general_user; unsigned int general_user_length; const char *general_command; unsigned int general_command_length; const char *general_query; unsigned int general_query_length; struct charset_info_st *general_charset; unsigned long long general_time; unsigned long long general_rows; }; /* AUDIT CLASS : CONNECTION CONNECT occurs after authentication phase is completed. DISCONNECT occurs after connection is terminated. CHANGE_USER occurs after COM_CHANGE_USER RPC is completed. */ #define MYSQL_AUDIT_CONNECTION_CLASS 1 #define MYSQL_AUDIT_CONNECTION_CLASSMASK (1 << MYSQL_AUDIT_CONNECTION_CLASS) #define MYSQL_AUDIT_CONNECTION_CONNECT 0 #define MYSQL_AUDIT_CONNECTION_DISCONNECT 1 #define MYSQL_AUDIT_CONNECTION_CHANGE_USER 2 struct mysql_event_connection { unsigned int event_subclass; int status; unsigned long thread_id; const char *user; unsigned int user_length; const char *priv_user; unsigned int priv_user_length; const char *external_user; unsigned int external_user_length; const char *proxy_user; unsigned int proxy_user_length; const char *host; unsigned int host_length; const char *ip; unsigned int ip_length; const char *database; unsigned int database_length; }; /************************************************************************* Here we define the descriptor structure, that is referred from st_mysql_plugin. release_thd() event occurs when the event class consumer is to be disassociated from the specified THD. This would typically occur before some operation which may require sleeping - such as when waiting for the next query from the client. event_notify() is invoked whenever an event occurs which is of any class for which the plugin has interest. The second argument indicates the specific event class and the third argument is data as required for that class. class_mask is an array of bits used to indicate what event classes that this plugin wants to receive. */ struct st_mysql_audit { int interface_version; void (*release_thd)(MYSQL_THD); void (*event_notify)(MYSQL_THD, unsigned int, const void *); unsigned long class_mask[MYSQL_AUDIT_CLASS_MASK_SIZE]; }; #endif
[ "Scott.K.Yeskie@Vanderbilt.edu" ]
Scott.K.Yeskie@Vanderbilt.edu
87555d6e1d673b06c1dea29382839a9f375ff646
faf8c585efa198a21a50a41d33aa94bfae5887c8
/ots/source/account.cpp
374927636e3573fc6efc1659793114b867e8d3b1
[]
no_license
Wirless/YurOTS
b4b41a684589afa2a5c1f84d6a0bc1623d4f17f4
7935d2a55f819776656972d49cf4157be112bb74
refs/heads/master
2021-01-11T17:36:22.775890
2020-02-28T03:45:08
2020-02-28T03:45:08
79,797,035
0
0
null
2017-01-23T11:08:19
2017-01-23T11:08:19
null
UTF-8
C++
false
false
212
cpp
#include <algorithm> #include <functional> #include <iostream> #include "definitions.h" #include "account.h" Account::Account() { accnumber = 0; } Account::~Account() { charList.clear(); }
[ "noreply@github.com" ]
Wirless.noreply@github.com
7f60b49eb0d6b71821eccdb76df0082f41859c45
42a88c6976327c307281e6767e2dd911c3375e51
/05_Errors/05_04_cerr_using_cin_state.cpp
601b181e70cf9da7c4784f707f3003be8efc8201
[]
no_license
abhi25t/Cplusplus
386780b25de1b95fd23b67c2a73f6e0483e1b941
b90876b29366460041fc3ac87ce158a667ac6813
refs/heads/master
2020-03-22T14:34:03.570207
2018-07-29T12:38:01
2018-07-29T12:38:01
140,188,828
1
0
null
null
null
null
UTF-8
C++
false
false
297
cpp
#include <iostream> #include <cstdio> #include <string> #include <vector> #include <algorithm> #include <cmath> #include <iterator> using namespace std; int main() { double d = 0; cin >> d; if (!cin) cerr << "couldn't read a double in your input\n"; // do something useful }
[ "noreply@github.com" ]
abhi25t.noreply@github.com
07aa57702d7d25d893536438bac6207c5dc94533
befc0aaec1e3861aeb01233721320f20a0005bf9
/codeforces/done/458/B.cpp
985cf26ef523e91ca86feca115b57436cab93326
[]
no_license
wcheung8/Programming-Team-Archive
16c009b1a9fe0f660bbdbdcbc384496a52b98a96
596cc1985e6ea0eaf7298cba125ae5e7439eacbd
refs/heads/master
2021-01-11T03:01:26.027970
2019-07-17T16:24:24
2019-07-17T16:24:24
70,872,186
0
0
null
null
null
null
UTF-8
C++
false
false
573
cpp
#include <bits/stdc++.h> #define ull unsigned long long #define f(i, n) for(int (i) = 0; (i) < (n); i++) using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; typedef pair<int, int> pi; typedef priority_queue<pi, vector<pi>, greater<pi> > q; const int INF = 1e5+1; int a[INF+2]; long long n, x; int main() { ios::sync_with_stdio(0); cin >> n; f(i, n) { cin >> x; a[x]++; } f(i,INF) { if((a[i]&1) == 1) { cout << "Conan"; return 0; } } cout << "Agasa"; return 0; }
[ "wcheung8@gatech.edu" ]
wcheung8@gatech.edu
3b365275bf83a1d1ec00ecc2b5b4c3706b417cbd
f65699dcc843f674159ee8d22de5e390c2482a3f
/5543_상근날드/5543.cpp
803bf410c96ef3b131f7d328fcef3efa5a13e8b5
[]
no_license
elddy0948/BaekjoonC-C-
949f7bf97653a72506409ae733fab4aebd210681
b1401f3fe442392f38899d7c735692df45579e3a
refs/heads/master
2022-03-01T02:29:39.667746
2019-10-30T05:12:26
2019-10-30T05:12:26
188,023,464
0
0
null
null
null
null
UTF-8
C++
false
false
596
cpp
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<cstdio> using namespace std; //FILE * fp=fopen("5543.inp","r"); int price[5]; int set_price; int min_price=1000000; int main(){ int ham=0; for(int i=0;i<5;i++){ scanf("%d",&ham); price[i]=ham; } //0 = sang 1 = jung 2 = ha 3 = coke 4 = sprite //set price = -50 for(int i=0;i<3;i++){ set_price=price[i]+price[3]-50; int temp=price[i]+price[4]-50; if(set_price>temp) set_price=temp; if(min_price>set_price) min_price=set_price; } printf("%d\n",min_price); }
[ "elddy0948@gmail.com" ]
elddy0948@gmail.com
bdd176a78e444345b21457d6dc378ce09c2ae7a7
88ae8695987ada722184307301e221e1ba3cc2fa
/storage/browser/file_system/isolated_file_system_backend.cc
6052566813b7818a6053b0c7910c8ffdad87e98b
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
5,804
cc
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "storage/browser/file_system/isolated_file_system_backend.h" #include <stdint.h> #include <memory> #include <string> #include <utility> #include "base/check.h" #include "base/files/file_path.h" #include "base/functional/bind.h" #include "base/notreached.h" #include "base/task/sequenced_task_runner.h" #include "base/task/single_thread_task_runner.h" #include "storage/browser/file_system/async_file_util_adapter.h" #include "storage/browser/file_system/copy_or_move_file_validator.h" #include "storage/browser/file_system/dragged_file_util.h" #include "storage/browser/file_system/file_stream_reader.h" #include "storage/browser/file_system/file_stream_writer.h" #include "storage/browser/file_system/file_system_context.h" #include "storage/browser/file_system/file_system_operation.h" #include "storage/browser/file_system/file_system_operation_context.h" #include "storage/browser/file_system/isolated_context.h" #include "storage/browser/file_system/native_file_util.h" #include "storage/browser/file_system/transient_file_util.h" #include "storage/browser/file_system/watcher_manager.h" #include "storage/common/file_system/file_system_types.h" #include "storage/common/file_system/file_system_util.h" namespace storage { IsolatedFileSystemBackend::IsolatedFileSystemBackend( bool use_for_type_native_local, bool use_for_type_platform_app) : use_for_type_native_local_(use_for_type_native_local), use_for_type_platform_app_(use_for_type_platform_app), isolated_file_util_(std::make_unique<AsyncFileUtilAdapter>( std::make_unique<LocalFileUtil>())), dragged_file_util_(std::make_unique<AsyncFileUtilAdapter>( std::make_unique<DraggedFileUtil>())), transient_file_util_(std::make_unique<AsyncFileUtilAdapter>( std::make_unique<TransientFileUtil>())) {} IsolatedFileSystemBackend::~IsolatedFileSystemBackend() = default; bool IsolatedFileSystemBackend::CanHandleType(FileSystemType type) const { switch (type) { case kFileSystemTypeIsolated: case kFileSystemTypeDragged: case kFileSystemTypeForTransientFile: return true; case kFileSystemTypeLocal: return use_for_type_native_local_; case kFileSystemTypeLocalForPlatformApp: return use_for_type_platform_app_; default: return false; } } void IsolatedFileSystemBackend::Initialize(FileSystemContext* context) {} void IsolatedFileSystemBackend::ResolveURL(const FileSystemURL& url, OpenFileSystemMode mode, ResolveURLCallback callback) { // We never allow opening a new isolated FileSystem via usual ResolveURL. base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), GURL(), std::string(), base::File::FILE_ERROR_SECURITY)); } AsyncFileUtil* IsolatedFileSystemBackend::GetAsyncFileUtil( FileSystemType type) { switch (type) { case kFileSystemTypeLocal: return isolated_file_util_.get(); case kFileSystemTypeDragged: return dragged_file_util_.get(); case kFileSystemTypeForTransientFile: return transient_file_util_.get(); default: NOTREACHED(); } return nullptr; } WatcherManager* IsolatedFileSystemBackend::GetWatcherManager( FileSystemType type) { return nullptr; } CopyOrMoveFileValidatorFactory* IsolatedFileSystemBackend::GetCopyOrMoveFileValidatorFactory( FileSystemType type, base::File::Error* error_code) { DCHECK(error_code); *error_code = base::File::FILE_OK; return nullptr; } std::unique_ptr<FileSystemOperation> IsolatedFileSystemBackend::CreateFileSystemOperation( const FileSystemURL& url, FileSystemContext* context, base::File::Error* error_code) const { return FileSystemOperation::Create( url, context, std::make_unique<FileSystemOperationContext>(context)); } bool IsolatedFileSystemBackend::SupportsStreaming( const FileSystemURL& url) const { return false; } bool IsolatedFileSystemBackend::HasInplaceCopyImplementation( FileSystemType type) const { DCHECK(type == kFileSystemTypeLocal || type == kFileSystemTypeDragged || type == kFileSystemTypeForTransientFile); return false; } std::unique_ptr<FileStreamReader> IsolatedFileSystemBackend::CreateFileStreamReader( const FileSystemURL& url, int64_t offset, int64_t max_bytes_to_read, const base::Time& expected_modification_time, FileSystemContext* context, file_access::ScopedFileAccessDelegate::RequestFilesAccessIOCallback file_access) const { return FileStreamReader::CreateForLocalFile( context->default_file_task_runner(), url.path(), offset, expected_modification_time, std::move(file_access)); } std::unique_ptr<FileStreamWriter> IsolatedFileSystemBackend::CreateFileStreamWriter( const FileSystemURL& url, int64_t offset, FileSystemContext* context) const { return FileStreamWriter::CreateForLocalFile( context->default_file_task_runner(), url.path(), offset, FileStreamWriter::OPEN_EXISTING_FILE); } FileSystemQuotaUtil* IsolatedFileSystemBackend::GetQuotaUtil() { // No quota support. return nullptr; } const UpdateObserverList* IsolatedFileSystemBackend::GetUpdateObservers( FileSystemType type) const { return nullptr; } const ChangeObserverList* IsolatedFileSystemBackend::GetChangeObservers( FileSystemType type) const { return nullptr; } const AccessObserverList* IsolatedFileSystemBackend::GetAccessObservers( FileSystemType type) const { return nullptr; } } // namespace storage
[ "jengelh@inai.de" ]
jengelh@inai.de
4649b84ab07e181448ebae69451072839ef457c4
a8f15b0016936013e611771c22c116fba8be1f04
/JuceLibraryCode/modules/juce_gui_basics/native/juce_linux_FileChooser.cpp
320cfd3ab84e008fca1d200db055906cf39fa082
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
fishuyo/loop-juce
7ba126250eb80f4aea823fd416c796c7109e09b9
9a03f12234d335acb387c373117d4984f6d296fc
refs/heads/master
2021-05-27T16:56:16.293042
2012-06-20T02:45:32
2012-06-20T02:45:32
4,293,037
2
0
null
null
null
null
UTF-8
C++
false
false
3,016
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ bool FileChooser::isPlatformDialogAvailable() { ChildProcess child; const bool ok = child.start ("which zenity") && child.readAllProcessOutput().trim().isNotEmpty(); child.waitForProcessToFinish (60 * 1000); return ok; } void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& file, const String& filters, bool isDirectory, bool selectsFiles, bool isSave, bool warnAboutOverwritingExistingFiles, bool selectMultipleFiles, FilePreviewComponent* previewComponent) { const String separator (":"); String command ("zenity --file-selection"); if (title.isNotEmpty()) command << " --title=\"" << title << "\""; if (file != File::nonexistent) command << " --filename=\"" << file.getFullPathName () << "\""; if (isDirectory) command << " --directory"; if (isSave) command << " --save"; if (selectMultipleFiles) command << " --multiple --separator=" << separator; command << " 2>&1"; ChildProcess child; if (child.start (command)) { const String result (child.readAllProcessOutput()); StringArray tokens; if (selectMultipleFiles) tokens.addTokens (result, separator, "\""); else tokens.add (result); for (int i = 0; i < tokens.size(); i++) results.add (File (tokens[i])); child.waitForProcessToFinish (60 * 1000); } }
[ "fishuyo@gmail.com" ]
fishuyo@gmail.com
ceb94a28a7968abce839a54cd9f1214b2a859f6a
29f4604d0e436723a069121c8baf8357847520ad
/tdt/cvs/apps/neutrino-hd2/lib/libdvbsub/dvbsub.cpp
17b1e09dcfaf2748fd7efafa31923087d3d951e4
[]
no_license
popazerty/evolux-spark-sh4
95b8c21d37d25b68fdcc71c819d649663046b8d4
b62c0b466a3f3eda613d86c010e45e5c7794b6b3
refs/heads/master
2021-01-02T22:32:23.817110
2013-06-03T04:42:36
2013-06-03T04:42:36
40,676,457
0
0
null
null
null
null
UTF-8
C++
false
false
12,231
cpp
#include <errno.h> #include <fcntl.h> #include <sys/ioctl.h> #include <inttypes.h> #include <pthread.h> #include <semaphore.h> #include <sys/time.h> #include <syscall.h> #include <cerrno> #include <dmx_cs.h> /* libcoolstream */ #include "Debug.hpp" #include "PacketQueue.hpp" #include "semaphore.h" #include "helpers.hpp" #include "dvbsubtitle.h" #define Log2File printf #define RECVBUFFER_STEPSIZE 1024 enum { NOERROR, NETWORK, DENIED, NOSERVICE, BOXTYPE, THREAD, ABOUT }; enum { GET_VOLUME, SET_VOLUME, SET_MUTE, SET_CHANNEL }; Debug sub_debug; static PacketQueue packet_queue; //sem_t event_semaphore; static pthread_t threadReader; static pthread_t threadDvbsub; static pthread_cond_t readerCond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t readerMutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t packetCond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t packetMutex = PTHREAD_MUTEX_INITIALIZER; static int reader_running; static int dvbsub_running; static int dvbsub_paused = true; static int dvbsub_pid; static int dvbsub_stopped; static int pid_change_req; cDvbSubtitleConverter *dvbSubtitleConverter = NULL; static void* reader_thread(void *arg); static void* dvbsub_thread(void* arg); static void clear_queue(); int dvbsub_initialise() { printf("dvbsub_init: starting... tid %ld\n", syscall(__NR_gettid)); int trc; sub_debug.set_level(0); //reader_running = true; //dvbsub_stopped = 1; //pid_change_req = 1; // reader-Thread starten //trc = pthread_create(&threadReader, 0, reader_thread, (void *) source); //if (trc) { // fprintf(stderr, "[dvb-sub] failed to create reader-thread (rc=%d)\n", trc); // reader_running = false; // return -1; //} #if 1 dvbsub_running = true; //if(!dvbsub_running) //{ // subtitle decoder-Thread starten trc = pthread_create(&threadDvbsub, 0, dvbsub_thread, NULL); if (trc) { fprintf(stderr, "[dvb-sub] failed to create dvbsub-thread (rc=%d)\n", trc); dvbsub_running = false; return -1; } //dvbsub_running = true; //} #endif return(0); } // int dvbsub_init(int source) { printf("dvbsub_start_reader: starting... tid %ld\n", syscall(__NR_gettid)); int trc; //sub_debug.set_level(0); reader_running = true; dvbsub_stopped = 1; pid_change_req = 1; // reader-Thread starten trc = pthread_create(&threadReader, 0, reader_thread, (void *) source); if (trc) { fprintf(stderr, "[dvb-sub] failed to create reader-thread (rc=%d)\n", trc); reader_running = false; return -1; } //if(!dvbsub_running) //{ // subtitle decoder-Thread starten // trc = pthread_create(&threadDvbsub, 0, dvbsub_thread, NULL); // // if (trc) // { // fprintf(stderr, "[dvb-sub] failed to create dvbsub-thread (rc=%d)\n", trc); // dvbsub_running = false; // return -1; // } // // dvbsub_running = true; //} return(0); } // int dvbsub_pause() { if(reader_running) { dvbsub_paused = true; if(dvbSubtitleConverter) dvbSubtitleConverter->Pause(true); } printf("[dvb-sub] paused\n"); return 0; } int dvbsub_start(int pid) { if(!dvbsub_paused && (pid == 0)) { return 0; } if(pid) { if(pid != dvbsub_pid) { dvbsub_pause(); if(dvbSubtitleConverter) dvbSubtitleConverter->Reset(); dvbsub_pid = pid; pid_change_req = 1; } } printf("[dvb-sub] start, stopped %d pid 0x%x\n", dvbsub_stopped, dvbsub_pid); #if 0 while(!dvbsub_stopped) usleep(10); #endif if(dvbsub_pid > 0) { dvbsub_stopped = 0; dvbsub_paused = false; if(dvbSubtitleConverter) dvbSubtitleConverter->Pause(false); pthread_mutex_lock(&readerMutex); pthread_cond_broadcast(&readerCond); pthread_mutex_unlock(&readerMutex); printf("[dvb-sub] started with pid 0x%x\n", pid); } return 1; } int dvbsub_stop() { dvbsub_pid = 0; if(reader_running) { dvbsub_stopped = 1; dvbsub_pause(); pid_change_req = 1; } printf("[dvb-sub] stopped...\n"); return 0; } int dvbsub_getpid() { return dvbsub_pid; } void dvbsub_setpid(int pid) { printf("dvbsub_setpid: 0x%x\n", pid); dvbsub_pid = pid; if(dvbsub_pid == 0) return; clear_queue(); if(dvbSubtitleConverter) dvbSubtitleConverter->Reset(); pid_change_req = 1; dvbsub_stopped = 0; pthread_mutex_lock(&readerMutex); pthread_cond_broadcast(&readerCond); pthread_mutex_unlock(&readerMutex); } //test int dvbsub_close() { //if(threadReader) if(reader_running) { dvbsub_pause(); reader_running = false; dvbsub_stopped = 1; pthread_mutex_lock(&readerMutex); pthread_cond_broadcast(&readerCond); pthread_mutex_unlock(&readerMutex); pthread_join(threadReader, NULL); threadReader = 0; } //if(threadDvbsub) //if(dvbsub_running) //{ // dvbsub_running = false; // // pthread_mutex_lock(&packetMutex); // pthread_cond_broadcast(&packetCond); // pthread_mutex_unlock(&packetMutex); // // pthread_join(threadDvbsub, NULL); // threadDvbsub = 0; // // if(dvbSubtitleConverter) // { // delete dvbSubtitleConverter; // dvbSubtitleConverter = NULL; // } //} printf("[dvb-sub] closed...\n"); return 0; } // //int dvbsub_close() int dvbsub_terminate() { //if(threadReader) //if(reader_running) //{ // dvbsub_pause(); // reader_running = false; // dvbsub_stopped = 1; // // pthread_mutex_lock(&readerMutex); // pthread_cond_broadcast(&readerCond); // pthread_mutex_unlock(&readerMutex); // // pthread_join(threadReader, NULL); // threadReader = 0; //} //if(threadDvbsub) if(dvbsub_running) { dvbsub_running = false; pthread_mutex_lock(&packetMutex); pthread_cond_broadcast(&packetCond); pthread_mutex_unlock(&packetMutex); pthread_join(threadDvbsub, NULL); threadDvbsub = 0; if(dvbSubtitleConverter) { delete dvbSubtitleConverter; dvbSubtitleConverter = NULL; } } printf("[dvb-sub] terminate...\n"); return 0; } static cDemux * dmx; void dvbsub_get_stc(int64_t * STC) { if(dmx) dmx->getSTC(STC); } static int64_t get_pts(unsigned char * packet) { int64_t pts; int pts_dts_flag; pts_dts_flag = getbits(packet, 7*8, 2); if ((pts_dts_flag == 2) || (pts_dts_flag == 3)) { pts = (uint64_t)getbits(packet, 9*8+4, 3) << 30; /* PTS[32..30] */ pts |= getbits(packet, 10*8, 15) << 15; /* PTS[29..15] */ pts |= getbits(packet, 12*8, 15); /* PTS[14..0] */ } else { pts = 0; } return pts; } #define LimitTo32Bit(n) (n & 0x00000000FFFFFFFFL) static int64_t get_pts_stc_delta(int64_t pts) { int64_t stc, delta; dvbsub_get_stc(&stc); delta = LimitTo32Bit(pts) - LimitTo32Bit(stc); delta /= 90; return delta; } static void clear_queue() { uint8_t* packet; pthread_mutex_lock(&packetMutex); while(packet_queue.size()) { packet = packet_queue.pop(); free(packet); } pthread_mutex_unlock(&packetMutex); } static void * reader_thread(void * arg) { int source = (int) arg; uint8_t tmp[16]; /* actually 6 should be enough */ int count; int len; uint16_t packlen; uint8_t* buf; dmx = new cDemux( LIVE_DEMUX ); dmx->Open(DMX_PES_CHANNEL, 64*1024, source); while (reader_running) { if(dvbsub_stopped /*dvbsub_paused*/) { sub_debug.print(Debug::VERBOSE, "%s stopped\n", __FUNCTION__); dmx->Stop(); pthread_mutex_lock(&packetMutex); pthread_cond_broadcast(&packetCond); pthread_mutex_unlock(&packetMutex); pthread_mutex_lock(&readerMutex ); int ret = pthread_cond_wait(&readerCond, &readerMutex); pthread_mutex_unlock(&readerMutex); if (ret) { sub_debug.print(Debug::VERBOSE, "pthread_cond_timedwait fails with %d\n", ret); } if(!reader_running) break; dvbsub_stopped = 0; sub_debug.print(Debug::VERBOSE, "%s (re)started with pid 0x%x\n", __FUNCTION__, dvbsub_pid); } if(pid_change_req) { pid_change_req = 0; clear_queue(); dmx->Stop(); dmx->pesFilter(dvbsub_pid); dmx->Start(); sub_debug.print(Debug::VERBOSE, "%s changed to pid 0x%x\n", __FUNCTION__, dvbsub_pid); } len = 0; count = 0; len = dmx->Read(tmp, 6, 1000); //printf("\n[dvbsub] len: %d\n", len); if(len <= 0) continue; if(memcmp(tmp, "\x00\x00\x01\xbd", 4)) { sub_debug.print(Debug::VERBOSE, "[subtitles] bad start code: %02x%02x%02x%02x\n", tmp[0], tmp[1], tmp[2], tmp[3]); continue; } count = 6; packlen = getbits(tmp, 4*8, 16) + 6; buf = (uint8_t*) malloc(packlen); memcpy(buf, tmp, 6); /* read rest of the packet */ while((count < packlen) /* && !dvbsub_paused*/) { len = dmx->Read(buf+count, packlen-count, 1000); if (len < 0) { continue; } else { count += len; } } #if 0 for(int i = 6; i < packlen - 4; i++) { if(!memcmp(&buf[i], "\x00\x00\x01\xbd", 4)) { int plen = getbits(&buf[i], 4*8, 16) + 6; printf("[subtitles] PES header at %d ?!\n", i); printf("[subtitles] start code: %02x%02x%02x%02x len %d\n", buf[i+0], buf[i+1], buf[i+2], buf[i+3], plen); free(buf); continue; } } #endif if(!dvbsub_stopped /* !dvbsub_paused*/ ) { //sub_debug.print(Debug::VERBOSE, "[subtitles] new packet, len %d buf 0x%x pts-stc diff %lld\n", count, buf, get_pts_stc_delta(get_pts(buf))); /* Packet now in memory */ packet_queue.push(buf); /* TODO: allocation exception */ // wake up dvb thread pthread_mutex_lock(&packetMutex); pthread_cond_broadcast(&packetCond); pthread_mutex_unlock(&packetMutex); } else { free(buf); buf=NULL; } } dmx->Stop(); delete dmx; dmx = NULL; sub_debug.print(Debug::VERBOSE, "%s shutdown\n", __FUNCTION__); pthread_exit(NULL); } static void* dvbsub_thread(void* /*arg*/) { struct timespec restartWait; struct timeval now; sub_debug.print(Debug::VERBOSE, "%s started\n", __FUNCTION__); if (!dvbSubtitleConverter) dvbSubtitleConverter = new cDvbSubtitleConverter(); int timeout = 1000000; while(dvbsub_running) { uint8_t* packet; int64_t pts; int dataoffset; int packlen; gettimeofday(&now, NULL); int ret = 0; now.tv_usec += (timeout == 0) ? 1000000 : timeout; // add the timeout while (now.tv_usec >= 1000000) { // take care of an overflow now.tv_sec++; now.tv_usec -= 1000000; } restartWait.tv_sec = now.tv_sec; // seconds restartWait.tv_nsec = now.tv_usec * 1000; // nano seconds pthread_mutex_lock( &packetMutex ); ret = pthread_cond_timedwait( &packetCond, &packetMutex, &restartWait ); pthread_mutex_unlock( &packetMutex ); if(dvbSubtitleConverter) timeout = dvbSubtitleConverter->Action(); if(packet_queue.size() == 0) { continue; } #if 1 sub_debug.print(Debug::VERBOSE, "PES: Wakeup, queue size %d\n\n", packet_queue.size()); #endif if(dvbsub_stopped /*dvbsub_paused*/) { clear_queue(); continue; } pthread_mutex_lock(&packetMutex); packet = packet_queue.pop(); pthread_mutex_unlock(&packetMutex); if (!packet) { sub_debug.print(Debug::VERBOSE, "Error no packet found\n"); continue; } packlen = (packet[4] << 8 | packet[5]) + 6; pts = get_pts(packet); dataoffset = packet[8] + 8 + 1; if (packet[dataoffset] != 0x20) { #if 1 sub_debug.print(Debug::VERBOSE, "Not a dvb subtitle packet, discard it (len %d)\n", packlen); for(int i = 0; i < packlen; i++) printf("%02X ", packet[i]); printf("\n"); #endif goto next_round; } #if 1 sub_debug.print(Debug::VERBOSE, "PES packet: len %d data len %d PTS=%Ld (%02d:%02d:%02d.%d) diff %lld\n", packlen, packlen - (dataoffset + 2), pts, (int)(pts/324000000), (int)((pts/5400000)%60), (int)((pts/90000)%60), (int)(pts%90000), get_pts_stc_delta(pts)); #endif if (packlen <= dataoffset + 3) { sub_debug.print(Debug::INFO, "Packet too short, discard\n"); goto next_round; } if (packet[dataoffset + 2] == 0x0f) { if(dvbSubtitleConverter) dvbSubtitleConverter->Convert(&packet[dataoffset + 2], packlen - (dataoffset + 2), pts); } else { sub_debug.print(Debug::INFO, "End_of_PES is missing\n"); } if(dvbSubtitleConverter) timeout = dvbSubtitleConverter->Action(); next_round: free(packet); } delete dvbSubtitleConverter; sub_debug.print(Debug::VERBOSE, "%s shutdown\n", __FUNCTION__); pthread_exit(NULL); }
[ "al_borland33@yahoo.de" ]
al_borland33@yahoo.de
b3d5ed255026025afd5081732ee93386134f3594
aeac025c3c39744d5e35df4b05e017c6846cedb0
/C++ Primer/第3章练习/3.39.cpp
7c378a5d622c07272e28e043eb8392159f27d745
[]
no_license
Rookie35/C-plus-plus-practice
8d774a5b551f6adefb8ca8a89503575e56d9622d
bd30c9861090479b9b62aa1905ee7d531d675220
refs/heads/master
2020-05-01T09:26:09.636329
2019-04-14T12:12:55
2019-04-14T12:12:55
177,400,130
0
0
null
null
null
null
UTF-8
C++
false
false
599
cpp
#include<iostream> #include<string> #include<cstring> using std::cout; using std::endl; using std::string; int main() { //use string string s1("Mooophy"),s2("Pezy"); if(s1==s2) cout<<"same string."<<endl; else if(s1>s2) cout<<"Mooophy > Pezy"<<endl; else cout<<"Mooophy < Pezy"<<endl; cout<<"========"<<endl; //using C-style charcater strings. const char* ca1="Wangyue"; const char* ca2="Pezy"; auto result = strcmp(ca1,ca2); if(result==0) cout<<"same string."<<endl; else if(result<0) cout<<"Wangyue < Pezy"<<endl; else cout<<"Wangyue > Pezy"<<endl; return 0; }
[ "754119201@qq.com" ]
754119201@qq.com
faed9cee0be1166293c80c39bdb97acf6f336592
8609ebbd94cdf26e8cfc9bb0fcda9f8d5cf8b73d
/src/Client.cpp
401ea3dec41d7dc71583c48c6545e3b59a94c9e5
[]
no_license
wutianze/fastrtps-test
569a591a615497011cd35d9c91d69a6db23062bd
b7970efc0ac036844cbe15f0da51629da328a473
refs/heads/master
2022-11-10T00:53:01.378924
2020-06-16T01:54:10
2020-06-16T01:54:10
272,585,010
0
0
null
null
null
null
UTF-8
C++
false
false
10,924
cpp
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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. /** * @file Client.cpp * */ #include "HelloWorldPubSubTypes.h" #include <fastdds/dds/domain/DomainParticipantFactory.hpp> #include <fastdds/dds/domain/DomainParticipant.hpp> #include <fastdds/dds/topic/TypeSupport.hpp> #include <fastdds/dds/publisher/Publisher.hpp> #include <fastdds/dds/publisher/DataWriter.hpp> #include <fastdds/dds/publisher/DataWriterListener.hpp> #include <fastdds/dds/subscriber/Subscriber.hpp> #include <fastdds/dds/subscriber/DataReader.hpp> #include <fastdds/dds/subscriber/DataReaderListener.hpp> #include <fastdds/dds/subscriber/qos/DataReaderQos.hpp> #include <fastdds/dds/subscriber/SampleInfo.hpp> #include <fastdds/rtps/transport/TCPv4TransportDescriptor.h> #include <fastrtps/utils/IPLocator.h> using namespace eprosima::fastdds::dds; using namespace eprosima::fastdds::rtps; class HelloWorldSubscriber { private: DomainParticipant* participant_; Subscriber* subscriber_; DataReader* reader_; Topic* topic_; TypeSupport type_; class SubListener : public DataReaderListener { public: SubListener() : samples_(0) { } ~SubListener() override { } void on_subscription_matched( DataReader*, const SubscriptionMatchedStatus& info) override { if (info.current_count_change == 1) { std::cout << "Subscriber matched." << std::endl; } else if (info.current_count_change == -1) { std::cout << "Subscriber unmatched." << std::endl; } else { std::cout << info.current_count_change << " is not a valid value for SubscriptionMatchedStatus current count change" << std::endl; } } void on_data_available( DataReader* reader) override { SampleInfo info; if (reader->take_next_sample(&hello_, &info) == ReturnCode_t::RETCODE_OK) { auto rec_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now()).time_since_epoch()).count(); if (info.instance_state == ALIVE) { samples_++; std::cout << "Message: " << hello_.message() << " with index: " << hello_.index() << " RECEIVED." <<" At time: "<< rec_time<<", latency:"<<rec_time-long(hello_.timestamp())<<std::endl; } } } HelloWorld hello_; std::atomic_int samples_; } listener_; public: HelloWorldSubscriber() : participant_(nullptr) , subscriber_(nullptr) , topic_(nullptr) , reader_(nullptr) , type_(new HelloWorldPubSubType()) { } virtual ~HelloWorldSubscriber() { if (reader_ != nullptr) { subscriber_->delete_datareader(reader_); } if (topic_ != nullptr) { participant_->delete_topic(topic_); } if (subscriber_ != nullptr) { participant_->delete_subscriber(subscriber_); } DomainParticipantFactory::get_instance()->delete_participant(participant_); } //!Initialize the subscriber bool init() { DomainParticipantQos participantQos; participantQos.name("Participant_subscriber"); //--- // Disable the built-in Transport Layer. participantQos.transport().use_builtin_transports = false; // Create a descriptor for the new transport. // Do not configure any listener port auto tcp_transport = std::make_shared<TCPv4TransportDescriptor>(); participantQos.transport().user_transports.push_back(tcp_transport); // Set initial peers. eprosima::fastrtps::rtps::Locator_t initial_peer_locator; initial_peer_locator.kind = LOCATOR_KIND_TCPv4; eprosima::fastrtps::rtps::IPLocator::setIPv4(initial_peer_locator, "39.101.140.145"); initial_peer_locator.port = 5105; participantQos.wire_protocol().builtin.initialPeersList.push_back(initial_peer_locator); // Avoid using the default transport participantQos.transport().use_builtin_transports = false; //--- participant_ = DomainParticipantFactory::get_instance()->create_participant(0, participantQos); if (participant_ == nullptr) { return false; } // Register the Type type_.register_type(participant_); // Create the subscriptions Topic topic_ = participant_->create_topic("HelloWorldClient", "HelloWorld", TOPIC_QOS_DEFAULT); if (topic_ == nullptr) { return false; } // Create the Subscriber subscriber_ = participant_->create_subscriber(SUBSCRIBER_QOS_DEFAULT, nullptr); if (subscriber_ == nullptr) { return false; } // Create the DataReader reader_ = subscriber_->create_datareader(topic_, DATAREADER_QOS_DEFAULT, &listener_); if (reader_ == nullptr) { return false; } return true; } //!Run the Subscriber void run( uint32_t samples) { while(listener_.samples_ < samples) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } }; class Client { private: HelloWorld hello_; DomainParticipant* participant_; Publisher* publisher_; Topic* topic_; DataWriter* writer_; TypeSupport type_; HelloWorldSubscriber* mysub_; class PubListener : public DataWriterListener { public: PubListener() : matched_(0) { } ~PubListener() override { } void on_publication_matched( DataWriter*, const PublicationMatchedStatus& info) override { if (info.current_count_change == 1) { matched_ = info.total_count; std::cout << "Publisher matched." << std::endl; } else if (info.current_count_change == -1) { matched_ = info.total_count; std::cout << "Publisher unmatched." << std::endl; } else { std::cout << info.current_count_change << " is not a valid value for PublicationMatchedStatus current count change." << std::endl; } } std::atomic_int matched_; } listener_; public: Client() : participant_(nullptr) , publisher_(nullptr) , topic_(nullptr) , writer_(nullptr) , type_(new HelloWorldPubSubType()) { mysub_ = new HelloWorldSubscriber(); } virtual ~Client() { if (writer_ != nullptr) { publisher_->delete_datawriter(writer_); } if (publisher_ != nullptr) { participant_->delete_publisher(publisher_); } if (topic_ != nullptr) { participant_->delete_topic(topic_); } delete mysub_; DomainParticipantFactory::get_instance()->delete_participant(participant_); } //!Initialize the publisher bool init() { hello_.index(0); hello_.message("HelloWorld"); mysub_->init(); DomainParticipantQos participantQos; participantQos.name("Participant_publisher"); //--- // Create a descriptor for the new transport. auto tcp_transport = std::make_shared<TCPv4TransportDescriptor>(); //tcp_transport->sendBufferSize = 9216; //tcp_transport->receiveBufferSize = 9216; tcp_transport->add_listener_port(5100); tcp_transport->set_WAN_address("152.136.134.100"); // Link the Transport Layer to the Participant. participantQos.transport().user_transports.push_back(tcp_transport); // Avoid using the default transport participantQos.transport().use_builtin_transports = false; //--- participant_ = DomainParticipantFactory::get_instance()->create_participant(0, participantQos); if (participant_ == nullptr) { return false; } // Register the Type type_.register_type(participant_); // Create the publications Topic topic_ = participant_->create_topic("HelloWorldServer", "HelloWorld", TOPIC_QOS_DEFAULT); if (topic_ == nullptr) { return false; } // Create the Publisher publisher_ = participant_->create_publisher(PUBLISHER_QOS_DEFAULT, nullptr); if (publisher_ == nullptr) { return false; } // Create the DataWriter writer_ = publisher_->create_datawriter(topic_, DATAWRITER_QOS_DEFAULT, &listener_); if (writer_ == nullptr) { return false; } return true; } //!Send a publication bool publish() { if (listener_.matched_ > 0) { hello_.index(hello_.index() + 1); hello_.timestamp(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now()).time_since_epoch()).count()); writer_->write(&hello_); return true; } return false; } //!Run the Publisher void run( uint32_t samples) { uint32_t samples_sent = 0; while (samples_sent < samples) { if (publish()) { samples_sent++; std::cout << "Message: " << hello_.message() << " with index: " << hello_.index() << " at time: "<<hello_.timestamp()<<" SENT" << std::endl; } std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } } }; int main( int argc, char** argv) { std::cout << "Starting publisher." << std::endl; int samples = 10; Client* mycli = new Client(); if(mycli->init()) { mycli->run(static_cast<uint32_t>(samples)); } delete mycli; return 0; }
[ "wutianze@ict.ac.cn" ]
wutianze@ict.ac.cn
50cc9b26c1446c5e2c8159ce8b8fe11998899f0c
336440fef7f75d4208c3fb824e64117ee36c92f4
/NetPie/TestConection_NetPie/TestConection_NetPie.ino
25257dff582db7351af32e952db7680a2bc00031
[]
no_license
wichukornk/WichukornArduino
693c9e5bad20a1b0ed1989db3576c07e40ffbe2c
76927fd5a028079cb628f58ea570dd5b7bf54c4a
refs/heads/master
2023-02-16T07:22:45.354051
2021-01-09T11:02:11
2021-01-09T11:02:11
279,614,694
0
0
null
null
null
null
UTF-8
C++
false
false
1,542
ino
#include <ESP8266WiFi.h> #include <PubSubClient.h> const char* ssid = "Besten_wifi2.4GHz"; const char* password = "Bestpass"; const char* mqtt_server = "broker.netpie.io"; const int mqtt_port = 1883; const char* mqtt_Client = "2c6563ec-ba7f-49a9-bcac-4ca69d1a2326"; const char* mqtt_username = "6uQEqCf7GSybeUFKBDjq8hm8urSJ53co"; const char* mqtt_password = "o9akb*H)1-72BYS8CL1f1MGkWmS4FBBE"; WiFiClient espClient; PubSubClient client(espClient); long lastMsg = 0; int value = 0; void reconnect() { while (!client.connected()) { Serial.print("Attempting MQTT connection…"); if (client.connect(mqtt_Client, mqtt_username, mqtt_password)) { Serial.println("connected"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println("try again in 5 seconds"); delay(5000); } } } void setup() { Serial.begin(115200); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); client.setServer(mqtt_server, mqtt_port); } void loop() { if (!client.connected()) { reconnect(); } client.loop(); long now = millis(); if (now - lastMsg > 2000) { lastMsg = now; ++value; client.publish("@msg/test", "Hello NETPIE2020"); Serial.println("Hello NETPIE2020"); } delay(1); }
[ "wichukorn.ku@outlook.com" ]
wichukorn.ku@outlook.com
61fffd8da0ec6fab860bed01957b587d068ee214
9f9660f318732124b8a5154e6670e1cfc372acc4
/Case_save/Case30/case9/100/T
8d23f5f3c3dde90cddc9bfaea9c7bae677c24693
[]
no_license
mamitsu2/aircond5
9a6857f4190caec15823cb3f975cdddb7cfec80b
20a6408fb10c3ba7081923b61e44454a8f09e2be
refs/heads/master
2020-04-10T22:41:47.782141
2019-09-02T03:42:37
2019-09-02T03:42:37
161,329,638
0
0
null
null
null
null
UTF-8
C++
false
false
7,214
// -*- C++ -*- // File generated by PyFoam - sorry for the ugliness FoamFile { version 2.0; format ascii; class volScalarField; location "100"; object T; } dimensions [ 0 0 0 1 0 0 0 ]; internalField nonuniform List<scalar> 459 ( 302.685 302.43 302.415 302.411 302.408 302.409 302.425 302.501 302.577 302.627 302.66 302.68 302.696 302.71 302.726 303.608 303.535 303.48 303.475 303.518 303.555 303.588 303.619 303.65 303.681 303.712 303.742 303.773 303.805 303.837 303.87 303.908 303.957 304.035 302.829 302.447 302.406 302.393 302.385 302.372 302.384 302.482 302.6 302.687 302.742 302.768 302.777 302.772 302.76 302.768 302.777 303.631 303.507 303.396 303.413 303.467 303.522 303.557 303.591 303.624 303.657 303.691 303.726 303.76 303.795 303.831 303.868 303.909 303.962 304.042 302.987 302.49 302.429 302.413 302.397 302.349 302.341 302.464 302.628 302.761 302.844 302.878 302.88 302.862 302.833 302.816 302.805 303.6 303.356 303.312 303.369 303.461 303.546 303.568 303.596 303.628 303.663 303.701 303.74 303.781 303.823 303.862 303.903 303.942 303.987 304.058 303.153 302.56 302.485 302.476 302.449 302.338 302.304 302.443 302.66 302.852 302.972 303.018 303.013 302.979 302.93 302.888 302.852 302.87 302.954 303.053 303.203 303.374 303.534 303.663 303.765 303.845 303.915 303.982 304.046 304.109 304.171 304.236 304.297 304.157 304.073 304.048 304.083 303.32 302.659 302.579 302.593 302.525 302.327 302.27 302.426 302.704 302.965 303.13 303.191 303.18 303.126 303.059 303.002 302.965 302.989 303.073 303.219 303.402 303.592 303.764 303.907 304.028 304.122 304.199 304.261 304.313 304.356 304.391 304.419 304.43 304.323 304.192 304.12 304.113 304.17 304.337 304.732 303.484 302.787 302.712 302.743 302.567 302.307 302.231 302.421 302.775 303.116 303.329 303.403 303.382 303.31 303.233 303.18 303.167 303.234 303.373 303.551 303.743 303.926 304.083 304.21 304.311 304.392 304.449 304.492 304.526 304.551 304.567 304.57 304.55 304.448 304.314 304.219 304.181 304.221 304.32 304.645 303.666 302.974 302.919 302.884 302.556 302.22 302.169 302.443 302.903 303.33 303.581 303.659 303.62 303.542 303.478 303.454 303.49 303.609 303.784 303.967 304.146 304.303 304.429 304.526 304.6 304.645 304.675 304.697 304.712 304.719 304.716 304.702 304.667 304.577 304.462 304.363 304.303 304.321 304.377 304.564 303.9 303.396 303.354 302.984 302.375 301.998 302.086 302.536 303.143 303.648 303.894 303.938 303.897 303.847 303.82 303.839 303.921 304.071 304.248 304.414 304.559 304.674 304.76 304.816 304.847 304.863 304.873 304.877 304.876 304.868 304.854 304.831 304.797 304.74 304.651 304.566 304.507 304.525 304.557 304.706 304.249 303.994 303.751 302.54 301.634 301.531 302.081 302.852 303.625 304.093 304.238 304.251 304.235 304.227 304.246 304.304 304.408 304.548 304.695 304.823 304.922 304.989 305.031 305.052 305.059 305.058 305.054 305.046 305.035 305.021 305.004 304.985 304.963 304.935 304.906 304.89 304.903 304.939 304.972 305.078 294.419 296.101 298.796 301.079 302.905 303.926 304.354 304.528 304.586 304.606 304.621 304.648 304.697 304.77 304.866 304.972 305.073 305.153 305.209 305.242 305.257 305.259 305.255 305.246 305.234 305.221 305.205 305.187 305.166 305.14 305.11 305.077 305.047 305.031 305.04 305.081 305.167 305.566 298.221 301.214 302.688 303.716 304.362 304.691 304.84 304.913 304.955 304.987 305.021 305.063 305.116 305.178 305.247 305.315 305.372 305.414 305.439 305.451 305.452 305.447 305.438 305.426 305.412 305.397 305.378 305.356 305.33 305.299 305.264 305.226 305.189 305.159 305.147 305.188 305.323 305.539 303.178 303.081 303.039 304.27 304.801 305.034 305.169 305.255 305.313 305.356 305.393 305.425 305.456 305.488 305.521 305.554 305.585 305.611 305.63 305.641 305.644 305.642 305.636 305.627 305.616 305.603 305.589 305.573 305.555 305.534 305.51 305.483 305.453 305.421 305.388 305.359 305.353 305.434 305.629 305.896 ) ; boundaryField { floor { type wallHeatTransfer; Tinf uniform 305.2; alphaWall uniform 0.24; value nonuniform List<scalar> 29 ( 302.959 303.838 303.748 303.676 303.658 303.692 303.728 303.766 303.804 303.842 303.878 303.914 303.949 303.983 304.017 304.05 304.085 304.124 304.173 304.251 304.251 304.248 304.258 304.276 302.959 303.838 303.861 303.832 303.08 ) ; } ceiling { type wallHeatTransfer; Tinf uniform 303.2; alphaWall uniform 0.24; value nonuniform List<scalar> 43 ( 303.18 303.089 303.049 304.211 304.704 304.915 305.033 305.106 305.154 305.191 305.223 305.252 305.281 305.311 305.341 305.371 305.397 305.419 305.432 305.438 305.437 305.431 305.421 305.41 305.397 305.382 305.367 305.349 305.329 305.307 305.281 305.253 305.222 305.19 305.158 305.13 305.123 305.193 305.369 305.607 304.203 303.963 298.494 ) ; } sWall { type wallHeatTransfer; Tinf uniform 315.2; alphaWall uniform 0.36; value uniform 304.326; } nWall { type wallHeatTransfer; Tinf uniform 307.2; alphaWall uniform 0.36; value nonuniform List<scalar> 6 ( 305.323 305.146 305.029 305.799 305.76 306.096 ) ; } sideWalls { type empty; } glass1 { type wallHeatTransfer; Tinf uniform 315.2; alphaWall uniform 4.3; value nonuniform List<scalar> 9 ( 310.501 309.932 309.566 309.285 309.057 308.87 308.814 308.945 309.23 ) ; } glass2 { type wallHeatTransfer; Tinf uniform 307.2; alphaWall uniform 4.3; value nonuniform List<scalar> 2 ( 306.422 306.517 ) ; } sun { type wallHeatTransfer; Tinf uniform 305.2; alphaWall uniform 0.24; value nonuniform List<scalar> 14 ( 302.895 302.641 302.619 302.604 302.591 302.584 302.596 302.667 302.746 302.8 302.841 302.871 302.898 302.925 ) ; } heatsource1 { type fixedGradient; gradient uniform 0; } heatsource2 { type fixedGradient; gradient uniform 0; } Table_master { type zeroGradient; } Table_slave { type zeroGradient; } inlet { type fixedValue; value uniform 293.15; } outlet { type zeroGradient; } } // ************************************************************************* //
[ "mitsuaki.makino@tryeting.jp" ]
mitsuaki.makino@tryeting.jp
d1ed29fc4207e9a5ec3e6e8f7725a6cb95d4dd80
fdb13695f395df564a1183dd978cfc2b0e8d2f1c
/src/Runnable.hpp
cc03934fb32b271d276510567b1a911f2ea38e4e
[]
no_license
nkh-lab/cpp
dfeb27201aa58166548ec50693002ecbac586445
36a0414a5f16f085c5ce6bfb991bb9b61db6906a
refs/heads/master
2022-12-10T21:32:14.404823
2022-12-01T14:08:33
2022-12-01T14:08:33
84,563,081
0
0
null
null
null
null
UTF-8
C++
false
false
55
hpp
#pragma once namespace Runnable { void test(void); }
[ "nkh@ua.fm" ]
nkh@ua.fm
9ea02d7707bebc49acf93c507230edb3a702829a
3af370bb18e0ebe0b33d60ca0652c56e5095840f
/version1/ObjLoader.cpp
04281cbadfb7867cf1a34f9b5928768d9719df91
[]
no_license
lin233/computer-graphics
bcd53e924c37eae43f457d34048c43170078c265
35071b0abc3c99efaf98d00d0237baac0d4529d6
refs/heads/master
2020-03-31T05:48:44.058679
2018-10-15T13:42:09
2018-10-15T13:42:09
151,959,623
0
0
null
null
null
null
GB18030
C++
false
false
7,234
cpp
#include "pch.h" #include "ObjLoader.h" #include <fstream> #include <iostream> using namespace std; void SplitString(const std::string& s, std::vector<std::string>& v, const std::string& c) { std::string::size_type pos1, pos2; pos2 = s.find(c); pos1 = 0; while (std::string::npos != pos2) { v.push_back(s.substr(pos1, pos2 - pos1)); pos1 = pos2 + c.size(); pos2 = s.find(c, pos1); } if (pos1 != s.length()) v.push_back(s.substr(pos1)); } ObjLoader::ObjLoader(string filename) { string line; fstream f; f.open(filename, ios::in); if (!f.is_open()) { std::cout << "Something Went Wrong When Opening Objfiles" << endl; } while (!f.eof()) { getline(f, line);//拿到obj文件中一行,作为一个字符串 vector<string> values; SplitString(line, values, " "); string material; if (values.size() != 0) { if (values[0] == "v") { vector<GLfloat>Point; for (int i = 1; i < 4; i++) { GLfloat xyz = atof(values[i].c_str()); Point.push_back(xyz); } vertices.push_back(Point); } else if (values[0] == "vn") { vector<GLfloat>vn; for (int i = 1; i < 4; i++) { GLfloat xyz = atof(values[i].c_str()); vn.push_back(xyz); } normals.push_back(vn); } else if (values[0] == "vt") { vector<GLfloat>vt; for (int i = 1; i < 3; i++) { GLfloat xyz = atof(values[i].c_str()); vt.push_back(xyz); } texcoords.push_back(vt); } else if (values[0] == "usemtl" || values[0] == "usemat") { material = values[1]; } else if (values[0] == "f") { vector<int>f ; vector<int>t ; vector<int>n ; for (int i = 1; i < values.size(); i++) { vector<string> w; SplitString(values[i], w, "/"); f.push_back(atof(w[0].c_str())); if (w.size() >= 2 && w[1].length() > 0) { t.push_back(atof(w[1].c_str())); } else { t.push_back(0); } if (w.size() >= 3 && w[2].length() > 0) { n.push_back(atof(w[2].c_str())); } else { n.push_back(0); } } Fac fac = {f,n,t,material}; faces.push_back(fac); } } } cout << "OK"; f.close(); int fsize = faces.size(); int JID = 0; for (int i = 0; i < fsize; i++) { Fac face = faces[i]; vector<int>ver = face.v_face; vector<int>nor = face.norms; vector<int>tex = face.texcoords; string mat = face.material; int vsize = ver.size(); for (int j = 0; j < vsize; j++) { int state = 0; int nj = nor[j] - 1; if (nj >= 0) { vector<float> norj = normals[nj]; JID_table[JID].VN[0] = norj[0]; JID_table[JID].VN[1] = norj[1]; JID_table[JID].VN[2] = norj[2]; state++; } int tj = tex[j] - 1; if (tj >= 0) { vector<float> texj = texcoords[tj]; JID_table[JID].TX[0] = texj[0]; JID_table[JID].TX[1] = texj[1]; state += 2; } vector<float> verj = vertices[ver[j] - 1]; JID_table[JID].VE[0]= verj[0]; JID_table[JID].VE[1] = verj[1]; JID_table[JID].VE[2] = verj[2]; //cout << JID_table[JID].VN[0]<<" "; JID_table[JID].state = state; JID++; } } return; /* int fsize = faces.size(); int JID = 0; vector<GLfloat> VN0; VN0.push_back(0); VN0.push_back(0); VN0.push_back(0); vector<GLfloat> TX0; TX0.push_back(0); TX0.push_back(0); for (int i = 0; i < fsize; i++) { Fac face = faces[i]; vector<int>ver = face.v_face; vector<int>nor = face.norms; vector<int>tex = face.texcoords; string mat = face.material; int vsize = ver.size(); for (int j = 0; j < vsize; j++) { int state = 0; int nj = nor[j] - 1; if (nj >= 0) { vector<GLfloat> VN; vector<float> norj = normals[nj]; VN.push_back(norj[0]); VN.push_back(norj[1]); VN.push_back(norj[2]); VNtable.push_back(VN); state++; } else { VNtable.push_back(VN0); } int tj = tex[j] - 1; if (tj >= 0) { vector<GLfloat> TX; vector<float> texj = texcoords[tj]; TX.push_back(texj[0]); TX.push_back(texj[1]); TXtable.push_back(TX); state += 2; } else { TXtable.push_back(TX0); } vector<GLfloat> VE; vector<float> verj = vertices[ver[j] - 1]; VE.push_back(verj[0]); VE.push_back(verj[1]); VE.push_back(verj[2]); VEtable.push_back(VE); state_table[JID] = state; JID++; } } */ //*/ // regHex = glGenLists(1); // glNewList(regHex, GL_COMPILE); // glEnable(GL_TEXTURE_2D); // glFrontFace(GL_CCW); //cout << "test1"; /* int fsize = faces.size(); for (int i = 0; i < 1000; i++) { Fac face = faces[i]; vector<int>ver = face.v_face; vector<int>nor = face.norms; vector<int>tex = face.texcoords; string mat = face.material; int vsize = ver.size(); glBegin(GL_POLYGON); for (int j = 0; j < vsize; j++) { int nj = nor[j] - 1; if (nj >= 0) { vector<float> norj = normals[nj]; glNormal3f(norj[0], norj[1], norj[2]); } int tj = tex[j] - 1; if (tj >= 0) { vector<float> texj = texcoords[tj]; glTexCoord2f(texj[0], texj[1]); } vector<float> verj = vertices[ver[j] - 1]; glVertex3f(verj[0], verj[1], verj[2]); } glEnd(); glEnable(GL_CULL_FACE); } // cout << "test10"; // glDisable(GL_TEXTURE_2D); glEndList();*/ } void ObjLoader::Draw() { //regHex = glGenLists(1); //glNewList(regHex, GL_COMPILE); //glEnable(GL_TEXTURE_2D); //glFrontFace(GL_CCW); //cout << "test1"; //glCallList(regHex); /* int fsize = faces.size(); for (int i = 0; i <fsize; i++) { Fac face = faces[i]; vector<int>ver = face.v_face; vector<int>nor = face.norms; vector<int>tex = face.texcoords; string mat = face.material; int vsize = ver.size(); glBegin(GL_POLYGON); for (int j = 0; j < vsize; j++) { int nj = nor[j] - 1; if (nj >= 0) { vector<float> norj = normals[nj]; glNormal3f(norj[0],norj[1],norj[2]); } int tj = tex[j]-1; if (tj >= 0) { vector<float> texj = texcoords[tj]; glTexCoord2f(texj[0],texj[1]); } vector<float> verj = vertices[ver[j] - 1]; glVertex3f(verj[0],verj[1],verj[2]); } glEnd(); glEnable(GL_CULL_FACE); } */ // cout << "test10"; //glDisable(GL_TEXTURE_2D); //glEndList(); glEnable(GL_TEXTURE_2D); int fsize = faces.size()-1; //cout << fsize; int JID = 0; for (int i = 0; i < 4000 ; i++) { Fac face = faces[i]; vector<int>ver = face.v_face; int vsize = ver.size(); glBegin(GL_POLYGON); for (int j = 0; j < vsize; j++) { Sta sta = JID_table[JID]; int state = sta.state; if (state % 2 ) { glNormal3fv(sta.VN); } if (state >= 2) { glTexCoord2fv(sta.TX); } glVertex3fv(sta.VE); JID++; } glEnd(); } glDisable(GL_TEXTURE_2D); /* int fsize = faces.size(); cout << fsize; int JID = 0; for (int i = 0; i < 4000; i++) { Fac face = faces[i]; vector<int>ver = face.v_face; int vsize = ver.size(); glBegin(GL_POLYGON); for (int j = 0; j < vsize; j++) { int state = state_table[JID]; if (state % 2 ) { glNormal3f(VNtable[JID][0], VNtable[JID][1], VNtable[JID][2]); } if (state >= 2) { glTexCoord2f(TXtable[JID][0],TXtable[JID][1]); } glVertex3f(VEtable[JID][0], VEtable[JID][1], VEtable[JID][2]); JID++; } glEnd(); glEnable(GL_CULL_FACE); } */ return; }
[ "790422967@qq.com" ]
790422967@qq.com
3f65a30eab3e4d711516a9386fe00cbd985a9ddf
44d01522cc6a7440518262b0778bc5e278f7edba
/Derzu/Roteiro3/Q4/OrcamentoEstouradoException.cpp
6533290e56489792ee6632f7fdce12a84942aa55
[]
no_license
MireleSCos/LP1
6b2323d84a9d201a611e3b1c90ec478778b8502f
fad0dd5f3cd20b532baf9ed2caab150c438f24b7
refs/heads/master
2020-09-05T09:38:25.245078
2020-03-29T23:55:08
2020-03-29T23:55:08
220,059,548
0
0
null
null
null
null
UTF-8
C++
false
false
179
cpp
#include "OrcamentoEstouradoException.h" OrcamentoEstouradoException::OrcamentoEstouradoException(/* args */) { } OrcamentoEstouradoException::~OrcamentoEstouradoException() { }
[ "mirele.si.co@outlook.com" ]
mirele.si.co@outlook.com
15c97db96a2759a534370a9ea7fe5ceeb1dceded
477fe5a1cbcadd72dad97208e622ce67771921ea
/twodOverset/run/meshes/region1/constant/regionProperties
b07aaf7cc7fa52d4286c25881b889e766b5a63a6
[]
no_license
rajkmsaini/geoOverlap
f8a40f42d722973b510b26293debc32038e01047
6d0e3bee5ade1d0c4cf41f2b103a0f9a55f2d738
refs/heads/master
2023-08-31T04:23:39.640622
2021-11-05T10:02:12
2021-11-05T10:02:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
926
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1812 | | \\ / A nd | Web: www.OpenFOAM.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "constant"; object regionProperties; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // regions ( componentMeshes (region1 region2) ); // ************************************************************************* //
[ "dominic.chandar@gmail.com" ]
dominic.chandar@gmail.com
609524acf6f24ebc9e69a98c5f8c87aa817d1fa3
eb46d0473e8d99a61dbe672da5d2deea4d9556b6
/src/module/stepper/trinamic.cpp
4f0751ec2e079c871e954e61cebf3f1962c666ef
[]
no_license
wkethman/Marlin
15eafff527b3cc62fab190057e087756351534e7
872ce16b8ac32849f1f0ef8406683896900b1c4a
refs/heads/master
2022-06-13T04:18:26.671830
2020-05-07T21:19:09
2020-05-07T21:19:09
262,160,385
2
0
null
null
null
null
UTF-8
C++
false
false
21,549
cpp
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * 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/>. * */ /** * stepper/trinamic.cpp * Stepper driver indirection for Trinamic */ #include "../../inc/MarlinConfig.h" #if HAS_TRINAMIC_CONFIG #include "trinamic.h" #include "../stepper.h" #include <HardwareSerial.h> #include <SPI.h> enum StealthIndex : uint8_t { STEALTH_AXIS_XY, STEALTH_AXIS_Z, STEALTH_AXIS_E }; #define TMC_INIT(ST, STEALTH_INDEX) tmc_init(stepper##ST, ST##_CURRENT, ST##_MICROSTEPS, ST##_HYBRID_THRESHOLD, stealthchop_by_axis[STEALTH_INDEX]) // IC = TMC model number // ST = Stepper object letter // L = Label characters // AI = Axis Enum Index // SWHW = SW/SH UART selection #if ENABLED(TMC_USE_SW_SPI) #define __TMC_SPI_DEFINE(IC, ST, L, AI) TMCMarlin<IC##Stepper, L, AI> stepper##ST(ST##_CS_PIN, float(ST##_RSENSE), TMC_SW_MOSI, TMC_SW_MISO, TMC_SW_SCK, ST##_CHAIN_POS) #else #define __TMC_SPI_DEFINE(IC, ST, L, AI) TMCMarlin<IC##Stepper, L, AI> stepper##ST(ST##_CS_PIN, float(ST##_RSENSE), ST##_CHAIN_POS) #endif #define TMC_UART_HW_DEFINE(IC, ST, L, AI) TMCMarlin<IC##Stepper, L, AI> stepper##ST(&ST##_HARDWARE_SERIAL, float(ST##_RSENSE), ST##_SLAVE_ADDRESS) #define TMC_UART_SW_DEFINE(IC, ST, L, AI) TMCMarlin<IC##Stepper, L, AI> stepper##ST(ST##_SERIAL_RX_PIN, ST##_SERIAL_TX_PIN, float(ST##_RSENSE), ST##_SLAVE_ADDRESS, ST##_SERIAL_RX_PIN > -1) #define _TMC_SPI_DEFINE(IC, ST, AI) __TMC_SPI_DEFINE(IC, ST, TMC_##ST##_LABEL, AI) #define TMC_SPI_DEFINE(ST, AI) _TMC_SPI_DEFINE(ST##_DRIVER_TYPE, ST, AI##_AXIS) #define _TMC_UART_DEFINE(SWHW, IC, ST, AI) TMC_UART_##SWHW##_DEFINE(IC, ST, TMC_##ST##_LABEL, AI) #define TMC_UART_DEFINE(SWHW, ST, AI) _TMC_UART_DEFINE(SWHW, ST##_DRIVER_TYPE, ST, AI##_AXIS) #if ENABLED(DISTINCT_E_FACTORS) && E_STEPPERS > 1 #define TMC_SPI_DEFINE_E(AI) TMC_SPI_DEFINE(E##AI, E##AI) #define TMC_UART_DEFINE_E(SWHW, AI) TMC_UART_DEFINE(SWHW, E##AI, E##AI) #else #define TMC_SPI_DEFINE_E(AI) TMC_SPI_DEFINE(E##AI, E) #define TMC_UART_DEFINE_E(SWHW, AI) TMC_UART_DEFINE(SWHW, E##AI, E) #endif // Stepper objects of TMC2130/TMC2160/TMC2660/TMC5130/TMC5160 steppers used #if AXIS_HAS_SPI(X) TMC_SPI_DEFINE(X, X); #endif #if AXIS_HAS_SPI(X2) TMC_SPI_DEFINE(X2, X); #endif #if AXIS_HAS_SPI(Y) TMC_SPI_DEFINE(Y, Y); #endif #if AXIS_HAS_SPI(Y2) TMC_SPI_DEFINE(Y2, Y); #endif #if AXIS_HAS_SPI(Z) TMC_SPI_DEFINE(Z, Z); #endif #if AXIS_HAS_SPI(Z2) TMC_SPI_DEFINE(Z2, Z); #endif #if AXIS_HAS_SPI(Z3) TMC_SPI_DEFINE(Z3, Z); #endif #if AXIS_HAS_SPI(Z4) TMC_SPI_DEFINE(Z4, Z); #endif #if AXIS_HAS_SPI(E0) TMC_SPI_DEFINE_E(0); #endif #if AXIS_HAS_SPI(E1) TMC_SPI_DEFINE_E(1); #endif #if AXIS_HAS_SPI(E2) TMC_SPI_DEFINE_E(2); #endif #if AXIS_HAS_SPI(E3) TMC_SPI_DEFINE_E(3); #endif #if AXIS_HAS_SPI(E4) TMC_SPI_DEFINE_E(4); #endif #if AXIS_HAS_SPI(E5) TMC_SPI_DEFINE_E(5); #endif #if AXIS_HAS_SPI(E6) TMC_SPI_DEFINE_E(6); #endif #if AXIS_HAS_SPI(E7) TMC_SPI_DEFINE_E(7); #endif #ifndef TMC_BAUD_RATE #if HAS_TMC_SW_SERIAL // Reduce baud rate for boards not already overriding TMC_BAUD_RATE for software serial. // Testing has shown that 115200 is not 100% reliable on AVR platforms, occasionally // failing to read status properly. 32-bit platforms typically define an even lower // TMC_BAUD_RATE, due to differences in how SoftwareSerial libraries work on different // platforms. #define TMC_BAUD_RATE 57600 #else #define TMC_BAUD_RATE 115200 #endif #endif #if HAS_DRIVER(TMC2130) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void tmc_init(TMCMarlin<TMC2130Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const uint16_t mA, const uint16_t microsteps, const uint32_t hyb_thrs, const bool stealth) { st.begin(); CHOPCONF_t chopconf{0}; chopconf.tbl = 1; chopconf.toff = chopper_timing.toff; chopconf.intpol = INTERPOLATE; chopconf.hend = chopper_timing.hend + 3; chopconf.hstrt = chopper_timing.hstrt - 1; TERN_(SQUARE_WAVE_STEPPING, chopconf.dedge = true); st.CHOPCONF(chopconf.sr); st.rms_current(mA, HOLD_MULTIPLIER); st.microsteps(microsteps); st.iholddelay(10); st.TPOWERDOWN(128); // ~2s until driver lowers to hold current st.en_pwm_mode(stealth); st.stored.stealthChop_enabled = stealth; PWMCONF_t pwmconf{0}; pwmconf.pwm_freq = 0b01; // f_pwm = 2/683 f_clk pwmconf.pwm_autoscale = true; pwmconf.pwm_grad = 5; pwmconf.pwm_ampl = 180; st.PWMCONF(pwmconf.sr); #if ENABLED(HYBRID_THRESHOLD) st.set_pwm_thrs(hyb_thrs); #else UNUSED(hyb_thrs); #endif st.GSTAT(); // Clear GSTAT } #endif // TMC2130 #if HAS_DRIVER(TMC2160) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void tmc_init(TMCMarlin<TMC2160Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const uint16_t mA, const uint16_t microsteps, const uint32_t hyb_thrs, const bool stealth) { st.begin(); CHOPCONF_t chopconf{0}; chopconf.tbl = 1; chopconf.toff = chopper_timing.toff; chopconf.intpol = INTERPOLATE; chopconf.hend = chopper_timing.hend + 3; chopconf.hstrt = chopper_timing.hstrt - 1; TERN_(SQUARE_WAVE_STEPPING, chopconf.dedge = true); st.CHOPCONF(chopconf.sr); st.rms_current(mA, HOLD_MULTIPLIER); st.microsteps(microsteps); st.iholddelay(10); st.TPOWERDOWN(128); // ~2s until driver lowers to hold current st.en_pwm_mode(stealth); st.stored.stealthChop_enabled = stealth; TMC2160_n::PWMCONF_t pwmconf{0}; pwmconf.pwm_lim = 12; pwmconf.pwm_reg = 8; pwmconf.pwm_autograd = true; pwmconf.pwm_autoscale = true; pwmconf.pwm_freq = 0b01; pwmconf.pwm_grad = 14; pwmconf.pwm_ofs = 36; st.PWMCONF(pwmconf.sr); #if ENABLED(HYBRID_THRESHOLD) st.set_pwm_thrs(hyb_thrs); #else UNUSED(hyb_thrs); #endif st.GSTAT(); // Clear GSTAT } #endif // TMC2160 // // TMC2208/2209 Driver objects and inits // #if HAS_TMC220x #if AXIS_HAS_UART(X) #ifdef X_HARDWARE_SERIAL TMC_UART_DEFINE(HW, X, X); #else TMC_UART_DEFINE(SW, X, X); #endif #endif #if AXIS_HAS_UART(X2) #ifdef X2_HARDWARE_SERIAL TMC_UART_DEFINE(HW, X2, X); #else TMC_UART_DEFINE(SW, X2, X); #endif #endif #if AXIS_HAS_UART(Y) #ifdef Y_HARDWARE_SERIAL TMC_UART_DEFINE(HW, Y, Y); #else TMC_UART_DEFINE(SW, Y, Y); #endif #endif #if AXIS_HAS_UART(Y2) #ifdef Y2_HARDWARE_SERIAL TMC_UART_DEFINE(HW, Y2, Y); #else TMC_UART_DEFINE(SW, Y2, Y); #endif #endif #if AXIS_HAS_UART(Z) #ifdef Z_HARDWARE_SERIAL TMC_UART_DEFINE(HW, Z, Z); #else TMC_UART_DEFINE(SW, Z, Z); #endif #endif #if AXIS_HAS_UART(Z2) #ifdef Z2_HARDWARE_SERIAL TMC_UART_DEFINE(HW, Z2, Z); #else TMC_UART_DEFINE(SW, Z2, Z); #endif #endif #if AXIS_HAS_UART(Z3) #ifdef Z3_HARDWARE_SERIAL TMC_UART_DEFINE(HW, Z3, Z); #else TMC_UART_DEFINE(SW, Z3, Z); #endif #endif #if AXIS_HAS_UART(Z4) #ifdef Z4_HARDWARE_SERIAL TMC_UART_DEFINE(HW, Z4, Z); #else TMC_UART_DEFINE(SW, Z4, Z); #endif #endif #if AXIS_HAS_UART(E0) #ifdef E0_HARDWARE_SERIAL TMC_UART_DEFINE_E(HW, 0); #else TMC_UART_DEFINE_E(SW, 0); #endif #endif #if AXIS_HAS_UART(E1) #ifdef E1_HARDWARE_SERIAL TMC_UART_DEFINE_E(HW, 1); #else TMC_UART_DEFINE_E(SW, 1); #endif #endif #if AXIS_HAS_UART(E2) #ifdef E2_HARDWARE_SERIAL TMC_UART_DEFINE_E(HW, 2); #else TMC_UART_DEFINE_E(SW, 2); #endif #endif #if AXIS_HAS_UART(E3) #ifdef E3_HARDWARE_SERIAL TMC_UART_DEFINE_E(HW, 3); #else TMC_UART_DEFINE_E(SW, 3); #endif #endif #if AXIS_HAS_UART(E4) #ifdef E4_HARDWARE_SERIAL TMC_UART_DEFINE_E(HW, 4); #else TMC_UART_DEFINE_E(SW, 4); #endif #endif #if AXIS_HAS_UART(E5) #ifdef E5_HARDWARE_SERIAL TMC_UART_DEFINE_E(HW, 5); #else TMC_UART_DEFINE_E(SW, 5); #endif #endif #if AXIS_HAS_UART(E6) #ifdef E6_HARDWARE_SERIAL TMC_UART_DEFINE_E(HW, 6); #else TMC_UART_DEFINE_E(SW, 6); #endif #endif #if AXIS_HAS_UART(E7) #ifdef E7_HARDWARE_SERIAL TMC_UART_DEFINE_E(HW, 7); #else TMC_UART_DEFINE_E(SW, 7); #endif #endif enum TMCAxis : uint8_t { X, Y, Z, X2, Y2, Z2, Z3, Z4, E0, E1, E2, E3, E4, E5, E6, E7, TOTAL }; void tmc_serial_begin() { struct { const void *ptr[TMCAxis::TOTAL]; bool began(const TMCAxis a, const void * const p) { LOOP_L_N(i, a) if (p == ptr[i]) return true; ptr[a] = p; return false; }; } sp_helper; #define HW_SERIAL_BEGIN(A) do{ if (!sp_helper.began(TMCAxis::A, &A##_HARDWARE_SERIAL)) \ A##_HARDWARE_SERIAL.begin(TMC_BAUD_RATE); }while(0) #if AXIS_HAS_UART(X) #ifdef X_HARDWARE_SERIAL HW_SERIAL_BEGIN(X); #else stepperX.beginSerial(TMC_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(X2) #ifdef X2_HARDWARE_SERIAL HW_SERIAL_BEGIN(X2); #else stepperX2.beginSerial(TMC_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(Y) #ifdef Y_HARDWARE_SERIAL HW_SERIAL_BEGIN(Y); #else stepperY.beginSerial(TMC_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(Y2) #ifdef Y2_HARDWARE_SERIAL HW_SERIAL_BEGIN(Y2); #else stepperY2.beginSerial(TMC_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(Z) #ifdef Z_HARDWARE_SERIAL HW_SERIAL_BEGIN(Z); #else stepperZ.beginSerial(TMC_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(Z2) #ifdef Z2_HARDWARE_SERIAL HW_SERIAL_BEGIN(Z2); #else stepperZ2.beginSerial(TMC_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(Z3) #ifdef Z3_HARDWARE_SERIAL HW_SERIAL_BEGIN(Z3); #else stepperZ3.beginSerial(TMC_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(Z4) #ifdef Z4_HARDWARE_SERIAL HW_SERIAL_BEGIN(Z4); #else stepperZ4.beginSerial(TMC_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(E0) #ifdef E0_HARDWARE_SERIAL HW_SERIAL_BEGIN(E0); #else stepperE0.beginSerial(TMC_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(E1) #ifdef E1_HARDWARE_SERIAL HW_SERIAL_BEGIN(E1); #else stepperE1.beginSerial(TMC_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(E2) #ifdef E2_HARDWARE_SERIAL HW_SERIAL_BEGIN(E2); #else stepperE2.beginSerial(TMC_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(E3) #ifdef E3_HARDWARE_SERIAL HW_SERIAL_BEGIN(E3); #else stepperE3.beginSerial(TMC_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(E4) #ifdef E4_HARDWARE_SERIAL HW_SERIAL_BEGIN(E4); #else stepperE4.beginSerial(TMC_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(E5) #ifdef E5_HARDWARE_SERIAL HW_SERIAL_BEGIN(E5); #else stepperE5.beginSerial(TMC_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(E6) #ifdef E6_HARDWARE_SERIAL HW_SERIAL_BEGIN(E6); #else stepperE6.beginSerial(TMC_BAUD_RATE); #endif #endif #if AXIS_HAS_UART(E7) #ifdef E7_HARDWARE_SERIAL HW_SERIAL_BEGIN(E7); #else stepperE7.beginSerial(TMC_BAUD_RATE); #endif #endif } #endif #if HAS_DRIVER(TMC2208) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void tmc_init(TMCMarlin<TMC2208Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const uint16_t mA, const uint16_t microsteps, const uint32_t hyb_thrs, const bool stealth) { TMC2208_n::GCONF_t gconf{0}; gconf.pdn_disable = true; // Use UART gconf.mstep_reg_select = true; // Select microsteps with UART gconf.i_scale_analog = false; gconf.en_spreadcycle = !stealth; st.GCONF(gconf.sr); st.stored.stealthChop_enabled = stealth; TMC2208_n::CHOPCONF_t chopconf{0}; chopconf.tbl = 0b01; // blank_time = 24 chopconf.toff = chopper_timing.toff; chopconf.intpol = INTERPOLATE; chopconf.hend = chopper_timing.hend + 3; chopconf.hstrt = chopper_timing.hstrt - 1; TERN_(SQUARE_WAVE_STEPPING, chopconf.dedge = true); st.CHOPCONF(chopconf.sr); st.rms_current(mA, HOLD_MULTIPLIER); st.microsteps(microsteps); st.iholddelay(10); st.TPOWERDOWN(128); // ~2s until driver lowers to hold current TMC2208_n::PWMCONF_t pwmconf{0}; pwmconf.pwm_lim = 12; pwmconf.pwm_reg = 8; pwmconf.pwm_autograd = true; pwmconf.pwm_autoscale = true; pwmconf.pwm_freq = 0b01; pwmconf.pwm_grad = 14; pwmconf.pwm_ofs = 36; st.PWMCONF(pwmconf.sr); #if ENABLED(HYBRID_THRESHOLD) st.set_pwm_thrs(hyb_thrs); #else UNUSED(hyb_thrs); #endif st.GSTAT(0b111); // Clear delay(200); } #endif // TMC2208 #if HAS_DRIVER(TMC2209) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void tmc_init(TMCMarlin<TMC2209Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const uint16_t mA, const uint16_t microsteps, const uint32_t hyb_thrs, const bool stealth) { TMC2208_n::GCONF_t gconf{0}; gconf.pdn_disable = true; // Use UART gconf.mstep_reg_select = true; // Select microsteps with UART gconf.i_scale_analog = false; gconf.en_spreadcycle = !stealth; st.GCONF(gconf.sr); st.stored.stealthChop_enabled = stealth; TMC2208_n::CHOPCONF_t chopconf{0}; chopconf.tbl = 0b01; // blank_time = 24 chopconf.toff = chopper_timing.toff; chopconf.intpol = INTERPOLATE; chopconf.hend = chopper_timing.hend + 3; chopconf.hstrt = chopper_timing.hstrt - 1; TERN_(SQUARE_WAVE_STEPPING, chopconf.dedge = true); st.CHOPCONF(chopconf.sr); st.rms_current(mA, HOLD_MULTIPLIER); st.microsteps(microsteps); st.iholddelay(10); st.TPOWERDOWN(128); // ~2s until driver lowers to hold current TMC2208_n::PWMCONF_t pwmconf{0}; pwmconf.pwm_lim = 12; pwmconf.pwm_reg = 8; pwmconf.pwm_autograd = true; pwmconf.pwm_autoscale = true; pwmconf.pwm_freq = 0b01; pwmconf.pwm_grad = 14; pwmconf.pwm_ofs = 36; st.PWMCONF(pwmconf.sr); #if ENABLED(HYBRID_THRESHOLD) st.set_pwm_thrs(hyb_thrs); #else UNUSED(hyb_thrs); #endif st.GSTAT(0b111); // Clear delay(200); } #endif // TMC2209 #if HAS_DRIVER(TMC2660) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void tmc_init(TMCMarlin<TMC2660Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const uint16_t mA, const uint16_t microsteps, const uint32_t, const bool) { st.begin(); TMC2660_n::CHOPCONF_t chopconf{0}; chopconf.tbl = 1; chopconf.toff = chopper_timing.toff; chopconf.hend = chopper_timing.hend + 3; chopconf.hstrt = chopper_timing.hstrt - 1; st.CHOPCONF(chopconf.sr); st.sdoff(0); st.rms_current(mA); st.microsteps(microsteps); TERN_(SQUARE_WAVE_STEPPING, st.dedge(true)); st.intpol(INTERPOLATE); st.diss2g(true); // Disable short to ground protection. Too many false readings? TERN_(TMC_DEBUG, st.rdsel(0b01)); } #endif // TMC2660 #if HAS_DRIVER(TMC5130) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void tmc_init(TMCMarlin<TMC5130Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const uint16_t mA, const uint16_t microsteps, const uint32_t hyb_thrs, const bool stealth) { st.begin(); CHOPCONF_t chopconf{0}; chopconf.tbl = 1; chopconf.toff = chopper_timing.toff; chopconf.intpol = INTERPOLATE; chopconf.hend = chopper_timing.hend + 3; chopconf.hstrt = chopper_timing.hstrt - 1; TERN_(SQUARE_WAVE_STEPPING, chopconf.dedge = true); st.CHOPCONF(chopconf.sr); st.rms_current(mA, HOLD_MULTIPLIER); st.microsteps(microsteps); st.iholddelay(10); st.TPOWERDOWN(128); // ~2s until driver lowers to hold current st.en_pwm_mode(stealth); st.stored.stealthChop_enabled = stealth; PWMCONF_t pwmconf{0}; pwmconf.pwm_freq = 0b01; // f_pwm = 2/683 f_clk pwmconf.pwm_autoscale = true; pwmconf.pwm_grad = 5; pwmconf.pwm_ampl = 180; st.PWMCONF(pwmconf.sr); #if ENABLED(HYBRID_THRESHOLD) st.set_pwm_thrs(hyb_thrs); #else UNUSED(hyb_thrs); #endif st.GSTAT(); // Clear GSTAT } #endif // TMC5130 #if HAS_DRIVER(TMC5160) template<char AXIS_LETTER, char DRIVER_ID, AxisEnum AXIS_ID> void tmc_init(TMCMarlin<TMC5160Stepper, AXIS_LETTER, DRIVER_ID, AXIS_ID> &st, const uint16_t mA, const uint16_t microsteps, const uint32_t hyb_thrs, const bool stealth) { st.begin(); CHOPCONF_t chopconf{0}; chopconf.tbl = 1; chopconf.toff = chopper_timing.toff; chopconf.intpol = INTERPOLATE; chopconf.hend = chopper_timing.hend + 3; chopconf.hstrt = chopper_timing.hstrt - 1; TERN_(SQUARE_WAVE_STEPPING, chopconf.dedge = true); st.CHOPCONF(chopconf.sr); st.rms_current(mA, HOLD_MULTIPLIER); st.microsteps(microsteps); st.iholddelay(10); st.TPOWERDOWN(128); // ~2s until driver lowers to hold current st.en_pwm_mode(stealth); st.stored.stealthChop_enabled = stealth; TMC2160_n::PWMCONF_t pwmconf{0}; pwmconf.pwm_lim = 12; pwmconf.pwm_reg = 8; pwmconf.pwm_autograd = true; pwmconf.pwm_autoscale = true; pwmconf.pwm_freq = 0b01; pwmconf.pwm_grad = 14; pwmconf.pwm_ofs = 36; st.PWMCONF(pwmconf.sr); #if ENABLED(HYBRID_THRESHOLD) st.set_pwm_thrs(hyb_thrs); #else UNUSED(hyb_thrs); #endif st.GSTAT(); // Clear GSTAT } #endif // TMC5160 void restore_trinamic_drivers() { #if AXIS_IS_TMC(X) stepperX.push(); #endif #if AXIS_IS_TMC(X2) stepperX2.push(); #endif #if AXIS_IS_TMC(Y) stepperY.push(); #endif #if AXIS_IS_TMC(Y2) stepperY2.push(); #endif #if AXIS_IS_TMC(Z) stepperZ.push(); #endif #if AXIS_IS_TMC(Z2) stepperZ2.push(); #endif #if AXIS_IS_TMC(Z3) stepperZ3.push(); #endif #if AXIS_IS_TMC(Z4) stepperZ4.push(); #endif #if AXIS_IS_TMC(E0) stepperE0.push(); #endif #if AXIS_IS_TMC(E1) stepperE1.push(); #endif #if AXIS_IS_TMC(E2) stepperE2.push(); #endif #if AXIS_IS_TMC(E3) stepperE3.push(); #endif #if AXIS_IS_TMC(E4) stepperE4.push(); #endif #if AXIS_IS_TMC(E5) stepperE5.push(); #endif #if AXIS_IS_TMC(E6) stepperE6.push(); #endif #if AXIS_IS_TMC(E7) stepperE7.push(); #endif } void reset_trinamic_drivers() { static constexpr bool stealthchop_by_axis[] = { #if ENABLED(STEALTHCHOP_XY) true #else false #endif , #if ENABLED(STEALTHCHOP_Z) true #else false #endif , #if ENABLED(STEALTHCHOP_E) true #else false #endif }; #if AXIS_IS_TMC(X) TMC_INIT(X, STEALTH_AXIS_XY); #endif #if AXIS_IS_TMC(X2) TMC_INIT(X2, STEALTH_AXIS_XY); #endif #if AXIS_IS_TMC(Y) TMC_INIT(Y, STEALTH_AXIS_XY); #endif #if AXIS_IS_TMC(Y2) TMC_INIT(Y2, STEALTH_AXIS_XY); #endif #if AXIS_IS_TMC(Z) TMC_INIT(Z, STEALTH_AXIS_Z); #endif #if AXIS_IS_TMC(Z2) TMC_INIT(Z2, STEALTH_AXIS_Z); #endif #if AXIS_IS_TMC(Z3) TMC_INIT(Z3, STEALTH_AXIS_Z); #endif #if AXIS_IS_TMC(Z4) TMC_INIT(Z4, STEALTH_AXIS_Z); #endif #if AXIS_IS_TMC(E0) TMC_INIT(E0, STEALTH_AXIS_E); #endif #if AXIS_IS_TMC(E1) TMC_INIT(E1, STEALTH_AXIS_E); #endif #if AXIS_IS_TMC(E2) TMC_INIT(E2, STEALTH_AXIS_E); #endif #if AXIS_IS_TMC(E3) TMC_INIT(E3, STEALTH_AXIS_E); #endif #if AXIS_IS_TMC(E4) TMC_INIT(E4, STEALTH_AXIS_E); #endif #if AXIS_IS_TMC(E5) TMC_INIT(E5, STEALTH_AXIS_E); #endif #if AXIS_IS_TMC(E6) TMC_INIT(E6, STEALTH_AXIS_E); #endif #if AXIS_IS_TMC(E7) TMC_INIT(E7, STEALTH_AXIS_E); #endif #if USE_SENSORLESS TERN_(X_SENSORLESS, stepperX.homing_threshold(X_STALL_SENSITIVITY)); TERN_(X2_SENSORLESS, stepperX2.homing_threshold(X2_STALL_SENSITIVITY)); TERN_(Y_SENSORLESS, stepperY.homing_threshold(Y_STALL_SENSITIVITY)); TERN_(Y2_SENSORLESS, stepperY2.homing_threshold(Y2_STALL_SENSITIVITY)); TERN_(Z_SENSORLESS, stepperZ.homing_threshold(Z_STALL_SENSITIVITY)); TERN_(Z2_SENSORLESS, stepperZ2.homing_threshold(Z2_STALL_SENSITIVITY)); TERN_(Z3_SENSORLESS, stepperZ3.homing_threshold(Z3_STALL_SENSITIVITY)); TERN_(Z4_SENSORLESS, stepperZ4.homing_threshold(Z4_STALL_SENSITIVITY)); #endif #ifdef TMC_ADV TMC_ADV() #endif stepper.set_directions(); } #endif // HAS_TRINAMIC_CONFIG
[ "william@wckethman.com" ]
william@wckethman.com
c500e651dba9f943dac1846b40558ea5e4af2556
2ace08a52db1dac5f173c9bc44453bc4cde731a4
/L4/TestProject/TestProject/unittest1.cpp
d3851984669b6938a70c7618a0ea4420b7e5cdb5
[]
no_license
peterzsuzsa/Ver-Val
ba135d0ba317bfd32d6c3bf89c827d8a4e26d155
ef1445c790f974304d65d6609ba9f137f6877114
refs/heads/master
2020-12-24T18:51:40.142202
2016-05-19T21:57:00
2016-05-19T21:57:00
57,131,843
0
0
null
null
null
null
UTF-8
C++
false
false
1,194
cpp
#include "stdafx.h" #include "CppUnitTest.h" #include "..\LogAnalyzer\LogAnalyzer.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace TestProject { TEST_CLASS(UnitTest1) { public: /* TEST_METHOD(TestMethod1) { // TODO: Your test code here Assert::AreEqual(1, 1); } */ TEST_METHOD(LogAnalyzer_isValidFileName_ValidFileName_ReturnsTrue) { shared_ptr<CFileExtMng> ffm = shared_ptr<CFakeFileExtMng>(new CFakeFileExtMng); std::dynamic_pointer_cast<CFakeFileExtMng>(ffm)->setErtek(true); CFileExtMngFactory::getFEMFactory()->setFileExtensionManager(ffm); CFakeFileExtMng* fem = new CFakeFileExtMng(); CLogAnalyzer la; string s = "filename.txt"; Assert::IsTrue(la.isTheFileValid(s)); } /* TEST_METHOD(LogAnalyzer_isValidFileName_ValidFileName_ReturnsFailed) { shared_ptr<CFileExtMng> ffm = shared_ptr<CFakeFileExtMng>(new CFakeFileExtMng); std::dynamic_pointer_cast<CFakeFileExtMng>(ffm)->setErtek(true); CFileExtMngFactory::getFEMFactory()->setFileExtensionManager(ffm); CFakeFileExtMng* fem = new CFakeFileExtMng(); CLogAnalyzer la; string s = "fi"; Assert::IsTrue(la.isTheFileValid(s)); }*/ }; }
[ "peter_zsuzsa94@yahoo.com" ]
peter_zsuzsa94@yahoo.com
3b5d4c74d044d981e4e77dfc5b007afa01c6fab3
47cd4e2be27c39a9242dd0bc57b195c293cd93d5
/contest7/20.cpp
e3c53da8ed7abd67e687d497a3c03caa900bcc4e
[]
no_license
ntung1005/Algo
18b403eb636333aa318b99fa37238403a21eef71
3e0942dc471ba03bb2da3736ebcc43f786834aec
refs/heads/master
2022-11-30T22:34:58.865637
2020-08-08T10:35:12
2020-08-08T10:35:12
264,919,990
0
0
null
null
null
null
UTF-8
C++
false
false
579
cpp
#include<bits/stdc++.h> using namespace std; long long a[100000]; int main(){ int t; cin>>t; while(t--){ long long n; cin>>n; for(int i=0;i<n;i++){ cin>>a[i]; } stack<long long> x; stack<long long> y; y.push(-1); for(int i=n-2;i>=0;i--){ for(int j=n-1;j>i;j--){ x.push(a[j]); } while(!x.empty()){ if(x.top() > a[i] ){ y.push(x.top()); break; } x.pop(); } if(x.empty()){ y.push(-1); } } while(!y.empty()){ cout<<y.top()<<" "; y.pop(); } cout<<endl; } return 0; }
[ "ntung7965@gmail.com" ]
ntung7965@gmail.com
015992194e1092ccd90ca4031f9705e8d77425db
c0a378d21afd25c5ce143f3db5ba414ae061f1f9
/imageSketch/src/ofApp.h
2abc7ca22b993c4518285457d066f4c84353de8d
[]
no_license
shelbywilson/sfpc-rtp
ffd62c940142bb9e3e7361e418ec122702e28bc6
cb359766e6c38789b98029ffde466530c48ade1c
refs/heads/master
2020-08-14T16:10:33.129885
2019-12-23T16:49:16
2019-12-23T16:49:16
215,196,632
7
0
null
null
null
null
UTF-8
C++
false
false
569
h
#pragma once #include "ofMain.h" class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); ofImage lillian; };
[ "s.wilson024@gmail.com" ]
s.wilson024@gmail.com
08fb88a790b646af3c2ef8095955029b058c5f17
c362f35934a3f23e0e7dc92cc622e78ae5c7f930
/Standard template library/list/sort_list.cc
102e32354e96cec7d7d07e6c56d391c0ef7815bc
[]
no_license
PrateekJoshi/Cpp_complete_reference
279ac23a9e666a99b6c4e4db3d2e56a2b23883f6
91692364af2852da2cb4c76cf670fc5b94c6b175
refs/heads/master
2020-03-25T21:01:30.433174
2018-09-16T13:10:40
2018-09-16T13:10:40
144,155,967
0
0
null
null
null
null
UTF-8
C++
false
false
668
cc
/* * sort_list.cc * * Created on: Sep 16, 2018 * Author: prateek * Pg: 687 */ #include <iostream> #include <list> int main(int argc, char **argv) { std::list<int> list; int i; /* Create a list of random integers */ for(int i=0;i<10;i++) { list.push_back(rand()%100); } std::cout<<"Original contents: "<<std::endl; std::list<int>::iterator itr = list.begin(); while( itr != list.end() ) { std::cout<<*itr<<" "; itr++; } std::cout<<"\n\n"; /* Sort the list */ list.sort(); std::cout<<"Sorted contents: "<<std::endl; itr = list.begin(); while( itr != list.end() ) { std::cout<<*itr <<" "; itr++; } return 0; }
[ "prateek@localhost.localdomain" ]
prateek@localhost.localdomain
c267566a1ab26ced0a3432346c93ef58bd5a3c18
259bacc81f4b663daac01574061b38f2cd93b867
/cf/1388/qq.cpp
0ec56b5eb02d493db2348242f013efa3af4f5690
[]
no_license
yashrsharma44/Competitive-Programming
6bf310d707efcb650fa6c732132a641c3c453112
77317baa4681c263c5926b62864a61b826f487ea
refs/heads/master
2023-03-03T13:59:53.713477
2022-11-16T09:10:25
2022-11-16T09:10:25
196,458,547
0
0
null
null
null
null
UTF-8
C++
false
false
5,514
cpp
#include <bits/stdc++.h> const double PI =3.141592653589793238463; using namespace std; typedef long long ll; #define ff first #define ss second #define pb push_back #define pf push_front #define mp make_pair #define pu push #define pp pop_back #define in insert #define MOD 1000000007 // #define endl "\n" #define sz(a) (int)((a).size()) #define all(x) (x).begin(), (x).end() #define trace(x) cerr << #x << ": " << x << " " << endl; #define prv(a) for(auto x : a) cout << x << ' ';cout << '\n'; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define OTP(s) cout<<s<<endl; #define FOR(i,j,k,l) for(ll i=j;i<k;i+=l) #define REP(i,j) FOR(i,0,j,1) inline ll add(ll a, ll b){a += b; if(a >= MOD)a -= MOD; return a;} inline ll sub(ll a, ll b){a -= b; if(a < 0)a += MOD; return a;} inline ll mul(ll a, ll b){return (ll)((ll) a * b %MOD);} typedef vector<ll> vl; typedef vector<vl> vvl; typedef pair<ll,ll> pll; typedef vector<pll> vpll; // long long fast_power(long long base, long long power) { // long long result = 1; // while(power > 0) { // if(power % 2 == 1) { // Can also use (power & 1) to make code even faster // result = (result*base);//%MOD; // } // base = (base * base);//%MOD; // power = power / 2; // Can also use power >>= 1; to make code even faster // } // return result; // } // ll min(ll a,ll b) // { // return a>b?b:a; // } // ll max(ll a,ll b) // { // return a>b?a:b; // } // ll dfs(ll s,vector<bool> &vis, vector<vector<ll>> &adlist, vector<ll> &pe) // { // if(vis[s]) return pe[s]; // vis[s]=true; // for(auto x:adlist[s]) // { // if(vis[x]==false) // { // pe[s] += dfs(x,vis,adlist,pe); // } // } // return pe[s]; // } // void bfs(ll x, vector<bool> &vis, vector<vector<ll>> &adlist, vector<ll> &level, vector<ll> &parent) // { // queue<ll> q; // vis[x] = true; // q.push(x); // while (!q.empty()) // { // ll s = q.front(); // q.pop(); // // process node s // for (auto u : adlist[s]) // { // if (vis[u]) continue; // vis[u] = true; // parent[u]=s; // level[u]=level[s]+1; // q.push(u); // } // } // } // bool bpchk(vector< vector < ll > > &adj, vector<ll> &color) // { // color[1] = 1; // queue < ll > q; // q.push(1); // while(!q.empty()) // { // ll u = q.front(); // q.pop(); // for(auto x : adj[u]) // { // if(color[x] == -1) // { // color[x] = color[u]^1; // q.push(x); // } // } // } // for(ll i = 1; i < adj.size();i++) // { // for(auto x : adj[i]) // { // if(color[x] == color[i]) return false; // } // } // return true; // } // void swap(ll *a, ll *b) // { // ll tmp=*a; // *a = *b; // *b = tmp; // } // void SieveOfEratosthenes(ll n, set<ll> &s) // { // vector<bool> prime(n+1,true); // for (ll p=2; p*p<=n; p++) // { // // If prime[p] is not changed, then it is a prime // if (prime[p] == true) // { // for (ll i=p*p; i<=n; i += p) // prime[i] = false; // } // } // for (ll p=2; p<=n; p++) // if (prime[p]) s.insert(p); // } int main() { // IOS // ll T; // cin>>T; // while(T--) ll n; cin>>n; vector<ll> a; a.push_back(-1); map<ll,ll> m; cout<<1<<endl; for(ll i=1;i<=n;i++) { int vl; cin>>vl; a.push_back(vl); m[i]=0; } vector<ll> nxt; nxt.push_back(-1); for(ll i=1;i<=n;i++) { int vl; cin>>vl; nxt.push_back(vl); if(nxt[i]!=-1) { m[nxt[i]]+=1; } } cout<<2<<endl; priority_queue<pair<ll,ll>, vector<pair<ll,ll> > > pq; vector<ll> ans1,ans2; for(auto &x:m) { if(x.second==0) { pq.push(make_pair(a[x.first],x.first)); } } ll val=0; pair<ll,ll> p; cout<<3<<endl; while(!pq.empty()) { p = pq.top(); pq.pop(); val+=p.first; if(p.first<=0) { ans2.pb(p.second); } else if(p.first>0) { ans1.pb(p.second); a[nxt[p.second]]+=p.first; } if(nxt[p.second]!=-1) { m[nxt[p.second]]-=1; if(m[nxt[p.second]]==0) { pq.push(make_pair(a[nxt[p.second]],nxt[p.second])); } } } cout<<4<<endl; vector<ll> ans; if(ans2.size()>0) { reverse(ans2.begin(),ans2.end()); } if(ans1.size()>0) { for(ll i=0;i<ans1.size();i++) { ans.pb(ans1[i]); } } cout<<4<<endl; if(ans2.size()>0) { for(ll i=0;i<ans2.size();i++) { ans.pb(ans2[i]); } } cout<<5<<endl; cout<<val<<endl; // cout<<"**********\n"; // prv(ans); for(ll el : ans){ cout<<el<<" "; } return 0; }
[ "yashrsharma44@gmail.com" ]
yashrsharma44@gmail.com
e854b30491bb1ed69a63311b63575232e4d8be5f
ce52632a58d2d67e55dbb21d17ceca43d0036fa0
/include/ray/thread.h
7c9740ebca2d9cf83a5efdf69d0a789e0c77b7bc
[ "BSD-3-Clause" ]
permissive
netdebug/ray
b17257fa53afc789802ed1cec28413b82c27ebad
906d3991ddd232a7f78f0e51f29aeead008a139a
refs/heads/master
2020-03-31T12:46:15.214089
2018-06-06T11:06:48
2018-06-06T11:07:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,153
h
// +---------------------------------------------------------------------- // | Project : ray. // | All rights reserved. // +---------------------------------------------------------------------- // | Copyright (c) 2013-2017. // +---------------------------------------------------------------------- // | * Redistribution and use of this software in source and binary forms, // | with or without modification, are permitted provided that the following // | conditions are met: // | // | * Redistributions of source code must retain the above // | copyright notice, this list of conditions and the // | following disclaimer. // | // | * Redistributions in binary form must reproduce the above // | copyright notice, this list of conditions and the // | following disclaimer in the documentation and/or other // | materials provided with the distribution. // | // | * Neither the name of the ray team, nor the names of its // | contributors may be used to endorse or promote products // | derived from this software without specific prior // | written permission of the ray team. // | // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // +---------------------------------------------------------------------- #ifndef _H_THREAD_H_ #define _H_THREAD_H_ #include <ray/platform.h> #include <thread> #include <mutex> #include <atomic> #include <queue> #include <condition_variable> _NAME_BEGIN class EXPORT ThreadLambda final { public: ThreadLambda() noexcept; ~ThreadLambda() noexcept; void start() noexcept; void stop() noexcept; void exce(std::function<void(void)>& func) noexcept; void exce(std::function<void(void)>&& func) noexcept; void join() noexcept; void flush() noexcept; void finish() noexcept; std::exception_ptr exception() const noexcept; private: void signalQuitCond() noexcept; void signalFlushCond() noexcept; void signalFlushFinishCond() noexcept; void waitFlushCond() noexcept; void waitFlushFinishedCond() noexcept; void dispose() noexcept; private: std::mutex _mutex; std::condition_variable _flushRequest; std::condition_variable _finishRequest; std::atomic<bool> _isQuitRequest; std::atomic<bool> _isFlushRequest; std::exception_ptr _exception; std::unique_ptr<std::thread> _thread; std::vector<std::function<void(void)>> _taskUpdate; std::vector<std::function<void(void)>> _taskDispose; }; _NAME_END #endif
[ "2221870259@qq.com" ]
2221870259@qq.com
8635581b4538e392dc0ea7ce2f6b5636cc0d0a39
63c133960f9932356bc888c264756b1e1771347e
/solution/gross_pitaevskii.h
939925409987b252f4407356c13481775b566800
[]
no_license
waylonflinn/fdtl
7f122bc3a41bf16722a90e556f441f4d76877e97
fb30b3299d8a3aad4eeff24765ce01d5d89d2fee
refs/heads/master
2016-09-10T22:15:31.234800
2015-03-13T01:12:45
2015-03-13T01:12:45
32,112,140
2
0
null
null
null
null
UTF-8
C++
false
false
2,232
h
/* a problem representing a finite differencing of the Gross-Pitaevskii * equation (a modified schrodinger equation representing a many body * electrodynamic system) given in cylindrical coordinates. */ #ifndef PDE_GROSS_PITAEVSKII #define PDE_GROSS_PITAEVSKII #include "problem_basic.h" #include "problem_resizable.h" #include "cmath" class gross_pitaevskii : public problem_basic { public: gross_pitaevskii(); // constructors gross_pitaevskii( int I, int J, pair<double, double> range_x, pair<double, double> range_y, const boundary& top, // boundary objects for each boundary const boundary& right, const boundary& bottom, const boundary& left, double coeff_x, double coeff_y, double eigenvalue, double parameter); // methods double a(int i, int j) const { return 1.0-sx/(2*(xm+sx*i));} double b(int i, int j) const { return 1.0+sx/(2*(xm+sx*i));} double c(int i, int j) const { return rss;} double d(int i, int j) const { return rss;} double e(int i, int j) const { return (meig+ast+(p1x+(p2x*i)+(p3x*i*i))+(p1y+(p2y*j)+(p3y*j*j)) + mparm*sol[i-1][j-1]*sol[i-1][j-1]);} double f(int i, int j) const { return 0;} double interaction_parameter() const {return parm;} double r_coefficient() const {return cx; } double z_coefficient() const {return cy; } double r(int i) const {return (xm+(sx*i));} double z(int j) const {return (ym+(sy*j));} void eigenvalue(double eig); void grow(operator_prolong& op); void shrink(operator_restrict& op); gross_pitaevskii clone(); private: double xm, ym; // lower bounds in x and y, resp. double cx; // coefficient to x in potential double cy; // coefficient to y in potential double eig; // eigenvalue double parm; // interaction parameter // intermediates for e(int,int) double meig; // -1*ssx*eig double mparm; /* the following terms represent intermediate values in the computation of the potential term in the two variable */ double p1x; // sx^2*cx*x.first^2 double p2x; // 2*sx^3*cx*x.first double p3x; // sx^4*cx double p1y; // sx^2*cy*y.first^2 double p2y; // 2*sx^2*sy*cy*y.first double p3y; // sx^2*sy^2*cy }; #endif // PDE_GROSS_PITAEVSKII
[ "waylonflinn@users.noreply.github.com" ]
waylonflinn@users.noreply.github.com
fcefe1f6aeb070852645f610192e5f68f4a94a84
2faae2a782ffbe7d7095af5a9c90485921003db9
/RF24.cpp
7a97a2ff51aad055d9a723656f0848a817d8ce03
[]
no_license
darcyg/RF24Mesh
e60c01cf54758cdcefe229e1a6e1e36f3640d31a
300e425214021fff95a0da83753a0ecac81e4f0b
refs/heads/master
2021-01-18T10:47:54.570850
2013-10-09T20:51:17
2013-10-09T20:51:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,283
cpp
/* Copyright (C) 2011 J. Coliz <maniacbug@ymail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. */ #include "nRF24L01.h" #include "RF24_config.h" #include "RF24.h" /****************************************************************************/ void RF24::csn(int mode) { // Minimum ideal SPI bus speed is 2x data rate // If we assume 2Mbs data rate and 16Mhz clock, a // divider of 4 is the minimum we want. // CLK:BUS 8Mhz:2Mhz, 16Mhz:4Mhz, or 20Mhz:5Mhz #ifdef ARDUINO SPI.setBitOrder(MSBFIRST); SPI.setDataMode(SPI_MODE0); SPI.setClockDivider(SPI_CLOCK_DIV4); #endif digitalWrite(csn_pin,mode); } /****************************************************************************/ void RF24::ce(int level) { digitalWrite(ce_pin,level); } /****************************************************************************/ uint8_t RF24::read_register(uint8_t reg, uint8_t* buf, uint8_t len) { uint8_t status; csn(LOW); status = SPI.transfer( R_REGISTER | ( REGISTER_MASK & reg ) ); while ( len-- ) *buf++ = SPI.transfer(0xff); csn(HIGH); return status; } /****************************************************************************/ uint8_t RF24::read_register(uint8_t reg) { csn(LOW); SPI.transfer( R_REGISTER | ( REGISTER_MASK & reg ) ); uint8_t result = SPI.transfer(0xff); csn(HIGH); return result; } /****************************************************************************/ uint8_t RF24::write_register(uint8_t reg, const uint8_t* buf, uint8_t len) { uint8_t status; csn(LOW); status = SPI.transfer( W_REGISTER | ( REGISTER_MASK & reg ) ); while ( len-- ) SPI.transfer(*buf++); csn(HIGH); return status; } /****************************************************************************/ uint8_t RF24::write_register(uint8_t reg, uint8_t value) { uint8_t status; IF_SERIAL_DEBUG(printf_P(PSTR("write_register(%02x,%02x)\r\n"),reg,value)); csn(LOW); status = SPI.transfer( W_REGISTER | ( REGISTER_MASK & reg ) ); SPI.transfer(value); csn(HIGH); return status; } /****************************************************************************/ uint8_t RF24::write_payload(const void* buf, uint8_t len) { uint8_t status; const uint8_t* current = reinterpret_cast<const uint8_t*>(buf); uint8_t data_len = min(len,payload_size); uint8_t blank_len = dynamic_payloads_enabled ? 0 : payload_size - data_len; //printf("[Writing %u bytes %u blanks]",data_len,blank_len); csn(LOW); status = SPI.transfer( W_TX_PAYLOAD ); while ( data_len-- ) SPI.transfer(*current++); while ( blank_len-- ) SPI.transfer(0); csn(HIGH); return status; } /****************************************************************************/ uint8_t RF24::read_payload(void* buf, uint8_t len) { uint8_t status; uint8_t* current = reinterpret_cast<uint8_t*>(buf); uint8_t data_len = min(len,payload_size); uint8_t blank_len = dynamic_payloads_enabled ? 0 : payload_size - data_len; //printf("[Reading %u bytes %u blanks]",data_len,blank_len); csn(LOW); status = SPI.transfer( R_RX_PAYLOAD ); while ( data_len-- ) *current++ = SPI.transfer(0xff); while ( blank_len-- ) SPI.transfer(0xff); csn(HIGH); return status; } /****************************************************************************/ uint8_t RF24::flush_rx(void) { uint8_t status; csn(LOW); status = SPI.transfer( FLUSH_RX ); csn(HIGH); return status; } /****************************************************************************/ uint8_t RF24::flush_tx(void) { uint8_t status; csn(LOW); status = SPI.transfer( FLUSH_TX ); csn(HIGH); return status; } /****************************************************************************/ uint8_t RF24::get_status(void) { uint8_t status; csn(LOW); status = SPI.transfer( NOP ); csn(HIGH); return status; } /****************************************************************************/ void RF24::print_status(uint8_t status) { printf_P(PSTR("STATUS\t\t = 0x%02x RX_DR=%x TX_DS=%x MAX_RT=%x RX_P_NO=%x TX_FULL=%x\r\n"), status, (status & _BV(RX_DR))?1:0, (status & _BV(TX_DS))?1:0, (status & _BV(MAX_RT))?1:0, ((status >> RX_P_NO) & B111), (status & _BV(TX_FULL))?1:0 ); } /****************************************************************************/ void RF24::print_observe_tx(uint8_t value) { printf_P(PSTR("OBSERVE_TX=%02x: POLS_CNT=%x ARC_CNT=%x\r\n"), value, (value >> PLOS_CNT) & B1111, (value >> ARC_CNT) & B1111 ); } /****************************************************************************/ void RF24::print_byte_register(const char* name, uint8_t reg, uint8_t qty) { char extra_tab = strlen_P(name) < 8 ? '\t' : 0; printf_P(PSTR(PRIPSTR"\t%c ="),name,extra_tab); while (qty--) printf_P(PSTR(" 0x%02x"),read_register(reg++)); printf_P(PSTR("\r\n")); } /****************************************************************************/ void RF24::print_address_register(const char* name, uint8_t reg, uint8_t qty) { char extra_tab = strlen_P(name) < 8 ? '\t' : 0; printf_P(PSTR(PRIPSTR"\t%c ="),name,extra_tab); while (qty--) { uint8_t buffer[5]; read_register(reg++,buffer,sizeof buffer); printf_P(PSTR(" 0x")); uint8_t* bufptr = buffer + sizeof buffer; while( --bufptr >= buffer ) printf_P(PSTR("%02x"),*bufptr); } printf_P(PSTR("\r\n")); } /****************************************************************************/ RF24::RF24(uint8_t _cepin, uint8_t _cspin): ce_pin(_cepin), csn_pin(_cspin), wide_band(true), p_variant(false), payload_size(32), ack_payload_available(false), dynamic_payloads_enabled(false), pipe0_reading_address(0) { } /****************************************************************************/ void RF24::setChannel(uint8_t channel) { // TODO: This method could take advantage of the 'wide_band' calculation // done in setChannel() to require certain channel spacing. const uint8_t max_channel = 127; write_register(RF_CH,min(channel,max_channel)); } /****************************************************************************/ void RF24::setPayloadSize(uint8_t size) { const uint8_t max_payload_size = 32; payload_size = min(size,max_payload_size); } /****************************************************************************/ uint8_t RF24::getPayloadSize(void) { return payload_size; } /****************************************************************************/ static const char rf24_datarate_e_str_0[] PROGMEM = "1MBPS"; static const char rf24_datarate_e_str_1[] PROGMEM = "2MBPS"; static const char rf24_datarate_e_str_2[] PROGMEM = "250KBPS"; static const char * const rf24_datarate_e_str_P[] PROGMEM = { rf24_datarate_e_str_0, rf24_datarate_e_str_1, rf24_datarate_e_str_2, }; static const char rf24_model_e_str_0[] PROGMEM = "nRF24L01"; static const char rf24_model_e_str_1[] PROGMEM = "nRF24L01+"; static const char * const rf24_model_e_str_P[] PROGMEM = { rf24_model_e_str_0, rf24_model_e_str_1, }; static const char rf24_crclength_e_str_0[] PROGMEM = "Disabled"; static const char rf24_crclength_e_str_1[] PROGMEM = "8 bits"; static const char rf24_crclength_e_str_2[] PROGMEM = "16 bits" ; static const char * const rf24_crclength_e_str_P[] PROGMEM = { rf24_crclength_e_str_0, rf24_crclength_e_str_1, rf24_crclength_e_str_2, }; static const char rf24_pa_dbm_e_str_0[] PROGMEM = "PA_MIN"; static const char rf24_pa_dbm_e_str_1[] PROGMEM = "PA_LOW"; static const char rf24_pa_dbm_e_str_2[] PROGMEM = "LA_MED"; static const char rf24_pa_dbm_e_str_3[] PROGMEM = "PA_HIGH"; static const char * const rf24_pa_dbm_e_str_P[] PROGMEM = { rf24_pa_dbm_e_str_0, rf24_pa_dbm_e_str_1, rf24_pa_dbm_e_str_2, rf24_pa_dbm_e_str_3, }; void RF24::printDetails(void) { print_status(get_status()); print_address_register(PSTR("RX_ADDR_P0-1"),RX_ADDR_P0,2); print_byte_register(PSTR("RX_ADDR_P2-5"),RX_ADDR_P2,4); print_address_register(PSTR("TX_ADDR"),TX_ADDR); print_byte_register(PSTR("RX_PW_P0-6"),RX_PW_P0,6); print_byte_register(PSTR("EN_AA"),EN_AA); print_byte_register(PSTR("EN_RXADDR"),EN_RXADDR); print_byte_register(PSTR("RF_CH"),RF_CH); print_byte_register(PSTR("RF_SETUP"),RF_SETUP); print_byte_register(PSTR("CONFIG"),CONFIG); print_byte_register(PSTR("DYNPD/FEATURE"),DYNPD,2); printf_P(PSTR("Data Rate\t = %S\r\n"),pgm_read_word(&rf24_datarate_e_str_P[getDataRate()])); printf_P(PSTR("Model\t\t = %S\r\n"),pgm_read_word(&rf24_model_e_str_P[isPVariant()])); printf_P(PSTR("CRC Length\t = %S\r\n"),pgm_read_word(&rf24_crclength_e_str_P[getCRCLength()])); printf_P(PSTR("PA Power\t = %S\r\n"),pgm_read_word(&rf24_pa_dbm_e_str_P[getPALevel()])); } /****************************************************************************/ void RF24::begin(void) { // Initialize pins pinMode(ce_pin,OUTPUT); pinMode(csn_pin,OUTPUT); // Initialize SPI bus SPI.begin(); ce(LOW); csn(HIGH); // Must allow the radio time to settle else configuration bits will not necessarily stick. // This is actually only required following power up but some settling time also appears to // be required after resets too. For full coverage, we'll always assume the worst. // Enabling 16b CRC is by far the most obvious case if the wrong timing is used - or skipped. // Technically we require 4.5ms + 14us as a worst case. We'll just call it 5ms for good measure. // WARNING: Delay is based on P-variant whereby non-P *may* require different timing. delay( 5 ) ; // Set 1500uS (minimum for 32B payload in ESB@250KBPS) timeouts, to make testing a little easier // WARNING: If this is ever lowered, either 250KBS mode with AA is broken or maximum packet // sizes must never be used. See documentation for a more complete explanation. write_register(SETUP_RETR,(B0100 << ARD) | (B1111 << ARC)); // Restore our default PA level setPALevel( RF24_PA_MAX ) ; // Determine if this is a p or non-p RF24 module and then // reset our data rate back to default value. This works // because a non-P variant won't allow the data rate to // be set to 250Kbps. if( setDataRate( RF24_250KBPS ) ) { p_variant = true ; } // Then set the data rate to the slowest (and most reliable) speed supported by all // hardware. setDataRate( RF24_1MBPS ) ; // Initialize CRC and request 2-byte (16bit) CRC setCRCLength( RF24_CRC_16 ) ; // Disable dynamic payloads, to match dynamic_payloads_enabled setting write_register(DYNPD,0); // Reset current status // Notice reset and flush is the last thing we do write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); // Set up default configuration. Callers can always change it later. // This channel should be universally safe and not bleed over into adjacent // spectrum. setChannel(76); // Flush buffers flush_rx(); flush_tx(); } /****************************************************************************/ void RF24::startListening(void) { printf_P(PSTR("start listening\n\r")); write_register(CONFIG, read_register(CONFIG) | _BV(PWR_UP) | _BV(PRIM_RX)); write_register(STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); // Restore the pipe0 adddress, if exists if (pipe0_reading_address) write_register(RX_ADDR_P0, reinterpret_cast<const uint8_t*>(&pipe0_reading_address), 5); // Flush buffers flush_rx(); flush_tx(); // Go! ce(HIGH); // wait for the radio to come up (130us actually only needed) delayMicroseconds(130); } /****************************************************************************/ void RF24::stopListening(void) { printf_P(PSTR("stop listening\n\r")); ce(LOW); flush_tx(); flush_rx(); } /****************************************************************************/ void RF24::powerDown(void) { write_register(CONFIG,read_register(CONFIG) & ~_BV(PWR_UP)); } /****************************************************************************/ void RF24::powerUp(void) { write_register(CONFIG,read_register(CONFIG) | _BV(PWR_UP)); } /******************************************************************/ bool RF24::write( const void* buf, uint8_t len ) { bool result = false; // Begin the write startWrite(buf,len); // ------------ // At this point we could return from a non-blocking write, and then call // the rest after an interrupt // Instead, we are going to block here until we get TX_DS (transmission completed and ack'd) // or MAX_RT (maximum retries, transmission failed). Also, we'll timeout in case the radio // is flaky and we get neither. // IN the end, the send should be blocking. It comes back in 60ms worst case, or much faster // if I tighted up the retry logic. (Default settings will be 1500us. // Monitor the send uint8_t observe_tx; uint8_t status; uint32_t sent_at = millis(); const uint32_t timeout = 500; //ms to wait for timeout do { status = read_register(OBSERVE_TX,&observe_tx,1); //print_observe_tx( observe_tx);//,HEX)); } while( ! ( status & ( _BV(TX_DS) | _BV(MAX_RT) ) ) && ( millis() - sent_at < timeout ) ); // The part above is what you could recreate with your own interrupt handler, // and then call this when you got an interrupt // ------------ // Call this when you get an interrupt // The status tells us three things // * The send was successful (TX_DS) // * The send failed, too many retries (MAX_RT) // * There is an ack packet waiting (RX_DR) bool tx_ok, tx_fail; whatHappened(tx_ok,tx_fail,ack_payload_available); //Serial.printf("What happened:%u%u%u\r\n",tx_ok,tx_fail,ack_payload_available); result = tx_ok; IF_SERIAL_DEBUG(Serial.print(result?"...OK.":"...Failed")); // Handle the ack packet if ( ack_payload_available ) { ack_payload_length = getDynamicPayloadSize(); IF_SERIAL_DEBUG(Serial.print("[AckPacket]/")); IF_SERIAL_DEBUG(Serial.println(ack_payload_length,DEC)); } // Yay, we are done. // Power down powerDown(); // Flush buffers (Is this a relic of past experimentation, and not needed anymore??) flush_tx(); return result; } /****************************************************************************/ void RF24::startWrite( const void* buf, uint8_t len ) { // Transmitter power-up write_register(CONFIG, ( read_register(CONFIG) | _BV(PWR_UP) ) & ~_BV(PRIM_RX) ); delayMicroseconds(150); // Send the payload write_payload( buf, len ); // Allons! ce(HIGH); delayMicroseconds(15); ce(LOW); } /****************************************************************************/ uint8_t RF24::getDynamicPayloadSize(void) { uint8_t result = 0; csn(LOW); SPI.transfer( R_RX_PL_WID ); result = SPI.transfer(0xff); csn(HIGH); return result; } /****************************************************************************/ bool RF24::available(void) { return available(NULL); } /****************************************************************************/ bool RF24::available(uint8_t* pipe_num) { uint8_t status = get_status(); // Too noisy, enable if you really want lots o data!! //IF_SERIAL_DEBUG(print_status(status)); bool result = ( status & _BV(RX_DR) ); if (result) { IF_SERIAL_DEBUG(printf_P(PSTR("%lu:rx data available\n\r"), millis())); // If the caller wants the pipe number, include that if ( pipe_num ) *pipe_num = ( status >> RX_P_NO ) & B111; // Clear the status bit // ??? Should this REALLY be cleared now? Or wait until we // actually READ the payload? write_register(STATUS,_BV(RX_DR) ); // Handle ack payload receipt if ( status & _BV(TX_DS) ) { write_register(STATUS,_BV(TX_DS)); } } return result; } /****************************************************************************/ bool RF24::read( void* buf, uint8_t len ) { // Fetch the payload read_payload( buf, len ); // was this the last of the data available? return read_register(FIFO_STATUS) & _BV(RX_EMPTY); } /****************************************************************************/ void RF24::whatHappened(bool& tx_ok,bool& tx_fail,bool& rx_ready) { // Read the status & reset the status in one easy call // Or is that such a good idea? uint8_t status = write_register(STATUS,_BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) ); // Report to the user what happened tx_ok = status & _BV(TX_DS); tx_fail = status & _BV(MAX_RT); rx_ready = status & _BV(RX_DR); } /****************************************************************************/ void RF24::openWritingPipe(uint64_t value) { // Note that AVR 8-bit uC's store this LSB first, and the NRF24L01(+) // expects it LSB first too, so we're good. write_register(RX_ADDR_P0, reinterpret_cast<uint8_t*>(&value), 5); write_register(TX_ADDR, reinterpret_cast<uint8_t*>(&value), 5); const uint8_t max_payload_size = 32; write_register(RX_PW_P0,min(payload_size,max_payload_size)); } /****************************************************************************/ static const uint8_t child_pipe[] PROGMEM = { RX_ADDR_P0, RX_ADDR_P1, RX_ADDR_P2, RX_ADDR_P3, RX_ADDR_P4, RX_ADDR_P5 }; static const uint8_t child_payload_size[] PROGMEM = { RX_PW_P0, RX_PW_P1, RX_PW_P2, RX_PW_P3, RX_PW_P4, RX_PW_P5 }; static const uint8_t child_pipe_enable[] PROGMEM = { ERX_P0, ERX_P1, ERX_P2, ERX_P3, ERX_P4, ERX_P5 }; void RF24::openReadingPipe(uint8_t child, uint64_t address) { printf_P(PSTR("RF24 openReadingPipe: child: %d addres:%lu\n\r"),child, address); // If this is pipe 0, cache the address. This is needed because // openWritingPipe() will overwrite the pipe 0 address, so // startListening() will have to restore it. if (child == 0) pipe0_reading_address = address; if (child <= 6) { // For pipes 2-5, only write the LSB if ( child < 2 ) write_register(pgm_read_byte(&child_pipe[child]), reinterpret_cast<const uint8_t*>(&address), 5); else write_register(pgm_read_byte(&child_pipe[child]), reinterpret_cast<const uint8_t*>(&address), 1); write_register(pgm_read_byte(&child_payload_size[child]),payload_size); // Note it would be more efficient to set all of the bits for all open // pipes at once. However, I thought it would make the calling code // more simple to do it this way. write_register(EN_RXADDR,read_register(EN_RXADDR) | _BV(pgm_read_byte(&child_pipe_enable[child]))); } } /****************************************************************************/ void RF24::toggle_features(void) { csn(LOW); SPI.transfer( ACTIVATE ); SPI.transfer( 0x73 ); csn(HIGH); } /****************************************************************************/ void RF24::enableDynamicPayloads(void) { // Enable dynamic payload throughout the system write_register(FEATURE,read_register(FEATURE) | _BV(EN_DPL) ); // If it didn't work, the features are not enabled if ( ! read_register(FEATURE) ) { // So enable them and try again toggle_features(); write_register(FEATURE,read_register(FEATURE) | _BV(EN_DPL) ); } IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE))); // Enable dynamic payload on all pipes // // Not sure the use case of only having dynamic payload on certain // pipes, so the library does not support it. write_register(DYNPD,read_register(DYNPD) | _BV(DPL_P5) | _BV(DPL_P4) | _BV(DPL_P3) | _BV(DPL_P2) | _BV(DPL_P1) | _BV(DPL_P0)); dynamic_payloads_enabled = true; } /****************************************************************************/ void RF24::enableAckPayload(void) { // // enable ack payload and dynamic payload features // write_register(FEATURE,read_register(FEATURE) | _BV(EN_ACK_PAY) | _BV(EN_DPL) ); // If it didn't work, the features are not enabled if ( ! read_register(FEATURE) ) { // So enable them and try again toggle_features(); write_register(FEATURE,read_register(FEATURE) | _BV(EN_ACK_PAY) | _BV(EN_DPL) ); } IF_SERIAL_DEBUG(printf("FEATURE=%i\r\n",read_register(FEATURE))); // // Enable dynamic payload on pipes 0 & 1 // write_register(DYNPD,read_register(DYNPD) | _BV(DPL_P1) | _BV(DPL_P0)); } /****************************************************************************/ void RF24::writeAckPayload(uint8_t pipe, const void* buf, uint8_t len) { const uint8_t* current = reinterpret_cast<const uint8_t*>(buf); csn(LOW); SPI.transfer( W_ACK_PAYLOAD | ( pipe & B111 ) ); const uint8_t max_payload_size = 32; uint8_t data_len = min(len,max_payload_size); while ( data_len-- ) SPI.transfer(*current++); csn(HIGH); } /****************************************************************************/ bool RF24::isAckPayloadAvailable(void) { bool result = ack_payload_available; ack_payload_available = false; return result; } /****************************************************************************/ bool RF24::isPVariant(void) { return p_variant ; } /****************************************************************************/ void RF24::setAutoAck(bool enable) { if ( enable ) write_register(EN_AA, B111111); else write_register(EN_AA, 0); } /****************************************************************************/ void RF24::setAutoAck( uint8_t pipe, bool enable ) { if ( pipe <= 6 ) { uint8_t en_aa = read_register( EN_AA ) ; if( enable ) { en_aa |= _BV(pipe) ; } else { en_aa &= ~_BV(pipe) ; } write_register( EN_AA, en_aa ) ; } } /****************************************************************************/ bool RF24::testCarrier(void) { return ( read_register(CD) & 1 ); } /****************************************************************************/ bool RF24::testRPD(void) { return ( read_register(RPD) & 1 ) ; } /****************************************************************************/ void RF24::setPALevel(rf24_pa_dbm_e level) { uint8_t setup = read_register(RF_SETUP) ; setup &= ~(_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ; // switch uses RAM (evil!) if ( level == RF24_PA_MAX ) { setup |= (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ; } else if ( level == RF24_PA_HIGH ) { setup |= _BV(RF_PWR_HIGH) ; } else if ( level == RF24_PA_LOW ) { setup |= _BV(RF_PWR_LOW); } else if ( level == RF24_PA_MIN ) { // nothing } else if ( level == RF24_PA_ERROR ) { // On error, go to maximum PA setup |= (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ; } write_register( RF_SETUP, setup ) ; } /****************************************************************************/ rf24_pa_dbm_e RF24::getPALevel(void) { rf24_pa_dbm_e result = RF24_PA_ERROR ; uint8_t power = read_register(RF_SETUP) & (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ; // switch uses RAM (evil!) if ( power == (_BV(RF_PWR_LOW) | _BV(RF_PWR_HIGH)) ) { result = RF24_PA_MAX ; } else if ( power == _BV(RF_PWR_HIGH) ) { result = RF24_PA_HIGH ; } else if ( power == _BV(RF_PWR_LOW) ) { result = RF24_PA_LOW ; } else { result = RF24_PA_MIN ; } return result ; } /****************************************************************************/ bool RF24::setDataRate(rf24_datarate_e speed) { bool result = false; uint8_t setup = read_register(RF_SETUP) ; // HIGH and LOW '00' is 1Mbs - our default wide_band = false ; setup &= ~(_BV(RF_DR_LOW) | _BV(RF_DR_HIGH)) ; if( speed == RF24_250KBPS ) { // Must set the RF_DR_LOW to 1; RF_DR_HIGH (used to be RF_DR) is already 0 // Making it '10'. wide_band = false ; setup |= _BV( RF_DR_LOW ) ; } else { // Set 2Mbs, RF_DR (RF_DR_HIGH) is set 1 // Making it '01' if ( speed == RF24_2MBPS ) { wide_band = true ; setup |= _BV(RF_DR_HIGH); } else { // 1Mbs wide_band = false ; } } write_register(RF_SETUP,setup); // Verify our result if ( read_register(RF_SETUP) == setup ) { result = true; } else { wide_band = false; } return result; } /****************************************************************************/ rf24_datarate_e RF24::getDataRate( void ) { rf24_datarate_e result ; uint8_t dr = read_register(RF_SETUP) & (_BV(RF_DR_LOW) | _BV(RF_DR_HIGH)); // switch uses RAM (evil!) // Order matters in our case below if ( dr == _BV(RF_DR_LOW) ) { // '10' = 250KBPS result = RF24_250KBPS ; } else if ( dr == _BV(RF_DR_HIGH) ) { // '01' = 2MBPS result = RF24_2MBPS ; } else { // '00' = 1MBPS result = RF24_1MBPS ; } return result ; } /****************************************************************************/ void RF24::setCRCLength(rf24_crclength_e length) { uint8_t config = read_register(CONFIG) & ~( _BV(CRCO) | _BV(EN_CRC)) ; // switch uses RAM (evil!) if ( length == RF24_CRC_DISABLED ) { // Do nothing, we turned it off above. } else if ( length == RF24_CRC_8 ) { config |= _BV(EN_CRC); } else { config |= _BV(EN_CRC); config |= _BV( CRCO ); } write_register( CONFIG, config ) ; } /****************************************************************************/ rf24_crclength_e RF24::getCRCLength(void) { rf24_crclength_e result = RF24_CRC_DISABLED; uint8_t config = read_register(CONFIG) & ( _BV(CRCO) | _BV(EN_CRC)) ; if ( config & _BV(EN_CRC ) ) { if ( config & _BV(CRCO) ) result = RF24_CRC_16; else result = RF24_CRC_8; } return result; } /****************************************************************************/ void RF24::disableCRC( void ) { uint8_t disable = read_register(CONFIG) & ~_BV(EN_CRC) ; write_register( CONFIG, disable ) ; } /****************************************************************************/ void RF24::setRetries(uint8_t delay, uint8_t count) { write_register(SETUP_RETR,(delay&0xf)<<ARD | (count&0xf)<<ARC); } // vim:ai:cin:sts=2 sw=2 ft=cpp
[ "gcanitezer@gmail.com" ]
gcanitezer@gmail.com
cf3ea6a79138b1ed5a5ecc7afbf62774f2aadcc7
cda59d05223059755636633b6d6298d3c56b36ce
/internal_hvh/sdk/interfaces/IMaterialSystem.h
6d8a83eb887d3e212f61597e916e878ead013346
[]
no_license
CSGOLeaks/Fatality-2018
f41c0fa03fb070a0a02446d36d076e87630f29f3
d00c4262e5d169bc3818c4faed035ea9039d6c29
refs/heads/main
2023-01-25T03:02:21.590854
2020-11-19T13:25:37
2020-11-19T13:25:37
314,255,162
4
3
null
null
null
null
UTF-8
C++
false
false
2,714
h
#pragma once typedef unsigned short MaterialHandle_t; struct MaterialVideoMode_t { int m_Width; int m_Height; int m_Format; int m_RefreshRate; }; struct MaterialSystem_Config_t { MaterialVideoMode_t m_VideoMode; float m_fMonitorGamma; float m_fGammaTVRangeMin; float m_fGammaTVRangeMax; float m_fGammaTVExponent; bool m_bGammaTVEnabled; bool m_bTripleBuffered; int m_nAASamples; int m_nForceAnisotropicLevel; int m_nSkipMipLevels; int m_nDxSupportLevel; int m_nFlags; bool m_bEditMode; char m_nProxiesTestMode; bool m_bCompressedTextures; bool m_bFilterLightmaps; bool m_bFilterTextures; bool m_bReverseDepth; bool m_bBufferPrimitives; bool m_bDrawFlat; bool m_bMeasureFillRate; bool m_bVisualizeFillRate; bool m_bNoTransparency; bool m_bSoftwareLighting; bool m_bAllowCheats; char m_nShowMipLevels; bool m_bShowLowResImage; bool m_bShowNormalMap; bool m_bMipMapTextures; char m_nFullbright; bool m_bFastNoBump; bool m_bSuppressRendering; bool m_bDrawGray; bool m_bShowSpecular; bool m_bShowDiffuse; int m_nWindowedSizeLimitWidth; int m_nWindowedSizeLimitHeight; int m_nAAQuality; bool m_bShadowDepthTexture; bool m_bMotionBlur; bool m_bSupportFlashlight; bool m_bPaintEnabled; char pad[ 0xC ]; }; class IMatRenderContext; class ITexture; class IMaterialSystem { public: VFUNC( 21, OverrideConfig( const MaterialSystem_Config_t& cfg, bool b ), bool( __thiscall* )( void*, const MaterialSystem_Config_t&, bool ) )( cfg, b ) VFUNC( 36, GetBackBufferFormat(), ImageFormat( __thiscall* )( void* ) )( ) VFUNC( 84, FindMaterial( const char* name, const char *texgroup, bool complain = true, const char *complainprefix = nullptr ), IMaterial*( __thiscall* )( void*, const char*, const char*, bool, const char* ) )( name, texgroup, complain, complainprefix ) VFUNC( 86, FirstMaterial(), MaterialHandle_t( __thiscall* )( void* ) )( ) VFUNC( 87, NextMaterial( MaterialHandle_t h ), MaterialHandle_t( __thiscall* )( void*, MaterialHandle_t ) )( h ) VFUNC( 88, InvalidMaterial(), MaterialHandle_t( __thiscall* )( void* ) )( ) VFUNC( 89, GetMaterial( MaterialHandle_t h ), IMaterial* ( __thiscall* )( void*, MaterialHandle_t ) )( h ) VFUNC( 90, GetNumMaterials(), int( __thiscall* )( void* ) )( ) VFUNC( 91, FindTexture( const char* name, const char *groupname, bool complain ), ITexture*( __thiscall* )( void*, const char*, const char*, bool ) )( name, groupname, complain ) VFUNC( 94, BeginRenderTargetAllocation(), void( __thiscall* )( void* ) )( ) VFUNC( 95, EndRenderTargetAllocation(), void( __thiscall* )( void* ) )( ) VFUNC( 115, GetRenderContext(), IMatRenderContext*( __thiscall* )( void* ) )( ) }; extern IMaterialSystem* g_pMaterialSystem;
[ "autocardag@gmail.com" ]
autocardag@gmail.com
22b13ff7d111fd0b483556bfc8518658d94b06f1
2d000b353e54ebb6f55d281d567f46be369b8cc6
/src/python/magnum/scenegraph.cpp
25563ba6ccc78790dd27669085ee0fc24c36055b
[ "MIT" ]
permissive
mosra/magnum-bindings
cb31ab52501bed22eddfa3d4688de56e902f22d8
93f9eb814bf8532129e1fa4a241bca3a0b69e4e6
refs/heads/master
2023-08-02T22:54:48.539927
2023-07-23T10:49:03
2023-07-23T10:49:03
184,422,650
20
11
NOASSERTION
2022-11-29T23:17:22
2019-05-01T13:46:31
C++
UTF-8
C++
false
false
10,697
cpp
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Vladimír Vondruš <mosra@centrum.cz> 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 <pybind11/pybind11.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/SceneGraph/Drawable.h> #include <Magnum/SceneGraph/AbstractObject.h> #include "magnum/scenegraph.h" namespace magnum { namespace { template<UnsignedInt dimensions, class T> struct PyDrawable: SceneGraph::PyFeature<SceneGraph::Drawable<dimensions, T>> { explicit PyDrawable(SceneGraph::AbstractObject<dimensions, T>& object, SceneGraph::DrawableGroup<dimensions, T>* drawables): SceneGraph::PyFeature<SceneGraph::Drawable<dimensions, T>>{object, drawables} {} void draw(const MatrixTypeFor<dimensions, T>& transformationMatrix, SceneGraph::Camera<dimensions, T>& camera) override { PYBIND11_OVERLOAD_PURE_NAME( void, PyDrawable, "draw", draw, transformationMatrix, camera ); } }; template<UnsignedInt dimensions, class T> void abstractObject(py::class_<SceneGraph::AbstractObject<dimensions, T>, SceneGraph::PyObjectHolder<SceneGraph::AbstractObject<dimensions, T>>>& c) { c /* Matrix transformation APIs */ .def("transformation_matrix", &SceneGraph::AbstractObject<dimensions, T>::transformationMatrix, "Transformation matrix") .def("absolute_transformation_matrix", &SceneGraph::AbstractObject<dimensions, T>::absoluteTransformationMatrix, "Transformation matrix relative to the root object"); } template<class PyFeature, UnsignedInt dimensions, class Feature, class T> void featureGroup(py::class_<SceneGraph::FeatureGroup<dimensions, Feature, T>>& c) { c .def(py::init(), "Constructor") .def("__len__", &SceneGraph::FeatureGroup<dimensions, Feature, T>::size, "Count of features in the group") /* Get item. Fetching the already registered instance and returning that instead of wrapping the pointer again. Need to raise IndexError in order to allow iteration: https://docs.python.org/3/reference/datamodel.html#object.__getitem__ */ .def("__getitem__", [](SceneGraph::FeatureGroup<dimensions, Feature, T>& self, std::size_t index) -> PyFeature& { if(index >= self.size()) { PyErr_SetNone(PyExc_IndexError); throw py::error_already_set{}; } return static_cast<PyFeature&>(self[index]); }, "Feature at given index") .def("add", [](SceneGraph::FeatureGroup<dimensions, Feature, T>& self, PyFeature& feature) { self.add(feature); }, "Add a feature to the group") .def("remove", [](SceneGraph::FeatureGroup<dimensions, Feature, T>& self, PyFeature& feature) { self.add(feature); }, "Remove a feature from the group"); } template<UnsignedInt dimensions, class T> void feature(py::class_<SceneGraph::AbstractFeature<dimensions, T>, SceneGraph::PyFeature<SceneGraph::AbstractFeature<dimensions, T>>, SceneGraph::PyFeatureHolder<SceneGraph::AbstractFeature<dimensions, T>>>& c) { c .def(py::init_alias<SceneGraph::AbstractObject<dimensions, T>&>(), "Constructor", py::arg("object")) .def_property_readonly("object", [](SceneGraph::AbstractFeature<dimensions, T>& self) -> SceneGraph::AbstractObject<dimensions, T>& { return self.object(); }, "Object holding this feature"); } template<UnsignedInt dimensions, class T> void drawable(py::class_<SceneGraph::Drawable<dimensions, T>, SceneGraph::AbstractFeature<dimensions, T>, PyDrawable<dimensions, T>, SceneGraph::PyFeatureHolder<SceneGraph::Drawable<dimensions, T>>>& c) { c .def(py::init_alias<SceneGraph::AbstractObject<dimensions, T>&, SceneGraph::DrawableGroup<dimensions, T>*>(), "Constructor", py::arg("object"), py::arg("drawables") = nullptr) .def_property_readonly("drawables", [](PyDrawable<dimensions, T>& self) { return self.drawables(); }, "Group containing this drawable") .def("draw", [](PyDrawable<dimensions, T>& self, const MatrixTypeFor<dimensions, T>& transformationMatrix, SceneGraph::Camera<dimensions, T>& camera) { self.draw(transformationMatrix, camera); }, "Draw the object using given camera", py::arg("transformation_matrix"), py::arg("camera")); } template<UnsignedInt dimensions, class T> void camera(py::class_<SceneGraph::Camera<dimensions, T>, SceneGraph::AbstractFeature<dimensions, T>, SceneGraph::PyFeature<SceneGraph::Camera<dimensions, T>>, SceneGraph::PyFeatureHolder<SceneGraph::Camera<dimensions, T>>>& c) { c .def(py::init_alias<SceneGraph::AbstractObject<dimensions, T>&>(), "Constructor", py::arg("object")) .def_property("aspect_ratio_policy", &SceneGraph::Camera<dimensions, T>::aspectRatioPolicy, /* Using a lambda because the setter has method chaining */ [](SceneGraph::Camera<dimensions, T>& self, SceneGraph::AspectRatioPolicy policy) { self.setAspectRatioPolicy(policy); }, "Aspect ratio policy") .def_property_readonly("camera_matrix", &SceneGraph::Camera<dimensions, T>::cameraMatrix, "Camera matrix") .def_property("projection_matrix", &SceneGraph::Camera<dimensions, T>::projectionMatrix, /* Using a lambda because the setter has method chaining */ [](SceneGraph::Camera<dimensions, T>& self, const MatrixTypeFor<dimensions, T>& matrix) { self.setProjectionMatrix(matrix); }, "Projection matrix") .def("projection_size", &SceneGraph::Camera<dimensions, T>::projectionSize, "Size of (near) XY plane in current projection") .def_property("viewport", &SceneGraph::Camera<dimensions, T>::viewport, &SceneGraph::Camera<dimensions, T>::setViewport, "Viewport size") .def("draw", static_cast<void(SceneGraph::Camera<dimensions, T>::*)(SceneGraph::DrawableGroup<dimensions, T>&)>(&SceneGraph::Camera<dimensions, T>::draw), "Draw"); } } void scenegraph(py::module_& m) { m.doc() = "Scene graph library"; /* Abstract objects. Returned from feature.object, so need to be registered as well. */ { py::class_<SceneGraph::AbstractObject2D, SceneGraph::PyObjectHolder<SceneGraph::AbstractObject2D>> abstractObject2D{m, "AbstractObject2D", "Base object for two-dimensional scenes"}; py::class_<SceneGraph::AbstractObject3D, SceneGraph::PyObjectHolder<SceneGraph::AbstractObject3D>> abstractObject3D{m, "AbstractObject3D", "Base object for three-dimensional scenes"}; abstractObject(abstractObject2D); abstractObject(abstractObject3D); } /* Drawables, camera */ { py::enum_<SceneGraph::AspectRatioPolicy>{m, "AspectRatioPolicy", "Camera aspect ratio policy"} .value("NOT_PRESERVED", SceneGraph::AspectRatioPolicy::NotPreserved) .value("EXTEND", SceneGraph::AspectRatioPolicy::Extend) .value("CLIP", SceneGraph::AspectRatioPolicy::Clip); py::class_<SceneGraph::DrawableGroup2D> drawableGroup2D{m, "DrawableGroup2D", "Group of drawables for two-dimensional float scenes"}; py::class_<SceneGraph::DrawableGroup3D> drawableGroup3D{m, "DrawableGroup3D", "Group of drawables for three-dimensional float scenes"}; py::class_<SceneGraph::AbstractFeature2D, SceneGraph::PyFeature<SceneGraph::AbstractFeature2D>, SceneGraph::PyFeatureHolder<SceneGraph::AbstractFeature2D>> feature2D{m, "AbstractFeature2D", "Base for two-dimensional float features"}; py::class_<SceneGraph::AbstractFeature3D, SceneGraph::PyFeature<SceneGraph::AbstractFeature3D>, SceneGraph::PyFeatureHolder<SceneGraph::AbstractFeature3D>> feature3D{m, "AbstractFeature3D", "Base for three-dimensional float features"}; feature(feature2D); feature(feature3D); py::class_<SceneGraph::Drawable2D, SceneGraph::AbstractFeature2D, PyDrawable<2, Float>, SceneGraph::PyFeatureHolder<SceneGraph::Drawable2D>> drawable2D{m, "Drawable2D", "Drawable for two-dimensional float scenes"}; py::class_<SceneGraph::Drawable3D, SceneGraph::AbstractFeature3D, PyDrawable<3, Float>, SceneGraph::PyFeatureHolder<SceneGraph::Drawable3D>> drawable3D{m, "Drawable3D", "Drawable for three-dimensional float scenes"}; py::class_<SceneGraph::Camera2D, SceneGraph::AbstractFeature2D, SceneGraph::PyFeature<SceneGraph::Camera2D>, SceneGraph::PyFeatureHolder<SceneGraph::Camera2D>> camera2D{m, "Camera2D", "Camera for two-dimensional float scenes"}; py::class_<SceneGraph::Camera3D, SceneGraph::AbstractFeature3D, SceneGraph::PyFeature<SceneGraph::Camera3D>, SceneGraph::PyFeatureHolder<SceneGraph::Camera3D>> camera3D{m, "Camera3D", "Camera for three-dimensional float scenes"}; featureGroup<PyDrawable<2, Float>>(drawableGroup2D); featureGroup<PyDrawable<3, Float>>(drawableGroup3D); drawable(drawable2D); drawable(drawable3D); camera(camera2D); camera(camera3D); } /* Concrete transformation implementations */ magnum::scenegraphMatrix(m); magnum::scenegraphTrs(m); } } #ifndef MAGNUM_BUILD_STATIC /* TODO: remove declaration when https://github.com/pybind/pybind11/pull/1863 is released */ extern "C" PYBIND11_EXPORT PyObject* PyInit_scenegraph(); PYBIND11_MODULE(scenegraph, m) { magnum::scenegraph(m); } #endif
[ "mosra@centrum.cz" ]
mosra@centrum.cz
4e8a133e8b73c82beb26d5468a2a55f878f0339e
311e0608b4005865b90eb153d961b8758ba6de28
/LAB 3/GeometryHomework3.cpp
64df8832dcd473cc75fc0d53953f1774aaa4d0e7
[]
no_license
JPL4494/DVC-COMSC200
e71c9c46b33bd4886932ee87c0be31e581cb8c3e
c76a7f087b353ba16fdac9a1b0ba27e972daa5f0
refs/heads/master
2020-03-19T00:25:03.075887
2018-05-30T19:23:33
2018-05-30T19:23:33
135,479,290
0
0
null
null
null
null
UTF-8
C++
false
false
7,631
cpp
/* Lab 3b, The third version of the geometry homework Program Programmer: Joshua Long Editor used: Notepad Compiler used: CodeBlocks */ #include<iostream> using std::cout; using std::endl; using std::ios; #include <fstream> using std::fstream; #include<iomanip> using std::setprecision; #include<string> using std::string; #include<cstdlib> #include<cstring> const float pi = 3.14159265359; const int MAX_CHARS_PER_LINE = 512; const int MAX_TOKENS_PER_LINE = 4; const char * const DELIMITER = " "; class Square { double side; public: Square(const char* []); void print(); }; Square::Square(const char* token[]) { side = token[1] ? atof(token[1]) : 0; } class Rectangle { double length; double width; public: Rectangle(const char* []); void print(); }; Rectangle::Rectangle(const char* token[]) { length = token[1] ? atof(token[1]) : 0; width = token[2] ? atof(token[2]) : 0; } class Circle { double radius; public: Circle(const char* []); void print(); }; Circle::Circle(const char* token[]) { radius = token[1] ? atof(token[1]) : 0; } class Cube { double side; public: Cube(const char* []); void print(); }; Cube::Cube(const char* token[]) { side = token[1] ? atof(token[1]) : 0; } class Prism { double length; double width; double height; public: Prism(const char* []); void print(); }; Prism::Prism(const char* token[]) { length = token[1] ? atof(token[1]) : 0; width = token[2] ? atof(token[2]) : 0; height = token[3] ? atof(token[3]) : 0; } class Cylinder { double radius; double height; public: Cylinder(const char* []); void print(); }; Cylinder::Cylinder(const char* token[]) { radius = token[1] ? atof(token[1]) : 0; height = token[2] ? atof(token[2]) : 0; } int main() { fstream source; source.open("geo.txt", ios::in); cout << "Lab 3b, The geometry homework Program" << endl; cout << "Programmer: Joshua Long" << endl; cout << "Editor used: Notepad" << endl; cout << "Compiler used: CodeBlocks" << endl; cout << "File: " << __FILE__ << endl; cout << "Compiled: " << __DATE__ << " at " << __TIME__ << endl << endl; int counter = 0; int shapeID[100]; const void * shapes[100]; if (source.fail()) { cout << "ERROR-No file to get information from!"; exit(EXIT_FAILURE); } while (!source.eof()) { char buf [MAX_CHARS_PER_LINE]; source.getline(buf, MAX_CHARS_PER_LINE); int n = 0; const char * token[MAX_TOKENS_PER_LINE] = {}; token[0] = strtok(buf, DELIMITER); if (token[0]) { for (n = 1; n < MAX_TOKENS_PER_LINE; n++) { token[n] = strtok(0, DELIMITER); if (!token[n]) { break; } } if (strstr(token[0],"SQUARE")) { shapeID[counter] = 1; Square* s = new Square(token); shapes[counter] = s; counter++; } if (strstr(token[0],"RECTANGLE")) { shapeID[counter] = 2; Rectangle* r = new Rectangle(token); shapes[counter] = r; counter++; } if (strstr(token[0],"CIRCLE")) { shapeID[counter] = 3; Circle* c = new Circle(token); shapes[counter] = c; counter++; } if (strstr(token[0],"CUBE")) { shapeID[counter] = 4; Cube* c = new Cube(token); shapes[counter] = c; counter++; } if (strstr(token[0],"PRISM")) { shapeID[counter] = 5; Prism* p = new Prism(token); shapes[counter] = p; counter++; } if (strstr(token[0],"CYLINDER")) { shapeID[counter] = 6; Cylinder* c = new Cylinder(token); shapes[counter] = c; counter++; } } } source.close(); for (int i = 0; i < counter; i++) { if (shapeID[i] == 1) { Square* s = (Square*) shapes[i]; s->print(); cout << endl; } if (shapeID[i] == 2) { Rectangle* r = (Rectangle*) shapes[i]; r->print(); cout << endl; } if (shapeID[i] == 3) { Circle* c = (Circle*) shapes[i]; c->print(); cout << endl; } if (shapeID[i] == 4) { Cube* c = (Cube*) shapes[i]; c->print(); cout << endl; } if (shapeID[i] == 5) { Prism* p = (Prism*) shapes[i]; p->print(); cout << endl; } if (shapeID[i] == 6) { Cylinder* c = (Cylinder*) shapes[i]; c->print(); cout << endl; } } for (int i = 0; i < counter; i++) { if (shapeID[i] == 1) { delete (Square*)shapes[i]; } if (shapeID[i] == 2) { delete (Rectangle*)shapes[i]; } if (shapeID[i] == 3) { delete (Circle*)shapes[i]; } if (shapeID[i] == 4) { delete (Cube*)shapes[i]; } if (shapeID[i] == 5) { delete (Prism*)shapes[i]; } if (shapeID[i] == 6) { delete (Cylinder*)shapes[i]; } } cout << endl << endl; } void Square::print() { double area, per; area = side * side; per = 4 * side; cout << "SQUARE side=" << side << " area="; cout.setf(ios::fixed|ios::showpoint); cout << setprecision(2); cout << area << " perimeter=" << per; cout << endl; cout.unsetf(ios::fixed|ios::showpoint); cout << setprecision(6); } void Rectangle::print() { double area, per; area = length * width; per = (2 * length) + (2 * width); cout << "RECTANGLE length=" << length << " width=" << width << " area="; cout.setf(ios::fixed|ios::showpoint); cout << setprecision(2); cout << area << " perimeter=" << per; cout << endl; cout.unsetf(ios::fixed|ios::showpoint); cout << setprecision(6); } void Circle::print() { double area, cir; area = pi * radius * radius; cir = 2 * pi * radius; cout << "CIRCLE radius=" << radius << " area="; cout.setf(ios::fixed|ios::showpoint); cout << setprecision(2); cout << area << " circumference=" << cir; cout << endl; cout.unsetf(ios::fixed|ios::showpoint); cout << setprecision(6); } void Cube::print() { double sa, v; v = side * side * side; sa = 6 * side * side; cout << "CUBE side=" << side << " surface area="; cout.setf(ios::fixed|ios::showpoint); cout << setprecision(2); cout << sa << " volume=" << v; cout << endl; cout.unsetf(ios::fixed|ios::showpoint); cout << setprecision(6); } void Prism::print() { double sa, v; v = length * width * height; sa = (2 * length * width) + (2 * width * height) + (2 * length * height); cout << "PRISM length=" << length << " width=" << width << " height=" << height << " surface area="; cout.setf(ios::fixed|ios::showpoint); cout << setprecision(2); cout << sa << " volume=" << v; cout << endl; cout.unsetf(ios::fixed|ios::showpoint); cout << setprecision(6); } void Cylinder::print() { double sa, v; v = pi * radius * radius * height; sa = (2 * pi * radius * radius) + (2 * pi * radius * height); cout << "CYLINDER radius=" << radius << " height=" << height << " surface area="; cout.setf(ios::fixed|ios::showpoint); cout << setprecision(2); cout << sa << " volume=" << v; cout << endl; cout.unsetf(ios::fixed|ios::showpoint); cout << setprecision(6); }
[ "noreply@github.com" ]
JPL4494.noreply@github.com
f9b8ecfd85b968b8a90439d85e35989acfcf4fa6
b956eb9be02f74d81176bc58d585f273accf73fb
/game/prefabs/AladdinAndAbuPrefab.cpp
320fc27aaf286999dc9e89f3982f1e16b049117c
[ "MIT" ]
permissive
Khuongnb/game-aladdin
b9b1c439d14658ca9d67d5c6fe261ec27084b2e9
74b13ffcd623de0d6f799b0669c7e8917eef3b14
refs/heads/master
2020-05-05T10:20:05.616126
2019-04-07T09:05:11
2019-04-07T09:05:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,120
cpp
#include "AladdinAndAbuPrefab.h" #include "../scripts/DirectionController.h" USING_NAMESPACE_ALA; ALA_CLASS_SOURCE_1(AladdinAndAbuPrefab, ala::PrefabV2) void AladdinAndAbuPrefab::doInstantiate( ala::GameObject* object, std::istringstream& argsStream ) const { // args const auto dir = nextChar( argsStream ); const auto speed = nextFloat( argsStream ); // constants const auto gameManager = GameManager::get(); // components const auto spriteRenderer = new SpriteRenderer( object, "aladdin.png" ); const auto animator = new Animator( object, "happy_run", "aladdin.anm" ); const auto body = new Rigidbody( object, PhysicsMaterial(), ALA_BODY_TYPE_DYNAMIC, 0 ); body->setVelocity( Vec2( speed, 0 ) ); const auto direction = new DirectionController( object, false ); if ( dir == 'L' ) direction->setLeft(); else if ( dir == 'R' ) direction->setRight(); const auto abu = new GameObject( object ); const auto abuSpriteRenderer = new SpriteRenderer( abu, "abu.png" ); const auto abuAnimator = new Animator( abu, "run", "abu.anm" ); abu->getTransform()->setPosition( -48, -12 ); }
[ "khuongnb1997@gmail.com" ]
khuongnb1997@gmail.com
5226fcda1d1dc91f64244013e6d3cd5f387a214d
7460f2c56af13c59157099432ffd5b8f9acbde21
/StackSchool.cpp
5e2866c79d03308bfd5082b3fc29a9db47df3766
[]
no_license
MartinKrumov/lessons
dbbc7f6598502382a8c2f56241033344a1c4600b
ae449276345d16dbe13fa255eec0b67d335fd196
refs/heads/master
2021-01-20T04:11:35.625664
2015-04-02T16:46:29
2015-04-02T16:46:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,117
cpp
#include <iostream> using namespace std; #ifndef TSTACK1_H #define TSTACK1_H template< class T > class Stack { public: Stack( int = 10 ); // подразбиращ се конструктор (размер на стека) ~Stack() { delete [] stackPtr; // деструктор } bool push( const T& ); // push функция bool pop( T& ); // pop функция private: int size; // брой на елементите в стека int top; // местоположение на top елемента (върха на стека) T *stackPtr; // указател към стека // utility bool isEmpty() const { return top == -1; //Когато стекът е празен } bool isFull() const { return top == size - 1; // Когато стекът е пълен } }; //Дефиниции на член-функциите // Конструктор с подразбиращ се размер 10 template< class T > Stack< T >::Stack( int s ) { size = s > 0 ? s : 10; //Ако s > 0, size = s, в противен случай size =10 // if (s > 0) { // size = s; // } // else { // size = 10; //} top = -1; // В начално положение стекът е празен stackPtr = new T[ size ]; // заделя се място за елементите на стека } template< class T > bool Stack< T >::push( const T &pushValue ) { if ( !isFull() ) { stackPtr[ ++top ] = pushValue; // place item in Stack return true; // push successful } return false; // push unsuccessful } // Pop an element off the stack template< class T > bool Stack< T >::pop( T &popValue ) { if ( !isEmpty() ) { popValue = stackPtr[ top-- ]; // remove item from return true; // pop successful } return false; // pop unsuccessful } #endif int main() { //Специализация на клас Stack за реални числа Stack< double > doubleStack( 5 ); double f = 1.5; cout << "Pushing elements onto doubleStack\n"; // Когато е възможно добавянето на данни в стека (не е пълен) връща true while ( doubleStack.push( f ) ) { cout << f << ' '; f += 1.0; } cout << "\nStack is full. Cannot push " << f << "\n\nPopping elements from doubleStack\n"; // Когато е възможно извеждането на данни от стека (не е празен )връща true while ( doubleStack.pop( f ) ) cout << f << ' '; cout << "\nStack is empty. Cannot pop\n"; //Специализация на клас Stack за цели числа Stack< int > intStack; int i = 1.6; cout << "\nPushing elements onto intStack\n"; // Когато е възможно добавянето на дани (не е пълен) в стека връща true while ( intStack.push( i ) ) { cout << i << ' '; ++i; } cout << "\nStack is full. Cannot push " << i << "\n\nPopping elements from intStack\n"; // Когато е възможно извеждането на данни от стека (не е празен )връща true while ( intStack.pop( i ) ) cout << i << ' '; cout << "\nStack is empty. Cannot pop\n"; Stack< string > stStack; string s ="1"; cout << "\nPushing elements onto intStack\n"; // Когато е възможно добавянето на дани (не е пълен) в стека връща true while ( stStack.push(1) ) { cout << s << ' '; } cout << "\nStack is full. Cannot push " << i << "\n\nPopping elements from intStack\n"; // Когато е възможно извеждането на данни от стека (не е празен )връща true while ( stStack.pop( s ) ) { cout << i << ' '; } cout << "\nStack is empty. Cannot pop\n"; return 0; }
[ "kristiyanjordanov@gmail.com" ]
kristiyanjordanov@gmail.com
5f647c5712dec5d5c9f1617a276596e8069fd71b
1ec2bbf1d08b5a27dbf16b8ea327d6dda4222861
/cget/include/range/v3/algorithm/find_end.hpp
32ad2deb4c22fe15f5437c45e779d95cb846b4b9
[]
no_license
myhau/geometry-orthogonal-space-search
ee967520e6fa5a493ab6cd24279d98471f92dede
a2a74d7d1fabe334ac8038253c660c0425899d76
refs/heads/master
2021-01-13T12:44:07.037649
2017-10-21T21:57:30
2017-10-21T21:57:30
72,533,074
1
2
null
2017-10-21T21:57:31
2016-11-01T12:15:08
C++
UTF-8
C++
false
false
115
hpp
/Users/mihau/workspace/geo-proj/cget/cget/pkg/ericniebler__range-v3/install/include/range/v3/algorithm/find_end.hpp
[ "mmyhau@gmail.com" ]
mmyhau@gmail.com
9159494d1a2a8aa854b182d67b880a84884333e2
5d6b15327b070aba847f6ca33172ae83037254ee
/Arduino/Advanced/4051_multiplex_test/4051_multiplex_test.ino
dcc8c5a885ccf28fdbccd5159e6b4594be114bab
[ "MIT", "CC-BY-NC-SA-3.0" ]
permissive
carloscastellanos/teaching
5daf85cc005f5f3b78c7b529e0b457a693ac01a5
0ac7ed4ef04d92095abba34127cc7ab5f3625e34
refs/heads/master
2023-08-31T21:59:10.729678
2023-08-30T13:30:47
2023-08-30T13:30:47
15,624,013
2
9
MIT
2021-09-17T21:17:46
2014-01-04T01:36:25
Max
UTF-8
C++
false
false
1,749
ino
/* * Example of using the 4051 (74HC4051) multiplexer/demultiplexer * * * Carlos Castellanos * August 19, 2020 * * Based on code by Nick Gammon * http://www.gammon.com.au/forum/?id=11976 * */ /*********************** === PIN DEFINITIONS === ***********************/ //where the multiplexer address select lines (A/B/C) (pins 11/10/9 on the 4051) are connected const byte addressA = 11; // low-order bit const byte addressB = 10; const byte addressC = 9; // high-order bit // where the multiplexer common in/out line (pin 3 on the 4051) is connected const byte sensor = A0; void setup (){ Serial.begin (9600); Serial.println ("Starting multiplexer test ..."); pinMode (addressA, OUTPUT); pinMode (addressB, OUTPUT); pinMode (addressC, OUTPUT); } void loop () { // show all 8 sensor readings for(byte i=0; i<=7; i++) { Serial.print("Sensor "); Serial.print(i); Serial.print(": "); Serial.println(readSensor(i)); Serial.println(); } delay(500); } int readSensor (const byte which) { // select correct MUX channel // low-order bit if((which & 1)) { digitalWrite(addressA, HIGH); } else { digitalWrite(addressA, LOW); } if((which & 2)) { digitalWrite(addressB, HIGH); } else { digitalWrite(addressB, LOW); } // high-order bit if((which & 4)) { digitalWrite(addressC, HIGH); } else { digitalWrite(addressC, LOW); } /* a more efficient (if slightly abstruse) way of doing the above digitalWrite (addressA, (which & 1) ? HIGH : LOW); // low-order bit digitalWrite (addressB, (which & 2) ? HIGH : LOW); digitalWrite (addressC, (which & 4) ? HIGH : LOW); // high-order bit */ // now read the sensor return analogRead(sensor); }
[ "carloscastellanossf@gmail.com" ]
carloscastellanossf@gmail.com
26c73deb4596e16a4042c01e085fc8d6bc43d240
fd7c5d4e6ab06dbbee4cb7f48ac73a2de81c0837
/Ladybug3D/Libraries/Renderer/Transform.hpp
f1dcda19f6d3ab318a48a2a05ac60995763f34fc
[ "MIT" ]
permissive
wlsvy/Ladybug3D
f70ccc4c7d9db6fba9390438b3620f3ce66b2eec
9cd92843bf6cdff806aa4283c5594028a53e20b3
refs/heads/master
2022-12-10T01:29:06.451434
2020-09-16T13:37:18
2020-09-16T13:37:18
286,414,910
0
0
null
null
null
null
UTF-8
C++
false
false
5,170
hpp
#pragma once #include <vector> #include <DirectXMath.h> #include "Object.hpp" namespace Ladybug3D { constexpr float POSITION_MAX = 10000.0f; constexpr float POSITION_MIN = -10000.0f; constexpr float Deg2Rad = 0.0174533f; // pi / 180 constexpr float Rad2Deg = 57.2958f; // 180 / pi class Scene; class SceneObject; class Transform : public Object { friend class Scene; public: Transform(); Transform(SceneObject* sceneObj); ~Transform(); void SetPosition(const DirectX::XMVECTOR& pos) { positionVec = pos; } void SetPosition(const DirectX::XMFLOAT3& pos) { position = pos; } void SetPosition(float x, float y, float z) { position = DirectX::XMFLOAT3(x, y, z); } void SetRotation(const DirectX::XMFLOAT3& rot) { rotation = rot; } void SetRotation(const DirectX::XMVECTOR& rot) { rotationVec = rot; } void SetRotation(float x, float y, float z) { rotation = DirectX::XMFLOAT3(x, y, z); } void SetScale(const DirectX::XMVECTOR& s) { scaleVec = s; } void SetScale(const DirectX::XMFLOAT3& s) { scale = s; } void SetScale(float x, float y, float z) { scale = DirectX::XMFLOAT3(x, y, z); } void SetLookAtPos(DirectX::XMFLOAT3 lookAtPos); void translate(const DirectX::XMVECTOR& pos) { using DirectX::operator+=; positionVec += pos; } void translate(const DirectX::XMFLOAT3& pos) { using DirectX::operator+=; positionVec += DirectX::XMVectorSet(pos.x, pos.y, pos.z, 0.0f); } void translate(float x, float y, float z) { using DirectX::operator+=; positionVec += DirectX::XMVectorSet(x, y, z, 0.0f); } void rotate(const DirectX::XMVECTOR& rot) { using DirectX::operator+=; rotationVec += rot; } void rotate(const DirectX::XMFLOAT3& rot) { using DirectX::operator+=; rotationVec += DirectX::XMVectorSet(rot.x, rot.y, rot.z, 0.0f); } void rotate(float x, float y, float z) { using DirectX::operator+=; rotationVec += DirectX::XMVectorSet(x, y, z, 0.0f); } DirectX::XMVECTOR GetGlobalPosition() const { return m_GlobalPositionVec; } DirectX::XMVECTOR GetGlobalQuaternion() const { return m_GlobalQuaternionVec; } DirectX::XMVECTOR GetLossyScale() const { return m_GlobalLossyScaleVec; } DirectX::XMVECTOR GetQuaternion() const { using DirectX::operator*; return DirectX::XMQuaternionRotationRollPitchYawFromVector(rotationVec * Deg2Rad); } const DirectX::XMVECTOR& GetForwardVector() const { return m_Forward; } const DirectX::XMVECTOR& GetUpwardVector() const { return m_Upward; } const DirectX::XMVECTOR& GetLeftVector() const { return m_Left; } DirectX::XMVECTOR GetBackwardVector() const { using DirectX::operator*; return m_Forward * -1; } DirectX::XMVECTOR GetDownwardVector() const { using DirectX::operator*; return m_Upward * -1; } DirectX::XMVECTOR GetRightVector() const { using DirectX::operator*; return m_Left * -1; } const DirectX::XMMATRIX& GetWorldMatrix() const { return m_WorldMatrix; } DirectX::XMMATRIX GetViewMatrix() const { using DirectX::operator+; return DirectX::XMMatrixLookAtLH(positionVec, m_Forward + positionVec, m_Upward); } std::shared_ptr<Transform> GetParent() const { return m_Parent; } std::shared_ptr<Transform> GetChild(int index) const { return m_Children[index]; } size_t GetChildNum() const { return m_Children.size(); } void SetParent(const std::shared_ptr<Transform>& transform); bool HaveChildTransform(Transform* _transform) const; auto GetSceneObject() const { return m_SceneObject; } void OnImGui() override; union { DirectX::XMFLOAT3 position = DirectX::XMFLOAT3(0.0f, 0.0f, 0.0f); DirectX::XMVECTOR positionVec; }; union { DirectX::XMFLOAT3 rotation = DirectX::XMFLOAT3(0.0f, 0.0f, 0.0f); DirectX::XMVECTOR rotationVec; }; union { DirectX::XMFLOAT3 scale = DirectX::XMFLOAT3(1.0f, 1.0f, 1.0f); DirectX::XMVECTOR scaleVec; }; static const DirectX::XMVECTOR DEFAULT_FORWARD_VECTOR; static const DirectX::XMVECTOR DEFAULT_BACKWARD_VECTOR; static const DirectX::XMVECTOR DEFAULT_UP_VECTOR; static const DirectX::XMVECTOR DEFAULT_DOWN_VECTOR; static const DirectX::XMVECTOR DEFAULT_LEFT_VECTOR; static const DirectX::XMVECTOR DEFAULT_RIGHT_VECTOR; private: void UpdateMatrix( const DirectX::XMMATRIX& parentm_WorldMatrix, const DirectX::XMVECTOR& parentQuat); void UpdateDirectionVectors(const DirectX::XMMATRIX& rotationMat); void SetChild(const std::shared_ptr<Transform>& child); void EraseChild(Transform* child); DirectX::XMVECTOR CalculateLossyScale() const; union { DirectX::XMFLOAT3 m_GlobalPosition = DirectX::XMFLOAT3(0.0f, 0.0f, 0.0f); DirectX::XMVECTOR m_GlobalPositionVec; }; union { DirectX::XMFLOAT4 m_GlobalQuaternion = DirectX::XMFLOAT4(0.0f, 0.0f, 0.0f, 1.0f); DirectX::XMVECTOR m_GlobalQuaternionVec; }; union { DirectX::XMFLOAT3 m_GlobalLossyScale = DirectX::XMFLOAT3(1.0f, 1.0f, 1.0f); DirectX::XMVECTOR m_GlobalLossyScaleVec; }; DirectX::XMMATRIX m_WorldMatrix = DirectX::XMMatrixIdentity(); DirectX::XMVECTOR m_Forward; DirectX::XMVECTOR m_Left; DirectX::XMVECTOR m_Upward; std::shared_ptr<Transform> m_Parent; std::vector<std::shared_ptr<Transform>> m_Children; SceneObject* const m_SceneObject; }; }
[ "hubjpkim@gmail.com" ]
hubjpkim@gmail.com
9a277f54dd7027df5b2c134a0e80df0f79df644d
f618226a0799c6b07fa66911ce12abbbd903022c
/saphientia2013/H/H/main.cpp
1f5ef9df92f6a9923caf5b31c3ba59d56a32518c
[]
no_license
schaumb/2011-2013-old-programming-competition-solutions
1ff065a057c2ec2772f3e9ae2f05c058a8046a5d
b350e37a24d25beae5263e9cda1e8af89435437e
refs/heads/master
2021-01-23T12:27:01.703490
2015-07-09T21:12:41
2015-07-09T21:12:41
93,162,374
0
0
null
null
null
null
UTF-8
C++
false
false
5,748
cpp
#include <iostream> #include <fstream> #include <string> #include <map> #include <vector> #include <cctype> std::map<char, int> precedences; struct ast { ast(int var) : type(VAR), variable(var) {} ast(std::string f) : type(OP), func(f) {} enum type_t { VAR, OP } type; std::string func; std::vector<ast> operands; int variable; }; std::ostream& operator<<(std::ostream& os, const ast& a) { if ( a.type == ast::VAR ) { os << a.variable; } else { os << a.func << "("; if ( a.operands.size() > 0 ) { os << a.operands.front(); } for ( int i = 1; i < a.operands.size(); ++i ) { os << ", " << a.operands[i]; } os << ")"; } return os; } struct token { enum type_t { NUM, OPERATOR } type; token(char op) : type(OPERATOR), op(op) {} token(int n) : type(NUM), number(n) {} int number; char op; }; std::ostream& operator<<(std::ostream& os, const token& t) { #if 0 if ( t.type == token::NUM ) { os << "num(" << t.number << ")"; } else { os << "op(" << t.op << ")"; } #else if ( t.type == token::NUM ) { os << t.number; } else { os << t.op; } #endif return os; } void parse(std::string line) { std::vector<token> tokens; for ( int i = 0; i < line.size(); ++i ) { char ch = line[i]; if ( std::isdigit(ch) ) { int num = 0; while ( i < line.size() && std::isdigit(line[i]) ) { num *= 10; num += (line[i] - '0'); ++i; } tokens.push_back(token(num)); --i; } else { tokens.push_back(token(ch)); } } std::vector<token> rpm; std::vector<char> opstack; for ( int i = 0; i < tokens.size(); ++i ) { const token& cur = tokens[i]; if ( cur.type == token::NUM ) { rpm.push_back(cur); } else { //OP if ( cur.op == '-' && ( i == 0 || tokens[i-1].type == token::OPERATOR ) ) { opstack.push_back('m'); } else if ( cur.op == '+' && ( i == 0 || tokens[i-1].type == token::OPERATOR ) ) { opstack.push_back('p'); } else if ( cur.op == '(' ) { opstack.push_back(cur.op); } else if ( cur.op == ')' ) { while ( opstack.back() != '(' ) { rpm.push_back(opstack.back()); opstack.pop_back(); } opstack.pop_back(); } else { while ( !opstack.empty() && opstack.back() != '(' && precedences[opstack.back()] < precedences[cur.op] ) { rpm.push_back(opstack.back()); opstack.pop_back(); } opstack.push_back(cur.op); } } } while ( !opstack.empty() ) { rpm.push_back(opstack.back()); opstack.pop_back(); } //for ( int i = 0; i < rpm.size(); ++i ) { //std::cout << rpm[i] << " "; //} std::vector<ast> stack; for ( int i = 0; i < rpm.size(); ++i ) { if ( rpm[i].type == token::NUM ) { stack.push_back( ast(rpm[i].number) ); } else { if ( rpm[i].op == 'm' ) { ast arg = stack.back(); stack.pop_back(); ast r("minus"); r.operands.push_back(arg); stack.push_back(r); } else if ( rpm[i].op == 'p' ) { ast arg = stack.back(); stack.pop_back(); ast r("plus"); r.operands.push_back(arg); stack.push_back(r); } else if ( rpm[i].op == '-' ) { ast lhs = stack.back(); stack.pop_back(); ast rhs = stack.back(); stack.pop_back(); if ( lhs.type == ast::OP && lhs.func == "sub" ) { lhs.operands.insert(lhs.operands.begin(), rhs); stack.push_back(lhs); } else { ast r("sub"); r.operands.push_back(rhs); r.operands.push_back(lhs); stack.push_back(r); } } else if ( rpm[i].op == '+' ) { ast lhs = stack.back(); stack.pop_back(); ast rhs = stack.back(); stack.pop_back(); if ( lhs.type == ast::OP && lhs.func == "add" ) { lhs.operands.insert(lhs.operands.begin(), rhs); stack.push_back(lhs); } else { ast r("add"); r.operands.push_back(rhs); r.operands.push_back(lhs); stack.push_back(r); } } else if ( rpm[i].op == '/' ) { ast lhs = stack.back(); stack.pop_back(); ast rhs = stack.back(); stack.pop_back(); if ( lhs.type == ast::OP && lhs.func == "div" ) { lhs.operands.insert(lhs.operands.begin(), rhs); stack.push_back(lhs); } else { ast r("div"); r.operands.push_back(rhs); r.operands.push_back(lhs); stack.push_back(r); } } else if ( rpm[i].op == '*' ) { ast lhs = stack.back(); stack.pop_back(); ast rhs = stack.back(); stack.pop_back(); if ( lhs.type == ast::OP && lhs.func == "mul" ) { lhs.operands.insert(lhs.operands.begin(), rhs); stack.push_back(lhs); } else { ast r("mul"); r.operands.push_back(rhs); r.operands.push_back(lhs); stack.push_back(r); } } else if ( rpm[i].op == '^' ) { ast lhs = stack.back(); stack.pop_back(); ast rhs = stack.back(); stack.pop_back(); if ( false && lhs.type == ast::OP && lhs.func == "pow" ) { lhs.operands.insert(lhs.operands.begin(), rhs); stack.push_back(lhs); } else { ast r("pow"); r.operands.push_back(lhs); r.operands.push_back(rhs); stack.push_back(r); } } } } std::cout << stack.back() << std::endl; } int main() { precedences['+'] = 5; precedences['-'] = 5; precedences['p'] = 3; precedences['m'] = 3; precedences['*'] = 3; precedences['/'] = 3; precedences['^'] = 1; std::ifstream in("h.in"); int tcs; in >> tcs; in.ignore(); while ( tcs-- ) { std::string line; std::getline(in, line); parse(line); } }
[ "schaumb@gmail.com" ]
schaumb@gmail.com
631ede0ace14a843bcaf5f3d3f8eee044247d532
ad150471057e916b17e8b13bd7c205c5fbc9551b
/operator.cpp
c62950d0a478636d42478a93a9f1aef7c84b9dd6
[]
no_license
masiarekrafal/HanoiTower
b869840b979a6d37e20d693c6ad25e91cffccd37
faf2274b525f18e2e7b5f602935078ac695f20fa
refs/heads/master
2021-04-15T03:42:14.239617
2017-06-16T15:44:33
2017-06-16T15:44:33
94,558,387
0
0
null
null
null
null
UTF-8
C++
false
false
2,201
cpp
#include <Classes.hpp> #include <algorithm> #pragma hdrstop #include "operator.h" #pragma package(smart_init) class CUpdater { public: void operator()(String& src) { src = StringReplace(src, m_pattern,m_value,TReplaceFlags() << rfReplaceAll); } void toReplace(String pattern,String value) { m_pattern = pattern; m_value = value; } private: String m_pattern; String m_value; }; String COperator::operator[](String container) { if(container == "pre") return toString(m_preConditions); else if(container == "effects") return toString(m_effects); return ""; } String COperator::toString(std::vector<String>& container,String delimiter) { String str; for(std::vector<String>::iterator it = container.begin(); it != container.end(); ++it) { str += *it + delimiter; } return str; } COperator::COperator(String schema) { m_schema = schema; parseArgs(); } void COperator::addPrecondition(String preCondition) { m_preConditions.push_back(preCondition); } void COperator::addEffect(String effect) { m_effects.push_back(effect); } void COperator::parseArgs() { TStringList *tmpStr = new TStringList(); tmpStr->Delimiter = ','; tmpStr->DelimitedText = m_schema.SubString(m_schema.Pos("(")+1,m_schema.Pos(")")-m_schema.Pos("(") - 1); TStringsEnumerator *e = tmpStr->GetEnumerator(); while(e->MoveNext()) { m_args.push_back(e->Current); } tmpStr->Free(); } int COperator::getArgsNumber() { return m_args.size(); } void COperator::update(std::vector<String> &args) { CUpdater updater; for(int i = 0; i < args.size(); ++i) { updater.toReplace(m_args[i],args[i]); std::for_each(m_preConditions.begin(),m_preConditions.end(),updater); std::for_each(m_effects.begin(),m_effects.end(),updater); m_schema = StringReplace(m_schema,m_args[i],args[i],TReplaceFlags() << rfReplaceAll); } //sort container to be able to use includes function std::sort(m_preConditions.begin(),m_preConditions.end()); std::sort(m_effects.begin(),m_effects.end()); } std::vector<String>& COperator::getPreConditions() { return m_preConditions; } std::vector<String>& COperator::getEffects() { return m_effects; } String COperator::getSchema() { return m_schema; }
[ "rafal@masiarek.pl" ]
rafal@masiarek.pl
f172392f284e2ec98634cededd34908dbcc4fe82
c3894a22b8dde5b92cc36f3bc84135bc58c5b74d
/core/privc3/paddle_tensor.cc
663270bc5a07b67b05236a5c4347fb5354de1718
[]
no_license
poloholmes/PaddleFL
25f4a2ce46b6e8428aa0e22d249642c4e0b3a65b
8140ad95693b668578ec7918b2e1b0a44dbee6e9
refs/heads/master
2023-01-22T01:37:53.997353
2020-11-11T12:11:04
2020-11-11T12:11:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,073
cc
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // 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 "paddle_tensor.h" namespace aby3 { std::shared_ptr<TensorAdapter<int64_t>> PaddleTensorFactory::create_int64_t(const std::vector<size_t> &shape) { auto ret = std::make_shared<PaddleTensor<int64_t>>(_device_ctx); ret->reshape(shape); return ret; } std::shared_ptr<TensorAdapter<int64_t>> PaddleTensorFactory::create_int64_t() { auto ret = std::make_shared<PaddleTensor<int64_t>>(_device_ctx); return ret; } } // namespace aby3
[ "jingqinghe@baidu.com" ]
jingqinghe@baidu.com
cdc53450a85644dc07ddf598e1baefb5d1630313
2aabf077d3f2dab5156ceac0e2f39f8b223ca6a8
/MMDOCR-HighPerformance/CTCDecoder.cpp
0a268381c8f8d0563b35ca05f6a97635f3af3a0c
[ "MIT", "Zlib" ]
permissive
PatchyVideo/MMDOCR-HighPerformance
991cb325fc238fc112458aa9199b59152901cc50
0469af2f687c2518d95511c91c3e170c9e9f8928
refs/heads/master
2022-12-31T00:57:48.870482
2020-10-18T00:51:24
2020-10-18T00:51:24
284,383,689
15
1
null
null
null
null
UTF-8
C++
false
false
11,453
cpp
#include <fstream> #include <queue> #include <algorithm> #include "CTCDecoder.h" #include "utf_utils.h" static std::vector<char32_t> g_alphabet; static std::unordered_map<std::pair<char32_t, char32_t>, float, pair_hash> g_bigram_probs; void BuildAlphabet() { std::ifstream file("alphabet.txt", std::ios::binary | std::ios::ate); if (file.bad() || file.fail()) throw std::runtime_error("failed to open alphabet.txt"); std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); auto buffer(std::make_unique<char[]>(size)); if (file.read(buffer.get(), size)) { char32_t* tmp(new char32_t[size]); memset(tmp, 0, size); auto num_chars(uu::UtfUtils::SseConvert(reinterpret_cast<uu::UtfUtils::char8_t*>(buffer.get()), reinterpret_cast<uu::UtfUtils::char8_t*>(buffer.get() + size), tmp + 1)); if (num_chars <= 0) { throw std::runtime_error("utf8 read failed"); } g_alphabet = std::vector<char32_t>(tmp, tmp + num_chars + 1); std::cout << "Alphabet read, total " << static_cast<std::size_t>(num_chars) << " chars\n"; delete[] tmp; } else throw std::runtime_error("failed to read alphabet file"); } void BuildBigramProbs() { std::ifstream ifs("bigram_probs_v2.txt"); if(ifs.bad() || ifs.fail()) throw std::runtime_error("failed to open bigram_probs_v2.txt"); std::string char_pair; float prob; while (ifs) { ifs >> char_pair >> prob; std::u32string char_pair_u32(ConvertU8toU32(char_pair)); if (char_pair_u32.size() != 2) throw std::runtime_error("corrupted bigram_probs_v2.txt"); g_bigram_probs[{char_pair_u32[0], char_pair_u32[1]}] = prob; } } std::int32_t GetSpaceWidth(std::int32_t const *seq, std::size_t seq_len) { std::int32_t spcace_between_chars(0), num_chars(0), num_space_since_last_char(0); enum class State { Init, Char, Space, SpaceAfterChar } state(State::Init); std::int32_t last_char_index(-1); for (std::size_t i(0); i < seq_len; ++i) { bool isSpace(seq[i] == 0); switch (state) { case State::Init: if (isSpace) state = State::Space; else { state = State::Char; last_char_index = seq[i]; ++num_chars; } break; case State::Char: if (isSpace) { state = State::SpaceAfterChar; num_space_since_last_char = 1; } else { state = State::Char; if (seq[i] != last_char_index) { last_char_index = seq[i]; ++num_chars; } } break; case State::Space: if (isSpace) { } else { state = State::Char; last_char_index = seq[i]; ++num_chars; } break; case State::SpaceAfterChar: if (isSpace) { ++num_space_since_last_char; } else { state = State::Char; spcace_between_chars += num_space_since_last_char; num_space_since_last_char = 0; last_char_index = seq[i]; ++num_chars; } break; default: break; } } if (num_chars == 0) return std::numeric_limits<std::int32_t>::max(); return static_cast<std::int32_t>(static_cast<float>(spcace_between_chars) / static_cast<float>(num_chars)); } inline float negative_log_probability(float prob) { return -std::logf(prob); } inline float transition_negative_log_probability(char32_t a, char32_t b) // -logP(b|a) { std::pair<char32_t, char32_t> item{ a, b }; if (g_bigram_probs.count(item)) return negative_log_probability(g_bigram_probs[item]); else return 10000000.0f; //if (a == 0 || b == 0) // return 10000.0f; //if (a == 'I' && b == '\'') // return 0.0f; //return 10.0f; } std::vector<std::pair<int, float>> list_source_vertices(std::vector<std::vector<std::pair<char32_t, float>>> const& candidates, int start_vertex_id, int j, std::size_t k) { if (j == 0) return { { start_vertex_id, 0 } }; else { std::vector<std::pair<int, float>> result; for (std::size_t u(0); u < candidates[j - 1].size(); ++u) { if (candidates[j - 1][u].first == 0) { auto recursive_vertices(list_source_vertices(candidates, start_vertex_id, j - 1, k)); for (auto [ver_id, neglogprob] : recursive_vertices) result.emplace_back(ver_id, neglogprob + candidates[j - 1][u].second * 10.0f); } else result.emplace_back((j - 1) * k * 2 + u * 2 + 1, 0); } return result; } } std::u32string DecodeCandidates(std::vector<std::vector<std::pair<char32_t, float>>> const& candidates, std::int64_t k, float cost_scale = 1000.0f) { if (candidates.size() == 0) return {}; if (candidates.size() == 1) return std::u32string({ candidates[0][0].first }); // build graph struct Edge { std::int64_t from, to, capacity, cost; Edge(std::int64_t from, std::int64_t to, std::int64_t capacity, float cost) :from(from), to(to), capacity(capacity), cost(static_cast<std::int64_t>(cost)) { } }; std::int64_t start_vertex_id(candidates.size() * k * 2); std::int64_t end_vertext_id(start_vertex_id + 1); std::vector<Edge> edges; std::vector<std::vector<std::int64_t>> next(end_vertext_id + 1); std::int64_t num_vertices(2); for (std::size_t u(0); u < candidates.front().size(); ++u) { edges.emplace_back(0 * k * 2 + u * 2, 0 * k * 2 + u * 2 + 1, 1, candidates.front()[0].second * cost_scale); // first column next[0 * k * 2 + u * 2].emplace_back(0 * k * 2 + u * 2 + 1); edges.emplace_back(start_vertex_id, 0 * k * 2 + u * 2, 1, 0.0f); next[start_vertex_id].emplace_back(0 * k * 2 + u * 2); num_vertices += 2; } auto get_vertex_char([&candidates, k](std::int64_t v) -> char32_t { std::int64_t col(v / (k * 2)); std::int64_t row(v % (k * 2)); row -= row & 1; return candidates[col][row / 2].first; }); for (std::size_t i(1); i < candidates.size(); ++i) { auto src_candidates(list_source_vertices(candidates, start_vertex_id, i, k)); auto dst_candidates(candidates[i]); for (std::size_t v(0); v < dst_candidates.size(); ++v) { edges.emplace_back(i * k * 2 + v * 2, i * k * 2 + v * 2 + 1, 1, candidates[i][v].second * cost_scale); // column i next[i * k * 2 + v * 2].emplace_back(i * k * 2 + v * 2 + 1); num_vertices += 2; for (std::size_t u(0); u < src_candidates.size(); ++u) { if (src_candidates[u].first == start_vertex_id) { edges.emplace_back(start_vertex_id, i * k * 2 + v * 2, 1, src_candidates[u].second * cost_scale); next[start_vertex_id].emplace_back(i * k * 2 + v * 2); } else { edges.emplace_back(src_candidates[u].first, i * k * 2 + v * 2, 1, (src_candidates[u].second + transition_negative_log_probability(get_vertex_char(src_candidates[u].first), candidates[i][v].first)) * cost_scale); next[src_candidates[u].first].emplace_back(i * k * 2 + v * 2); } } } } for (auto [src_id, addtional_cost] : list_source_vertices(candidates, start_vertex_id, candidates.size(), k)) { edges.emplace_back(src_id, end_vertext_id, 1, addtional_cost * cost_scale); next[src_id].emplace_back(end_vertext_id); } // step 2: run SSP std::vector<std::vector<std::int64_t>> adj, cost, capacity; auto shortest_paths([&adj, &cost, &capacity](std::int64_t n, std::int64_t v0, std::vector<std::int64_t>& d, std::vector<std::int64_t>& p) { d.assign(n, std::numeric_limits<std::int64_t>::max()); d[v0] = 0; std::vector<char> inq(n, 0); std::queue<std::int64_t> q; q.push(v0); p.assign(n, -1); while (!q.empty()) { std::int64_t u = q.front(); q.pop(); inq[u] = 0; for (std::int64_t v : adj[u]) { if (capacity[u][v] > 0 && d[v] > d[u] + cost[u][v]) { d[v] = d[u] + cost[u][v]; p[v] = u; if (!inq[v]) { inq[v] = 1; q.push(v); } } } } }); auto min_cost_flow([&adj, &cost, &capacity, &shortest_paths](std::int64_t N, std::vector<Edge> edges, std::int64_t K, std::int64_t s, std::int64_t t) -> std::int64_t { adj.assign(N, std::vector<std::int64_t>()); cost.assign(N, std::vector<std::int64_t>(N, 0)); capacity.assign(N, std::vector<std::int64_t>(N, 0)); for (Edge e : edges) { adj[e.from].push_back(e.to); adj[e.to].push_back(e.from); cost[e.from][e.to] = e.cost; cost[e.to][e.from] = -e.cost; capacity[e.from][e.to] = e.capacity; } std::int64_t flow = 0; std::int64_t cost = 0; std::vector<std::int64_t> d, p; while (flow < K) { shortest_paths(N, s, d, p); if (d[t] == std::numeric_limits<std::int64_t>::max()) break; // find max flow on that path std::int64_t f = K - flow; std::int64_t cur = t; while (cur != s) { f = std::min(f, capacity[p[cur]][cur]); cur = p[cur]; } // apply flow flow += f; cost += f * d[t]; cur = t; while (cur != s) { capacity[p[cur]][cur] -= f; capacity[cur][p[cur]] += f; cur = p[cur]; } } if (flow < K) return -1; else return cost; }); auto flowcost(min_cost_flow(end_vertext_id + 1, edges, num_vertices, start_vertex_id, end_vertext_id)); // always -1 std::u32string result; std::int64_t cur(start_vertex_id); while (next[cur].size()) { bool found(false); for (auto next_id : next[cur]) { if (capacity[cur][next_id] == 0) { if (next_id % 2 == 0) result.append(1, get_vertex_char(next_id)); cur = next_id; found = true; break; } } if (!found) throw std::runtime_error("flow failed"); } return result; } std::u32string DecodeSingleSentenceTop1(std::int32_t const* const indices, float const* const probs, std::size_t k, std::size_t sentence_length, float threshold = 0.9f) { std::u32string result; char32_t last_ch(std::numeric_limits<char32_t>::max()); for (std::size_t i(0); i < sentence_length; ++i) { char32_t top1_ch(g_alphabet[indices[i * k + 0]]); float top1_prob(probs[i * k + 0]); if (top1_ch == last_ch || top1_ch == 0) { last_ch = top1_ch; continue; } last_ch = top1_ch; result.append(1, top1_ch); } return result; } std::u32string DecodeSingleSentence(std::int32_t const* const indices, float const* const probs, std::size_t k, std::size_t sentence_length, float threshold = 0.9f) { // generate candidates std::vector<std::vector<std::pair<char32_t, float>>> candidates; char32_t last_ch(std::numeric_limits<char32_t>::max()); for (std::size_t i(0); i < sentence_length; ++i) { char32_t top1_ch(g_alphabet[indices[i * k + 0]]); float top1_prob(probs[i * k + 0]); if (top1_ch == last_ch) { last_ch = top1_ch; continue; } last_ch = top1_ch; if (top1_prob >= threshold && top1_ch == 0) continue; // we are certrain this is [blank], skipping if (top1_prob < threshold) { std::vector<std::pair<char32_t, float>> cur; for (std::size_t j(0); j < k; ++j) { char32_t topk_ch(g_alphabet[indices[i * k + j]]); float topk_prob(probs[i * k + j]); cur.emplace_back(topk_ch, negative_log_probability(topk_prob)); } candidates.emplace_back(cur); } else { std::vector<std::pair<char32_t, float>> cur; cur.emplace_back(top1_ch, negative_log_probability(top1_prob)); candidates.emplace_back(cur); } } return DecodeCandidates(candidates, k); } std::vector<std::u32string> CTCDecode( cudawrapper::CUDAHostMemoryUnique<std::int32_t> const& ocr_result_indices, cudawrapper::CUDAHostMemoryUnique<float> const& ocr_result_probs, std::size_t num_imgs, std::size_t image_width, std::size_t k ) { std::vector<std::u32string> result(num_imgs); for (std::int64_t i(0); i < num_imgs; ++i) { result[i] = DecodeSingleSentenceTop1(ocr_result_indices.at_offset(image_width * k, i), ocr_result_probs.at_offset(image_width * k, i), k, image_width); } return result; }
[ "zyddnys@outlook.com" ]
zyddnys@outlook.com
92cfa65207c92c612eded139b2ac16a1a66f169b
39bac498c22f3acd9a9c869d43b144b5dbc4f685
/PCClient/QtBB/BB/l2window.h
54c1c9a05a92e5ed92f7840b1692111a6483b7df
[]
no_license
dennn66/BB
9a2f0b0700a192c0890342dd6562ddddd86e5399
ccdd3ec7c79b180280d7407b29d99b54463af570
refs/heads/master
2021-01-24T03:42:13.135487
2017-06-26T12:10:05
2017-06-26T12:10:05
40,249,066
0
0
null
null
null
null
UTF-8
C++
false
false
3,281
h
#ifndef L2WINDOW_H #define L2WINDOW_H #include <QString> #include <QtWinExtras/QtWin> #include <QImage> #include <QIcon> #include <QFile> #include <QTextCodec> #include <QTextStream> #include <QSettings> #include <QMessageBox> #include <windows.h> #include "xpbar.h" #include "keycondition.h" #include "keyconditionsset.h" #define L2_OFF false #define L2_ON true #define TOOLLOFFSET 38 #define TOOLTOFFSET 9 #define TOOLVGAP 14 #define TOOLHGAP 5 #define TOOLH2GAP 7 #define TOOLSELL 32 class L2Window { public: int targettype; L2Window(HWND winhwnd); bool init(QImage image); QIcon* getIcon(); int getTokenState(); QColor* getTokenColor(); QString getTitle(); QString getNic(); HWND getHWND(); QString project_file_name; QColor token_color; //token QPoint windowtopright; bool isActiveWindow; int LoadProject(QString file_name); int SaveProject(QString file_name); int LoadConfig(QString file_name); int SaveConfig(QString file_name); int AddConfig(QString file_name); int getXP(int bar); int check(); QImage* getTool(int n); QImage* findTool(int n); QImage image; QString getConditionLabel(int index); bool getConditionState(int index); void resetBars(); bool isValidIndex(int index); bool activateSettings(int index); KeyConditionsSet* getCurrentSettings(); bool isSkillRdy(int num); bool getConditionSkill(int index){return getCurrentSettings()->condition[index]->getConditionB(idCheckSkillTimeout);} bool getMainLeftStatus(){return (maintopleft.rx() > 0);} bool getMainRightStatus(){return (maintopright.rx() > 0);} bool getMobLeftStatus(){return (mobtopleft.rx() > 0);} bool getMobRightStatus(){return (mobtopright.rx() > 0);} bool getToolbarStatus(){return (toolbartopleft.rx() > 0);} bool getPetStatus(){return (pettopleft.rx() > 0);} int getTargetType(){return targettype;} // bool getGroupState(int gr){return group_state[gr];} // void setGroupState(int gr, bool stt){group_state[gr] = stt;} void getBarStatistic(); //KeyCondition* condition[KEYNUM]; int activeCondSet; //KeyConditionsSet* conditionSet; QVector <KeyConditionsSet*> cond_set_list; private: HWND hwnd; bool status; XPBar bar[BARNUM]; //QString nic; QIcon* L2icon; int nToken; bool bEnableToolbar; int image_width; int image_height; bool skillrdy[KEYNUM]; // bool group_state[GROUPSNUM]; QImage mainleft; QImage mainright; QPoint maintopleft; QPoint maintopright; QImage mobleft_o; QImage mobright_o; QImage mobleft_c; QImage mobright_c; QPoint mobtopleft; QPoint mobtopright; int mobdetectcounter; QImage star; QPoint startopleft; int stardetectcounter; QImage toolbarleft; QPoint toolbartopleft; QImage tool[KEYNUM]; int tooldetectcounter; QImage petleft; QPoint pettopleft; int petdetectcounter; bool bPetDetected; bool bPet; QImage mobhp; QImage mobmp; QPoint findPattern(QImage source, QPoint topleft, QPoint bottomright, QImage pattern, int delta); QImage capture(); bool findCPHPMP(QImage image); signals: public slots: }; #endif // L2WINDOW_H
[ "dennn6696@gmail.com" ]
dennn6696@gmail.com
ccf7433bd3b834f419f96a39c194b42274fbaacc
adfcd15da351a38af5713ea4e138160e1744bc1e
/src/System.h
ecf89072299324ef2ccae388bfc4de9fe5706742
[ "BSD-2-Clause" ]
permissive
natecollins/vecs
05ea013a89d4c6a3a5a76bec288212ba797dbc4c
b003b8f856acd20c8d02cfea89baed119b8cd794
refs/heads/master
2020-03-23T01:24:48.192243
2018-07-14T04:30:55
2018-07-14T04:30:55
140,915,974
0
0
null
null
null
null
UTF-8
C++
false
false
1,945
h
#ifndef VECS_SYSTEM_H_ #define VECS_SYSTEM_H_ #include <memory> #include "ComponentBase.h" #include "Component.h" #include "ComponentTypeSet.h" #include "EventReceiver.h" namespace vecs { class Domain; class Entity; enum SystemThreadState : int32_t { NON_THREAD = 0, THREAD_QUEUED = 1, THREAD_RUNNING = 2, THREAD_TERM_REQUESTED = 4, THREAD_TERMINATED = 8, }; class System : public EventReceiver { private: // Link to manager that holds this system Domain* dom; // This System requires this type set ComponentTypeSet type_set; // Thread State SystemThreadState thread_state; // minumum time required between running update code (ms) int64_t min_update_period; // the last time update code ran int64_t last_update; // the last time delta in ms int64_t last_delta; // rescan for matching entities void rescan(); protected: // This is our current list of valid (matching the type set) entities std::unordered_map<ENT_ID, Entity*> entities; const Domain* getDomain(); public: System(SystemThreadState thread_state=NON_THREAD, Domain* dom=nullptr); virtual ~System(); void setDomain(Domain* dom); void setThreadState(SystemThreadState thread_state); SystemThreadState getThreadState() const; void internalUpdate(); void setMinimumUpdateTime(int64_t time_ms); int64_t getTimeDelta() const; int64_t getLastUpdateTime() const; void requireType(COMP_TYPE_ID ctid); bool validEntity(Entity* en) const; // Check if this system is already tracking the entity bool isTracking(Entity* en) const; // Attempt to track the given entity (assuming type_set match) void trackEntity(Entity* en); // Stop tracking the given entity void forgetEntity(Entity* en); virtual void runEvent(EventBase* ev); virtual void update() = 0; virtual void dump() const; }; } #endif // VECS_SYSTEM_H_
[ "npcollins@gmail.com" ]
npcollins@gmail.com
5f4e68010c6d90ccb482808d6d623bfb1e8524f6
a858496405a9a06699d8fa12c0d106610b04f8ed
/cybervision/cybervision-app/UI/aboutwindow.cpp
ae109da1cb4a0d7cfa23bb75ca7d747d008f8ea7
[]
no_license
mrsaleh/cybervision
e9e7dc24d6a8ccd8f47a52b5cd8ca5637b6fc9ee
45ccdfaa5d4a113386f26686060efbb84d7a2099
refs/heads/master
2021-12-08T06:14:47.095253
2015-02-26T00:04:11
2015-02-26T00:04:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
421
cpp
#include "aboutwindow.h" #include "ui_aboutwindow.h" #include <QDesktopServices> #include <QUrl> AboutWindow::AboutWindow(QWidget *parent) : QDialog(parent),ui(new Ui::AboutWindow){ ui->setupUi(this); } AboutWindow::~AboutWindow(){ delete ui; } void AboutWindow::on_closeButton_clicked(){ close(); } void AboutWindow::on_copyrightLabel_linkActivated(const QString &link){ QDesktopServices::openUrl(QUrl(link)); }
[ "zlogic@gmail.com" ]
zlogic@gmail.com
17373f556abda586f7533faada3f7592d9f979c1
2d480d7a87d0778119210df31a9a715afc1af279
/Lafore 6.9/main.cpp
efc93fded33e2b3e3b5460408513859507bca962
[]
no_license
Nukem74/CPPSolutions
144a9c13d1a4528e279e0f0eddaecd51f5b4cbe2
f7440cc5d5c6cc28c1baff2fc8eca2f70bca4513
refs/heads/master
2020-05-04T17:28:29.557034
2019-04-21T02:57:56
2019-04-21T02:57:56
179,312,496
0
0
null
2019-04-15T04:05:55
2019-04-03T14:55:10
C++
WINDOWS-1251
C++
false
false
1,156
cpp
#include <iostream> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ class fraction { private: //перечисление приватных членов int _numerator; int _denominator; public: //перечисление публичных членов fraction() //конструктор без аргументов { //empty } void setVal() { cout << "Enter numerator: "; cin >> _numerator; cout << "Enter denominator: "; cin >> _denominator; } void dispFrac()const { cout << _numerator << endl; cout << "__" << endl; cout << _denominator << endl; } void add(fraction a, fraction b) { _numerator = (a._numerator*b._denominator) + (a._denominator*b._numerator); _denominator = a._denominator * b._denominator; } }; int main(int argc, char** argv) { fraction A, B, C; A.setVal(); A.dispFrac(); int number = 1; cout << "\nEnter new fraction to add, or 0 to quit" << endl; B.setVal(); B.dispFrac(); C.add(A,B); C.dispFrac(); return 0; }
[ "Nukem74@gmail.com" ]
Nukem74@gmail.com
e74f07e258c80d3848370a5aa92166506688faea
89251cf93dbf403197f62a0e4d817faf07bcf43f
/Self Dividing Numbers/selfdividing.cpp
5dd07bc23810837739c1b58783692db2378ca669
[]
no_license
Lazeeez/DSA-1
3c68edd86106e35080b427e7c7eb6314863dfbc9
421f685a45d4bc565da376d82f8df52fd689751d
refs/heads/main
2023-08-18T10:33:27.759785
2021-10-03T16:27:24
2021-10-03T16:27:24
412,912,157
0
0
null
2021-10-03T17:30:12
2021-10-02T21:08:58
C++
UTF-8
C++
false
false
497
cpp
class Solution { public: bool selfDivide(int num){ int left = num; int remainder; while(left){ remainder = left%10; if(remainder==0 || num%remainder != 0) return false; left/=10; } return true; } vector<int> selfDividingNumbers(int left, int right) { vector<int> result; for(int i=left;i<=right;i++){ if(selfDivide(i)) result.push_back(i); } return result; } };
[ "parthkhare307@gmail.com" ]
parthkhare307@gmail.com
c2c175716f164d45fbe853dc86477b465696a84e
22f2b80a16bb6854c91a182c387ee1b23ae4426c
/stacks and queues/queue/dynamicqueueusingarray.cpp
ef901f4b838c26886fe341f1d63fe10bf1ab230f
[]
no_license
imakathuria/Practice
a4750266698dc9ada32eb302a24ff9ae39ae1db5
ea622261c2c768be7e698102c0a73d55f6b4a782
refs/heads/master
2023-05-11T09:28:29.080787
2021-06-01T08:18:44
2021-06-01T08:18:44
372,415,722
0
0
null
null
null
null
UTF-8
C++
false
false
1,910
cpp
#include<bits/stdc++.h> using namespace std; template <typename T> class QueueUsingArray{ T* data; int size; int FirstIndex; int NextIndex; int capacity; public: QueueUsingArray(){ size=0; data=new T[5]; capacity=5; FirstIndex=-1; NextIndex=0; } void insertElement(T d){ if(size==capacity){ T*newData=new T[2*capacity]; int j=0; for(int i=FirstIndex;i<capacity;i++){ newData[j++]=data[i]; } for(int i=0;i<FirstIndex;i++){ newData[j++]=data[i]; } delete []data; data=newData; FirstIndex=0; NextIndex=capacity; capacity*=2; } data[NextIndex]=d; NextIndex=(NextIndex+1)%capacity; if(FirstIndex==-1){ FirstIndex=0; } size++; } T deleteElement(){ if(size==0){ cout<<"Queue Empty"; return 0; } T ans=data[FirstIndex]; FirstIndex=(FirstIndex+1)%capacity; size--; return ans; } int sizeOfQueue(){ return size; } bool IsEmpty(){ return size==0; } T top(){ if(size==0){ return 0; } return data[FirstIndex]; } }; int main(){ // IsEmpty, top , sizeOfQueue,deleteElement,insertElement QueueUsingArray<int> q; for(int i=0;i<=100;i++){ q.insertElement(i); } cout<<endl; for(int i=0;i<=100;i++){ cout<<"IsEmpty : "<<q.IsEmpty() <<" top : "<< q.top()<<" sizeOfQueue : "<< q.sizeOfQueue()<<endl; q.deleteElement(); } cout<<"IsEmpty : "<<q.IsEmpty() <<" top : "<< q.top()<<" sizeOfQueue : "<< q.sizeOfQueue()<<endl; return 0; }
[ "imakathuria@gmail.com" ]
imakathuria@gmail.com
5e1e30ffaa8af0d564faf9b43c4ac1c445adc162
5c35f7bd29cc73cd6909f0a59c22740f6c1fe88f
/src/ast/mangle.h
943ea77abd3332afe7aa6187418c392c6922aa6b
[ "MIT" ]
permissive
cxcorp/delta
96a340112e389982bb557198e7dc45c9784c4af2
2a1bf8cba60eca71d3ff1636102c4536d69a3f6f
refs/heads/master
2021-07-10T03:14:53.991359
2017-10-11T17:18:51
2017-10-11T17:18:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
574
h
#pragma once #include <string> namespace llvm { class StringRef; template<typename T> class ArrayRef; } namespace delta { struct Type; class FunctionDecl; class TypeDecl; std::string mangle(const FunctionDecl& decl, llvm::ArrayRef<Type> typeGenericArgs = {}, llvm::ArrayRef<Type> functionGenericArgs = {}); std::string mangleFunctionDecl(llvm::StringRef receiverType, llvm::StringRef functionName, llvm::ArrayRef<Type> genericArgs = {}); std::string mangle(const TypeDecl& decl, llvm::ArrayRef<Type> genericArgs); }
[ "emil@cs.helsinki.fi" ]
emil@cs.helsinki.fi
5c558d66439762bbe04d3a1f5adef30d88e5135f
8acc3860c0a6b9dcf80dd99d4c226e1a50cf420f
/src/qt/optionsdialog.cpp
61fdefd23426717d434716c126c173ff9436f440
[ "MIT" ]
permissive
010000110101100101010100/CYTN
e4807549dd65c00da93c289fb47251e303f2b2bf
7459426b7a5f8e8192940fc67585335d2ad5b17b
refs/heads/master
2021-06-01T15:27:26.092206
2020-07-06T13:06:09
2020-07-06T13:06:09
42,249,973
0
0
null
null
null
null
UTF-8
C++
false
false
8,242
cpp
#include "optionsdialog.h" #include "ui_optionsdialog.h" #include "bitcoinunits.h" #include "monitoreddatamapper.h" #include "netbase.h" #include "optionsmodel.h" #include <QDir> #include <QIntValidator> #include <QLocale> #include <QMessageBox> #include <QRegExp> #include <QRegExpValidator> OptionsDialog::OptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::OptionsDialog), model(0), mapper(0), fRestartWarningDisplayed_Proxy(false), fRestartWarningDisplayed_Lang(false), fProxyIpValid(true) { ui->setupUi(this); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(1, 65535, this)); ui->socksVersion->setEnabled(false); ui->socksVersion->addItem("5", 5); ui->socksVersion->addItem("4", 4); ui->socksVersion->setCurrentIndex(0); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy())); ui->proxyIp->installEventFilter(this); /* Window elements init */ #ifdef Q_OS_MAC ui->tabWindow->setVisible(false); #endif /* Display elements init */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); foreach(const QString &langStr, translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if(langStr.contains("_")) { #if QT_VERSION >= 0x040800 /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } else { #if QT_VERSION >= 0x040800 /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language (locale name)", e.g. "German (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } } ui->unit->setModel(new BitcoinUnits(this)); /* Widget-to-option mapper */ mapper = new MonitoredDataMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* enable apply button when data modified */ connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton())); /* disable apply button when new data loaded */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton())); /* setup/change UI elements when proxy IP is invalid/valid */ connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool))); } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; if(model) { connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); mapper->setModel(model); setMapper(); mapper->toFirst(); } /* update the display unit, to not use the default ("BTC") */ updateDisplayUnit(); /* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */ connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang())); /* disable apply button after settings are loaded as there is nothing to save */ disableApplyButton(); } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->transactionFee, OptionsModel::Fee); mapper->addMapping(ui->reserveBalance, OptionsModel::ReserveBalance); mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup); mapper->addMapping(ui->detachDatabases, OptionsModel::DetachDatabases); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion); /* Window */ #ifndef Q_OS_MAC mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); #endif /* Display */ mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses); mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures); } void OptionsDialog::enableApplyButton() { ui->applyButton->setEnabled(true); } void OptionsDialog::disableApplyButton() { ui->applyButton->setEnabled(false); } void OptionsDialog::enableSaveButtons() { /* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */ if(fProxyIpValid) setSaveButtonState(true); } void OptionsDialog::disableSaveButtons() { setSaveButtonState(false); } void OptionsDialog::setSaveButtonState(bool fState) { ui->applyButton->setEnabled(fState); ui->okButton->setEnabled(fState); } void OptionsDialog::on_okButton_clicked() { mapper->submit(); accept(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::on_applyButton_clicked() { mapper->submit(); disableApplyButton(); } void OptionsDialog::showRestartWarning_Proxy() { if(!fRestartWarningDisplayed_Proxy) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Cryptoken."), QMessageBox::Ok); fRestartWarningDisplayed_Proxy = true; } } void OptionsDialog::showRestartWarning_Lang() { if(!fRestartWarningDisplayed_Lang) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Cryptoken."), QMessageBox::Ok); fRestartWarningDisplayed_Lang = true; } } void OptionsDialog::updateDisplayUnit() { if(model) { /* Update transactionFee with the current unit */ ui->transactionFee->setDisplayUnit(model->getDisplayUnit()); } } void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState) { // this is used in a check before re-enabling the save buttons fProxyIpValid = fState; if(fProxyIpValid) { enableSaveButtons(); ui->statusLabel->clear(); } else { disableSaveButtons(); object->setValid(fProxyIpValid); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); } } bool OptionsDialog::eventFilter(QObject *object, QEvent *event) { if(event->type() == QEvent::FocusOut) { if(object == ui->proxyIp) { CService addr; /* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */ emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr)); } } return QDialog::eventFilter(object, event); }
[ "L&N" ]
L&N
73bfc9faf11e15e9d0f9958c08dea0d5bf0e6ccf
15f8a4a0594ab7c55ed314236baefc2821ad9c62
/6. Sorting/selection_sort.cpp
2956cf47f49cc4a9cd26fa1b13b9d96a30fef136
[]
no_license
raktim-roy/coding-practise
4fadee92c179c7b890b3805182398b467fa298b9
46cb613b54df178d33a255b5f69a303eb7691e88
refs/heads/master
2020-12-11T11:37:30.614533
2020-01-14T12:41:39
2020-01-14T12:41:39
233,837,864
0
0
null
null
null
null
UTF-8
C++
false
false
1,080
cpp
// C++ program for implementation of selection sort #include <bits/stdc++.h> using namespace std; void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } void selectionSort(int arr[], int n) { int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n-1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i+1; j < n; j++) { if (arr[j] < arr[min_idx]) { min_idx = j; } } // Swap the found minimum element with the first element swap(&arr[min_idx], &arr[i]); } } /* Function to print an array */ void printArray(int arr[], int size) { int i; for (i=0; i < size; i++) cout << arr[i] << " "; cout << endl; } // Driver program to test above functions int main() { int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr)/sizeof(arr[0]); selectionSort(arr, n); cout << "Sorted array: \n"; printArray(arr, n); return 0; } // This is code is contributed by rathbhupendra
[ "rroy@cypress.com" ]
rroy@cypress.com
a54c20ea6875ea539a443d467e4da5ad77dd68d6
5fc98af617aff4af5e543bbbde1b8226753628a5
/1.cpp
8396626edf41699f65ff1840a1a3511ace2d4b5a
[]
no_license
myk7hackon/night
5194f2339fc4f0d192f0a806671badb6c1b33731
c7c1f30cd647e910127fceb4fbd0bb43c7df8cf4
refs/heads/master
2020-03-23T18:42:31.369580
2020-01-03T07:09:21
2020-01-03T07:09:21
141,926,837
0
1
null
2020-01-03T07:26:10
2018-07-22T20:03:27
C++
UTF-8
C++
false
false
6,935
cpp
#include<iostream> using namespace std; class list { public: int a; list *next; /* list(int p) { a=p; next=NULL; }*/ }; void buildlist(list **start,int p) { list *temp=new list; temp->a=p; temp->next=NULL; if(*start==NULL) *start=temp; else { list *copy=*start; while(copy->next!=NULL) copy=copy->next; copy->next=temp; } } void atpos(list **start,int p,int val) { list *temp=new list; temp->a=val; temp->next=NULL; if(p==1) { temp->next=*start; *start=temp; } else { list *copy=*start; int count=0; while(copy->next!=NULL&&count<p-2) { copy=copy->next; count++; } if(count!=p-2) cout<<"NOT enough values in the list"; else { temp->next=copy->next; copy->next=temp; } } } void delpos(list **start,int p) { if(p==1) *start=(*start)->next; else { list *copy=*start; while(copy->next!=NULL&&p-2!=0) { copy=copy->next; p--; } if(p-2>0) cout<<"NOT enough values in the list"; else copy->next=copy->next->next; } } int cyclefinder(list *start) { list *slow=start; list *fast=start; if(slow->next==NULL) return 0; else slow=slow->next; if(fast->next==NULL || fast->next->next==NULL) return 0; else fast=fast->next->next; while(1) { if(fast==slow) { cout<<fast->a<<endl; break; } if(slow->next==NULL) break; else slow=slow->next; if(fast->next==NULL || fast->next->next==NULL) break; else fast=fast->next->next; } slow=fast; fast=fast->next; int ans=0; while(fast!=slow) {fast=fast->next; ans++; } cout<<ans<<endl; return 0; } list *traverse; void reverse(list **start,int val,list *prev) { list *curr,*next; curr=*start; //prev=NULL; int temp=0; while(curr!=NULL) { next=curr->next; curr->next=prev; prev=curr; curr=next; temp++; } // cout<<prev->next->a; } list* riverse(list *start,int val,int doi) { list *curr,*next=NULL,*prev=NULL; curr=start; if(doi==1) { int temp=0; while(temp<val&&curr!=NULL) { next=curr->next; curr->next=prev; prev=curr; curr=next; temp++; } if(next!=NULL) start->next=riverse(next,val,0); } else return start; return prev; } void recrev(list *cur,list *prev,list **start,int val) { if(!cur->next) { *start=cur; return ; } else if(val==0) { *start=prev; //list **temp=&cur; recrev(cur,prev,&cur,val); } else { list *next=cur->next; cur->next=prev; recrev(next,cur,start,val-1); } } /*void reverseup(list **start) { list **inter=reverse(start,3,NULL); list *temp=*inter; while(*inter!=NULL) inter=reverse((*inter)->next,3,temp); }*/ /*void revblock(list **start,int win) { link *temp=*start; int view=0; while(temp!=NULL&&view<win) { temp=temp->next; view++; } reverseup(start,temp); }*/ void merge(list* start1,list*start2,list **start3) { if(*start3==NULL) { *start3=new list; if(start1!=NULL&&start2!=NULL) { (*start3)->a=(start1->a>start2->a)?start2->a:start1->a; (*start3)->next=NULL; if(start1->a>start2->a) merge(start1,start2->next,&((*start3)->next)); else merge(start1->next,start2,&((*start3)->next)); } else if(start1==NULL&&start2!=NULL) { (*start3)->a=start2->a; (*start3)->next=NULL; merge(start1,start2->next,&((*start3)->next)); } else if(start2==NULL&&start1!=NULL) { (*start3)->a=start1->a; (*start3)->next=NULL; merge(start1->next,start2,&((*start3)->next)); } else return; } } void helper(list *start1,list *start2,list **start3) { if(start1==NULL&&start2==NULL) return; else if(start1==NULL&&start2!=NULL) { buildlist(start3,start2->a); helper(start1,start2->next,start3); } else if(start1!=NULL&&start2==NULL) { buildlist(start3,start1->a); helper(start2,start1->next,start3); } else { if(start1->a<=start2->a) { buildlist(start3,start1->a); helper(start2,start1->next,start3); } else { buildlist(start3,start2->a); helper(start1,start2->next,start3); } } } /*void caller(list **start,int val,list *prev,int size) { if(size>0) { *start=riverse(start,val,prev); size-=val; list *temp=*start; while(temp->next!=prev) temp=temp->next; caller(start,val,temp,size-val); } }*/ void hogya(list **start) { if(*start==NULL) return; else if((*start)->next->a<(*start)->a) { (*start)=(*start)->next; hogya(start); } else { list* temp=*start; while(temp!=NULL) { if(temp->next) { if(temp->next->next) { if(temp->next->a>temp->next->next->a) temp->next=temp->next->next; else temp=temp->next; } else temp=temp->next; } else temp=temp->next; } } } int main() { list *start=new list; list *start2=new list; start2->a=-7; start2->next=NULL; start->a=1; start->next=NULL; int i=2; list* firstcopy=start; //cout<<(*firstcopy)->a<<endl; //list *temp; int ar[]={2,14,6,7,5,6,-3,10,11,0}; while(i<=10) { /*list* temp=new list; temp->a=i; temp->next=NULL; firstcopy->next=temp; firstcopy=firstcopy->next; i++;*/ buildlist(&start,i); i++; } list *temp=start; while(temp!=NULL) { cout<<temp->a<<"--->"; temp=temp->next; } cout<<endl; start=riverse(start,3,1); //list **tempi=&(start->next->next->next->next->next->next); //temp=riverse(*tempi,3,1); // cout<<start->a; start->next->next->next->next->next->next=riverse(start->next->next->next->next->next->next,3,1); temp=start; while(temp!=NULL) { cout<<temp->a<<"--->"; temp=temp->next; } cout<<endl; hogya(&start); temp=start; while(temp!=NULL) { cout<<temp->a<<"--->"; temp=temp->next; } /*i=-3; while(i<=20) { buildlist(&start2,i); i=i+3; } list *temp=start2; while(temp!=NULL) { cout<<temp->a<<"--->"; temp=temp->next; } cout<<endl; temp=start; while(temp!=NULL) { cout<<temp->a<<"--->"; temp=temp->next; } cout<<endl; list *start3=NULL; helper(start,start2,&start3); temp=start3; while(temp!=NULL) { cout<<temp->a<<"--->"; temp=temp->next; } cout<<endl; recrev(start3,NULL,&start3,3); temp=start3; while(temp!=NULL) { cout<<temp->a<<"--->"; temp=temp->next; } cout<<endl; //cout<<endl<<start->next->a; /*atpos(&start,3,88); list *temp=start; while(start!=NULL) { cout<<start->a<<"--->"; start=start->next; } cout<<endl; delpos(&temp,1); while(temp!=NULL) { cout<<temp->a<<"--->"; temp=temp->next; }*/ /*start->next->next->next->next->next->next->next=start; cyclefinder(start); */ // list *prev,*next; // prev=NULL; // next=NULL; //cout<<start->a; /*recrev(start,NULL,&start,3); while(start!=NULL) { cout<<start->a<<"--->"; start=start->next; }*/ return 0; }
[ "noreply@github.com" ]
myk7hackon.noreply@github.com
6cb6d04e2bc917f92d1a060b22cb95d31309a347
95b0b614e01d9731f82aee5e185927c012a3b70b
/Asteroids/bullet.h
13c4c9889db0c2689e95e0814a4a31e9a901b93c
[]
no_license
mosiah10Z/Asteroids
57cc75d4695a0dc41f57f8df94c9cf58161be32d
a5ab403782bd8b4823033328cf7eb3cb59633964
refs/heads/master
2020-03-23T04:08:16.171558
2018-07-16T00:05:57
2018-07-16T00:05:57
141,066,814
0
0
null
null
null
null
UTF-8
C++
false
false
629
h
#ifndef bullet_h #define bullet_h #define BULLET_SPEED 5 #define BULLET_LIFE 40 #include "flyingObject.h" /******************************************************************** * The Bullet Class. Derived from the FlyingObject class. * contains methods pertaining to where the bullet should fly and initiated. ***************************************************************/ class Bullet : public FlyingObject { private: int count; public: Bullet(); void draw(); virtual int getCount() { return count; } void fire(Point point, float angle, float x, float y); }; // Put your Bullet class here #endif /* bullet_h */
[ "que14003@byui.edu" ]
que14003@byui.edu
5cf2cda86d2a56b337ef6b932193b7cb77b29b94
27b78a089fa389244eefcdd08d8d7e273a3bb3e8
/tst/src/Edge-Trace2D.cpp
60cbd1bf285e67164bd76a45060a33b14497bd9d
[]
no_license
GIBIS-UNIFESP/BIAL
651f3a7f44238df977be245b07a1391d2518f974
eddd3d756b744b5caf8429acec7abe208b3a3bd1
refs/heads/master
2021-01-12T13:32:10.299904
2018-02-09T11:55:34
2018-02-09T11:55:34
69,836,560
11
6
null
2017-12-01T16:01:12
2016-10-03T02:55:05
C++
UTF-8
C++
false
false
1,740
cpp
/* Biomedical Image Analysis Library */ /* See README file in the root instalation directory for more information. */ /* Date: 2015/Jun/09 */ /* Content: Test file. */ /* Description: Test with Edge detection function. */ #include "FileImage.hpp" #include "Image.hpp" #include "Color.hpp" using namespace std; using namespace Bial; int main( int argc, char **argv ) { if( argc < 6 ) { cout << "Program to trace the edges of a path after running edge delineation algorithms such as live-wire." << endl; cout << "Usage: " << argv[ 0 ] << " <input image> <predecessor map image> <output basename> <end point coordinates>" << endl; cout << "\t\t<end point coordinates>: Coordinates of the point that ends the path." << endl; return( 0 ); } COMMENT( "Reading input image.", 0 ); Image< int > pred( Read< int >( argv[ 2 ] ) ); COMMENT( "Reading end coordinates.", 0 ); Vector< int > coord( 3, 0 ); coord[ 0 ] = atoi( argv[ 4 ] ); coord[ 1 ] = atoi( argv[ 5 ] ); COMMENT( "Creating resulting image.", 0 ); Image< int > res( pred.Dim( ), pred.PixelSize( ) ); Image< Color > cres( Read< Color >( argv[ 1 ] ) ); COMMENT( "Running though the image backwards to the root.", 0 ); res( coord ) = 1; cres( coord )[ 3 ] = 255; int leaf = static_cast< int >( pred.Position( coord ) ); do { res[ leaf ] = 1; cres[ leaf ][ 1 ] = 128; cres[ leaf ][ 2 ] = 128; leaf = pred[ leaf ]; cout << leaf << endl; } while( ( pred[ leaf ] != leaf ) && ( pred[ leaf ] != -1 ) ); res[ leaf ] = 1; cres[ leaf ][ 1 ] = 255; COMMENT( "Writing result.", 0 ); Write( res, string( argv[ 3 ] ) + ".pgm", argv[ 2 ] ); Write( cres, string( argv[ 3 ] ) + ".ppm", argv[ 1 ] ); return( 0 ); }
[ "fcappabianco@gmail.com" ]
fcappabianco@gmail.com
1f959dad3bfe68d39cf852c9265762e1839ec241
d93fe0484fc3b32c8fd9b33cc66cfd636a148ec4
/Codeforces/ECR85/probC.cpp
d068314ee1467362e0488045e24cd5c645299616
[]
no_license
wattaihei/ProgrammingContest
0d34f42f60fa6693e04c933c978527ffaddceda7
c26de8d42790651aaee56df0956e0b206d1cceb4
refs/heads/master
2023-04-22T19:43:43.394907
2021-05-02T13:05:21
2021-05-02T13:05:21
264,400,706
0
0
null
null
null
null
UTF-8
C++
false
false
241
cpp
#include <bits/stdc++.h> typedef long long ll; #define REP(i, n) for(int i = 0; i < (int)(n); i++) #define FOR(i, a, b) for(int i = (int)(a); i < (int)(b); i++) using namespace std; ll A[505050]; ll B[505050]; int main() { vector<> }
[ "wattaihei.rapyuta@gmail.com" ]
wattaihei.rapyuta@gmail.com
bf7e51f8792eb94c560cbf9acbec4d001bd22a7a
ef9a782df42136ec09485cbdbfa8a56512c32530
/branches/fasset2.3.2threads/src/fields/ALFAM.cpp
a556e1e578974e7c0e9d56cfdf6937a07ecf294b
[]
no_license
penghuz/main
c24ca5f2bf13b8cc1f483778e72ff6432577c83b
26d9398309eeacbf24e3c5affbfb597be1cc8cd4
refs/heads/master
2020-04-22T15:59:50.432329
2017-11-23T10:30:22
2017-11-23T10:30:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,777
cpp
/****************************************************************************\ $URL$ $LastChangedDate$ $LastChangedRevision$ $LastChangedBy$ \****************************************************************************/ #include "ALFAM.h" #include "../base/message.h" #include "../base/id.h" /****************************************************************************\ \****************************************************************************/ ALFAM::ALFAM() { maxTime =168.0; b_Nmx0 = -6.5757 ; b_sm1Nmx =0.0971; b_atNmx =0.0221 ; b_wsNmx =0.0409 ; b_mt1Nmx= -0.156 ; b_mdmNmx =0.1024 ; b_mtanNmx = -0.1888 ; b_ma0Nmx =3.5691; b_ma1Nmx =3.0198 ; b_ma2Nmx =3.1592 ; b_ma3Nmx =2.2702 ; b_ma4Nmx = 2.9582 ; b_mrNmx =-0.00433 ; b_mi0Nmx =2.4291 ; b_met1Nmx = -0.6382 ; b_met2Nmx = -0.5485 ; b_Km0 =0.037; b_sm1Km= 0.0974; b_atKm = -0.0409; b_wsKm = -0.0517 ; b_mt1Km =1.3567; b_mdmKm =0.1614; b_mtanKm =0.1011; b_mrKm =0.0175; b_met1Km =0.3888; b_met2Km =0.7024; } /****************************************************************************\ manureType: 0 = cattle, 1 = pig \****************************************************************************/ void ALFAM::initialise(int soilWet, double aveAirTemp, double aveWindspeed, int manureType, double initDM, double initTAN, double appRate, int appMeth, double anexposureTime) { TAN=initTAN; applicRate=appRate; exposureTime=anexposureTime; timeElapsed=0.0; switch (appMeth) { case 1: //broadcast Nmax=exp(b_Nmx0 + b_sm1Nmx*soilWet + b_atNmx*aveAirTemp + b_wsNmx*aveWindspeed + b_mt1Nmx*manureType + b_mdmNmx*initDM + b_mtanNmx*TAN + b_ma0Nmx + b_mrNmx*appRate + b_mi0Nmx + b_met2Nmx); km= exp(b_Km0 + b_sm1Km*soilWet + b_atKm*aveAirTemp + b_wsKm*aveWindspeed + b_mt1Km*manureType + b_mdmKm*initDM + b_mtanKm*TAN + b_mrKm*appRate + b_met2Km); break; case 2: //trailing hose Nmax=exp(b_Nmx0 + b_sm1Nmx*soilWet + b_atNmx*aveAirTemp + b_wsNmx*aveWindspeed + b_mt1Nmx*manureType + b_mdmNmx*initDM + b_mtanNmx*TAN + b_ma1Nmx + b_mrNmx*appRate + b_mi0Nmx + b_met2Nmx); km= exp(b_Km0 + b_sm1Km*soilWet + b_atKm*aveAirTemp + b_wsKm*aveWindspeed + b_mt1Km*manureType + b_mdmKm*initDM + b_mtanKm*TAN + b_mrKm*appRate + b_met2Km); break; case 3: //trailing shoe Nmax=exp(b_Nmx0 + b_sm1Nmx*soilWet + b_atNmx*aveAirTemp + b_wsNmx*aveWindspeed + b_mt1Nmx*manureType + b_mdmNmx*initDM + b_mtanNmx*TAN + b_ma2Nmx + b_mrNmx*appRate + b_mi0Nmx + b_met2Nmx); km= exp(b_Km0 + b_sm1Km*soilWet + b_atKm*aveAirTemp + b_wsKm*aveWindspeed + b_mt1Km*manureType + b_mdmKm*initDM + b_mtanKm*TAN + b_mrKm*appRate + b_met2Km); break; case 4: //open slot Nmax=exp(b_Nmx0 + b_sm1Nmx*soilWet + b_atNmx*aveAirTemp + b_wsNmx*aveWindspeed + b_mt1Nmx*manureType + b_mdmNmx*initDM + b_mtanNmx*TAN + b_ma3Nmx + b_mrNmx*appRate + b_mi0Nmx + b_met2Nmx); km= exp(b_Km0 + b_sm1Km*soilWet + b_atKm*aveAirTemp + b_wsKm*aveWindspeed + b_mt1Km*manureType + b_mdmKm*initDM + b_mtanKm*TAN + b_mrKm*appRate + b_met2Km); break; case 5: //closed slot Nmax=exp(b_Nmx0 + b_sm1Nmx*soilWet + b_atNmx*aveAirTemp + b_wsNmx*aveWindspeed + b_mt1Nmx*manureType + b_mdmNmx*initDM + b_mtanNmx*TAN + b_ma4Nmx + b_mrNmx*appRate + b_mi0Nmx + b_met2Nmx); km= exp(b_Km0 + b_sm1Km*soilWet + b_atKm*aveAirTemp + b_wsKm*aveWindspeed + b_mt1Km*manureType + b_mdmKm*initDM + b_mtanKm*TAN + b_mrKm*appRate + b_met2Km); break; }; }; double ALFAM::ALFAM_volatilisation(double duration) { if (timeElapsed>=exposureTime) { timeElapsed+=duration; return 0.0; } else { if ((timeElapsed+duration)>exposureTime) duration=exposureTime-timeElapsed; double ret_val = Nmax * ((timeElapsed+duration)/((timeElapsed+duration)+km)-timeElapsed/(timeElapsed+km)); if (ret_val>1.0) ret_val=1.0; ret_val *=TAN * applicRate; timeElapsed+=duration; return ret_val; } }; int ALFAM::GetALFAMApplicCode(int OpCode) { switch (OpCode) { case 7://SpreadingLiquidManure return 1; case 8: //ClosedSlotInjectingLiquidManure return 5; case 9://SpreadingSolidManure return 1; case 35: //OpenSlotInjectingLiquidManure return 4; case 36: //TrailingHoseSpreadingLiquidManure return 2; case 37: //TrailingShoeSpreadingLiquidManure return 3; default: int id =threadID->getID(std::this_thread::get_id()); theMessage[id]->FatalError("ALFAM: application method code not found"); } return 0; }; bool ALFAM::GetIsfinished() { if (timeElapsed>=maxTime) return true; else return false; }
[ "sai@agro.au.dk" ]
sai@agro.au.dk
4727e641f7845ca5ac5bbf3847bfe1070d362728
67b9a956151e54aba0fb06c037c9e5fb02be8149
/Pratica02/pratica2.cpp
ef3257fd040a525f2eda2ed66a63f439c8a471b4
[]
no_license
vinny-vin/Algoritimo-e-Estrutura-de-Dados
2d5c4145482d1cfbc4079338e0e6727c8c0965a0
d4b24e4d1a30bbb6e5ab204457dca2cd99346a09
refs/heads/master
2021-02-05T11:31:40.312040
2020-03-14T14:34:11
2020-03-14T14:34:11
243,775,310
0
0
null
null
null
null
UTF-8
C++
false
false
735
cpp
/* * pratica2.cpp * * Created on: 29 de fev de 2020 * Author: ALUNO */ #include <iostream> #include "veiculo.h" using namespace std; int main(){ Veiculo v1 ("V1"); Terrestre t1 ("T1"); Aquatico aq1 ("Aq1"); Aereo ae1("Ae1"); Veiculo * terr = new Terrestre("VT1"); // ((Terrestre *) terr)->setCap_pass(45); dynamic_cast<terr>(Terrestre)->setCap_pass(); Veiculo * aqua = new Aquatico("VO1"); ((Aquatico *) aqua)->setCarga_Max(12.5); Veiculo * aereo = new Aereo("VA1"); ((Aereo *) aereo)->setVel_max(1040.5); terr->mover(); aqua->mover(); aereo->mover(); delete terr; delete aqua; delete aereo; dynamic_cast<NovoTipo>(var)->metodo(); }
[ "noreply@github.com" ]
vinny-vin.noreply@github.com
c430a99b92fbd48910c36252b26e6e19c305f56f
fa274ec4f0c66c61d6acd476e024d8e7bdfdcf54
/Resoluções OJ/codeforces/Maratona de Programação Contra o COVID-19 /b.cpp
56c3e50f2f47931bbf17d2c86b2d3078044c0519
[]
no_license
luanaamorim04/Competitive-Programming
1c204b9c21e9c22b4d63ad425a98f4453987b879
265ad98ffecb304524ac805612dfb698d0a419d8
refs/heads/master
2023-07-13T03:04:51.447580
2021-08-11T00:28:57
2021-08-11T00:28:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,058
cpp
#include<bits/stdc++.h> #define _ ios_base::sync_with_stdio(0); #define endl '\n' #define INF 0x3f3f3f3f #define MAX (1<<20) #define i64 long long #define all(x) (x).begin() , (x).end() #define sz(x) (int)(x).size() #define ii pair<int, int> #define fs first #define sc second #define eb emplace_back #define vi vector<int> #define vvi vector<vi> #define vii vector<ii> #define vvii vector<vii> #define lsb(x) ((x) & (-x)) #define gcd(x,y) __gcd((x),(y)) using namespace std; int c, v; int a[1<<7][1<<7]; int x, y, m; int main(){_ cin >> c >> v; while (v--) { cin >> x >> y; for (int i=-1; i<=1; ++i){ for (int j=-1; j<=1; ++j){ a[x+i][y+j] = 1; } } } cin >> m; while (m--){ cin >> x >> y; if (a[x][y]){ cout << "Nao" << endl; continue; } for (int i=-1; i<=1; ++i){ for (int j=-1; j<=1; ++j){ a[x+i][y+j] = 1; } } cout << "Sim" << endl; } return 0; }
[ "fepaf.eng@dmz.org.br" ]
fepaf.eng@dmz.org.br
382fc4ee65a8e85e2fe8bc30dbbe8eacf6420e6d
792a52844d2e53fdbd3582d9edb95eedec651a74
/ThirdParty/rapidjson/example/serialize/serialize.cpp
078e59ee32ff68b410701da1fff48670fd7820e3
[ "MIT" ]
permissive
alanly/comp371
42ade8a6bf4bbd5031fa7e552af0e6e7f3246c1d
dd0e4f3c3b9e8e4a67b048e5c354a1ded0578a0d
refs/heads/master
2021-01-18T23:20:34.469596
2014-08-19T17:01:13
2014-08-19T17:01:13
22,010,621
1
0
null
null
null
null
UTF-8
C++
false
false
3,614
cpp
// Serialize example // This example shows writing JSON string with writer directly. #include "rapidjson/prettywriter.h" // for stringify JSON #include "rapidjson/filestream.h" // wrapper of C stream for prettywriter as output #include <cstdio> #include <string> #include <vector> using namespace rapidjson; class Person { public: Person(const std::string& name, unsigned age) : name_(name), age_(age) {} virtual ~Person(); protected: template <typename Writer> void Serialize(Writer& writer) const { // This base class just write out name-value pairs, without wrapping within an object. writer.String("name"); writer.String(name_.c_str(), (SizeType)name_.length()); // Suppling length of string is faster. writer.String("age"); writer.Uint(age_); } private: std::string name_; unsigned age_; }; Person::~Person() { } class Education { public: Education(const std::string& school, double GPA) : school_(school), GPA_(GPA) {} template <typename Writer> void Serialize(Writer& writer) const { writer.StartObject(); writer.String("school"); writer.String(school_.c_str(), (SizeType)school_.length()); writer.String("GPA"); writer.Double(GPA_); writer.EndObject(); } private: std::string school_; double GPA_; }; class Dependent : public Person { public: Dependent(const std::string& name, unsigned age, Education* education = 0) : Person(name, age), education_(education) {} Dependent(const Dependent& rhs) : Person(rhs), education_(0) { education_ = (rhs.education_ == 0) ? 0 : new Education(*rhs.education_); } virtual ~Dependent(); Dependent& operator=(const Dependent& rhs) { if (this == &rhs) return *this; delete education_; education_ = (rhs.education_ == 0) ? 0 : new Education(*rhs.education_); return *this; } template <typename Writer> void Serialize(Writer& writer) const { writer.StartObject(); Person::Serialize(writer); writer.String("education"); if (education_) education_->Serialize(writer); else writer.Null(); writer.EndObject(); } private: Education *education_; }; Dependent::~Dependent() { delete education_; } class Employee : public Person { public: Employee(const std::string& name, unsigned age, bool married) : Person(name, age), dependents_(), married_(married) {} virtual ~Employee(); void AddDependent(const Dependent& dependent) { dependents_.push_back(dependent); } template <typename Writer> void Serialize(Writer& writer) const { writer.StartObject(); Person::Serialize(writer); writer.String("married"); writer.Bool(married_); writer.String(("dependents")); writer.StartArray(); for (std::vector<Dependent>::const_iterator dependentItr = dependents_.begin(); dependentItr != dependents_.end(); ++dependentItr) dependentItr->Serialize(writer); writer.EndArray(); writer.EndObject(); } private: std::vector<Dependent> dependents_; bool married_; }; Employee::~Employee() { } int main(int, char*[]) { std::vector<Employee> employees; employees.push_back(Employee("Milo YIP", 34, true)); employees.back().AddDependent(Dependent("Lua YIP", 3, new Education("Happy Kindergarten", 3.5))); employees.back().AddDependent(Dependent("Mio YIP", 1)); employees.push_back(Employee("Percy TSE", 30, false)); FileStream s(stdout); PrettyWriter<FileStream> writer(s); // Can also use Writer for condensed formatting writer.StartArray(); for (std::vector<Employee>::const_iterator employeeItr = employees.begin(); employeeItr != employees.end(); ++employeeItr) employeeItr->Serialize(writer); writer.EndArray(); return 0; }
[ "louis.mclean@gmail.com" ]
louis.mclean@gmail.com
ed42b9229f511c63e7a033780614ca1526eb769a
2e3577c77cc43a558342aeab8a83a82d6c4a021c
/C++/useArrayToInit.cpp
82866bdd2356cf9a137df7461172f28e227f5b76
[]
no_license
Tokiya-wang/CodeInLinux
a964d6faf85f3d6e5a821bcf787672fd33560c92
345b7dd6ba81e673b188af6d188d636c728ba40e
refs/heads/master
2022-03-18T09:19:24.759226
2019-11-07T03:07:14
2019-11-07T03:07:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
226
cpp
#include <iostream> #include <vector> #include <iterator> using namespace std; int main(void) { int arr[10] = {1, 2, 3, 4, 5}; vector<int> v(begin(arr), end(arr)); for (const auto it : v) cout << it << endl; return 0; }
[ "1240953839@qq.com" ]
1240953839@qq.com
55ae2a75bb3279fd2622aa02e83e403f9fd79ee3
2dbb6208f065a6e6bc4c3d3996f3dd4253821cfb
/thirdparty/FreeImage/FreeImageToolkit/Resize.cpp
0c6b2d9f02502d7e8f9f95e5a67c96bce6472b00
[ "MIT" ]
permissive
ShalokShalom/echo
2ef7475f6f3bd65fe106a1bb730de2ade0b64bab
02e3d9d8f0066f47cbc25288666977cef3e26a2f
refs/heads/master
2022-12-13T07:14:49.064952
2020-09-17T02:08:41
2020-09-17T02:08:41
296,278,603
0
0
MIT
2020-09-17T09:21:31
2020-09-17T09:21:30
null
WINDOWS-1250
C++
false
false
76,162
cpp
// ========================================================== // Upsampling / downsampling classes // // Design and implementation by // - Hervé Drolon (drolon@infonie.fr) // - Detlev Vendt (detlev.vendt@brillit.de) // - Carsten Klein (cklein05@users.sourceforge.net) // // This file is part of FreeImage 3 // // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER // THIS DISCLAIMER. // // Use at your own risk! // ========================================================== #include "Resize.h" /** Returns the color type of a bitmap. In contrast to FreeImage_GetColorType, this function optionally supports a boolean OUT parameter, that receives TRUE, if the specified bitmap is greyscale, that is, it consists of grey colors only. Although it returns the same value as returned by FreeImage_GetColorType for all image types, this extended function primarily is intended for palletized images, since the boolean pointed to by 'bIsGreyscale' remains unchanged for RGB(A/F) images. However, the outgoing boolean is properly maintained for palletized images, as well as for any non-RGB image type, like FIT_UINTxx and FIT_DOUBLE, for example. @param dib A pointer to a FreeImage bitmap to calculate the extended color type for @param bIsGreyscale A pointer to a boolean, that receives TRUE, if the specified bitmap is greyscale, that is, it consists of grey colors only. This parameter can be NULL. @return the color type of the specified bitmap */ static FREE_IMAGE_COLOR_TYPE GetExtendedColorType(FIBITMAP *dib, BOOL *bIsGreyscale) { const unsigned bpp = FreeImage_GetBPP(dib); const unsigned size = CalculateUsedPaletteEntries(bpp); const RGBQUAD * const pal = FreeImage_GetPalette(dib); FREE_IMAGE_COLOR_TYPE color_type = FIC_MINISBLACK; BOOL bIsGrey = TRUE; switch (bpp) { case 1: { for (unsigned i = 0; i < size; i++) { if ((pal[i].rgbRed != pal[i].rgbGreen) || (pal[i].rgbRed != pal[i].rgbBlue)) { color_type = FIC_PALETTE; bIsGrey = FALSE; break; } } if (bIsGrey) { if (pal[0].rgbBlue == 255 && pal[1].rgbBlue == 0) { color_type = FIC_MINISWHITE; } else if (pal[0].rgbBlue != 0 || pal[1].rgbBlue != 255) { color_type = FIC_PALETTE; } } break; } case 4: case 8: { for (unsigned i = 0; i < size; i++) { if ((pal[i].rgbRed != pal[i].rgbGreen) || (pal[i].rgbRed != pal[i].rgbBlue)) { color_type = FIC_PALETTE; bIsGrey = FALSE; break; } if (color_type != FIC_PALETTE && pal[i].rgbBlue != i) { if ((size - i - 1) != pal[i].rgbBlue) { color_type = FIC_PALETTE; if (!bIsGreyscale) { // exit loop if we're not setting // bIsGreyscale parameter break; } } else { color_type = FIC_MINISWHITE; } } } break; } default: { color_type = FreeImage_GetColorType(dib); bIsGrey = (color_type == FIC_MINISBLACK) ? TRUE : FALSE; break; } } if (bIsGreyscale) { *bIsGreyscale = bIsGrey; } return color_type; } /** Returns a pointer to an RGBA palette, created from the specified bitmap. The RGBA palette is a copy of the specified bitmap's palette, that, additionally contains the bitmap's transparency information in the rgbReserved member of the palette's RGBQUAD elements. @param dib A pointer to a FreeImage bitmap to create the RGBA palette from. @param buffer A pointer to the buffer to store the RGBA palette. @return A pointer to the newly created RGBA palette or NULL, if the specified bitmap is no palletized standard bitmap. If non-NULL, the returned value is actually the pointer passed in parameter 'buffer'. */ static inline RGBQUAD * GetRGBAPalette(FIBITMAP *dib, RGBQUAD * const buffer) { // clone the palette const unsigned ncolors = FreeImage_GetColorsUsed(dib); if (ncolors == 0) { return NULL; } memcpy(buffer, FreeImage_GetPalette(dib), ncolors * sizeof(RGBQUAD)); // merge the transparency table const unsigned ntransp = MIN(ncolors, FreeImage_GetTransparencyCount(dib)); const BYTE * const tt = FreeImage_GetTransparencyTable(dib); for (unsigned i = 0; i < ntransp; i++) { buffer[i].rgbReserved = tt[i]; } for (unsigned i = ntransp; i < ncolors; i++) { buffer[i].rgbReserved = 255; } return buffer; } // -------------------------------------------------------------------------- CWeightsTable::CWeightsTable(CGenericFilter *pFilter, unsigned uDstSize, unsigned uSrcSize) { double dWidth; double dFScale; const double dFilterWidth = pFilter->GetWidth(); // scale factor const double dScale = double(uDstSize) / double(uSrcSize); if(dScale < 1.0) { // minification dWidth = dFilterWidth / dScale; dFScale = dScale; } else { // magnification dWidth = dFilterWidth; dFScale = 1.0; } // allocate a new line contributions structure // // window size is the number of sampled pixels m_WindowSize = 2 * (int)ceil(dWidth) + 1; // length of dst line (no. of rows / cols) m_LineLength = uDstSize; // allocate list of contributions m_WeightTable = (Contribution*)malloc(m_LineLength * sizeof(Contribution)); for(unsigned u = 0; u < m_LineLength; u++) { // allocate contributions for every pixel m_WeightTable[u].Weights = (double*)malloc(m_WindowSize * sizeof(double)); } // offset for discrete to continuous coordinate conversion const double dOffset = (0.5 / dScale); for(unsigned u = 0; u < m_LineLength; u++) { // scan through line of contributions // inverse mapping (discrete dst 'u' to continous src 'dCenter') const double dCenter = (double)u / dScale + dOffset; // find the significant edge points that affect the pixel const int iLeft = MAX(0, (int)(dCenter - dWidth + 0.5)); const int iRight = MIN((int)(dCenter + dWidth + 0.5), int(uSrcSize)); m_WeightTable[u].Left = iLeft; m_WeightTable[u].Right = iRight; double dTotalWeight = 0; // sum of weights (initialized to zero) for(int iSrc = iLeft; iSrc < iRight; iSrc++) { // calculate weights const double weight = dFScale * pFilter->Filter(dFScale * ((double)iSrc + 0.5 - dCenter)); // assert((iSrc-iLeft) < m_WindowSize); m_WeightTable[u].Weights[iSrc-iLeft] = weight; dTotalWeight += weight; } if((dTotalWeight > 0) && (dTotalWeight != 1)) { // normalize weight of neighbouring points for(int iSrc = iLeft; iSrc < iRight; iSrc++) { // normalize point m_WeightTable[u].Weights[iSrc-iLeft] /= dTotalWeight; } } // simplify the filter, discarding null weights at the right { int iTrailing = iRight - iLeft - 1; while(m_WeightTable[u].Weights[iTrailing] == 0) { m_WeightTable[u].Right--; iTrailing--; if(m_WeightTable[u].Right == m_WeightTable[u].Left) { break; } } } } // next dst pixel } CWeightsTable::~CWeightsTable() { for(unsigned u = 0; u < m_LineLength; u++) { // free contributions for every pixel free(m_WeightTable[u].Weights); } // free list of pixels contributions free(m_WeightTable); } // -------------------------------------------------------------------------- FIBITMAP* CResizeEngine::scale(FIBITMAP *src, unsigned dst_width, unsigned dst_height, unsigned src_left, unsigned src_top, unsigned src_width, unsigned src_height) { const FREE_IMAGE_TYPE image_type = FreeImage_GetImageType(src); const unsigned src_bpp = FreeImage_GetBPP(src); // determine the image's color type BOOL bIsGreyscale = FALSE; FREE_IMAGE_COLOR_TYPE color_type; if (src_bpp <= 8) { color_type = GetExtendedColorType(src, &bIsGreyscale); } else { color_type = FIC_RGB; } // determine the required bit depth of the destination image unsigned dst_bpp; if (color_type == FIC_PALETTE && !bIsGreyscale) { // non greyscale FIC_PALETTE images require a high-color destination // image (24- or 32-bits depending on the image's transparent state) dst_bpp = FreeImage_IsTransparent(src) ? 32 : 24; } else if (src_bpp <= 8) { // greyscale images require an 8-bit destination image // (or a 32-bit image if the image is transparent) dst_bpp = FreeImage_IsTransparent(src) ? 32 : 8; if (dst_bpp == 32) { // additionally, for transparent images we always need a // palette including transparency information (an RGBA palette) // so, set color_type accordingly. color_type = FIC_PALETTE; } } else if (src_bpp == 16 && image_type == FIT_BITMAP) { // 16-bit 555 and 565 RGB images require a high-color destination image // (fixed to 24 bits, since 16-bit RGBs don't support transparency in FreeImage) dst_bpp = 24; } else { // bit depth remains unchanged for all other images dst_bpp = src_bpp; } // early exit if destination size is equal to source size if ((src_width == dst_width) && (src_height == dst_height)) { FIBITMAP *out = src; FIBITMAP *tmp = src; if ((src_width != FreeImage_GetWidth(src)) || (src_height != FreeImage_GetHeight(src))) { out = FreeImage_Copy(tmp, src_left, src_top, src_left + src_width, src_top + src_height); tmp = out; } if (src_bpp != dst_bpp) { switch (dst_bpp) { case 8: out = FreeImage_ConvertToGreyscale(tmp); if (tmp != src) { FreeImage_Unload(tmp); } break; case 24: out = FreeImage_ConvertTo24Bits(tmp); if (tmp != src) { FreeImage_Unload(tmp); } break; case 32: out = FreeImage_ConvertTo32Bits(tmp); if (tmp != src) { FreeImage_Unload(tmp); } break; } } return (out != src) ? out : FreeImage_Clone(src); } RGBQUAD pal_buffer[256]; RGBQUAD *src_pal = NULL; // provide the source image's palette to the rescaler for // FIC_PALETTE type images (this includes palletized greyscale // images with an unordered palette as well as transparent images) if (color_type == FIC_PALETTE) { if (dst_bpp == 32) { // a 32 bit destination image signals transparency, so // create an RGBA palette from the source palette src_pal = GetRGBAPalette(src, pal_buffer); } else { src_pal = FreeImage_GetPalette(src); } } // allocate the dst image FIBITMAP *dst = FreeImage_AllocateT(image_type, dst_width, dst_height, dst_bpp, 0, 0, 0); if (!dst) { return NULL; } if (dst_bpp == 8) { RGBQUAD * const dst_pal = FreeImage_GetPalette(dst); if (color_type == FIC_MINISWHITE) { // build an inverted greyscale palette CREATE_GREYSCALE_PALETTE_REVERSE(dst_pal, 256); } /* else { // build a default greyscale palette // Currently, FreeImage_AllocateT already creates a default // greyscale palette for 8 bpp images, so we can skip this here. CREATE_GREYSCALE_PALETTE(dst_pal, 256); } */ } // calculate x and y offsets; since FreeImage uses bottom-up bitmaps, the // value of src_offset_y is measured from the bottom of the image unsigned src_offset_x = src_left; unsigned src_offset_y; if (src_top > 0) { src_offset_y = FreeImage_GetHeight(src) - src_height - src_top; } else { src_offset_y = 0; } /* Decide which filtering order (xy or yx) is faster for this mapping. --- The theory --- Try to minimize calculations by counting the number of convolution multiplies if(dst_width*src_height <= src_width*dst_height) { // xy filtering } else { // yx filtering } --- The practice --- Try to minimize calculations by counting the number of vertical convolutions (the most time consuming task) if(dst_width*dst_height <= src_width*dst_height) { // xy filtering } else { // yx filtering } */ if (dst_width <= src_width) { // xy filtering // ------------- FIBITMAP *tmp = NULL; if (src_width != dst_width) { // source and destination widths are different so, we must // filter horizontally if (src_height != dst_height) { // source and destination heights are also different so, we need // a temporary image tmp = FreeImage_AllocateT(image_type, dst_width, src_height, dst_bpp, 0, 0, 0); if (!tmp) { FreeImage_Unload(dst); return NULL; } } else { // source and destination heights are equal so, we can directly // scale into destination image (second filter method will not // be invoked) tmp = dst; } // scale source image horizontally into temporary (or destination) image horizontalFilter(src, src_height, src_width, src_offset_x, src_offset_y, src_pal, tmp, dst_width); // set x and y offsets to zero for the second filter method // invocation (the temporary image only contains the portion of // the image to be rescaled with no offsets) src_offset_x = 0; src_offset_y = 0; // also ensure, that the second filter method gets no source // palette (the temporary image is palletized only, if it is // greyscale; in that case, it is an 8-bit image with a linear // palette so, the source palette is not needed or will even be // mismatching, if the source palette is unordered) src_pal = NULL; } else { // source and destination widths are equal so, just copy the // image pointer tmp = src; } if (src_height != dst_height) { // source and destination heights are different so, scale // temporary (or source) image vertically into destination image verticalFilter(tmp, dst_width, src_height, src_offset_x, src_offset_y, src_pal, dst, dst_height); } // free temporary image, if not pointing to either src or dst if (tmp != src && tmp != dst) { FreeImage_Unload(tmp); } } else { // yx filtering // ------------- // Remark: // The yx filtering branch could be more optimized by taking into, // account that (src_width != dst_width) is always true, which // follows from the above condition, which selects filtering order. // Since (dst_width <= src_width) == TRUE selects xy filtering, // both widths must be different when performing yx filtering. // However, to make the code more robust, not depending on that // condition and more symmetric to the xy filtering case, these // (src_width != dst_width) conditions are still in place. FIBITMAP *tmp = NULL; if (src_height != dst_height) { // source and destination heights are different so, we must // filter vertically if (src_width != dst_width) { // source and destination widths are also different so, we need // a temporary image tmp = FreeImage_AllocateT(image_type, src_width, dst_height, dst_bpp, 0, 0, 0); if (!tmp) { FreeImage_Unload(dst); return NULL; } } else { // source and destination widths are equal so, we can directly // scale into destination image (second filter method will not // be invoked) tmp = dst; } // scale source image vertically into temporary (or destination) image verticalFilter(src, src_width, src_height, src_offset_x, src_offset_y, src_pal, tmp, dst_height); // set x and y offsets to zero for the second filter method // invocation (the temporary image only contains the portion of // the image to be rescaled with no offsets) src_offset_x = 0; src_offset_y = 0; // also ensure, that the second filter method gets no source // palette (the temporary image is palletized only, if it is // greyscale; in that case, it is an 8-bit image with a linear // palette so, the source palette is not needed or will even be // mismatching, if the source palette is unordered) src_pal = NULL; } else { // source and destination heights are equal so, just copy the // image pointer tmp = src; } if (src_width != dst_width) { // source and destination heights are different so, scale // temporary (or source) image horizontally into destination image horizontalFilter(tmp, dst_height, src_width, src_offset_x, src_offset_y, src_pal, dst, dst_width); } // free temporary image, if not pointing to either src or dst if (tmp != src && tmp != dst) { FreeImage_Unload(tmp); } } return dst; } void CResizeEngine::horizontalFilter(FIBITMAP *const src, unsigned height, unsigned src_width, unsigned src_offset_x, unsigned src_offset_y, const RGBQUAD *const src_pal, FIBITMAP *const dst, unsigned dst_width) { // allocate and calculate the contributions CWeightsTable weightsTable(m_pFilter, dst_width, src_width); // step through rows switch(FreeImage_GetImageType(src)) { case FIT_BITMAP: { switch(FreeImage_GetBPP(src)) { case 1: { switch(FreeImage_GetBPP(dst)) { case 8: { // transparently convert the 1-bit non-transparent greyscale // image to 8 bpp src_offset_x >>= 3; if (src_pal) { // we have got a palette for (unsigned y = 0; y < height; y++) { // scale each row const BYTE * const src_bits = FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x; BYTE * const dst_bits = FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iRight = weightsTable.getRightBoundary(x); // retrieve right boundary double value = 0; for (unsigned i = iLeft; i < iRight; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const unsigned pixel = (src_bits[i >> 3] & (0x80 >> (i & 0x07))) != 0; value += (weightsTable.getWeight(x, i - iLeft) * (double)*(BYTE *)&src_pal[pixel]); } // clamp and place result in destination pixel dst_bits[x] = (BYTE)CLAMP<int>((int)(value + 0.5), 0, 0xFF); } } } else { // we do not have a palette for (unsigned y = 0; y < height; y++) { // scale each row const BYTE * const src_bits = FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x; BYTE * const dst_bits = FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iRight = weightsTable.getRightBoundary(x); // retrieve right boundary double value = 0; for (unsigned i = iLeft; i < iRight; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const unsigned pixel = (src_bits[i >> 3] & (0x80 >> (i & 0x07))) != 0; value += (weightsTable.getWeight(x, i - iLeft) * (double)pixel); } value *= 0xFF; // clamp and place result in destination pixel dst_bits[x] = (BYTE)CLAMP<int>((int)(value + 0.5), 0, 0xFF); } } } } break; case 24: { // transparently convert the non-transparent 1-bit image // to 24 bpp; we always have got a palette here src_offset_x >>= 3; for (unsigned y = 0; y < height; y++) { // scale each row const BYTE * const src_bits = FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x; BYTE *dst_bits = FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iRight = weightsTable.getRightBoundary(x); // retrieve right boundary double r = 0, g = 0, b = 0; for (unsigned i = iLeft; i < iRight; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(x, i - iLeft); const unsigned pixel = (src_bits[i >> 3] & (0x80 >> (i & 0x07))) != 0; const BYTE * const entry = (BYTE *)&src_pal[pixel]; r += (weight * (double)entry[FI_RGBA_RED]); g += (weight * (double)entry[FI_RGBA_GREEN]); b += (weight * (double)entry[FI_RGBA_BLUE]); } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(r + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(g + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(b + 0.5), 0, 0xFF); dst_bits += 3; } } } break; case 32: { // transparently convert the transparent 1-bit image // to 32 bpp; we always have got a palette here src_offset_x >>= 3; for (unsigned y = 0; y < height; y++) { // scale each row const BYTE * const src_bits = FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x; BYTE *dst_bits = FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iRight = weightsTable.getRightBoundary(x); // retrieve right boundary double r = 0, g = 0, b = 0, a = 0; for (unsigned i = iLeft; i < iRight; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(x, i - iLeft); const unsigned pixel = (src_bits[i >> 3] & (0x80 >> (i & 0x07))) != 0; const BYTE * const entry = (BYTE *)&src_pal[pixel]; r += (weight * (double)entry[FI_RGBA_RED]); g += (weight * (double)entry[FI_RGBA_GREEN]); b += (weight * (double)entry[FI_RGBA_BLUE]); a += (weight * (double)entry[FI_RGBA_ALPHA]); } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(r + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(g + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(b + 0.5), 0, 0xFF); dst_bits[FI_RGBA_ALPHA] = (BYTE)CLAMP<int>((int)(a + 0.5), 0, 0xFF); dst_bits += 4; } } } break; } } break; case 4: { switch(FreeImage_GetBPP(dst)) { case 8: { // transparently convert the non-transparent 4-bit greyscale image // to 8 bpp; we always have got a palette for 4-bit images src_offset_x >>= 1; for (unsigned y = 0; y < height; y++) { // scale each row const BYTE * const src_bits = FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x; BYTE * const dst_bits = FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iRight = weightsTable.getRightBoundary(x); // retrieve right boundary double value = 0; for (unsigned i = iLeft; i < iRight; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const unsigned pixel = i & 0x01 ? src_bits[i >> 1] & 0x0F : src_bits[i >> 1] >> 4; value += (weightsTable.getWeight(x, i - iLeft) * (double)*(BYTE *)&src_pal[pixel]); } // clamp and place result in destination pixel dst_bits[x] = (BYTE)CLAMP<int>((int)(value + 0.5), 0, 0xFF); } } } break; case 24: { // transparently convert the non-transparent 4-bit image // to 24 bpp; we always have got a palette for 4-bit images src_offset_x >>= 1; for (unsigned y = 0; y < height; y++) { // scale each row const BYTE * const src_bits = FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x; BYTE *dst_bits = FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iRight = weightsTable.getRightBoundary(x); // retrieve right boundary double r = 0, g = 0, b = 0; for (unsigned i = iLeft; i < iRight; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(x, i - iLeft); const unsigned pixel = i & 0x01 ? src_bits[i >> 1] & 0x0F : src_bits[i >> 1] >> 4; const BYTE * const entry = (BYTE *)&src_pal[pixel]; r += (weight * (double)entry[FI_RGBA_RED]); g += (weight * (double)entry[FI_RGBA_GREEN]); b += (weight * (double)entry[FI_RGBA_BLUE]); } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(r + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(g + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(b + 0.5), 0, 0xFF); dst_bits += 3; } } } break; case 32: { // transparently convert the transparent 4-bit image // to 32 bpp; we always have got a palette for 4-bit images src_offset_x >>= 1; for (unsigned y = 0; y < height; y++) { // scale each row const BYTE * const src_bits = FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x; BYTE *dst_bits = FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iRight = weightsTable.getRightBoundary(x); // retrieve right boundary double r = 0, g = 0, b = 0, a = 0; for (unsigned i = iLeft; i < iRight; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(x, i - iLeft); const unsigned pixel = i & 0x01 ? src_bits[i >> 1] & 0x0F : src_bits[i >> 1] >> 4; const BYTE * const entry = (BYTE *)&src_pal[pixel]; r += (weight * (double)entry[FI_RGBA_RED]); g += (weight * (double)entry[FI_RGBA_GREEN]); b += (weight * (double)entry[FI_RGBA_BLUE]); a += (weight * (double)entry[FI_RGBA_ALPHA]); } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(r + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(g + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(b + 0.5), 0, 0xFF); dst_bits[FI_RGBA_ALPHA] = (BYTE)CLAMP<int>((int)(a + 0.5), 0, 0xFF); dst_bits += 4; } } } break; } } break; case 8: { switch(FreeImage_GetBPP(dst)) { case 8: { // scale the 8-bit non-transparent greyscale image // into an 8 bpp destination image if (src_pal) { // we have got a palette for (unsigned y = 0; y < height; y++) { // scale each row const BYTE * const src_bits = FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x; BYTE * const dst_bits = FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(x) - iLeft; // retrieve right boundary const BYTE * const pixel = src_bits + iLeft; double value = 0; // for(i = iLeft to iRight) for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel value += (weightsTable.getWeight(x, i) * (double)*(BYTE *)&src_pal[pixel[i]]); } // clamp and place result in destination pixel dst_bits[x] = (BYTE)CLAMP<int>((int)(value + 0.5), 0, 0xFF); } } } else { // we do not have a palette for (unsigned y = 0; y < height; y++) { // scale each row const BYTE * const src_bits = FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x; BYTE * const dst_bits = FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(x) - iLeft; // retrieve right boundary const BYTE * const pixel = src_bits + iLeft; double value = 0; // for(i = iLeft to iRight) for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel value += (weightsTable.getWeight(x, i) * (double)pixel[i]); } // clamp and place result in destination pixel dst_bits[x] = (BYTE)CLAMP<int>((int)(value + 0.5), 0, 0xFF); } } } } break; case 24: { // transparently convert the non-transparent 8-bit image // to 24 bpp; we always have got a palette here for (unsigned y = 0; y < height; y++) { // scale each row const BYTE * const src_bits = FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x; BYTE *dst_bits = FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(x) - iLeft; // retrieve right boundary const BYTE * const pixel = src_bits + iLeft; double r = 0, g = 0, b = 0; // for(i = iLeft to iRight) for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(x, i); const BYTE *const entry = (BYTE *)&src_pal[pixel[i]]; r += (weight * (double)entry[FI_RGBA_RED]); g += (weight * (double)entry[FI_RGBA_GREEN]); b += (weight * (double)entry[FI_RGBA_BLUE]); } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(r + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(g + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(b + 0.5), 0, 0xFF); dst_bits += 3; } } } break; case 32: { // transparently convert the transparent 8-bit image // to 32 bpp; we always have got a palette here for (unsigned y = 0; y < height; y++) { // scale each row const BYTE * const src_bits = FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x; BYTE *dst_bits = FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(x) - iLeft; // retrieve right boundary const BYTE * const pixel = src_bits + iLeft; double r = 0, g = 0, b = 0, a = 0; // for(i = iLeft to iRight) for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(x, i); const BYTE * const entry = (BYTE *)&src_pal[pixel[i]]; r += (weight * (double)entry[FI_RGBA_RED]); g += (weight * (double)entry[FI_RGBA_GREEN]); b += (weight * (double)entry[FI_RGBA_BLUE]); a += (weight * (double)entry[FI_RGBA_ALPHA]); } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(r + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(g + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(b + 0.5), 0, 0xFF); dst_bits[FI_RGBA_ALPHA] = (BYTE)CLAMP<int>((int)(a + 0.5), 0, 0xFF); dst_bits += 4; } } } break; } } break; case 16: { // transparently convert the 16-bit non-transparent image // to 24 bpp if (IS_FORMAT_RGB565(src)) { // image has 565 format for (unsigned y = 0; y < height; y++) { // scale each row const WORD * const src_bits = (WORD *)FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x / sizeof(WORD); BYTE *dst_bits = FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(x) - iLeft; // retrieve right boundary const WORD *pixel = src_bits + iLeft; double r = 0, g = 0, b = 0; // for(i = iLeft to iRight) for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(x, i); r += (weight * (double)((*pixel & FI16_565_RED_MASK) >> FI16_565_RED_SHIFT)); g += (weight * (double)((*pixel & FI16_565_GREEN_MASK) >> FI16_565_GREEN_SHIFT)); b += (weight * (double)((*pixel & FI16_565_BLUE_MASK) >> FI16_565_BLUE_SHIFT)); pixel++; } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(((r * 0xFF) / 0x1F) + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(((g * 0xFF) / 0x3F) + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(((b * 0xFF) / 0x1F) + 0.5), 0, 0xFF); dst_bits += 3; } } } else { // image has 555 format for (unsigned y = 0; y < height; y++) { // scale each row const WORD * const src_bits = (WORD *)FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x; BYTE *dst_bits = FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(x) - iLeft; // retrieve right boundary const WORD *pixel = src_bits + iLeft; double r = 0, g = 0, b = 0; // for(i = iLeft to iRight) for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(x, i); r += (weight * (double)((*pixel & FI16_555_RED_MASK) >> FI16_555_RED_SHIFT)); g += (weight * (double)((*pixel & FI16_555_GREEN_MASK) >> FI16_555_GREEN_SHIFT)); b += (weight * (double)((*pixel & FI16_555_BLUE_MASK) >> FI16_555_BLUE_SHIFT)); pixel++; } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(((r * 0xFF) / 0x1F) + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(((g * 0xFF) / 0x1F) + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(((b * 0xFF) / 0x1F) + 0.5), 0, 0xFF); dst_bits += 3; } } } } break; case 24: { // scale the 24-bit non-transparent image // into a 24 bpp destination image for (unsigned y = 0; y < height; y++) { // scale each row const BYTE * const src_bits = FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x * 3; BYTE *dst_bits = FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(x) - iLeft; // retrieve right boundary const BYTE * pixel = src_bits + iLeft * 3; double r = 0, g = 0, b = 0; // for(i = iLeft to iRight) for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(x, i); r += (weight * (double)pixel[FI_RGBA_RED]); g += (weight * (double)pixel[FI_RGBA_GREEN]); b += (weight * (double)pixel[FI_RGBA_BLUE]); pixel += 3; } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(r + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(g + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(b + 0.5), 0, 0xFF); dst_bits += 3; } } } break; case 32: { // scale the 32-bit transparent image // into a 32 bpp destination image for (unsigned y = 0; y < height; y++) { // scale each row const BYTE * const src_bits = FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x * 4; BYTE *dst_bits = FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(x) - iLeft; // retrieve right boundary const BYTE *pixel = src_bits + iLeft * 4; double r = 0, g = 0, b = 0, a = 0; // for(i = iLeft to iRight) for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(x, i); r += (weight * (double)pixel[FI_RGBA_RED]); g += (weight * (double)pixel[FI_RGBA_GREEN]); b += (weight * (double)pixel[FI_RGBA_BLUE]); a += (weight * (double)pixel[FI_RGBA_ALPHA]); pixel += 4; } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(r + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(g + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(b + 0.5), 0, 0xFF); dst_bits[FI_RGBA_ALPHA] = (BYTE)CLAMP<int>((int)(a + 0.5), 0, 0xFF); dst_bits += 4; } } } break; } } break; case FIT_UINT16: { // Calculate the number of words per pixel (1 for 16-bit, 3 for 48-bit or 4 for 64-bit) const unsigned wordspp = (FreeImage_GetLine(src) / src_width) / sizeof(WORD); for (unsigned y = 0; y < height; y++) { // scale each row const WORD *src_bits = (WORD*)FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x / sizeof(WORD); WORD *dst_bits = (WORD*)FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(x) - iLeft; // retrieve right boundary const WORD *pixel = src_bits + iLeft * wordspp; double value = 0; // for(i = iLeft to iRight) for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(x, i); value += (weight * (double)pixel[0]); pixel++; } // clamp and place result in destination pixel dst_bits[0] = (WORD)CLAMP<int>((int)(value + 0.5), 0, 0xFFFF); dst_bits += wordspp; } } } break; case FIT_RGB16: { // Calculate the number of words per pixel (1 for 16-bit, 3 for 48-bit or 4 for 64-bit) const unsigned wordspp = (FreeImage_GetLine(src) / src_width) / sizeof(WORD); for (unsigned y = 0; y < height; y++) { // scale each row const WORD *src_bits = (WORD*)FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x / sizeof(WORD); WORD *dst_bits = (WORD*)FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(x) - iLeft; // retrieve right boundary const WORD *pixel = src_bits + iLeft * wordspp; double r = 0, g = 0, b = 0; // for(i = iLeft to iRight) for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(x, i); r += (weight * (double)pixel[0]); g += (weight * (double)pixel[1]); b += (weight * (double)pixel[2]); pixel += wordspp; } // clamp and place result in destination pixel dst_bits[0] = (WORD)CLAMP<int>((int)(r + 0.5), 0, 0xFFFF); dst_bits[1] = (WORD)CLAMP<int>((int)(g + 0.5), 0, 0xFFFF); dst_bits[2] = (WORD)CLAMP<int>((int)(b + 0.5), 0, 0xFFFF); dst_bits += wordspp; } } } break; case FIT_RGBA16: { // Calculate the number of words per pixel (1 for 16-bit, 3 for 48-bit or 4 for 64-bit) const unsigned wordspp = (FreeImage_GetLine(src) / src_width) / sizeof(WORD); for (unsigned y = 0; y < height; y++) { // scale each row const WORD *src_bits = (WORD*)FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x / sizeof(WORD); WORD *dst_bits = (WORD*)FreeImage_GetScanLine(dst, y); for (unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(x) - iLeft; // retrieve right boundary const WORD *pixel = src_bits + iLeft * wordspp; double r = 0, g = 0, b = 0, a = 0; // for(i = iLeft to iRight) for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(x, i); r += (weight * (double)pixel[0]); g += (weight * (double)pixel[1]); b += (weight * (double)pixel[2]); a += (weight * (double)pixel[3]); pixel += wordspp; } // clamp and place result in destination pixel dst_bits[0] = (WORD)CLAMP<int>((int)(r + 0.5), 0, 0xFFFF); dst_bits[1] = (WORD)CLAMP<int>((int)(g + 0.5), 0, 0xFFFF); dst_bits[2] = (WORD)CLAMP<int>((int)(b + 0.5), 0, 0xFFFF); dst_bits[3] = (WORD)CLAMP<int>((int)(a + 0.5), 0, 0xFFFF); dst_bits += wordspp; } } } break; case FIT_FLOAT: case FIT_RGBF: case FIT_RGBAF: { // Calculate the number of floats per pixel (1 for 32-bit, 3 for 96-bit or 4 for 128-bit) const unsigned floatspp = (FreeImage_GetLine(src) / src_width) / sizeof(float); for(unsigned y = 0; y < height; y++) { // scale each row const float *src_bits = (float*)FreeImage_GetScanLine(src, y + src_offset_y) + src_offset_x / sizeof(float); float *dst_bits = (float*)FreeImage_GetScanLine(dst, y); for(unsigned x = 0; x < dst_width; x++) { // loop through row const unsigned iLeft = weightsTable.getLeftBoundary(x); // retrieve left boundary const unsigned iRight = weightsTable.getRightBoundary(x); // retrieve right boundary double value[4] = {0, 0, 0, 0}; // 4 = 128 bpp max for(unsigned i = iLeft; i < iRight; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(x, i-iLeft); unsigned index = i * floatspp; // pixel index for (unsigned j = 0; j < floatspp; j++) { value[j] += (weight * (double)src_bits[index++]); } } // place result in destination pixel for (unsigned j = 0; j < floatspp; j++) { dst_bits[j] = (float)value[j]; } dst_bits += floatspp; } } } break; } } /// Performs vertical image filtering void CResizeEngine::verticalFilter(FIBITMAP *const src, unsigned width, unsigned src_height, unsigned src_offset_x, unsigned src_offset_y, const RGBQUAD *const src_pal, FIBITMAP *const dst, unsigned dst_height) { // allocate and calculate the contributions CWeightsTable weightsTable(m_pFilter, dst_height, src_height); // step through columns switch(FreeImage_GetImageType(src)) { case FIT_BITMAP: { const unsigned dst_pitch = FreeImage_GetPitch(dst); BYTE * const dst_base = FreeImage_GetBits(dst); switch(FreeImage_GetBPP(src)) { case 1: { const unsigned src_pitch = FreeImage_GetPitch(src); const BYTE * const src_base = FreeImage_GetBits(src) + src_offset_y * src_pitch + (src_offset_x >> 3); switch(FreeImage_GetBPP(dst)) { case 8: { // transparently convert the 1-bit non-transparent greyscale // image to 8 bpp if (src_pal) { // we have got a palette for (unsigned x = 0; x < width; x++) { // work on column x in dst BYTE *dst_bits = dst_base + x; const unsigned index = x >> 3; const unsigned mask = 0x80 >> (x & 0x07); // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const BYTE *src_bits = src_base + iLeft * src_pitch + index; double value = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const unsigned pixel = (*src_bits & mask) != 0; value += (weightsTable.getWeight(y, i) * (double)*(BYTE *)&src_pal[pixel]); src_bits += src_pitch; } value *= 0xFF; // clamp and place result in destination pixel *dst_bits = (BYTE)CLAMP<int>((int)(value + 0.5), 0, 0xFF); dst_bits += dst_pitch; } } } else { // we do not have a palette for (unsigned x = 0; x < width; x++) { // work on column x in dst BYTE *dst_bits = dst_base + x; const unsigned index = x >> 3; const unsigned mask = 0x80 >> (x & 0x07); // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const BYTE *src_bits = src_base + iLeft * src_pitch + index; double value = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel value += (weightsTable.getWeight(y, i) * (double)((*src_bits & mask) != 0)); src_bits += src_pitch; } value *= 0xFF; // clamp and place result in destination pixel *dst_bits = (BYTE)CLAMP<int>((int)(value + 0.5), 0, 0xFF); dst_bits += dst_pitch; } } } } break; case 24: { // transparently convert the non-transparent 1-bit image // to 24 bpp; we always have got a palette here for (unsigned x = 0; x < width; x++) { // work on column x in dst BYTE *dst_bits = dst_base + x * 3; const unsigned index = x >> 3; const unsigned mask = 0x80 >> (x & 0x07); // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const BYTE *src_bits = src_base + iLeft * src_pitch + index; double r = 0, g = 0, b = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(y, i); const unsigned pixel = (*src_bits & mask) != 0; const BYTE * const entry = (BYTE *)&src_pal[pixel]; r += (weight * (double)entry[FI_RGBA_RED]); g += (weight * (double)entry[FI_RGBA_GREEN]); b += (weight * (double)entry[FI_RGBA_BLUE]); src_bits += src_pitch; } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(r + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(g + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(b + 0.5), 0, 0xFF); dst_bits += dst_pitch; } } } break; case 32: { // transparently convert the transparent 1-bit image // to 32 bpp; we always have got a palette here for (unsigned x = 0; x < width; x++) { // work on column x in dst BYTE *dst_bits = dst_base + x * 4; const unsigned index = x >> 3; const unsigned mask = 0x80 >> (x & 0x07); // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const BYTE *src_bits = src_base + iLeft * src_pitch + index; double r = 0, g = 0, b = 0, a = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(y, i); const unsigned pixel = (*src_bits & mask) != 0; const BYTE * const entry = (BYTE *)&src_pal[pixel]; r += (weight * (double)entry[FI_RGBA_RED]); g += (weight * (double)entry[FI_RGBA_GREEN]); b += (weight * (double)entry[FI_RGBA_BLUE]); a += (weight * (double)entry[FI_RGBA_ALPHA]); src_bits += src_pitch; } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(r + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(g + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(b + 0.5), 0, 0xFF); dst_bits[FI_RGBA_ALPHA] = (BYTE)CLAMP<int>((int)(a + 0.5), 0, 0xFF); dst_bits += dst_pitch; } } } break; } } break; case 4: { const unsigned src_pitch = FreeImage_GetPitch(src); const BYTE *const src_base = FreeImage_GetBits(src) + src_offset_y * src_pitch + (src_offset_x >> 1); switch(FreeImage_GetBPP(dst)) { case 8: { // transparently convert the non-transparent 4-bit greyscale image // to 8 bpp; we always have got a palette for 4-bit images for (unsigned x = 0; x < width; x++) { // work on column x in dst BYTE *dst_bits = dst_base + x; const unsigned index = x >> 1; // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const BYTE *src_bits = src_base + iLeft * src_pitch + index; double value = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const unsigned pixel = x & 0x01 ? *src_bits & 0x0F : *src_bits >> 4; value += (weightsTable.getWeight(y, i) * (double)*(BYTE *)&src_pal[pixel]); src_bits += src_pitch; } // clamp and place result in destination pixel *dst_bits = (BYTE)CLAMP<int>((int)(value + 0.5), 0, 0xFF); dst_bits += dst_pitch; } } } break; case 24: { // transparently convert the non-transparent 4-bit image // to 24 bpp; we always have got a palette for 4-bit images for (unsigned x = 0; x < width; x++) { // work on column x in dst BYTE *dst_bits = dst_base + x * 3; const unsigned index = x >> 1; // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const BYTE *src_bits = src_base + iLeft * src_pitch + index; double r = 0, g = 0, b = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(y, i); const unsigned pixel = x & 0x01 ? *src_bits & 0x0F : *src_bits >> 4; const BYTE *const entry = (BYTE *)&src_pal[pixel]; r += (weight * (double)entry[FI_RGBA_RED]); g += (weight * (double)entry[FI_RGBA_GREEN]); b += (weight * (double)entry[FI_RGBA_BLUE]); src_bits += src_pitch; } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(r + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(g + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(b + 0.5), 0, 0xFF); dst_bits += dst_pitch; } } } break; case 32: { // transparently convert the transparent 4-bit image // to 32 bpp; we always have got a palette for 4-bit images for (unsigned x = 0; x < width; x++) { // work on column x in dst BYTE *dst_bits = dst_base + x * 4; const unsigned index = x >> 1; // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const BYTE *src_bits = src_base + iLeft * src_pitch + index; double r = 0, g = 0, b = 0, a = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(y, i); const unsigned pixel = x & 0x01 ? *src_bits & 0x0F : *src_bits >> 4; const BYTE *const entry = (BYTE *)&src_pal[pixel]; r += (weight * (double)entry[FI_RGBA_RED]); g += (weight * (double)entry[FI_RGBA_GREEN]); b += (weight * (double)entry[FI_RGBA_BLUE]); a += (weight * (double)entry[FI_RGBA_ALPHA]); src_bits += src_pitch; } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(r + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(g + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(b + 0.5), 0, 0xFF); dst_bits[FI_RGBA_ALPHA] = (BYTE)CLAMP<int>((int)(a + 0.5), 0, 0xFF); dst_bits += dst_pitch; } } } break; } } break; case 8: { const unsigned src_pitch = FreeImage_GetPitch(src); const BYTE *const src_base = FreeImage_GetBits(src) + src_offset_y * src_pitch + src_offset_x; switch(FreeImage_GetBPP(dst)) { case 8: { // scale the 8-bit non-transparent greyscale image // into an 8 bpp destination image if (src_pal) { // we have got a palette for (unsigned x = 0; x < width; x++) { // work on column x in dst BYTE *dst_bits = dst_base + x; // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const BYTE *src_bits = src_base + iLeft * src_pitch + x; double value = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel value += (weightsTable.getWeight(y, i) * (double)*(BYTE *)&src_pal[*src_bits]); src_bits += src_pitch; } // clamp and place result in destination pixel *dst_bits = (BYTE)CLAMP<int>((int)(value + 0.5), 0, 0xFF); dst_bits += dst_pitch; } } } else { // we do not have a palette for (unsigned x = 0; x < width; x++) { // work on column x in dst BYTE *dst_bits = dst_base + x; // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const BYTE *src_bits = src_base + iLeft * src_pitch + x; double value = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel value += (weightsTable.getWeight(y, i) * (double)*src_bits); src_bits += src_pitch; } // clamp and place result in destination pixel *dst_bits = (BYTE)CLAMP<int>((int)(value + 0.5), 0, 0xFF); dst_bits += dst_pitch; } } } } break; case 24: { // transparently convert the non-transparent 8-bit image // to 24 bpp; we always have got a palette here for (unsigned x = 0; x < width; x++) { // work on column x in dst BYTE *dst_bits = dst_base + x * 3; // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const BYTE *src_bits = src_base + iLeft * src_pitch + x; double r = 0, g = 0, b = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(y, i); const BYTE * const entry = (BYTE *)&src_pal[*src_bits]; r += (weight * (double)entry[FI_RGBA_RED]); g += (weight * (double)entry[FI_RGBA_GREEN]); b += (weight * (double)entry[FI_RGBA_BLUE]); src_bits += src_pitch; } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(r + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(g + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(b + 0.5), 0, 0xFF); dst_bits += dst_pitch; } } } break; case 32: { // transparently convert the transparent 8-bit image // to 32 bpp; we always have got a palette here for (unsigned x = 0; x < width; x++) { // work on column x in dst BYTE *dst_bits = dst_base + x * 4; // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const BYTE *src_bits = src_base + iLeft * src_pitch + x; double r = 0, g = 0, b = 0, a = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(y, i); const BYTE * const entry = (BYTE *)&src_pal[*src_bits]; r += (weight * (double)entry[FI_RGBA_RED]); g += (weight * (double)entry[FI_RGBA_GREEN]); b += (weight * (double)entry[FI_RGBA_BLUE]); a += (weight * (double)entry[FI_RGBA_ALPHA]); src_bits += src_pitch; } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(r + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(g + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(b + 0.5), 0, 0xFF); dst_bits[FI_RGBA_ALPHA] = (BYTE)CLAMP<int>((int)(a + 0.5), 0, 0xFF); dst_bits += dst_pitch; } } } break; } } break; case 16: { // transparently convert the 16-bit non-transparent image // to 24 bpp const unsigned src_pitch = FreeImage_GetPitch(src) / sizeof(WORD); const WORD *const src_base = (WORD *)FreeImage_GetBits(src) + src_offset_y * src_pitch + src_offset_x; if (IS_FORMAT_RGB565(src)) { // image has 565 format for (unsigned x = 0; x < width; x++) { // work on column x in dst BYTE *dst_bits = dst_base + x * 3; // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const WORD *src_bits = src_base + iLeft * src_pitch + x; double r = 0, g = 0, b = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(y, i); r += (weight * (double)((*src_bits & FI16_565_RED_MASK) >> FI16_565_RED_SHIFT)); g += (weight * (double)((*src_bits & FI16_565_GREEN_MASK) >> FI16_565_GREEN_SHIFT)); b += (weight * (double)((*src_bits & FI16_565_BLUE_MASK) >> FI16_565_BLUE_SHIFT)); src_bits += src_pitch; } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(((r * 0xFF) / 0x1F) + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(((g * 0xFF) / 0x3F) + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(((b * 0xFF) / 0x1F) + 0.5), 0, 0xFF); dst_bits += dst_pitch; } } } else { // image has 555 format for (unsigned x = 0; x < width; x++) { // work on column x in dst BYTE *dst_bits = dst_base + x * 3; // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const WORD *src_bits = src_base + iLeft * src_pitch + x; double r = 0, g = 0, b = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(y, i); r += (weight * (double)((*src_bits & FI16_555_RED_MASK) >> FI16_555_RED_SHIFT)); g += (weight * (double)((*src_bits & FI16_555_GREEN_MASK) >> FI16_555_GREEN_SHIFT)); b += (weight * (double)((*src_bits & FI16_555_BLUE_MASK) >> FI16_555_BLUE_SHIFT)); src_bits += src_pitch; } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int)(((r * 0xFF) / 0x1F) + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int)(((g * 0xFF) / 0x1F) + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int)(((b * 0xFF) / 0x1F) + 0.5), 0, 0xFF); dst_bits += dst_pitch; } } } } break; case 24: { // scale the 24-bit transparent image // into a 24 bpp destination image const unsigned src_pitch = FreeImage_GetPitch(src); const BYTE *const src_base = FreeImage_GetBits(src) + src_offset_y * src_pitch + src_offset_x * 3; for (unsigned x = 0; x < width; x++) { // work on column x in dst const unsigned index = x * 3; BYTE *dst_bits = dst_base + index; // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const BYTE *src_bits = src_base + iLeft * src_pitch + index; double r = 0, g = 0, b = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(y, i); r += (weight * (double)src_bits[FI_RGBA_RED]); g += (weight * (double)src_bits[FI_RGBA_GREEN]); b += (weight * (double)src_bits[FI_RGBA_BLUE]); src_bits += src_pitch; } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int) (r + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int) (g + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int) (b + 0.5), 0, 0xFF); dst_bits += dst_pitch; } } } break; case 32: { // scale the 32-bit transparent image // into a 32 bpp destination image const unsigned src_pitch = FreeImage_GetPitch(src); const BYTE *const src_base = FreeImage_GetBits(src) + src_offset_y * src_pitch + src_offset_x * 4; for (unsigned x = 0; x < width; x++) { // work on column x in dst const unsigned index = x * 4; BYTE *dst_bits = dst_base + index; // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const BYTE *src_bits = src_base + iLeft * src_pitch + index; double r = 0, g = 0, b = 0, a = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(y, i); r += (weight * (double)src_bits[FI_RGBA_RED]); g += (weight * (double)src_bits[FI_RGBA_GREEN]); b += (weight * (double)src_bits[FI_RGBA_BLUE]); a += (weight * (double)src_bits[FI_RGBA_ALPHA]); src_bits += src_pitch; } // clamp and place result in destination pixel dst_bits[FI_RGBA_RED] = (BYTE)CLAMP<int>((int) (r + 0.5), 0, 0xFF); dst_bits[FI_RGBA_GREEN] = (BYTE)CLAMP<int>((int) (g + 0.5), 0, 0xFF); dst_bits[FI_RGBA_BLUE] = (BYTE)CLAMP<int>((int) (b + 0.5), 0, 0xFF); dst_bits[FI_RGBA_ALPHA] = (BYTE)CLAMP<int>((int) (a + 0.5), 0, 0xFF); dst_bits += dst_pitch; } } } break; } } break; case FIT_UINT16: { // Calculate the number of words per pixel (1 for 16-bit, 3 for 48-bit or 4 for 64-bit) const unsigned wordspp = (FreeImage_GetLine(src) / width) / sizeof(WORD); const unsigned dst_pitch = FreeImage_GetPitch(dst) / sizeof(WORD); WORD *const dst_base = (WORD *)FreeImage_GetBits(dst); const unsigned src_pitch = FreeImage_GetPitch(src) / sizeof(WORD); const WORD *const src_base = (WORD *)FreeImage_GetBits(src) + src_offset_y * src_pitch + src_offset_x * wordspp; for (unsigned x = 0; x < width; x++) { // work on column x in dst const unsigned index = x * wordspp; // pixel index WORD *dst_bits = dst_base + index; // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const WORD *src_bits = src_base + iLeft * src_pitch + index; double value = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(y, i); value += (weight * (double)src_bits[0]); src_bits += src_pitch; } // clamp and place result in destination pixel dst_bits[0] = (WORD)CLAMP<int>((int)(value + 0.5), 0, 0xFFFF); dst_bits += dst_pitch; } } } break; case FIT_RGB16: { // Calculate the number of words per pixel (1 for 16-bit, 3 for 48-bit or 4 for 64-bit) const unsigned wordspp = (FreeImage_GetLine(src) / width) / sizeof(WORD); const unsigned dst_pitch = FreeImage_GetPitch(dst) / sizeof(WORD); WORD *const dst_base = (WORD *)FreeImage_GetBits(dst); const unsigned src_pitch = FreeImage_GetPitch(src) / sizeof(WORD); const WORD *const src_base = (WORD *)FreeImage_GetBits(src) + src_offset_y * src_pitch + src_offset_x * wordspp; for (unsigned x = 0; x < width; x++) { // work on column x in dst const unsigned index = x * wordspp; // pixel index WORD *dst_bits = dst_base + index; // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const WORD *src_bits = src_base + iLeft * src_pitch + index; double r = 0, g = 0, b = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(y, i); r += (weight * (double)src_bits[0]); g += (weight * (double)src_bits[1]); b += (weight * (double)src_bits[2]); src_bits += src_pitch; } // clamp and place result in destination pixel dst_bits[0] = (WORD)CLAMP<int>((int)(r + 0.5), 0, 0xFFFF); dst_bits[1] = (WORD)CLAMP<int>((int)(g + 0.5), 0, 0xFFFF); dst_bits[2] = (WORD)CLAMP<int>((int)(b + 0.5), 0, 0xFFFF); dst_bits += dst_pitch; } } } break; case FIT_RGBA16: { // Calculate the number of words per pixel (1 for 16-bit, 3 for 48-bit or 4 for 64-bit) const unsigned wordspp = (FreeImage_GetLine(src) / width) / sizeof(WORD); const unsigned dst_pitch = FreeImage_GetPitch(dst) / sizeof(WORD); WORD *const dst_base = (WORD *)FreeImage_GetBits(dst); const unsigned src_pitch = FreeImage_GetPitch(src) / sizeof(WORD); const WORD *const src_base = (WORD *)FreeImage_GetBits(src) + src_offset_y * src_pitch + src_offset_x * wordspp; for (unsigned x = 0; x < width; x++) { // work on column x in dst const unsigned index = x * wordspp; // pixel index WORD *dst_bits = dst_base + index; // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iLimit = weightsTable.getRightBoundary(y) - iLeft; // retrieve right boundary const WORD *src_bits = src_base + iLeft * src_pitch + index; double r = 0, g = 0, b = 0, a = 0; for (unsigned i = 0; i < iLimit; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(y, i); r += (weight * (double)src_bits[0]); g += (weight * (double)src_bits[1]); b += (weight * (double)src_bits[2]); a += (weight * (double)src_bits[3]); src_bits += src_pitch; } // clamp and place result in destination pixel dst_bits[0] = (WORD)CLAMP<int>((int)(r + 0.5), 0, 0xFFFF); dst_bits[1] = (WORD)CLAMP<int>((int)(g + 0.5), 0, 0xFFFF); dst_bits[2] = (WORD)CLAMP<int>((int)(b + 0.5), 0, 0xFFFF); dst_bits[3] = (WORD)CLAMP<int>((int)(a + 0.5), 0, 0xFFFF); dst_bits += dst_pitch; } } } break; case FIT_FLOAT: case FIT_RGBF: case FIT_RGBAF: { // Calculate the number of floats per pixel (1 for 32-bit, 3 for 96-bit or 4 for 128-bit) const unsigned floatspp = (FreeImage_GetLine(src) / width) / sizeof(float); const unsigned dst_pitch = FreeImage_GetPitch(dst) / sizeof(float); float *const dst_base = (float *)FreeImage_GetBits(dst); const unsigned src_pitch = FreeImage_GetPitch(src) / sizeof(float); const float *const src_base = (float *)FreeImage_GetBits(src) + src_offset_y * src_pitch + src_offset_x * floatspp; for (unsigned x = 0; x < width; x++) { // work on column x in dst const unsigned index = x * floatspp; // pixel index float *dst_bits = (float *)dst_base + index; // scale each column for (unsigned y = 0; y < dst_height; y++) { // loop through column const unsigned iLeft = weightsTable.getLeftBoundary(y); // retrieve left boundary const unsigned iRight = weightsTable.getRightBoundary(y); // retrieve right boundary const float *src_bits = src_base + iLeft * src_pitch + index; double value[4] = {0, 0, 0, 0}; // 4 = 128 bpp max for (unsigned i = iLeft; i < iRight; i++) { // scan between boundaries // accumulate weighted effect of each neighboring pixel const double weight = weightsTable.getWeight(y, i - iLeft); for (unsigned j = 0; j < floatspp; j++) { value[j] += (weight * (double)src_bits[j]); } src_bits += src_pitch; } // place result in destination pixel for (unsigned j = 0; j < floatspp; j++) { dst_bits[j] = (float)value[j]; } dst_bits += dst_pitch; } } } break; } }
[ "qq79402005@gmail.com" ]
qq79402005@gmail.com
ef4a5a7727d5078e4ad06298bbc8816910d8d9f5
f0415d8538b0d329a09accde765e3aa4c39a5650
/misc/read_from_rear_debug.cpp
667857ea2524502b07d53edfb040cff804ebb033
[]
no_license
tiborh/cplusplus
0f7e27e1df69ef0c497fa486bb3ff413bb9e8d21
229ddaed13d26de6a03e1420c32d1f07424e0e67
refs/heads/master
2021-01-17T18:51:03.194333
2018-04-09T02:56:09
2018-04-09T02:56:09
59,860,513
0
0
null
null
null
null
UTF-8
C++
false
false
5,190
cpp
#define __cplusplus 201103L // for c++11 //#define __cplusplus 199711L // for c++98 and c++03 #include <iostream> //#include <algorithm> // e.g. split //#include <cassert> // assert() //#include <climits> // e.g. INT_MAX //#include <cmath> //#include <cstdio> //#include <cstdlib> // e.g. for srand(time(NULL)) and rand() #include <cstring> // e.g. for strlen //#include <ctime> // for time operation #include <deque> // double linked list //#include <exception> #include <fstream> // file operations //#include <functional> // for lambda #include <iomanip> // e.g. setw, setprecision, setfill, setbase //#include <limits> // e.g. numeric_limits<streamsize>::max() //#include <list> #include <sstream> // stringstream //#include <string> //#include <typeinfo> // for typeid //#include <unistd.h> //#include <vector> using namespace std; bool open_file(fstream& fh, const char* fn, const char* fm) { ios::openmode fmode; int fmode_int = 0; for(unsigned int i = 0; i < strlen(fm); i++) switch(fm[i]) { case 'r': fmode_int += ios::in; break; case 'w': fmode_int += ios::out; break; case 'a': fmode_int += ios::app; break; // use it with write case 't': fmode_int += ios::trunc; break; // use it with write case 'e': fmode_int += ios::ate; break; // use it with r (if used with write, it overwrites file) case 'b': fmode_int += ios::binary; break; // use it with r or w default: cerr << "Unknown fileopen mode:" << fm << "Exiting...\n"; return false; } fmode = static_cast<ios::openmode>(fmode_int); fh.open(fn,fmode); if (fh.is_open()) return true; else return false; } int check_flags(const fstream& fh) { int status = 0; //cout << "file is:\n"; if (fh.good()) status+=16; if (fh.bad()) status+=2; if (fh.fail()) status+=4; if (fh.eof()) status+=8; if (0 == status) status = -1; return status; } unsigned char read_next(fstream& fh) { char read_char = 0; fh.read(&read_char,sizeof(char)); if (check_flags(fh) != 16) { fh.clear(); check_flags(fh); } return static_cast<unsigned char>(read_char); } template<typename T> void printq(const deque<T>& aq, const char charsep = ' ') { typename deque<T>::const_iterator aqit; if (aq.empty()) cout << "<empty>"; else for(aqit = aq.begin(); aqit != aq.end(); ++aqit) cout << *aqit << ((aq.end() != aqit+1) ? charsep : '\0'); } unsigned char* empty_q(deque<unsigned char> &dq, int nuu) { unsigned char* ch_arr = new unsigned char[6]; //queue is max 5 (+ 1 for \0) unsigned char* ch_uni = new unsigned char[5]; //utf8 is max 4 (+ 1 for \0) //cout << "queue received: "; //printq(dq); //cout << '\n'; int i = 0; for (; i < nuu; ++i) { ch_uni[i] = dq.back(); dq.pop_back(); } //ch_uni[i] = '\0'; int j = 0; for(; !dq.empty(); ++j) { ch_arr[j] = dq.front(); dq.pop_front(); } //ch_arr[j] = '\0'; int k = 0; for (; k < i; ++k,++j) { ch_arr[j] = ch_uni[k]; } ch_arr[k] = '\0'; delete [] ch_uni; return ch_arr; } string read_from_rear(const char* fn) { fstream fh; if (!open_file(fh,fn,"re")) { cout << "Cannot open file: " << fn << '\n'; return ""; } int filepos = static_cast<int>(fh.tellg()); if (0 == filepos) { cout << "File " << fn << " is empty.\n"; return ""; } unsigned char this_char = 0; deque<unsigned char> prev_chars; stringstream s; while(filepos > 0) { filepos--; fh.seekg(filepos); //check_flags(fh); //prev_chars.push_back(this_char); //cout << "this_char: " << this_char << " stream: " << s.str() << '\n'; //cout << "this_char: " << hex << static_cast<int>(this_char) << '\n'; //cout << "prev_chars: "; //printq(prev_chars); //cout << '\n'; this_char = read_next(fh); if (0x0 <= this_char && this_char < 0x80) s << this_char; else if (0x80 <= this_char && this_char <= 0xbf) { //clog << "part of multi byte\n"; prev_chars.push_back(this_char); } else if (0xc0 <= this_char && this_char <= 0xdf) { //clog << "first of two-byte\n"; prev_chars.push_back(this_char); s << empty_q(prev_chars,2); this_char = '\0'; } else if (0xe0 <= this_char && this_char <= 0xef) { //clog << "first of three-byte\n"; prev_chars.push_back(this_char); s << empty_q(prev_chars,3); this_char = '\0'; } else if (0xf0 <= this_char && this_char <= 0xf7) { //clog << "first of four-byte\n"; prev_chars.push_back(this_char); s << empty_q(prev_chars,4); this_char = '\0'; } else { cerr << "\nUnaccounted for char!\n"; } } while(!prev_chars.empty()) { s << prev_chars.front(); prev_chars.pop_front(); } fh.close(); s << this_char << '\n'; if (!prev_chars.empty()) cerr << "Some leftover in queue!\n"; return s.str(); } int main(int argc, char** argv) { cout << read_from_rear("wandrers_nachtlied.txt"); cout << read_from_rear("konnichiwa.txt"); cout << read_from_rear("test_hun.txt"); return 0; }
[ "tibor.harcsa@ericsson.com" ]
tibor.harcsa@ericsson.com
0d789fa772e8867c3fc8be34bb676732b5a4770a
be663f51aa417c0939b3efef29d5837ac2e7c99f
/Code/WSTrainingTJM/FrmTXTRead/MyAddinMod.m/LocalInterfaces/MyAddinMain.h
1cbd0193d684552a41abd6a71648cff495dbeb29
[ "MIT" ]
permissive
msdos41/CATIA_CAA_V5
d87598923797867ae322478773e2372a2febb11b
1274de43e1ebfffc5398f34ed1b63093cae27fc2
refs/heads/master
2022-06-01T23:05:20.419221
2022-05-10T07:23:41
2022-05-10T07:23:41
220,181,165
11
7
null
null
null
null
UTF-8
C++
false
false
2,056
h
// COPYRIGHT Dassault Systemes 2018 //=================================================================== // // MyAddinMain.h // Provide implementation to interface // CATIAfrGeneralWksAddin // CATIWorkbenchAddin // //=================================================================== // // Usage notes: // //=================================================================== //CAA2 Wizard Generation Report //IMPLEMENTATION // TIE: CATIAfrGeneralWksAddin // TIE: CATIWorkbenchAddin //End CAA2 Wizard Generation Report // // Nov 2018 Creation: Code generated by the CAA wizard Administrator //=================================================================== #ifndef MyAddinMain_H #define MyAddinMain_H #include "CATBaseUnknown.h" #include "CATCmdContainer.h" #include "CATCreateWorkshop.h" //----------------------------------------------------------------------- /** * Class representing xxx. * * <br><b>Role</b>: Provide the basic class function... * <p> * It implements the interfaces : * <ol> * <li>@href CATIAfrGeneralWksAddin * <li>@href CATIWorkbenchAddin * </ol> * * @href ClassReference, Class#MethodReference, #InternalMethod... */ class MyAddinMain: public CATBaseUnknown { CATDeclareClass; public: // Standard constructors and destructors for an implementation class // ----------------------------------------------------------------- MyAddinMain (); virtual ~MyAddinMain (); /** * Implements a function from an interface. * @href CATIWorkbenchAddin#CreateCommands */ void CreateCommands () ; /** * Implements a function from an interface. * @href CATIWorkbenchAddin#CreateToolbars */ CATCmdContainer * CreateToolbars () ; private: // The copy constructor and the equal operator must not be implemented // ------------------------------------------------------------------- MyAddinMain (MyAddinMain &); MyAddinMain& operator=(MyAddinMain&); }; //----------------------------------------------------------------------- #endif
[ "tjm.mosquito@gmail.com" ]
tjm.mosquito@gmail.com
6f8c1114e25769197dab38a8fc3d0a0d031226f1
129156ae37f54958871c81d2a6acf5535736f93f
/leetcode/贪心算法/406根据身高排序.cpp
fde6aadadf91a42d8e12d9a35f542f02aa60e8d3
[]
no_license
TristramAr/LeetcodeCode
bb3a41ed15d778c75e4e43eb035559d32287245a
35a664c3fb1487fece017fbab53c51db8cfc5949
refs/heads/master
2022-12-25T05:02:33.371709
2020-10-07T02:54:12
2020-10-07T02:54:12
301,910,412
0
0
null
null
null
null
UTF-8
C++
false
false
1,560
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; // 不要用vector的操作方式进行比较 bool cmp(vector<int> &a, vector<int> &b) { if (a[0] > b[0]) { return true; } if (a[0]==b[0] && a[1] < b[1]) { return true; } return false; } //运用这个排序方式会出现错误,虽然和上边表示的意思相同但是会出现错误 bool cmp_2(vector<int> &a, vector<int> &b) { if (a.begin() > b.begin()) { return true; } if (a.begin() == b.begin() && a.back() < b.back()) { return true; } return false; } class Solution { public: vector<vector<int>> reconstructQueue(vector<vector<int>> &people) { sort(people.begin(), people.end(), cmp); if (people.size() < 2) { return people; } vector<vector<int>> result; for (int i = 0; i < people.size(); i++) { if (people[i][1] < i) { result.insert(result.begin() + people[i][1], people[i]); } else { result.push_back(people[i]); } } return result; } }; int main() { vector<vector<int>> people{{7, 0}, {4, 4}, {7, 1}, {5, 0}, {6, 1}, {5, 2}}; vector<vector<int>> result; Solution solve; result = solve.reconstructQueue(people); for(auto item:result) { for(auto i:item) { cout << i << " "; } cout << endl; } return 0; }
[ "mianmuquanfeijiao@gmail.com" ]
mianmuquanfeijiao@gmail.com
bb9a327e2be0ef3586c1295ae1d7aa6e40f8df4c
2262a0fd44891bd29b4f6b2c5a96d40c7db5de9d
/structure_module/include/Section.h
cef478ce6c63c3da479551a4c8dffea1005ca91d
[]
no_license
tenshun/StorageManager
9cb9f8be38fac61cd1b7aec93a6f43dff935c55e
15295fd47f0cc28e3f81986b952b1148457f56f8
refs/heads/master
2021-04-26T16:47:29.924736
2016-05-16T20:47:31
2016-05-16T20:47:31
58,306,042
1
0
null
null
null
null
UTF-8
C++
false
false
601
h
#ifndef COURSE_WORK_ALGO_SECTION_H #define COURSE_WORK_ALGO_SECTION_H #include <iostream> #include "string" #include "Cell.h" #include "SLinkedList.h" typedef Cell Elem; class Section { private: SLinkedList<Elem> S; int n; public: Section(); // constructor int size() const; // number of items in the stack bool empty() const; // is the stack empty? const Elem& top() const ; // the top element TODO throw(StackEmpty) void push(const Elem& e); // push element onto stack void pop(); // pop the stack TODO throw(StackEmpty) }; #endif //COURSE_WORK_ALGO_SECTION_H
[ "r.sadretdinov4110@gmail.com" ]
r.sadretdinov4110@gmail.com
3828028f648b0ad32ce9e1dd2f521cc2a43538a5
907f75a6b68a2ab3b306c03a37407368029fc9bc
/src/aruco/markerdetector.h
1cc0627f127e693b3a6c5d5f484c7628c58d7b75
[ "BSD-2-Clause" ]
permissive
byteofsoren/python-aruco
f14b318663c4e1fdb867ffb795c58aa3363b5b68
3a306f067ad9730124bb4487bed22012b07fde0b
refs/heads/master
2022-12-02T11:04:23.300241
2020-08-16T20:36:04
2020-08-16T20:36:04
288,019,653
0
0
NOASSERTION
2020-08-16T20:31:05
2020-08-16T20:31:04
null
UTF-8
C++
false
false
19,204
h
/** Copyright 2017 Rafael Muñoz Salinas. 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 Rafael Muñoz Salinas ''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 Rafael Muñoz Salinas 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Rafael Muñoz Salinas. */ #ifndef _ARUCO_MarkerDetector_H #define _ARUCO_MarkerDetector_H #include "aruco_export.h" #include <opencv2/core/core.hpp> #include <cstdio> #include <iostream> #include <queue> #include <mutex> #include <condition_variable> #include <vector> #include <map> #include "marker.h" #include <opencv2/imgproc/imgproc.hpp> namespace aruco { /** * @brief The DetectionMode enum defines the different possibilities for detection. * Specifies the detection mode. We have preset three types of detection modes. These are * ways to configure the internal parameters for the most typical situations. The modes are: * - DM_NORMAL: In this mode, the full resolution image is employed for detection and slow threshold method. Use this method when * you process individual images that are not part of a video sequence and you are not interested in speed. * * - DM_FAST: In this mode, there are two main improvements. First, image is threshold using a faster method using a global threshold. * Also, the full resolution image is employed for detection, but, you could speed up detection even more by indicating a minimum size of the * markers you will accept. This is set by the variable minMarkerSize which shoud be in range [0,1]. When it is 0, means that you do not set * a limit in the size of the accepted markers. However, if you set 0.1, it means that markers smaller than 10% of the total image area, will not * be detected. Then, the detection can be accelated up to orders of magnitude compared to the normal mode. * * - DM_VIDEO_FAST: This is similar to DM_FAST, but specially adapted to video processing. In that case, we assume that the observed markers * when you call to detect() have a size similar to the ones observed in the previous frame. Then, the processing can be speeded up by employing smaller versions * of the image automatically calculated. * */ enum DetectionMode: int{DM_NORMAL=0,DM_FAST=1,DM_VIDEO_FAST=2}; /** Method employed to refine the estimation of the corners * - CORNER_SUBPIX: uses subpixel refinement implemented in opencv * - CORNER_LINES: uses all the pixels in the corner border to estimate the 4 lines of the square. Then * estimate the point in which they intersect. In seems that it more robust to noise. However, it only works if input image is not resized. * So, the value minMarkerSize will be set to 0. * * - CORNER_NONE: Does no refinement of the corner. Again, it requires minMakerSize to be 0 */ enum CornerRefinementMethod: int{CORNER_SUBPIX=0,CORNER_LINES=1,CORNER_NONE=2}; class CameraParameters; class MarkerLabeler; class MarkerDetector_Impl; typedef Marker MarkerCandidate; /**\brief Main class for marker detection * */ class ARUCO_EXPORT MarkerDetector { enum ThresMethod: int{THRES_ADAPTIVE=0,THRES_AUTO_FIXED=1 }; friend class MarkerDetector_Impl; public: /**Operating params */ struct ARUCO_EXPORT Params { /**Specifies the detection mode. We have preset three types of detection modes. These are * ways to configure the internal parameters for the most typical situations. The modes are: * - DM_NORMAL: In this mode, the full resolution image is employed for detection and slow threshold method. Use this method when * you process individual images that are not part of a video sequence and you are not interested in speed. * * - DM_FAST: In this mode, there are two main improvements. First, image is threshold using a faster method using a global threshold. * Also, the full resolution image is employed for detection, but, you could speed up detection even more by indicating a minimum size of the * markers you will accept. This is set by the variable minMarkerSize which shoud be in range [0,1]. When it is 0, means that you do not set * a limit in the size of the accepted markers. However, if you set 0.1, it means that markers smaller than 10% of the total image area, will not * be detected. Then, the detection can be accelated up to orders of magnitude compared to the normal mode. * * - DM_VIDEO_FAST: This is similar to DM_FAST, but specially adapted to video processing. In that case, we assume that the observed markers * when you call to detect() have a size similar to the ones observed in the previous frame. Then, the processing can be speeded up by employing smaller versions * of the image automatically calculated. * */ void setDetectionMode( DetectionMode dm,float minMarkerSize); /**Enables/Disbles the detection of enclosed markers. Enclosed markers are markers where corners are like opencv chessboard pattern */ void detectEnclosedMarkers(bool do_){enclosedMarker=do_;} /**Sets the corner refinement method * - CORNER_SUBPIX: uses subpixel refinement implemented in opencv * - CORNER_LINES: uses all the pixels in the corner border to estimate the 4 lines of the square. Then * estimate the point in which they intersect. In seems that it more robust to noise. However, it only works if input image is not resized. * So, the value minMarkerSize will be set to 0. * * - CORNER_NONE: Does no refinement of the corner. Again, it requires minMakerSize to be 0 */ void setCornerRefinementMethod( CornerRefinementMethod method); //----------------------------------------------------------------------------- // Below this point you probably should not use the functions /**Sets the thresholding method manually. Do no */ void setThresholdMethod(ThresMethod method,int thresHold=-1,int wsize=-1,int wsize_range=0 ); void setAutoSizeSpeedUp(bool v,float Ts=0.25){autoSize=v;ts=Ts;} bool getAutoSizeSpeedUp()const{return autoSize;} void save(cv::FileStorage &fs)const; void load(cv::FileStorage &fs); void toStream(std::ostream &str)const; void fromStream(std::istream &str); static std::string toString(DetectionMode dm); static DetectionMode getDetectionModeFromString(const std::string &str); static std::string toString(CornerRefinementMethod dm); static CornerRefinementMethod getCornerRefinementMethodFromString(const std::string &str); static std::string toString(ThresMethod dm); static ThresMethod getCornerThresMethodFromString(const std::string &str); //Detection mode DetectionMode detectMode=DM_NORMAL; //maximum number of parallel threads int maxThreads=1;//-1 means all // border around image limits in which corners are not allowed to be detected. (0,1) float borderDistThres=0.015f; int lowResMarkerSize=20; //minimum size of a marker in the low resolution image // minimum size of a contour lenght. We use the following formula // minLenght= min ( _minSize_pix , _minSize* Is)*4 // being Is=max(imageWidth,imageHeight) // the value _minSize are normalized, thus, depends on camera image size // However, _minSize_pix is expressed in pixels (you can use the one you prefer) float minSize=-1;//tau_i in paper int minSize_pix=-1; bool enclosedMarker=false;//special treatment for enclosed markers float error_correction_rate=0; std::string dictionary="ALL_DICTS"; //threshold methods ThresMethod thresMethod=THRES_ADAPTIVE; int NAttemptsAutoThresFix=3;//number of times that tries a random threshold in case of THRES_AUTO_FIXED int trackingMinDetections=0;//no tracking // Threshold parameters int AdaptiveThresWindowSize=-1, ThresHold=7, AdaptiveThresWindowSize_range=0; // size of the image passedta to the MarkerLabeler int markerWarpPixSize=5;//tau_c in paper CornerRefinementMethod cornerRefinementM=CORNER_SUBPIX; //enable/disables the method for automatic size estimation for speed up bool autoSize=false; float ts=0.25f;//$\tau_s$ is a factor in the range $(0,1]$ that accounts for the camera motion speed. For instance, when $\tau_s=0.1$, it means that in the next frame, $\tau_i$ is such that markers $10\%$ smaller than the smallest marker in the current image will be seek. To avoid loosing track of the markers. If no markers are detected in a frame, $\tau_i$ is set to zero for the next frame so that markers of any size can be detected. /**Enables automatic image resize according to elements detected in previous frame * @param v * @param ts is a factor in the range $(0,1]$ that accounts for the camera motion speed. For instance, when ts=0.1 , it means that in the next frame, $\tau_i$ is such that markers $10\%$ smaller than the smallest marker in the current image will be seek. To avoid loosing track of the markers. */ float pyrfactor=2; private: static void _toStream(const std::string &strg,std::ostream &str); static void _fromStream(std::string &strg,std::istream &str); template<typename Type> static bool attemtpRead(const std::string &name,Type &var,cv::FileStorage&fs ){ if ( fs[name].type()!=cv::FileNode::NONE){ fs[name]>>var; return true; } return false; } }; /** * See */ MarkerDetector(); /**Creates indicating the dictionary. See @see setDictionary for further details * @param dict_type Dictionary employed. See @see setDictionary for further details * @param error_correction_rate value indicating the correction error allowed. Is in range [0,1]. 0 means no * correction at all. So * an erroneous bit will result in discarding the marker. 1, mean full correction. The maximum number of bits * that can be corrected depends on each ditionary. * We recommend using values from 0 to 0.5. (in general, this will allow up to 3 bits or correction). */ MarkerDetector(int dict_type, float error_correction_rate = 0); MarkerDetector(std::string dict_type, float error_correction_rate = 0); /**Saves the configuration of the detector to a file. */ void saveParamsToFile(const std::string &path)const; /**Loads the configuration from a file. */ void loadParamsFromFile(const std::string &path); /** */ ~MarkerDetector(); /**Specifies the detection mode. We have preset three types of detection modes. These are * ways to configure the internal parameters for the most typical situations. The modes are: * - DM_NORMAL: In this mode, the full resolution image is employed for detection and slow threshold method. Use this method when * you process individual images that are not part of a video sequence and you are not interested in speed. * * - DM_FAST: In this mode, there are two main improvements. First, image is threshold using a faster method using a global threshold. * Also, the full resolution image is employed for detection, but, you could speed up detection even more by indicating a minimum size of the * markers you will accept. This is set by the variable minMarkerSize which shoud be in range [0,1]. When it is 0, means that you do not set * a limit in the size of the accepted markers. However, if you set 0.1, it means that markers smaller than 10% of the total image area, will not * be detected. Then, the detection can be accelated up to orders of magnitude compared to the normal mode. * * - DM_VIDEO_FAST: This is similar to DM_FAST, but specially adapted to video processing. In that case, we assume that the observed markers * when you call to detect() have a size similar to the ones observed in the previous frame. Then, the processing can be speeded up by employing smaller versions * of the image automatically calculated. * */ void setDetectionMode( DetectionMode dm,float minMarkerSize=0); /**returns current detection mode */ DetectionMode getDetectionMode( ); /**Detects the markers in the image passed * * If you provide information about the camera parameters and the size of the marker, then, the extrinsics of * the markers are detected * * @param input input color image * @param camMatrix intrinsic camera information. * @param distCoeff camera distorsion coefficient. If set Mat() if is assumed no camera distorion * @param markerSizeMeters size of the marker sides expressed in meters. If not specified this value, the * extrinsics of the markers are not detected. * @param setYPerperdicular If set the Y axis will be perpendicular to the surface. Otherwise, it will be the Z * axis * @return vector with the detected markers */ std::vector<aruco::Marker> detect(const cv::Mat& input); std::vector<aruco::Marker> detect(const cv::Mat& input, const CameraParameters& camParams, float markerSizeMeters, bool setYPerperdicular = false); /**Returns operating params */ Params getParameters() const; /**Returns operating params */ Params & getParameters() ; /** Sets the dictionary to be employed. * You can choose:ARUCO,//original aruco dictionary. By default ARUCO_MIP_25h7, ARUCO_MIP_16h3, ARUCO_MIP_36h12, **** recommended ARTAG,// ARTOOLKITPLUS, ARTOOLKITPLUSBCH,// TAG16h5,TAG25h7,TAG25h9,TAG36h11,TAG36h10//APRIL TAGS DICIONARIES CHILITAGS,//chili tags dictionary . NOT RECOMMENDED. It has distance 0. Markers 806 and 682 should not be used!!! If dict_type is none of the above ones, it is assumed you mean a CUSTOM dicionary saved in a file @see Dictionary::loadFromFile Then, it tries to open it */ void setDictionary(std::string dict_type, float error_correction_rate = 0); /** * @brief setDictionary Specifies the dictionary you want to use for marker decoding * @param dict_type dictionary employed for decoding markers @see Dictionary * @param error_correction_rate value indicating the correction error allowed. Is in range [0,1]. 0 means no * correction at all. So * an erroneous bit will result in discarding the marker. 1, mean full correction. The maximum number of bits * that can be corrected depends on each ditionary. * We recommend using values from 0 to 0.5. (in general, this will allow up to 3 bits or correction). */ void setDictionary(int dict_type, float error_correction_rate = 0); /** * Returns a reference to the internal image thresholded. Since there can be generated many of them, specify which */ cv::Mat getThresholdedImage(uint32_t idx=0); /**returns the number of thresholed images available */ // size_t getNhresholdedImages()const{return _thres_Images.size();} ///------------------------------------------------- /// Methods you may not need /// Thesde methods do the hard work. They have been set public in case you want to do customizations ///------------------------------------------------- /** * @brief setMakerLabeler sets the labeler employed to analyze the squares and extract the inner binary code * @param detector */ void setMarkerLabeler(cv::Ptr<MarkerLabeler> detector); cv::Ptr<MarkerLabeler> getMarkerLabeler(); /**Returns a list candidates to be markers (rectangles), for which no valid id was found after calling * detectRectangles */ std::vector<MarkerCandidate> getCandidates()const; std::vector<cv::Mat> getImagePyramid(); /* * @param corners vectors of vectors */ void cornerUpsample(std::vector<std::vector<cv::Point2f> >& corners, cv::Size lowResImageSize ); //void cornerUpsample(std::vector<Marker >& corners, cv::Size lowResImageSize ); /** * Given the iput image with markers, creates an output image with it in the canonical position * @param in input image * @param out image with the marker * @param size of out * @param points 4 corners of the marker in the image in * @return true if the operation succeed */ //bool warp(cv::Mat& in, cv::Mat& out, cv::Size size, std::vector<cv::Point2f> points); //serialization in binary mode void toStream(std::ostream &str)const; void fromStream(std::istream &str); //configure the detector from a set of parameters void setParameters(const Params &params); private: MarkerDetector_Impl *_impl; }; }; #endif
[ "marcus@degenkolbe.eu" ]
marcus@degenkolbe.eu
da47fdba09a4d8b2ed6796cf7c6d932a722e4302
4a00b645010bb29b83ae494d462ef79fb843c08d
/Assimp-Converter/Src/MMDFileRoader/MMDModel.h
51dc898429838e1a125594a0c8e6cbde9e4723f5
[]
no_license
OrangeCocoa/Model-Converter
6da0aab2f8fd4328eec9bc870e158e3150b141cb
7d641c0018db361df0d3fa36a8f45c46ebe87eb6
refs/heads/master
2020-03-29T07:59:27.540108
2019-02-19T12:22:01
2019-02-19T12:22:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
51
h
#pragma once class MMDModel { private: public: };
[ "shoheyhey1111@yahoo.co.jp" ]
shoheyhey1111@yahoo.co.jp
9c17058150c0d438a8240a3fd3fd372cad218f62
99c765fbb3d84a730a1b88ce7bb505c6ec99a007
/src/Controller/SillyAppController.cpp
267b1dd78d0aa6fd50bd6a50fb7937215c4f7046
[]
no_license
madeast/SecondC-
3b67a91cc3c6381fe4964e163229dcc13f458011
ca5194af26edc1cea923260a1362dfccf35e0431
refs/heads/master
2021-01-10T07:45:17.549297
2016-01-20T14:35:37
2016-01-20T14:35:37
49,967,036
0
0
null
null
null
null
UTF-8
C++
false
false
701
cpp
/* * SillyAppController.cpp * * Created on: Jan 19, 2016 * Author: emad6932 */ #include "SillyAppController.h" #include <iostream> using namespace std; SillyAppController :: SillyAppController() { this->count = 99; } void SillyAppController :: setCount(int count) { this->count = count; } int SillyAppController :: getCount() { return this->count; } void SillyAppController :: start() { cout << "In the Silly Controller's start Method." << endl; cout << getCount() << " is the count right now. " << endl; cout <<"Type in a new value for count please." << endl; int tempCount; cin >> tempCount; setCount(tempCount); cout << getCount() << " is the updated count." << endl; }
[ "eeagle25@comcast.net" ]
eeagle25@comcast.net
05f8432741e80b81988d02aac1e51240214679e1
f044161caccafefcb5af67d6b1e9775c09229bdf
/src/KTX.hpp
356001aacc0da0ac3753f5382fd7bc48f2bad0f7
[ "Zlib" ]
permissive
Didgy74/Texas
a2fe471b1cb2b66fff6f19dd31a8ba59d4edebbf
618a043b185358c6d189fa87435e557c50867f97
refs/heads/master
2021-09-09T23:34:44.415661
2020-11-06T20:58:43
2020-11-06T20:58:43
179,952,263
9
2
NOASSERTION
2021-02-17T13:29:15
2019-04-07T10:49:53
C
UTF-8
C++
false
false
1,671
hpp
#pragma once #include "Texas/InputStream.hpp" #include "Texas/ResultValue.hpp" #include "Texas/Result.hpp" #include "Texas/TextureInfo.hpp" #include "Texas/Span.hpp" #include "Texas/FileInfo.hpp" #include <cstdint> #include <cstddef> namespace Texas::detail::KTX { constexpr std::uint8_t identifier[12] = { 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A }; [[nodiscard]] Result loadFromStream( InputStream& stream, TextureInfo& textureInfo); [[nodiscard]] Result loadImageData( InputStream& stream, ByteSpan dstBuffer, TextureInfo const& textureInfo, FileInfo_KTX_BackendData const& backendData); namespace Header { constexpr std::uint32_t correctEndian = 0x04030201; constexpr std::size_t totalSize = 64; constexpr std::size_t identifier_Offset = 0; constexpr std::size_t endianness_Offset = 12; constexpr std::size_t glType_Offset = 16; constexpr std::size_t glTypeSize_Offset = 20; constexpr std::size_t glFormat_Offset = 24; constexpr std::size_t glInternalFormat_Offset = 28; constexpr std::size_t glBaseInternalFormat_Offset = 32; constexpr std::size_t pixelWidth_Offset = 36; constexpr std::size_t pixelHeight_Offset = 40; constexpr std::size_t pixelDepth_Offset = 44; constexpr std::size_t numberOfArrayElements_Offset = 48; constexpr std::size_t numberOfFaces_Offset = 52; constexpr std::size_t numberOfMipmapLevels_Offset = 56; constexpr std::size_t bytesOfKeyValueData_Offset = 60; } }
[ "np_skalerud@hotmail.com" ]
np_skalerud@hotmail.com
2d72a3954873c5e90ea6c4d26d6b175353e27926
4ed8364da72396ee833c106eb0fae2beaecdf777
/app/pikachu/include/pikachu/pikachu_app.h
79485ac2d6406ee0bac54b86aa1b9f9d16cf6625
[]
no_license
SSSSSolution/my_lib
ea9d2f7c4bd7896df3762484a063684d3a9b6b93
26fb2f933efcc06888164e23ee7036cb11315180
refs/heads/main
2023-03-01T20:25:37.881756
2021-02-06T14:50:13
2021-02-06T14:50:13
313,587,300
0
0
null
null
null
null
UTF-8
C++
false
false
634
h
#ifndef REALITY_PIKACHU_PIKACHU_APPLICATION_H #define REALITY_PIKACHU_PIKACHU_APPLICATION_H #include <QApplication> #include <functional> #include <vector> #include <QMouseEvent> namespace reality { namespace pikachu { class PikachuApplication : public QApplication { public: PikachuApplication(int argc, char **argv); void add_mouse_move_cb(std::function<void(QMouseEvent *)> f); virtual bool notify(QObject *obj, QEvent *e) override; private: std::vector<std::function<void(QMouseEvent *)>> m_mouse_move_cbs; }; } } #endif
[ "1845739048@qq.com" ]
1845739048@qq.com
bb68ec2a40d660406a67b11e859f1bf460aeae8b
3284c358ffbf33852aef6fce1513ed320bde0d64
/csapex_ml/src/waldboost_trainer.cpp
b7bf702ba6a556bbe8e05cfdf0c50771121b16ac
[]
no_license
eglrp/csapex_core_plugins
b082a1abf3ac25106fcb168961abb2d79f4d2fca
f68d4e42a0cb06e8779003b9fcb71cc048efd175
refs/heads/master
2020-04-06T22:08:34.602083
2018-06-28T19:33:04
2018-06-28T19:33:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,619
cpp
/// HEADER #include "waldboost_trainer.h" /// PROJECT #include <csapex/msg/io.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex/param/parameter_factory.h> #include <csapex/model/node_modifier.h> #include <csapex/msg/generic_vector_message.hpp> CSAPEX_REGISTER_CLASS(csapex::WaldBoostTrainer, csapex::Node) using namespace csapex; using namespace csapex::connection_types; WaldBoostTrainer::WaldBoostTrainer() { } void WaldBoostTrainer::setup(NodeModifier &modifier) { CollectionNode<connection_types::FeaturesMessage>::setup(modifier); } void WaldBoostTrainer::setupParameters(Parameterizable &parameters) { CollectionNode<connection_types::FeaturesMessage>::setupParameters(parameters); parameters.addParameter(param::ParameterFactory::declareFileOutputPath("/waldboost/path", param::ParameterDescription("File to write boosted classifier to."), "", "*.yaml *.tar.gz"), path_); parameters.addParameter(param::ParameterFactory::declareRange("/waldboost/classifier_count", 1, 4096, 100, 1), weak_count_); } bool WaldBoostTrainer::processCollection(std::vector<FeaturesMessage> &collection) { std::size_t step = collection.front().value.size(); std::map<int, std::vector<std::size_t>> indices; const std::size_t size = collection.size(); for(std::size_t i = 0 ; i < size ; ++i) { const FeaturesMessage &fm = collection[i]; if(fm.value.size() != step) throw std::runtime_error("All descriptors must have the same length!"); if(fm.classification != 1 && fm.classification != -1) throw std::runtime_error("Only class labels supported are '-1' and '1'!"); indices[fm.classification].push_back(i); } const std::vector<std::size_t> &positive_indices = indices[1]; const std::vector<std::size_t> &negative_indices = indices[-1]; const std::size_t positive_size = positive_indices.size(); const std::size_t negative_size = negative_indices.size(); cv::Mat positive_samples(positive_size, step, CV_32FC1, cv::Scalar()); cv::Mat negative_samples(negative_size, step, CV_32FC1, cv::Scalar()); for(std::size_t i = 0 ; i < positive_size ; ++i) { const std::vector<float> &sample = collection[positive_indices[i]].value; for(std::size_t j = 0 ; j < step ; ++j) { positive_samples.at<float>(i,j) = sample[j]; } } for(std::size_t i = 0 ; i < negative_size ; ++i) { const std::vector<float> &sample = collection[negative_indices[i]].value; for(std::size_t j = 0 ; j < step ; ++j) { negative_samples.at<float>(i,j) = sample[j]; } } cv::transpose(positive_samples, positive_samples); cv::transpose(negative_samples, negative_samples); cv::WaldBoost wb; wb.reset(weak_count_); std::cout << "[WaldBoost]: Started training with " << collection.size() << " samples!" << std::endl; wb.train(positive_samples, negative_samples); wb.save(path_); std::cout << "[WaldBoost]: Finished training!" << std::endl; return true; }
[ "Richard.Hanten@uni-tuebingen.de" ]
Richard.Hanten@uni-tuebingen.de
d719f1269b45ea6acd73b751ac0ad025d545d7e1
054efd9a6ff17000f6d13cec9c5e50601496f661
/vf/src/main/jni/Foundation/IOUniformer.cpp
6879c16b9d69f339e919779465818e5bb0bf909c
[]
no_license
dfcfvf/dfvf
511783c632ab3764696ace80e54435e82c937221
b3de5795e98bf16f70be4f40b6fc6fa9bf19d26c
refs/heads/master
2021-08-18T16:39:43.275051
2017-11-23T09:20:50
2017-11-23T09:20:50
108,795,458
0
0
null
null
null
null
UTF-8
C++
false
false
24,238
cpp
// // VirtualApp Native Project // #include <unistd.h> #include <stdlib.h> #include <fb/include/fb/ALog.h> extern "C" { #include <HookZz/include/hookzz.h> } #include "IOUniformer.h" #include "SandboxFs.h" #include "Path.h" #include "SymbolFinder.h" bool iu_loaded = false; void IOUniformer::init_before_all() { if (iu_loaded) return; char *api_level_chars = getenv("V_API_LEVEL"); char *preview_api_level_chars = getenv("V_PREVIEW_API_LEVEL"); if (api_level_chars) { ALOGE("Enter init before all."); int api_level = atoi(api_level_chars); int preview_api_level; preview_api_level = atoi(preview_api_level_chars); char keep_env_name[25]; char forbid_env_name[25]; char replace_src_env_name[25]; char replace_dst_env_name[25]; int i = 0; while (true) { sprintf(keep_env_name, "V_KEEP_ITEM_%d", i); char *item = getenv(keep_env_name); if (!item) { break; } add_keep_item(item); i++; } i = 0; while (true) { sprintf(forbid_env_name, "V_FORBID_ITEM_%d", i); char *item = getenv(forbid_env_name); if (!item) { break; } add_forbidden_item(item); i++; } i = 0; while (true) { sprintf(replace_src_env_name, "V_REPLACE_ITEM_SRC_%d", i); char *item_src = getenv(replace_src_env_name); if (!item_src) { break; } sprintf(replace_dst_env_name, "V_REPLACE_ITEM_DST_%d", i); char *item_dst = getenv(replace_dst_env_name); add_replace_item(item_src, item_dst); i++; } startUniformer(getenv("V_SO_PATH"),api_level, preview_api_level); iu_loaded = true; } } static inline void hook_function(void *handle, const char *symbol, void *new_func, void **old_func) { void *addr = dlsym(handle, symbol); if (addr == NULL) { return; } ZzHookReplace(addr, new_func, old_func); } void onSoLoaded(const char *name, void *handle); void IOUniformer::redirect(const char *orig_path, const char *new_path) { add_replace_item(orig_path, new_path); } const char *IOUniformer::query(const char *orig_path) { int res; return relocate_path(orig_path, &res); } void IOUniformer::whitelist(const char *_path) { add_keep_item(_path); } void IOUniformer::forbid(const char *_path) { add_forbidden_item(_path); } const char *IOUniformer::restore(const char *_path) { char *path = canonicalize_filename(_path); for (int i = 0; i < get_replace_item_count(); ++i) { ReplaceItem &item = get_replace_items()[i]; if (strncmp(item.new_path, path, item.new_size) == 0) { char *redirect_path = (char *) malloc(strlen(path) - item.new_size + item.orig_size); strncpy(redirect_path, item.orig_path, item.orig_size); strcpy(redirect_path + item.orig_size, path + item.new_size); free(path); return redirect_path; } } return _path; } __BEGIN_DECLS #define FREE(ptr, org_ptr) { if ((void*) ptr != NULL && (void*) ptr != (void*) org_ptr) { free((void*) ptr); } } // int faccessat(int dirfd, const char *pathname, int mode, int flags); HOOK_DEF(int, faccessat, int dirfd, const char *pathname, int mode, int flags) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_faccessat, dirfd, redirect_path, mode, flags); FREE(redirect_path, pathname); return ret; } // int fchmodat(int dirfd, const char *pathname, mode_t mode, int flags); HOOK_DEF(int, fchmodat, int dirfd, const char *pathname, mode_t mode, int flags) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_fchmodat, dirfd, redirect_path, mode, flags); FREE(redirect_path, pathname); return ret; } // int fchmod(const char *pathname, mode_t mode); HOOK_DEF(int, fchmod, const char *pathname, mode_t mode) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_chmod, redirect_path, mode); FREE(redirect_path, pathname); return ret; } // int fstatat(int dirfd, const char *pathname, struct stat *buf, int flags); HOOK_DEF(int, fstatat, int dirfd, const char *pathname, struct stat *buf, int flags) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_fstatat64, dirfd, redirect_path, buf, flags); FREE(redirect_path, pathname); return ret; } // int fstatat64(int dirfd, const char *pathname, struct stat *buf, int flags); HOOK_DEF(int, fstatat64, int dirfd, const char *pathname, struct stat *buf, int flags) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_fstatat64, dirfd, redirect_path, buf, flags); FREE(redirect_path, pathname); return ret; } // int fstat(const char *pathname, struct stat *buf, int flags); HOOK_DEF(int, fstat, const char *pathname, struct stat *buf) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_fstat64, redirect_path, buf); FREE(redirect_path, pathname); return ret; } // int mknodat(int dirfd, const char *pathname, mode_t mode, dev_t dev); HOOK_DEF(int, mknodat, int dirfd, const char *pathname, mode_t mode, dev_t dev) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_mknodat, dirfd, redirect_path, mode, dev); FREE(redirect_path, pathname); return ret; } // int mknod(const char *pathname, mode_t mode, dev_t dev); HOOK_DEF(int, mknod, const char *pathname, mode_t mode, dev_t dev) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_mknod, redirect_path, mode, dev); FREE(redirect_path, pathname); return ret; } // int utimensat(int dirfd, const char *pathname, const struct timespec times[2], int flags); HOOK_DEF(int, utimensat, int dirfd, const char *pathname, const struct timespec times[2], int flags) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_utimensat, dirfd, redirect_path, times, flags); FREE(redirect_path, pathname); return ret; } // int fchownat(int dirfd, const char *pathname, uid_t owner, gid_t group, int flags); HOOK_DEF(int, fchownat, int dirfd, const char *pathname, uid_t owner, gid_t group, int flags) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_fchownat, dirfd, redirect_path, owner, group, flags); FREE(redirect_path, pathname); return ret; } // int chroot(const char *pathname); HOOK_DEF(int, chroot, const char *pathname) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_chroot, redirect_path); FREE(redirect_path, pathname); return ret; } // int renameat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath); HOOK_DEF(int, renameat, int olddirfd, const char *oldpath, int newdirfd, const char *newpath) { int res_old; int res_new; const char *redirect_path_old = relocate_path(oldpath, &res_old); const char *redirect_path_new = relocate_path(newpath, &res_new); int ret = syscall(__NR_renameat, olddirfd, redirect_path_old, newdirfd, redirect_path_new); FREE(redirect_path_old, oldpath); FREE(redirect_path_new, newpath); return ret; } // int rename(const char *oldpath, const char *newpath); HOOK_DEF(int, rename, const char *oldpath, const char *newpath) { int res_old; int res_new; const char *redirect_path_old = relocate_path(oldpath, &res_old); const char *redirect_path_new = relocate_path(newpath, &res_new); int ret = syscall(__NR_rename, redirect_path_old, redirect_path_new); FREE(redirect_path_old, oldpath); FREE(redirect_path_new, newpath); return ret; } // int unlinkat(int dirfd, const char *pathname, int flags); HOOK_DEF(int, unlinkat, int dirfd, const char *pathname, int flags) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_unlinkat, dirfd, redirect_path, flags); FREE(redirect_path, pathname); return ret; } // int unlink(const char *pathname); HOOK_DEF(int, unlink, const char *pathname) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_unlink, redirect_path); FREE(redirect_path, pathname); return ret; } // int symlinkat(const char *oldpath, int newdirfd, const char *newpath); HOOK_DEF(int, symlinkat, const char *oldpath, int newdirfd, const char *newpath) { int res_old; int res_new; const char *redirect_path_old = relocate_path(oldpath, &res_old); const char *redirect_path_new = relocate_path(newpath, &res_new); int ret = syscall(__NR_symlinkat, redirect_path_old, newdirfd, redirect_path_new); FREE(redirect_path_old, oldpath); FREE(redirect_path_new, newpath); return ret; } // int symlink(const char *oldpath, const char *newpath); HOOK_DEF(int, symlink, const char *oldpath, const char *newpath) { int res_old; int res_new; const char *redirect_path_old = relocate_path(oldpath, &res_old); const char *redirect_path_new = relocate_path(newpath, &res_new); int ret = syscall(__NR_symlink, redirect_path_old, redirect_path_new); FREE(redirect_path_old, oldpath); FREE(redirect_path_new, newpath); return ret; } // int linkat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, int flags); HOOK_DEF(int, linkat, int olddirfd, const char *oldpath, int newdirfd, const char *newpath, int flags) { int res_old; int res_new; const char *redirect_path_old = relocate_path(oldpath, &res_old); const char *redirect_path_new = relocate_path(newpath, &res_new); int ret = syscall(__NR_linkat, olddirfd, redirect_path_old, newdirfd, redirect_path_new, flags); FREE(redirect_path_old, oldpath); FREE(redirect_path_new, newpath); return ret; } // int link(const char *oldpath, const char *newpath); HOOK_DEF(int, link, const char *oldpath, const char *newpath) { int res_old; int res_new; const char *redirect_path_old = relocate_path(oldpath, &res_old); const char *redirect_path_new = relocate_path(newpath, &res_new); int ret = syscall(__NR_link, redirect_path_old, redirect_path_new); FREE(redirect_path_old, oldpath); FREE(redirect_path_new, newpath); return ret; } // int utimes(const char *filename, const struct timeval *tvp); HOOK_DEF(int, utimes, const char *pathname, const struct timeval *tvp) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_utimes, redirect_path, tvp); FREE(redirect_path, pathname); return ret; } // int access(const char *pathname, int mode); HOOK_DEF(int, access, const char *pathname, int mode) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_access, redirect_path, mode); FREE(redirect_path, pathname); return ret; } // int chmod(const char *path, mode_t mode); HOOK_DEF(int, chmod, const char *pathname, mode_t mode) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_chmod, redirect_path, mode); FREE(redirect_path, pathname); return ret; } // int chown(const char *path, uid_t owner, gid_t group); HOOK_DEF(int, chown, const char *pathname, uid_t owner, gid_t group) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_chown, redirect_path, owner, group); FREE(redirect_path, pathname); return ret; } // int lstat(const char *path, struct stat *buf); HOOK_DEF(int, lstat, const char *pathname, struct stat *buf) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_lstat64, redirect_path, buf); FREE(redirect_path, pathname); return ret; } // int stat(const char *path, struct stat *buf); HOOK_DEF(int, stat, const char *pathname, struct stat *buf) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_stat64, redirect_path, buf); FREE(redirect_path, pathname); return ret; } // int mkdirat(int dirfd, const char *pathname, mode_t mode); HOOK_DEF(int, mkdirat, int dirfd, const char *pathname, mode_t mode) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_mkdirat, dirfd, redirect_path, mode); FREE(redirect_path, pathname); return ret; } // int mkdir(const char *pathname, mode_t mode); HOOK_DEF(int, mkdir, const char *pathname, mode_t mode) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_mkdir, redirect_path, mode); FREE(redirect_path, pathname); return ret; } // int rmdir(const char *pathname); HOOK_DEF(int, rmdir, const char *pathname) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_rmdir, redirect_path); FREE(redirect_path, pathname); return ret; } // int readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz); HOOK_DEF(int, readlinkat, int dirfd, const char *pathname, char *buf, size_t bufsiz) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_readlinkat, dirfd, redirect_path, buf, bufsiz); FREE(redirect_path, pathname); return ret; } // ssize_t readlink(const char *path, char *buf, size_t bufsiz); HOOK_DEF(ssize_t, readlink, const char *pathname, char *buf, size_t bufsiz) { int res; const char *redirect_path = relocate_path(pathname, &res); ssize_t ret = syscall(__NR_readlink, redirect_path, buf, bufsiz); FREE(redirect_path, pathname); return ret; } // int __statfs64(const char *path, size_t size, struct statfs *stat); HOOK_DEF(int, __statfs64, const char *pathname, size_t size, struct statfs *stat) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_statfs64, redirect_path, size, stat); FREE(redirect_path, pathname); return ret; } // int truncate(const char *path, off_t length); HOOK_DEF(int, truncate, const char *pathname, off_t length) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_truncate, redirect_path, length); FREE(redirect_path, pathname); return ret; } #define RETURN_IF_FORBID if(res == FORBID) return -1; // int truncate64(const char *pathname, off_t length); HOOK_DEF(int, truncate64, const char *pathname, off_t length) { int res; const char *redirect_path = relocate_path(pathname, &res); RETURN_IF_FORBID int ret = syscall(__NR_truncate64, redirect_path, length); FREE(redirect_path, pathname); return ret; } // int chdir(const char *path); HOOK_DEF(int, chdir, const char *pathname) { int res; const char *redirect_path = relocate_path(pathname, &res); RETURN_IF_FORBID int ret = syscall(__NR_chdir, redirect_path); FREE(redirect_path, pathname); return ret; } // int __getcwd(char *buf, size_t size); HOOK_DEF(int, __getcwd, char *buf, size_t size) { int ret = syscall(__NR_getcwd, buf, size); if (!ret) { } return ret; } // int __openat(int fd, const char *pathname, int flags, int mode); HOOK_DEF(int, __openat, int fd, const char *pathname, int flags, int mode) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_openat, fd, redirect_path, flags, mode); FREE(redirect_path, pathname); return ret; } // int __open(const char *pathname, int flags, int mode); HOOK_DEF(int, __open, const char *pathname, int flags, int mode) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_open, redirect_path, flags, mode); FREE(redirect_path, pathname); return ret; } // int __statfs (__const char *__file, struct statfs *__buf); HOOK_DEF(int, __statfs, __const char *__file, struct statfs *__buf) { int res; const char *redirect_path = relocate_path(__file, &res); int ret = syscall(__NR_statfs, redirect_path, __buf); FREE(redirect_path, __file); return ret; } // int lchown(const char *pathname, uid_t owner, gid_t group); HOOK_DEF(int, lchown, const char *pathname, uid_t owner, gid_t group) { int res; const char *redirect_path = relocate_path(pathname, &res); int ret = syscall(__NR_lchown, redirect_path, owner, group); FREE(redirect_path, pathname); return ret; } int inline getArrayItemCount(char *const array[]) { int i; for (i = 0; array[i]; ++i); return i; } char **build_new_env(char *const envp[]) { char *provided_ld_preload = NULL; int provided_ld_preload_index = -1; int orig_envp_count = getArrayItemCount(envp); for (int i = 0; i < orig_envp_count; i++) { if (strstr(envp[i], "LD_PRELOAD")) { provided_ld_preload = envp[i]; provided_ld_preload_index = i; } } char ld_preload[200]; char *so_path = getenv("V_SO_PATH"); if (provided_ld_preload) { sprintf(ld_preload, "LD_PRELOAD=%s:%s", so_path, provided_ld_preload + 11); } else { sprintf(ld_preload, "LD_PRELOAD=%s", so_path); } int new_envp_count = orig_envp_count + get_keep_item_count() + get_forbidden_item_count() + get_replace_item_count() * 2 + 1; if (provided_ld_preload) { new_envp_count--; } char **new_envp = (char **) malloc(new_envp_count * sizeof(char *)); int cur = 0; new_envp[cur++] = ld_preload; for (int i = 0; i < orig_envp_count; ++i) { if (i != provided_ld_preload_index) { new_envp[cur++] = envp[i]; } } for (int i = 0; environ[i]; ++i) { if (environ[i][0] == 'V' && environ[i][1] == '_') { new_envp[cur++] = environ[i]; } } new_envp[cur] = NULL; return new_envp; } // int (*origin_execve)(const char *pathname, char *const argv[], char *const envp[]); HOOK_DEF(int, execve, const char *pathname, char *argv[], char *const envp[]) { /** * CANNOT LINK EXECUTABLE "/system/bin/cat": "/data/app/io.virtualapp-1/lib/arm/libva-native.so" is 32-bit instead of 64-bit. * * We will support 64Bit to adopt it. */ ALOGE("execve : %s", pathname); int res; const char *redirect_path = relocate_path(pathname, &res); char *ld = getenv("LD_PRELOAD"); if (ld) { if (strstr(ld, "libNimsWrap.so") || strstr(ld, "stamina.so")) { int ret = syscall(__NR_execve, redirect_path, argv, envp); FREE(redirect_path, pathname); return ret; } } if (strstr(pathname, "dex2oat")) { char **new_envp = build_new_env(envp); int ret = syscall(__NR_execve, redirect_path, argv, new_envp); FREE(redirect_path, pathname); return ret; } int ret = syscall(__NR_execve, redirect_path, argv, envp); FREE(redirect_path, pathname); return ret; } HOOK_DEF(void*, dlopen, const char *filename, int flag) { int res; const char *redirect_path = relocate_path(filename, &res); void *ret = orig_dlopen(redirect_path, flag); onSoLoaded(filename, ret); ALOGD("dlopen : %s, return : %p.", redirect_path, ret); FREE(redirect_path, filename); return ret; } HOOK_DEF(void*, do_dlopen_V19, const char *filename, int flag, const void *extinfo) { int res; const char *redirect_path = relocate_path(filename, &res); void *ret = orig_do_dlopen_V19(redirect_path, flag, extinfo); onSoLoaded(filename, ret); ALOGD("do_dlopen : %s, return : %p.", redirect_path, ret); FREE(redirect_path, filename); return ret; } HOOK_DEF(void*, do_dlopen_V24, const char *name, int flags, const void *extinfo, void *caller_addr) { int res; const char *redirect_path = relocate_path(name, &res); void *ret = orig_do_dlopen_V24(redirect_path, flags, extinfo, caller_addr); onSoLoaded(name, ret); ALOGD("do_dlopen : %s, return : %p.", redirect_path, ret); FREE(redirect_path, name); return ret; } //void *dlsym(void *handle,const char *symbol) HOOK_DEF(void*, dlsym, void *handle, char *symbol) { ALOGD("dlsym : %p %s.", handle, symbol); return orig_dlsym(handle, symbol); } // int kill(pid_t pid, int sig); HOOK_DEF(int, kill, pid_t pid, int sig) { ALOGD(">>>>> kill >>> pid: %d, sig: %d.", pid, sig); int ret = syscall(__NR_kill, pid, sig); return ret; } HOOK_DEF(pid_t, vfork) { return fork(); } __END_DECLS // end IO DEF void onSoLoaded(const char *name, void *handle) { } int findSymbol(const char *name, const char *libn, unsigned long *addr) { return find_name(getpid(), name, libn, addr); } void hook_dlopen(int api_level) { void *symbol = NULL; if (api_level > 23) { if (findSymbol("__dl__Z9do_dlopenPKciPK17android_dlextinfoPv", "linker", (unsigned long *) &symbol) == 0) { ZzHookReplace(symbol, (void *) new_do_dlopen_V24, (void **) &orig_do_dlopen_V24); } } else if (api_level >= 19) { if (findSymbol("__dl__Z9do_dlopenPKciPK17android_dlextinfo", "linker", (unsigned long *) &symbol) == 0) { ZzHookReplace(symbol, (void *) new_do_dlopen_V19, (void **) &orig_do_dlopen_V19); } } else { if (findSymbol("__dl_dlopen", "linker", (unsigned long *) &symbol) == 0) { ZzHookReplace(symbol, (void *) new_dlopen, (void **) &orig_dlopen); } } } void IOUniformer::startUniformer(const char *so_path, int api_level, int preview_api_level) { char api_level_chars[5]; setenv("V_SO_PATH", so_path, 1); sprintf(api_level_chars, "%i", api_level); setenv("V_API_LEVEL", api_level_chars, 1); sprintf(api_level_chars, "%i", preview_api_level); setenv("V_PREVIEW_API_LEVEL", api_level_chars, 1); void *handle = dlopen("libc.so", RTLD_NOW); if (handle) { HOOK_SYMBOL(handle, faccessat); HOOK_SYMBOL(handle, __openat); HOOK_SYMBOL(handle, fchmodat); HOOK_SYMBOL(handle, fchownat); HOOK_SYMBOL(handle, renameat); HOOK_SYMBOL(handle, fstatat64); HOOK_SYMBOL(handle, __statfs); HOOK_SYMBOL(handle, __statfs64); HOOK_SYMBOL(handle, mkdirat); HOOK_SYMBOL(handle, mknodat); HOOK_SYMBOL(handle, truncate); HOOK_SYMBOL(handle, linkat); HOOK_SYMBOL(handle, readlinkat); HOOK_SYMBOL(handle, unlinkat); HOOK_SYMBOL(handle, symlinkat); HOOK_SYMBOL(handle, utimensat); HOOK_SYMBOL(handle, __getcwd); // HOOK_SYMBOL(handle, __getdents64); HOOK_SYMBOL(handle, chdir); HOOK_SYMBOL(handle, execve); if (api_level <= 20) { HOOK_SYMBOL(handle, access); HOOK_SYMBOL(handle, __open); HOOK_SYMBOL(handle, stat); HOOK_SYMBOL(handle, lstat); HOOK_SYMBOL(handle, fstatat); HOOK_SYMBOL(handle, chmod); HOOK_SYMBOL(handle, chown); HOOK_SYMBOL(handle, rename); HOOK_SYMBOL(handle, rmdir); HOOK_SYMBOL(handle, mkdir); HOOK_SYMBOL(handle, mknod); HOOK_SYMBOL(handle, link); HOOK_SYMBOL(handle, unlink); HOOK_SYMBOL(handle, readlink); HOOK_SYMBOL(handle, symlink); // HOOK_SYMBOL(handle, getdents); // HOOK_SYMBOL(handle, execv); } dlclose(handle); } // hook_dlopen(api_level); }
[ "dfcfvf@outlook.com" ]
dfcfvf@outlook.com
38eddb5c522474789e9d9bdec725e85bc13dcc15
c4e72d23b34be6673abd66c8e4012ed524c29dda
/iialib/src/socket/HostEnt.cpp
7203a04888b57444b309403c20d918b4a4df7891
[]
no_license
Sevalecan/IIA
3fbf95dd7102ba3251ccac6d7ed6e6827cb929b1
3ac82e2dc11b695020ad038e7389b44c22c288d8
refs/heads/master
2020-04-25T12:35:32.665435
2006-05-21T01:15:29
2006-05-21T01:15:29
31,803,164
0
0
null
null
null
null
UTF-8
C++
false
false
1,654
cpp
#define IIASOURCE #include "socket/HostEnt.hpp" namespace IIALib { namespace Socket { uint32_t HostEnt::Fromhostent(hostent *hRet) { uint32_t iLen, iPos; hName = hRet->h_name; for (iLen=0;hRet->h_aliases[iLen];iLen++); hAliases.resize(iLen); for (iPos=0;iPos<iLen;iPos++) hAliases[iPos] = hRet->h_aliases[iPos]; hAddrType = hRet->h_addrtype; hLength = hRet->h_length; for (iLen=0;hRet->h_addr_list[iLen];iLen++); hAddrList.resize(iLen); for (iPos=0;iPos<iLen;iPos++) memcpy(hAddrList[iPos].iData, hRet->h_addr_list[iPos], hLength); hAddr = (uint8_t *)&hAddrList[0]; return 0; } uint32_t HostEnt::GetHostByAddr(InAddr *aAddr, uint32_t iLength, uint32_t iFormat) { hostent *hRet; hRet = gethostbyaddr((const char *)aAddr->iData, iLength, iFormat); if (hRet == NULL) return 1; Fromhostent(hRet); return 0; } uint32_t HostEnt::GetHostByName(const char *zName) { hostent *hRet; hRet = gethostbyname(zName); if (hRet == NULL) return 1; Fromhostent(hRet); return 0; } }; };
[ "sevalecan@gmail.com" ]
sevalecan@gmail.com
0d7981aae93f5d9615b40fd1013c9c1653da0f45
05b024ea0bf6bc22dc8bba612074565fb559b306
/chapter14-reusing/composite.cpp
9c2b917f469e2d05a453fd868b4eafaf7fb2982a
[]
no_license
Mp5A5/c--primer-plus
fcf3276725c4431e354282a8dc19f6bfbd4486cf
23c4251978f58adf7eb4dc355b9f4118313dc742
refs/heads/master
2022-12-07T15:21:18.019859
2020-08-23T09:15:14
2020-08-23T09:15:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
639
cpp
#include <iostream> #include <string> using namespace std; class Person { public: string name; explicit Person(const string &name): name(name) { cout << "constructor one arg" << endl; } Person() { cout << "constructor empty" << endl; } }; class ClassRoom { public: Person person; explicit ClassRoom(const string & name) { this->person = Person(name); } // explicit ClassRoom(const string & name): person(name) // { // } }; int main(int argc, char const *argv[]) { string name = "tom"; // Person p(name); ClassRoom cr(name); return 0; }
[ "youaiduan@gamil.com" ]
youaiduan@gamil.com
e10d946762fe3836f26790cf6aa5ab9a3d76ff44
fac52aacf1a7145d46f420bb2991528676e3be3f
/SDK/UI_ConfirmationBase_parameters.h
4b54c92ac93ec4ea86da6b7a8e88a0f1fe7f063d
[]
no_license
zH4x-SDK/zSCUM-SDK
2342afd6ee54f4f0b14b0a0e9e3920d75bdb4fed
711376eb272b220521fec36d84ca78fc11d4802a
refs/heads/main
2023-07-15T16:02:22.649492
2021-08-27T13:44:21
2021-08-27T13:44:21
400,522,163
2
0
null
null
null
null
UTF-8
C++
false
false
1,302
h
#pragma once #include "../SDK.h" // Name: SCUM, Version: 4.20.3 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function UI_ConfirmationBase.UI_ConfirmationBase_C.AddToCanvas struct UUI_ConfirmationBase_C_AddToCanvas_Params { class UCanvasPanel* Canvas; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) }; // Function UI_ConfirmationBase.UI_ConfirmationBase_C.OnNo struct UUI_ConfirmationBase_C_OnNo_Params { }; // Function UI_ConfirmationBase.UI_ConfirmationBase_C.ExecuteUbergraph_UI_ConfirmationBase struct UUI_ConfirmationBase_C_ExecuteUbergraph_UI_ConfirmationBase_Params { int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; // Function UI_ConfirmationBase.UI_ConfirmationBase_C.NoClicked__DelegateSignature struct UUI_ConfirmationBase_C_NoClicked__DelegateSignature_Params { }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
0ddc2bfe308e3ea9ac4cdf83c05b3a123e357906
34bba90c69d8a01205b1376bc95d6f63ab72118e
/laser_scan_matcher/include/laser_scan_matcher/Math.h
3576446de8e212394a19607af3e3274834af8745
[]
no_license
Joye-zhangbo/laser-slam
fdfbdf39d50a24103e2cd2ce332c6f65ba63682b
f9f5a08eba2bb7997bf5bc639f1241ce621a28b4
refs/heads/master
2023-07-09T04:55:21.261011
2021-08-21T08:55:38
2021-08-21T08:55:38
397,945,487
1
0
null
null
null
null
UTF-8
C++
false
false
4,747
h
/* * Copyright 2010 SRI International * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LASER_SCAN_MATCHER_MATH_H #define LASER_SCAN_MATCHER_MATH_H #include <assert.h> #include <cmath> #include <cstddef> #include <limits> namespace scan_tools { /** * Enumerated type for valid grid cell states */ const int GridStates_Unknown = 0; const int GridStates_Occupied = 100; const int GridStates_Free = 255; /** * Platform independent pi definitions */ const double KT_PI = 3.14159265358979323846; // The value of PI const double KT_2PI = 6.28318530717958647692; // 2 * PI const double KT_PI_2 = 1.57079632679489661923; // PI / 2 const double KT_PI_180 = 0.01745329251994329577; // PI / 180 const double KT_180_PI = 57.29577951308232087685; // 180 / PI /** * Lets define a small number! */ const double KT_TOLERANCE = 1e-06; namespace math { /** * Converts degrees into radians * @param degrees * @return radian equivalent of degrees */ inline double DegreesToRadians(double degrees) { return degrees * KT_PI_180; } /** * Converts radians into degrees * @param radians * @return degree equivalent of radians */ inline double RadiansToDegrees(double radians) { return radians * KT_180_PI; } /** * Square function * @param value * @return square of value */ template <typename T> inline T Square(T value) { return (value * value); } /** * Round function * @param value * @return rounds value to the nearest whole number (as double) */ inline double Round(double value) { return value >= 0.0 ? floor(value + 0.5) : ceil(value - 0.5); } /** * Binary minimum function * @param value1 * @param value2 * @return the lesser of value1 and value2 */ template <typename T> inline const T& Minimum(const T& value1, const T& value2) { return value1 < value2 ? value1 : value2; } /** * Binary maximum function * @param value1 * @param value2 * @return the greater of value1 and value2 */ template <typename T> inline const T& Maximum(const T& value1, const T& value2) { return value1 > value2 ? value1 : value2; } /** * Clips a number to the specified minimum and maximum values. * @param n number to be clipped * @param minValue minimum value * @param maxValue maximum value * @return the clipped value */ template <typename T> inline const T& Clip(const T& n, const T& minValue, const T& maxValue) { return Minimum(Maximum(n, minValue), maxValue); } /** * Checks whether two numbers are equal within a certain tolerance. * @param a * @param b * @return true if a and b differ by at most a certain tolerance. */ inline bool DoubleEqual(double a, double b) { double delta = a - b; return delta < 0.0 ? delta >= -KT_TOLERANCE : delta <= KT_TOLERANCE; } /** * Checks whether value is in the range [0;maximum) * @param value * @param maximum */ template <typename T> inline bool IsUpTo(const T& value, const T& maximum) { return (value >= 0 && value < maximum); } /** * Checks whether value is in the range [a;b] * @param value * @param a * @param b */ template <typename T> inline bool InRange(const T& value, const T& a, const T& b) { return (value >= a && value <= b); } /** * Normalizes angle to be in the range of (-pi, pi] * @param angle to be normalized * @return normalized angle */ inline double NormalizeAngle(double angle) { while (angle > KT_PI) { angle -= KT_2PI; } while (angle <= -KT_PI) { angle += KT_2PI; } assert(math::InRange(angle, -M_PI, M_PI)); return angle; } /** * Align a value to the alignValue. * The alignValue should be the power of two (2, 4, 8, 16, 32 and so on) * @param value * @param alignValue * @return aligned value */ template <class T> inline T AlignValue(size_t value, size_t alignValue = 8) { return static_cast<T>((value + (alignValue - 1)) & ~(alignValue - 1)); } } // namespace math } // namespace scan_tools #endif // LASER_SCAN_MATCHER_MATH_H
[ "495203317@qq.com" ]
495203317@qq.com
59e0841149572fc0018108b2fad0c9fa88dee72f
5197e8e9e324a08a95010d1e51b596b3b30c5b12
/src/qt/titlebar.h
f533b9c98e70771fc730792f58c4bba51cb77bd4
[ "MIT" ]
permissive
bitcoinx-project/bitcoinx
8bb5144e313c5995c192386b55202a0b4ff45fed
d422a992e7efee1ea1fb82cf7a1e81e04ca716c0
refs/heads/master
2021-07-11T19:03:44.279254
2019-01-24T06:24:30
2019-01-24T06:24:30
116,213,243
159
86
MIT
2019-01-28T09:02:36
2018-01-04T04:08:40
C++
UTF-8
C++
false
false
1,634
h
#ifndef TITLEBAR_H #define TITLEBAR_H #include <QWidget> #include <QSize> #include <QTabBar> #include <QIcon> #include "walletmodel.h" namespace Ui { class TitleBar; } class WalletModel; class TabBarInfo; class PlatformStyle; /** * @brief The TitleBar class Title bar widget */ class TitleBar : public QWidget { Q_OBJECT public: /** * @brief TitleBar Constructor * @param parent Parent widget */ explicit TitleBar(const PlatformStyle *platformStyle, QWidget *parent = 0); /** * @brief TitleBar Destrustor */ ~TitleBar(); /** * @brief setTabBarInfo Set the tab bar info * @param info Information about tabs */ void setTabBarInfo(QObject* info); /** * @brief setModel Set wallet model * @param _model Wallet model */ void setModel(WalletModel *_model); Q_SIGNALS: public Q_SLOTS: /** * @brief setBalance Slot for changing the balance */ void setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& stake, const CAmount& watchBalance, const CAmount& watchUnconfirmedBalance, const CAmount& watchImmatureBalance, const CAmount& watchStake); /** * @brief on_navigationResized Slot for changing the size of the navigation bar * @param _size Size of the navigation bar */ void on_navigationResized(const QSize& _size); private: Ui::TitleBar *ui; WalletModel *model; TabBarInfo* m_tab; QIcon m_iconCloseTab; }; #endif // TITLEBAR_H
[ "11780456+neuralbayes@users.noreply.github.com" ]
11780456+neuralbayes@users.noreply.github.com
99a65d1442844d8abb5d0b1387dd073fcdfe0685
4dbe7cb8665cc4e183d948d1bd0664031ba287fa
/src/gtpV2Codec/ieClasses/listOfRabsInForwardRelocationResponse.cpp
1235d97684f341cfb37b1b74baf76b3706969baa
[ "Apache-2.0" ]
permissive
aggarwalanubhav/Nucleus
1356a58201cb6aecd44662420a40413102dde85c
107113cd9a1b68b1a28b35091ed17785ed32d319
refs/heads/master
2023-06-10T12:09:44.316674
2021-07-06T09:03:18
2021-07-06T09:03:18
365,923,062
0
1
Apache-2.0
2021-05-18T09:16:19
2021-05-10T05:01:58
C++
UTF-8
C++
false
false
20,493
cpp
/* * Copyright 2019-present Infosys Limited * * SPDX-License-Identifier: Apache-2.0 */ /****************************************************************************** * * This is an auto generated file. * Please do not edit this file. * All edits to be made through template source file * <TOP-DIR/scripts/GtpV2StackCodeGen/tts/grpieinsttemplate.cpp.tt> ******************************************************************************/ #include "listOfRabsInForwardRelocationResponse.h" #include "manual/gtpV2Ie.h" #include "gtpV2IeFactory.h" #include "ebiIe.h" #include "packetFlowIdIe.h" #include "fTeidIe.h" #include "fTeidIe.h" #include "fTeidIe.h" #include "fTeidIe.h" #include "fTeidIe.h" #include "fTeidIe.h" ListOfRabsInForwardRelocationResponse:: ListOfRabsInForwardRelocationResponse() { } ListOfRabsInForwardRelocationResponse:: ~ListOfRabsInForwardRelocationResponse() { } bool ListOfRabsInForwardRelocationResponse:: encodeListOfRabsInForwardRelocationResponse(MsgBuffer &buffer, ListOfRabsInForwardRelocationResponseData const &data) { bool rc = false; GtpV2IeHeader header; Uint16 startIndex = 0; Uint16 endIndex = 0; Uint16 length = 0; if (data.epsBearerIdIePresent) { // Encode the Ie Header header.ieType = EbiIeType; header.instance = 0; header.length = 0; // We will encode the IE first and then update the length GtpV2Ie::encodeGtpV2IeHeader(buffer, header); startIndex = buffer.getCurrentIndex(); EbiIe epsBearerId= dynamic_cast< EbiIe&>(GtpV2IeFactory::getInstance().getIeObject(EbiIeType)); rc = epsBearerId.encodeEbiIe(buffer, data.epsBearerId); endIndex = buffer.getCurrentIndex(); length = endIndex - startIndex; // encode the length value now buffer.goToIndex(startIndex - 3); buffer.writeUint16(length, false); buffer.goToIndex(endIndex); if (!(rc)) { errorStream.add((char *)"Failed to encode IE: epsBearerId\n"); return false; } } if (data.packetFlowIdIePresent) { // Encode the Ie Header header.ieType = PacketFlowIdIeType; header.instance = 0; header.length = 0; // We will encode the IE first and then update the length GtpV2Ie::encodeGtpV2IeHeader(buffer, header); startIndex = buffer.getCurrentIndex(); PacketFlowIdIe packetFlowId= dynamic_cast< PacketFlowIdIe&>(GtpV2IeFactory::getInstance().getIeObject(PacketFlowIdIeType)); rc = packetFlowId.encodePacketFlowIdIe(buffer, data.packetFlowId); endIndex = buffer.getCurrentIndex(); length = endIndex - startIndex; // encode the length value now buffer.goToIndex(startIndex - 3); buffer.writeUint16(length, false); buffer.goToIndex(endIndex); if (!(rc)) { errorStream.add((char *)"Failed to encode IE: packetFlowId\n"); return false; } } if (data.enodebFTeidForDlDataForwardingIePresent) { // Encode the Ie Header header.ieType = FTeidIeType; header.instance = 0; header.length = 0; // We will encode the IE first and then update the length GtpV2Ie::encodeGtpV2IeHeader(buffer, header); startIndex = buffer.getCurrentIndex(); FTeidIe enodebFTeidForDlDataForwarding= dynamic_cast< FTeidIe&>(GtpV2IeFactory::getInstance().getIeObject(FTeidIeType)); rc = enodebFTeidForDlDataForwarding.encodeFTeidIe(buffer, data.enodebFTeidForDlDataForwarding); endIndex = buffer.getCurrentIndex(); length = endIndex - startIndex; // encode the length value now buffer.goToIndex(startIndex - 3); buffer.writeUint16(length, false); buffer.goToIndex(endIndex); if (!(rc)) { errorStream.add((char *)"Failed to encode IE: enodebFTeidForDlDataForwarding\n"); return false; } } if (data.enodebFTeidForUlDataForwardingIePresent) { // Encode the Ie Header header.ieType = FTeidIeType; header.instance = 1; header.length = 0; // We will encode the IE first and then update the length GtpV2Ie::encodeGtpV2IeHeader(buffer, header); startIndex = buffer.getCurrentIndex(); FTeidIe enodebFTeidForUlDataForwarding= dynamic_cast< FTeidIe&>(GtpV2IeFactory::getInstance().getIeObject(FTeidIeType)); rc = enodebFTeidForUlDataForwarding.encodeFTeidIe(buffer, data.enodebFTeidForUlDataForwarding); endIndex = buffer.getCurrentIndex(); length = endIndex - startIndex; // encode the length value now buffer.goToIndex(startIndex - 3); buffer.writeUint16(length, false); buffer.goToIndex(endIndex); if (!(rc)) { errorStream.add((char *)"Failed to encode IE: enodebFTeidForUlDataForwarding\n"); return false; } } if (data.sgwUpfFTeidForDlDataForwardingIePresent) { // Encode the Ie Header header.ieType = FTeidIeType; header.instance = 2; header.length = 0; // We will encode the IE first and then update the length GtpV2Ie::encodeGtpV2IeHeader(buffer, header); startIndex = buffer.getCurrentIndex(); FTeidIe sgwUpfFTeidForDlDataForwarding= dynamic_cast< FTeidIe&>(GtpV2IeFactory::getInstance().getIeObject(FTeidIeType)); rc = sgwUpfFTeidForDlDataForwarding.encodeFTeidIe(buffer, data.sgwUpfFTeidForDlDataForwarding); endIndex = buffer.getCurrentIndex(); length = endIndex - startIndex; // encode the length value now buffer.goToIndex(startIndex - 3); buffer.writeUint16(length, false); buffer.goToIndex(endIndex); if (!(rc)) { errorStream.add((char *)"Failed to encode IE: sgwUpfFTeidForDlDataForwarding\n"); return false; } } if (data.rncFTeidForDlDataForwardingIePresent) { // Encode the Ie Header header.ieType = FTeidIeType; header.instance = 3; header.length = 0; // We will encode the IE first and then update the length GtpV2Ie::encodeGtpV2IeHeader(buffer, header); startIndex = buffer.getCurrentIndex(); FTeidIe rncFTeidForDlDataForwarding= dynamic_cast< FTeidIe&>(GtpV2IeFactory::getInstance().getIeObject(FTeidIeType)); rc = rncFTeidForDlDataForwarding.encodeFTeidIe(buffer, data.rncFTeidForDlDataForwarding); endIndex = buffer.getCurrentIndex(); length = endIndex - startIndex; // encode the length value now buffer.goToIndex(startIndex - 3); buffer.writeUint16(length, false); buffer.goToIndex(endIndex); if (!(rc)) { errorStream.add((char *)"Failed to encode IE: rncFTeidForDlDataForwarding\n"); return false; } } if (data.sgsnFTeidForDlDataForwardingIePresent) { // Encode the Ie Header header.ieType = FTeidIeType; header.instance = 4; header.length = 0; // We will encode the IE first and then update the length GtpV2Ie::encodeGtpV2IeHeader(buffer, header); startIndex = buffer.getCurrentIndex(); FTeidIe sgsnFTeidForDlDataForwarding= dynamic_cast< FTeidIe&>(GtpV2IeFactory::getInstance().getIeObject(FTeidIeType)); rc = sgsnFTeidForDlDataForwarding.encodeFTeidIe(buffer, data.sgsnFTeidForDlDataForwarding); endIndex = buffer.getCurrentIndex(); length = endIndex - startIndex; // encode the length value now buffer.goToIndex(startIndex - 3); buffer.writeUint16(length, false); buffer.goToIndex(endIndex); if (!(rc)) { errorStream.add((char *)"Failed to encode IE: sgsnFTeidForDlDataForwarding\n"); return false; } } if (data.sgwFTeidForUlDataForwardingIePresent) { // Encode the Ie Header header.ieType = FTeidIeType; header.instance = 5; header.length = 0; // We will encode the IE first and then update the length GtpV2Ie::encodeGtpV2IeHeader(buffer, header); startIndex = buffer.getCurrentIndex(); FTeidIe sgwFTeidForUlDataForwarding= dynamic_cast< FTeidIe&>(GtpV2IeFactory::getInstance().getIeObject(FTeidIeType)); rc = sgwFTeidForUlDataForwarding.encodeFTeidIe(buffer, data.sgwFTeidForUlDataForwarding); endIndex = buffer.getCurrentIndex(); length = endIndex - startIndex; // encode the length value now buffer.goToIndex(startIndex - 3); buffer.writeUint16(length, false); buffer.goToIndex(endIndex); if (!(rc)) { errorStream.add((char *)"Failed to encode IE: sgwFTeidForUlDataForwarding\n"); return false; } } return rc; } bool ListOfRabsInForwardRelocationResponse:: decodeListOfRabsInForwardRelocationResponse(MsgBuffer &buffer, ListOfRabsInForwardRelocationResponseData &data, Uint16 length) { Uint16 groupedIeBoundary = length + buffer.getCurrentIndex(); bool rc = false; GtpV2IeHeader ieHeader; set<Uint16> mandatoryIeLocalList = mandatoryIeSet; while ((buffer.lengthLeft() > IE_HEADER_SIZE) && (buffer.getCurrentIndex() < groupedIeBoundary)) { GtpV2Ie::decodeGtpV2IeHeader(buffer, ieHeader); if (ieHeader.length > buffer.lengthLeft()) { // We do not have enough bytes left in the message for this IE errorStream.add((char *)"IE Length exceeds beyond message boundary\n"); errorStream.add((char *)" Offending IE Type: "); errorStream.add(ieHeader.ieType); errorStream.add((char *)"\n Ie Length in Header: "); errorStream.add(ieHeader.length); errorStream.add((char *)"\n Bytes left in message: "); errorStream.add(buffer.lengthLeft()); errorStream.endOfLine(); return false; } switch (ieHeader.ieType){ case EbiIeType: { EbiIe ieObject = dynamic_cast< EbiIe&>(GtpV2IeFactory::getInstance(). getIeObject(EbiIeType)); if(ieHeader.instance == 0) { rc = ieObject.decodeEbiIe(buffer, data.epsBearerId, ieHeader.length); data.epsBearerIdIePresent = true; if (!(rc)) { errorStream.add((char *)"Failed to decode IE: epsBearerId\n"); return false; } } else { // Unknown IE instance print error TODO errorStream.add((char *)"Unknown IE Type: "); errorStream.add(ieHeader.ieType); errorStream.endOfLine(); buffer.skipBytes(ieHeader.length); } break; } case PacketFlowIdIeType: { PacketFlowIdIe ieObject = dynamic_cast< PacketFlowIdIe&>(GtpV2IeFactory::getInstance(). getIeObject(PacketFlowIdIeType)); if(ieHeader.instance == 0) { rc = ieObject.decodePacketFlowIdIe(buffer, data.packetFlowId, ieHeader.length); data.packetFlowIdIePresent = true; if (!(rc)) { errorStream.add((char *)"Failed to decode IE: packetFlowId\n"); return false; } } else { // Unknown IE instance print error TODO errorStream.add((char *)"Unknown IE Type: "); errorStream.add(ieHeader.ieType); errorStream.endOfLine(); buffer.skipBytes(ieHeader.length); } break; } case FTeidIeType: { FTeidIe ieObject = dynamic_cast< FTeidIe&>(GtpV2IeFactory::getInstance(). getIeObject(FTeidIeType)); if(ieHeader.instance == 0) { rc = ieObject.decodeFTeidIe(buffer, data.enodebFTeidForDlDataForwarding, ieHeader.length); data.enodebFTeidForDlDataForwardingIePresent = true; if (!(rc)) { errorStream.add((char *)"Failed to decode IE: enodebFTeidForDlDataForwarding\n"); return false; } } else if(ieHeader.instance == 1) { rc = ieObject.decodeFTeidIe(buffer, data.enodebFTeidForUlDataForwarding, ieHeader.length); data.enodebFTeidForUlDataForwardingIePresent = true; if (!(rc)) { errorStream.add((char *)"Failed to decode IE: enodebFTeidForUlDataForwarding\n"); return false; } } else if(ieHeader.instance == 2) { rc = ieObject.decodeFTeidIe(buffer, data.sgwUpfFTeidForDlDataForwarding, ieHeader.length); data.sgwUpfFTeidForDlDataForwardingIePresent = true; if (!(rc)) { errorStream.add((char *)"Failed to decode IE: sgwUpfFTeidForDlDataForwarding\n"); return false; } } else if(ieHeader.instance == 3) { rc = ieObject.decodeFTeidIe(buffer, data.rncFTeidForDlDataForwarding, ieHeader.length); data.rncFTeidForDlDataForwardingIePresent = true; if (!(rc)) { errorStream.add((char *)"Failed to decode IE: rncFTeidForDlDataForwarding\n"); return false; } } else if(ieHeader.instance == 4) { rc = ieObject.decodeFTeidIe(buffer, data.sgsnFTeidForDlDataForwarding, ieHeader.length); data.sgsnFTeidForDlDataForwardingIePresent = true; if (!(rc)) { errorStream.add((char *)"Failed to decode IE: sgsnFTeidForDlDataForwarding\n"); return false; } } else if(ieHeader.instance == 5) { rc = ieObject.decodeFTeidIe(buffer, data.sgwFTeidForUlDataForwarding, ieHeader.length); data.sgwFTeidForUlDataForwardingIePresent = true; if (!(rc)) { errorStream.add((char *)"Failed to decode IE: sgwFTeidForUlDataForwarding\n"); return false; } } else { // Unknown IE instance print error TODO errorStream.add((char *)"Unknown IE Type: "); errorStream.add(ieHeader.ieType); errorStream.endOfLine(); buffer.skipBytes(ieHeader.length); } break; } default: { // Unknown IE print error errorStream.add((char *)"Unknown IE Type: "); errorStream.add(ieHeader.ieType); errorStream.endOfLine(); buffer.skipBytes(ieHeader.length); } } } if (!mandatoryIeLocalList.empty()) { // some mandatory IEs are missing errorStream.add((char *)"Missing Mandatory IEs:"); errorStream.endOfLine(); while (!mandatoryIeLocalList.empty()) { Uint16 missingMandIe = *mandatoryIeLocalList.begin (); mandatoryIeLocalList.erase (mandatoryIeLocalList.begin ()); Uint16 missingInstance = missingMandIe & 0x00FF; Uint16 missingIeType = (missingMandIe >> 8); errorStream.add ((char *)"Missing Ie type: "); errorStream.add (missingIeType); errorStream.add ((char *)" Instance: "); errorStream.add (missingInstance); errorStream.endOfLine(); } rc = false; } return rc; } void ListOfRabsInForwardRelocationResponse:: displayListOfRabsInForwardRelocationResponseData_v (ListOfRabsInForwardRelocationResponseData const &data, Debug &stream) { stream.incrIndent(); stream.add((char *)"ListOfRabsInForwardRelocationResponse:"); stream.endOfLine(); stream.incrIndent(); if (data.epsBearerIdIePresent) { stream.add((char *)"epsBearerId:"); stream.endOfLine(); EbiIe epsBearerId= dynamic_cast< EbiIe&>(GtpV2IeFactory::getInstance().getIeObject(EbiIeType)); epsBearerId.displayEbiIe_v(data.epsBearerId, stream); } if (data.packetFlowIdIePresent) { stream.add((char *)"packetFlowId:"); stream.endOfLine(); PacketFlowIdIe packetFlowId= dynamic_cast< PacketFlowIdIe&>(GtpV2IeFactory::getInstance().getIeObject(PacketFlowIdIeType)); packetFlowId.displayPacketFlowIdIe_v(data.packetFlowId, stream); } if (data.enodebFTeidForDlDataForwardingIePresent) { stream.add((char *)"enodebFTeidForDlDataForwarding:"); stream.endOfLine(); FTeidIe enodebFTeidForDlDataForwarding= dynamic_cast< FTeidIe&>(GtpV2IeFactory::getInstance().getIeObject(FTeidIeType)); enodebFTeidForDlDataForwarding.displayFTeidIe_v(data.enodebFTeidForDlDataForwarding, stream); } if (data.enodebFTeidForUlDataForwardingIePresent) { stream.add((char *)"enodebFTeidForUlDataForwarding:"); stream.endOfLine(); FTeidIe enodebFTeidForUlDataForwarding= dynamic_cast< FTeidIe&>(GtpV2IeFactory::getInstance().getIeObject(FTeidIeType)); enodebFTeidForUlDataForwarding.displayFTeidIe_v(data.enodebFTeidForUlDataForwarding, stream); } if (data.sgwUpfFTeidForDlDataForwardingIePresent) { stream.add((char *)"sgwUpfFTeidForDlDataForwarding:"); stream.endOfLine(); FTeidIe sgwUpfFTeidForDlDataForwarding= dynamic_cast< FTeidIe&>(GtpV2IeFactory::getInstance().getIeObject(FTeidIeType)); sgwUpfFTeidForDlDataForwarding.displayFTeidIe_v(data.sgwUpfFTeidForDlDataForwarding, stream); } if (data.rncFTeidForDlDataForwardingIePresent) { stream.add((char *)"rncFTeidForDlDataForwarding:"); stream.endOfLine(); FTeidIe rncFTeidForDlDataForwarding= dynamic_cast< FTeidIe&>(GtpV2IeFactory::getInstance().getIeObject(FTeidIeType)); rncFTeidForDlDataForwarding.displayFTeidIe_v(data.rncFTeidForDlDataForwarding, stream); } if (data.sgsnFTeidForDlDataForwardingIePresent) { stream.add((char *)"sgsnFTeidForDlDataForwarding:"); stream.endOfLine(); FTeidIe sgsnFTeidForDlDataForwarding= dynamic_cast< FTeidIe&>(GtpV2IeFactory::getInstance().getIeObject(FTeidIeType)); sgsnFTeidForDlDataForwarding.displayFTeidIe_v(data.sgsnFTeidForDlDataForwarding, stream); } if (data.sgwFTeidForUlDataForwardingIePresent) { stream.add((char *)"sgwFTeidForUlDataForwarding:"); stream.endOfLine(); FTeidIe sgwFTeidForUlDataForwarding= dynamic_cast< FTeidIe&>(GtpV2IeFactory::getInstance().getIeObject(FTeidIeType)); sgwFTeidForUlDataForwarding.displayFTeidIe_v(data.sgwFTeidForUlDataForwarding, stream); } stream.decrIndent(); stream.decrIndent(); }
[ "aggarwalanubhav98@gmail.com" ]
aggarwalanubhav98@gmail.com
ebd185117867cc06a18e6a335adf4855642e707a
0a5c30db4c7d24a8b82223883d5ceacf25f58aae
/src/html/ht_token.h
29f3e6765f65fa313b734617ec7a5f5483a8889e
[]
no_license
lineCode/Newtoo
65f4fb3a97e90b965efc4ea75914113ef03b9f75
5de04c61320b0c121a5fb1f244afafb587f6b6ee
refs/heads/master
2020-04-11T14:26:29.809229
2018-12-14T16:47:09
2018-12-14T16:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
652
h
#pragma once #include "ht_active_id_table.h" #include "ht_identifier.h" namespace newtoo { typedef unsigned long ht_pos; const ht_pos ht_unset_pos = 2147483647; enum ht_flag { ht_flag_not_a_tag, ht_flag_open, ht_flag_close_self, ht_flag_close_self_auto, ht_flag_close }; const int ht_global_prefix = -1; struct boundary { ht_pos begin; ht_pos end; boundary(); }; struct ht_token { ht_token(); ht_token(ht_pos begin_); ht_pos begin; ht_pos end; long prefix; ht_identifier id; short flag; bool flag_taken_by_user; boundary attributes; bool is_inline; bool has_attributes(); bool is_open(); }; }
[ "flightblaze@gmail.com" ]
flightblaze@gmail.com
05a4527df6daceee2bd526a1dcfd097460c619b7
644f097a6d583921c40dc219a75498758a869574
/DevineEngine/DevineEngine/Graphics/Primitives/Arena/Cylinder.h
016ec0429061ae8a4410f13e0e9befc3305adfff
[]
no_license
Devine33/SimulationACW
33248beea3f85a71fd6aae8587c211371cae538c
e019dbbc2c054abe0a8121cf89e134f4822680f0
refs/heads/master
2021-03-27T19:17:45.997382
2017-09-05T21:00:49
2017-09-05T21:00:49
88,354,136
1
0
null
null
null
null
UTF-8
C++
false
false
724
h
#pragma once #include <d3d11.h> #include <memory> #include "../../../../packages/directxtk_desktop_2015.2017.2.10.1/build/native/include/GeometricPrimitive.h" #include <SimpleMath.h> class Cylinder { public: Cylinder(ID3D11DeviceContext* context,float height, float diameter); ~Cylinder(); void SetPosition(DirectX::SimpleMath::Vector3 POSIN); void SetHeight(int Height); std::shared_ptr<DirectX::GeometricPrimitive> GetPrim() const; int GetFloorHeight(); float GetRadius(); DirectX::SimpleMath::Vector3 GetPosition() const; private: DirectX::SimpleMath::Vector3 m_Position; int m_Height; int m_FloorHeight;; std::shared_ptr<DirectX::GeometricPrimitive> m_shape; float m_Radius; DirectX::XMFLOAT4 color; };
[ "devine33@live.co.uk" ]
devine33@live.co.uk
9bcb70f59513e526ccc4dc8b88442aeb421b5517
04b1803adb6653ecb7cb827c4f4aa616afacf629
/ash/wallpaper/wallpaper_utils/wallpaper_resizer_unittest.cc
f2153f5b202642093d62d6ced5f002bcbe05705d
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
5,609
cc
// Copyright 2018 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 "ash/wallpaper/wallpaper_utils/wallpaper_resizer.h" #include <stdint.h> #include <memory> #include "ash/public/cpp/wallpaper_types.h" #include "ash/wallpaper/wallpaper_utils/wallpaper_resizer_observer.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/stl_util.h" #include "base/threading/thread.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/image/image_skia_rep.h" namespace ash { namespace { const int kTestImageWidth = 5; const int kTestImageHeight = 2; const int kTargetWidth = 1; const int kTargetHeight = 1; const uint32_t kExpectedCenter = 0x02020202u; const uint32_t kExpectedCenterCropped = 0x03030303u; const uint32_t kExpectedStretch = 0x04040404u; const uint32_t kExpectedTile = 0; gfx::ImageSkia CreateTestImage(const gfx::Size& size) { SkBitmap src; int w = size.width(); int h = size.height(); src.allocN32Pixels(w, h); // Fill bitmap with data. for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { const uint8_t component = static_cast<uint8_t>(y * w + x); const SkColor pixel = SkColorSetARGB(component, component, component, component); *(src.getAddr32(x, y)) = pixel; } } gfx::ImageSkia image = gfx::ImageSkia::CreateFrom1xBitmap(src); return image; } bool IsColor(const gfx::ImageSkia& image, const uint32_t expect) { EXPECT_EQ(image.width(), kTargetWidth); EXPECT_EQ(image.height(), kTargetHeight); return *image.bitmap()->getAddr32(0, 0) == expect; } } // namespace namespace wallpaper { class WallpaperResizerTest : public testing::Test, public WallpaperResizerObserver { public: WallpaperResizerTest() : worker_thread_("WallpaperResizerTest") {} ~WallpaperResizerTest() override {} void SetUp() override { ASSERT_TRUE(worker_thread_.Start()); } gfx::ImageSkia Resize(const gfx::ImageSkia& image, const gfx::Size& target_size, WallpaperLayout layout) { std::unique_ptr<WallpaperResizer> resizer; resizer.reset(new WallpaperResizer( image, target_size, WallpaperInfo("", layout, DEFAULT, base::Time::Now().LocalMidnight()), task_runner())); resizer->AddObserver(this); resizer->StartResize(); WaitForResize(); resizer->RemoveObserver(this); return resizer->image(); } scoped_refptr<base::TaskRunner> task_runner() { return worker_thread_.task_runner(); } void WaitForResize() { active_runloop_ = std::make_unique<base::RunLoop>(); active_runloop_->Run(); } void OnWallpaperResized() override { active_runloop_->Quit(); } private: base::MessageLoop message_loop_; std::unique_ptr<base::RunLoop> active_runloop_; base::Thread worker_thread_; DISALLOW_COPY_AND_ASSIGN(WallpaperResizerTest); }; TEST_F(WallpaperResizerTest, BasicResize) { // Keeps in sync with WallpaperLayout enum. WallpaperLayout layouts[4] = { WALLPAPER_LAYOUT_CENTER, WALLPAPER_LAYOUT_CENTER_CROPPED, WALLPAPER_LAYOUT_STRETCH, WALLPAPER_LAYOUT_TILE, }; const int length = base::size(layouts); for (int i = 0; i < length; i++) { WallpaperLayout layout = layouts[i]; gfx::ImageSkia small_image(gfx::ImageSkiaRep(gfx::Size(10, 20), 1.0f)); gfx::ImageSkia resized_small = Resize(small_image, gfx::Size(800, 600), layout); EXPECT_EQ(10, resized_small.width()); EXPECT_EQ(20, resized_small.height()); gfx::ImageSkia large_image(gfx::ImageSkiaRep(gfx::Size(1000, 1000), 1.0f)); gfx::ImageSkia resized_large = Resize(large_image, gfx::Size(800, 600), layout); EXPECT_EQ(800, resized_large.width()); EXPECT_EQ(600, resized_large.height()); } } // Test for crbug.com/244629. "CENTER_CROPPED generates the same image as // STRETCH layout" TEST_F(WallpaperResizerTest, AllLayoutDifferent) { gfx::ImageSkia image = CreateTestImage(gfx::Size(kTestImageWidth, kTestImageHeight)); gfx::Size target_size = gfx::Size(kTargetWidth, kTargetHeight); gfx::ImageSkia center = Resize(image, target_size, WALLPAPER_LAYOUT_CENTER); gfx::ImageSkia center_cropped = Resize(image, target_size, WALLPAPER_LAYOUT_CENTER_CROPPED); gfx::ImageSkia stretch = Resize(image, target_size, WALLPAPER_LAYOUT_STRETCH); gfx::ImageSkia tile = Resize(image, target_size, WALLPAPER_LAYOUT_TILE); EXPECT_TRUE(IsColor(center, kExpectedCenter)); EXPECT_TRUE(IsColor(center_cropped, kExpectedCenterCropped)); EXPECT_TRUE(IsColor(stretch, kExpectedStretch)); EXPECT_TRUE(IsColor(tile, kExpectedTile)); } TEST_F(WallpaperResizerTest, ImageId) { gfx::ImageSkia image = CreateTestImage(gfx::Size(kTestImageWidth, kTestImageHeight)); // Create a WallpaperResizer and check that it reports an original image ID // both pre- and post-resize that matches the ID returned by GetImageId(). WallpaperResizer resizer(image, gfx::Size(10, 20), WallpaperInfo("", WALLPAPER_LAYOUT_STRETCH, DEFAULT, base::Time::Now().LocalMidnight()), task_runner()); EXPECT_EQ(WallpaperResizer::GetImageId(image), resizer.original_image_id()); resizer.AddObserver(this); resizer.StartResize(); WaitForResize(); resizer.RemoveObserver(this); EXPECT_EQ(WallpaperResizer::GetImageId(image), resizer.original_image_id()); } } // namespace wallpaper } // namespace ash
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
ab6921335dc5de0e3b176bf7dcc1292d2beef371
2a9fa870f43a41c131662ede8ce44464ddff8e71
/build-interactionAvecLesFichiers-Desktop_Qt_5_11_1_GCC_64bit-Debug/moc_widget.cpp
83ce037c163e953fa768be10f9562f26828498e4
[]
no_license
LehouxKevin/QtCreator
9fc9a05ddc3add2ec7ce2606ea715345e3721c1d
3d50ead86ac4754b7f6695b35752787aa9d50873
refs/heads/master
2022-01-19T23:19:25.969107
2019-06-28T14:36:03
2019-06-28T14:36:03
194,287,905
1
0
null
null
null
null
UTF-8
C++
false
false
2,580
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'widget.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.11.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../interactionAvecLesFichiers/widget.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'widget.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.11.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_Widget_t { QByteArrayData data[1]; char stringdata0[7]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_Widget_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_Widget_t qt_meta_stringdata_Widget = { { QT_MOC_LITERAL(0, 0, 6) // "Widget" }, "Widget" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_Widget[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; void Widget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } QT_INIT_METAOBJECT const QMetaObject Widget::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_Widget.data, qt_meta_data_Widget, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *Widget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *Widget::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_Widget.stringdata0)) return static_cast<void*>(this); return QWidget::qt_metacast(_clname); } int Widget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "klehoux@pommier4.depinfo.touchard.edu" ]
klehoux@pommier4.depinfo.touchard.edu
13f59db56c6b72c5dc616522eb58166b2689611d
07306d96ba61d744cb54293d75ed2e9a09228916
/External/AutodeskNav/sdk/include/gwnavgeneration/input/sectorinputdata.h
7375ae4244223bd5ae6ad7813a20e7b4edb722ad
[]
no_license
D34Dspy/warz-client
e57783a7c8adab1654f347f389c1dace35b81158
5262ea65e0baaf3f37ffaede5f41c9b7eafee7c1
refs/heads/master
2023-03-17T00:56:46.602407
2015-12-20T16:43:00
2015-12-20T16:43:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,545
h
/* * Copyright 2013 Autodesk, Inc. All rights reserved. * Use of this software is subject to the terms of the Autodesk license agreement and any attachments or Appendices thereto provided at the time of installation or download, * or which otherwise accompanies this software in either electronic or hard copy form, or which is signed by you and accepted by Autodesk. */ // primary contact: GUAL - secondary contact: NOBODY #ifndef GwNavGen_SectorInputData_H #define GwNavGen_SectorInputData_H #include "gwnavgeneration/input/inputcellblob.h" #include "gwnavgeneration/input/inputtileblob.h" namespace Kaim { class GeneratorSystem; class ClientInputConsumer; class GeneratorSectorBuilder; /// Relevant if m_doEnableLimitedMemoryMode is true, maintains the per InputTile information that will allows to load the /// InputCellBlob from file only when it's necessary. class InputTileImprint : public RefCountBase<InputTileImprint, MemStat_NavDataGen> { public: InputTileImprint() {} // To make KyArray happy InputTileImprint(GeneratorSectorBuilder* sectorBuilder, const TilePos& tilePos) : m_sectorBuilder(sectorBuilder), m_tilePos(tilePos) {} public: GeneratorSectorBuilder* m_sectorBuilder; TilePos m_tilePos; KyArray<CellPos> m_cellPositions; }; /// Maintains the InputCellBlobs spatialized per CellPos for 1 SectorInput. /// If m_doEnableLimitedMemoryMode is true, SectorInputData maintains InputTileImprint instead of m_inputCellHandlers. /// SectorInputData is the final result of the Input production/consumption class SectorInputData { KY_DEFINE_NEW_DELETE_OPERATORS(MemStat_NavDataGen) KY_CLASS_WITHOUT_COPY(SectorInputData) public: SectorInputData() : m_sys(KY_NULL), m_sectorBuilder(KY_NULL) {} // called at the end GeneratorSectorBuilder::ProduceInputs() via inputConsumer.FinalizeSectorInput(m_sectorInput); KyResult Init(GeneratorSectorBuilder* sectorBuilder, ClientInputConsumer& inputConsumer); private: KyResult Init_NoInputTiling(ClientInputConsumer& inputConsumer); KyResult Init_WithInputTiling(ClientInputConsumer& inputConsumer); void RegisterCellPos(const CellPos& cellPos); public: GeneratorSystem* m_sys; GeneratorSectorBuilder* m_sectorBuilder; // No InputTiling => InputCellBlob are aggregated directly in SectorInput KyArray<Ptr<BlobHandler<InputCellBlob> > > m_inputCellHandlers; // InputTiling activated => InputCellBlob are saved to files // we only keep in memory the cellPos imprints of each inputTile KyArray<Ptr<InputTileImprint> > m_inputTileImprints; }; } #endif
[ "hasan@openkod.com" ]
hasan@openkod.com
3d7c784d01f865dd00d7df09312b9ca903156051
5b4810947ed4f45e75468e8f734b2a12b7de48bf
/PROJET/main.cpp
cf2f8ee31e62c8dc4263a77c3d3c420d2e429118
[]
no_license
Sururrrr/LocationVoiture
c333357beb09a03f8f75902a172030220397130e
33cf97fd96025bfb9af11ddeba9adf180f5d975e
refs/heads/master
2022-09-13T15:45:31.185330
2020-05-28T09:47:32
2020-05-28T09:47:32
267,522,704
0
0
null
2020-05-28T07:28:16
2020-05-28T07:28:15
null
UTF-8
C++
false
false
775
cpp
#include "mainwindow.h" #include <QApplication> #include <QMessageBox> #include "connection.h" #include"voiture.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); Connection c; bool test=c.createconnect(); MainWindow w; if(test) {w.show(); //QMessageBox::information(nullptr, QObject::tr("database is open"), // QObject::tr("connection successful.\n" // "Click Cancel to exit."), QMessageBox::Cancel); } else QMessageBox::critical(nullptr, QObject::tr("database is not open"), QObject::tr("connection failed.\n" "Click Cancel to exit."), QMessageBox::Cancel); return a.exec(); }
[ "noreply@github.com" ]
Sururrrr.noreply@github.com
3d51f2784dd86f51e9e74408d31b38c62389edd4
de6e6e42b35fa961a21fd77004a679c26c648c13
/src/physics/intersectData.h
3c95a44aa5e4a96563375b6534c140e2cf8eb045
[ "Apache-2.0" ]
permissive
KylePearce-SoftwareDeveloper/3DGameEngineCpp
175f8c9c6df29354f85aad2d279373ddaefb71d8
73f62f4298ee97a7d9752a0e466cf11ae6e20442
refs/heads/master
2020-12-26T22:34:53.830807
2020-04-11T17:17:51
2020-04-11T17:17:51
237,670,161
0
0
null
null
null
null
UTF-8
C++
false
false
1,337
h
/* * This engine was built uppon * tutorials created by: Copyright (C) 2014 Benny Bobaganoosh. * The above tutorials served as the base on which * this engine was developed further by Kyle Pearce. * The game created using this engine has been entirly * created by Kyle Pearce. */ #ifndef INTERSECT_DATA_INCLUDED_H #define INTERSECT_DATA_INCLUDED_H #include "../core/math3d.h" /** * The IntersectData class stores information about two intersecting objects. */ class IntersectData { public: /** * Creates Intersect Data in a usable state. * * @param doesIntersect Whether or not the objects are intersecting. * @param direction The collision normal, with length set to distance. */ IntersectData(const bool doesIntersect, const Vector3f& direction) : m_doesIntersect(doesIntersect), m_direction(direction) {} /** Basic getter for m_doesIntersect */ inline bool GetDoesIntersect() const { return m_doesIntersect; } /** Basic getter for m_distance */ inline float GetDistance() const { return m_direction.Length(); } /** Basic getter */ inline const Vector3f& GetDirection() const { return m_direction; } private: /** Whether or not the objects are intersecting */ const bool m_doesIntersect; /** The collision normal, with length set to distance. */ const Vector3f m_direction; }; #endif
[ "kylepearcesoftwaredeveloper@gmail.com" ]
kylepearcesoftwaredeveloper@gmail.com
054d695e1c208eecb8e0552ba729aa2df1d3b3b7
d2d57035834b73143fdb0db1e7ccc3b4fb863494
/develop/v0.4/Ngen.Diagnostic/Ngen.Diagnostic.cpp
e74b6009f80da421cd6b7914f03a6193e690bfa5
[ "MIT" ]
permissive
archendian/ngensdk
062647701c6eef54de818782ca0798f7b9540c59
0d8b8e21e00ba71f0596e228dd073017e1c785ed
refs/heads/master
2021-01-11T15:19:32.233361
2019-01-07T16:43:47
2019-01-07T16:43:47
80,326,405
1
0
null
null
null
null
UTF-8
C++
false
false
1,293
cpp
/* _______ ________ \ \ / _____/ ____ ___ / | \/ \ ____/ __ \ / \ / | \ \_\ \ ___/| | \ \____|__ /\______ /\___ >___| / \/ \/ \/ \/ The MIT License (MIT) COPYRIGHT (C) 2016 FIXCOM, LLC 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, sub-license, 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. */
[ "arch.endian@gmail.com" ]
arch.endian@gmail.com
ae69030ca316e6c072233c87393ed196284780ce
63c71060f36866bca4ac27304cef6d5755fdc35c
/src/DataGenUtil/DataGenSimpleRand.h
03889621b1c9a796d9a3045c73e7a4cf0bbebd2c
[]
no_license
15831944/barry_dev
bc8441cbfbd4b62fbb42bee3dcb79ff7f5fcaf8a
d4a83421458aa28ca293caa7a5567433e9358596
refs/heads/master
2022-03-24T07:00:26.810732
2015-12-22T07:19:58
2015-12-22T07:19:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,382
h
//////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2005 // Packet Engineering, Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification is not permitted unless authorized in writing by a duly // appointed officer of Packet Engineering, Inc. or its derivatives // // Description: // This is a utility to select docs. // // Modification History: // 04/26/2011 Created by Chen Ding //////////////////////////////////////////////////////////////////////////// #ifndef AOS_DataGenUtil_DataGenSimpleRand_h #define AOS_DataGenUtil_DataGenSimpleRand_h #include "DataGenUtil/DataGenUtil.h" #include "SEUtil/Ptrs.h" class AosDataGenSimpleRand : public AosDataGenUtil { private: int mMin; int mMax; public: AosDataGenSimpleRand(const bool reg); AosDataGenSimpleRand(const AosXmlTagPtr &config, const AosRundataPtr &rdata); AosDataGenSimpleRand(); ~AosDataGenSimpleRand(); virtual bool nextValue( AosValueRslt &value, const AosXmlTagPtr &sdoc, const AosRundataPtr &rdata); virtual bool nextValue(AosValueRslt &value, const AosRundataPtr &rdata); OmnString RandomInteger(int min, int max); virtual AosDataGenUtilPtr clone(const AosXmlTagPtr &config, const AosRundataPtr &rdata); bool parse(const AosXmlTagPtr &config, const AosRundataPtr &rdata); }; #endif
[ "barryniu@jimodb.com" ]
barryniu@jimodb.com
f79cdc643b46b18f2412fc93ef372b2765ddab7b
79c4f83ad370adf64d411c976afddbf5a35060e9
/pos of elemnt in arr.cpp
376cf9aa917bc04ecf0ec9ea8d1d1aac8a9aedfd
[]
no_license
Anniebhalla10/Cpp
8bcd3d15a6526916624f0c3de789b4c9d7a1cd59
9783c2c60fa746a76e74c11bd682b5db3641621a
refs/heads/master
2021-02-18T11:31:59.347439
2020-12-10T16:59:50
2020-12-10T16:59:50
245,190,935
0
0
null
null
null
null
UTF-8
C++
false
false
585
cpp
//to return position of elemnet #include<iostream> using namespace std; int pos(int A[15], int size, int a); int main() { int size; int ARRAY[15]; int x; cout<<"\nEnter no to be found "; cin>>x; cout<<"\nEnter size of array "; cin>>size; cout<<"\nEnter elements of array : "<<endl; for(int i=0;i<size;i++){ cin>>ARRAY[i]; } int position=pos(ARRAY , size , x); cout<<"\nElement found at "<<position+1; return 0; } int pos(int A[15], int size, int a){ for(int j=0;j<size;j++){ if(A[j]==a) return j; } }
[ "noreply@github.com" ]
Anniebhalla10.noreply@github.com
27980412b92059702a7cb9b8d35dfef3d5303b42
b30cee8c5984fdeb7df841a364e413b1f26a6e5b
/Lanczos/parallel/tJ_Lanczos_khash.cpp
2818f15b364b8e7e323d8c80d0356731680aed05
[]
no_license
ntuloser/Lanczos-tJ
b9664c3c99cf8d069fa3d462b8e2b8b6621c89fd
6d42dffaf1bb2ccebd5ad7a99fc442479e7d6326
refs/heads/master
2016-09-05T14:09:45.863892
2015-07-31T08:24:24
2015-07-31T08:24:24
34,052,323
0
0
null
null
null
null
UTF-8
C++
false
false
35,356
cpp
#include<iostream> #include <stdlib.h> #include <ctime> #include <cmath> #include <stdio.h> #include <vector> //#include <omp.h> #include <mpi.h> #include <functional> //#include <unordered_map> #include "khash.h" KHASH_MAP_INIT_INT64(kMap, double) //sturct kh_kMap_t #define SIZE 4 #define DELTA 6//6 #define LEV 1// calculation given to H^lev #include"config.h" using namespace std; #define PI 3.1415926535897932 //int sss=4; //int ddd=6; const double t=1.; const double J=2.;//0.33; const int num_e=SIZE*SIZE-DELTA; const int Variational_steps=10; const double del_t = 0.015;//0.03 const double differStep=0.008; //little larger then the variation of energy per site. ////Variational parameter//// double D= 0.3;//0.862516; // the first parameter double Mu= 0.3;//-1.29518; // the second parameter double g=1; // the third parameter ///////////////////////////// std::vector<double> Energy_log; std::vector<double> D_log; std::vector<double> Mu_log; int countaccept=0; int counttotal=0; void createInverse(double c[SIZE*SIZE/2][SIZE*SIZE/2],double b[SIZE*SIZE/2][SIZE*SIZE/2],int n){ double a[n][n]; for (int i=0;i<n;i=i+1) for (int j=0;j<n;j=j+1) a[i][j]=c[i][j]; double Inv[n][n]; for (int i=0;i<n;i=i+1){ for (int j=0;j<n;j=j+1){ if(i==j) Inv[i][j]=1; else Inv[i][j]=0; } } for (int i=0;i<n;i=i+1){ int k=i; while (abs(a[k][i])<0.00001&&k<n) k=k+1; if (k==n) {cout<<"stop"<<endl;system("pause");} if (k!=i) for (int j=0;j<n;j=j+1) { double b=a[i][j]; a[i][j]=a[k][j]; a[k][j]=b; b=Inv[i][j]; Inv[i][j]=Inv[k][j]; Inv[k][j]=b; } double diag=a[i][i]; for (int j=0;j<n;j=j+1) { Inv[i][j]=Inv[i][j]/diag; a[i][j]=a[i][j]/diag; } for (int j=0;j<n;j=j+1) { double b=a[j][i]; for (int l=0;l<n;l=l+1) { if (j!=i) { Inv[j][l]=Inv[j][l]-Inv[i][l]*b; a[j][l]=a[j][l]-a[i][l]*b; } } } } //cout<<determinant(c)*determinant(Inv)<<endl; for (int i=0;i<n;i=i+1) for (int j=0;j<n;j=j+1) b[i][j]=Inv[i][j]; } void update_aij(double ** a_ij, double kk[SIZE*SIZE][2]){ for (int i=0; i< (SIZE*2-1); i++) { for (int j=0; j <(SIZE*2 -1 ); j++) { a_ij[i][j]=0; for (int m=0; m<SIZE*SIZE; m++) { double ek,Dk; ek = (-2.)*t*(cos(kk[m][0])+cos(kk[m][1])) - Mu; Dk = D*(cos(kk[m][0])-cos(kk[m][1])) ; if (D>0.0001) { //If D is not vanishing //sine term is cancel when summing over the BZ zone. a_ij[i][j] += Dk/(ek+pow(pow(ek,2)+pow(Dk,2),0.5) )*cos(kk[m][0]*(i-(SIZE-1))+kk[m][1]*(j-(SIZE-1)) ) / (SIZE*SIZE); } else{ //cout<<"error in vanishing D"<<endl; a_ij[i][j]+=0.5*(1-std::abs(ek)/ek)*cos(kk[m][0]*(i-(SIZE-1))+kk[m][1]*(j-(SIZE-1)) )/(SIZE*SIZE);} } //Checked //printf("a[%i][%i]=%f\n",i,j,a_ij[i][j]); } } } double determinant(double** a) { double x[num_e/2][num_e/2]; for (int i=0;i< num_e/2;i=i+1) for (int j=0;j< num_e/2;j=j+1) x[i][j]=a[i][j]; int k=0,n=0; while (k< num_e/2) { int l=k; while (std::abs(x[l][k])<0.00001) { l=l+1; if (l== num_e/2) return 0; } if (l!=k) { n=n+1; for (int i=0;i< num_e/2;i=i+1) { double b; b=x[k][i]; x[k][i]=x[l][i]; x[l][i]=b; } } for (int i=k+1;i< num_e/2;i=i+1) { double r=x[i][k]/x[k][k]; for (int j=k;j< num_e/2;j=j+1) { x[i][j]=x[i][j]-r*x[k][j]; } } k=k+1; } double det=1; for (int i=0;i< num_e/2;i=i+1) {det=det*x[i][i]; } return det*pow(-1.0,n); } void Traversal(int level, int bound, config* config_level, double ** a_ij, double *** slater,const double& deter_origin,const double& deriv_D, const double& deriv_Mu, double* ptr_tot_E, double* ptr_tot_O_DtimesE, double* ptr_tot_O_MutimesE, double* ptr_tot_O_C1timesE, double* ptr_temp_EperSample,double *Energy_level, double * tot_E_power, kh_kMap_t* khashMap); long long tonumber(const config& alpha){ long long number=0; /* for (int idx=0; idx<alpha.num_ele/2 ; idx++) { double tmp = 4.0*idx; number += alpha.electronsup[idx][0] * pow(4,(tmp+0.)); number += alpha.electronsup[idx][1] * pow(4,(tmp+1.)); number += alpha.electronsdown[idx][0]*pow(4,(tmp+2.)); number += alpha.electronsdown[idx][1]*pow(4,(tmp+3.)); }*/ //cout<<" The number transform from the config :"<<number<<endl; int power[16]={1,4,16,64,256,1024,4096,16384,65536,262144,1048576,4194304,16777216,67108864,268435456,1073741824 }; number += alpha.electronsup[0][0] * power[0]; number += alpha.electronsup[0][1] * power[1]; number += alpha.electronsdown[0][0]*power[2]; number += alpha.electronsdown[0][1]*power[3]; number += alpha.electronsup[1][0] * power[4]; number += alpha.electronsup[1][1] * power[5]; number += alpha.electronsdown[1][0]*power[6]; number += alpha.electronsdown[1][1]*power[7]; number += alpha.electronsup[2][0] * power[8]; number += alpha.electronsup[2][1] * power[9]; number += alpha.electronsdown[2][0]*power[10]; number += alpha.electronsdown[2][1]*power[11]; number += alpha.electronsup[3][0] * power[12]; number += alpha.electronsup[3][1] * power[13]; number += alpha.electronsdown[3][0]*power[14]; number += (long long)alpha.electronsdown[3][1]* power[15]; number += (long long)alpha.electronsup[4][0] * power[15]*power[1]; number += (long long)alpha.electronsup[4][1] * power[15]*power[2]; number += (long long)alpha.electronsdown[4][0]*power[15]*power[3]; number += (long long)alpha.electronsdown[4][1]*power[15]*power[4]; return number; } int main(int argc, char** argv){ double buffer[3]={D,Mu,0};//D,Mu,g double ksum, Nsum; /////////// Using MPI //////// MPI::Status status; MPI_Request request; MPI::Init(argc,argv); int numnodes = MPI::COMM_WORLD.Get_size(); int mynode = MPI::COMM_WORLD.Get_rank(); std::cout << "Process " << mynode<< " of " << numnodes << std::endl; //srand( pow((unsigned)time(0),(mynode+1)) ); srand((mynode+1)*(unsigned)time(0)); // The Brillouin Zone with periodic in x, antiperiodic in y double kk[SIZE*SIZE][2]; // 1-dim vector representation of kx,ky for (int idx =0; idx<SIZE*SIZE; idx++) { int i= idx % SIZE; int j= idx / SIZE; kk[idx][0]= PI*( 1.-2.0*i/SIZE); kk[idx][1]= PI*( (SIZE-1.0)/SIZE-2.0*j/SIZE); //Checked //printf("%f, %f\n",kk[idx][0],kk[idx][1]); } int ret; khiter_t k; khash_t(kMap) *khashMap = kh_init(kMap); //unordered_map<long long,double,hash<long long> > dMap; ///////////////////////////// ////Variational Procedure//// ///////////////////////////// for (int stp=0;stp<Variational_steps ; stp++) { kh_clear(kMap, khashMap); ///Reset all variable/// int tot_doub =0; double tot_E =0; double tot_E_power[LEV]; for (int i=0; i<LEV; i++) { tot_E_power[i]=0; } double tot_accept =0; double tot_O[3]={0,0,0}; double tot_O_DtimesE =0; double tot_O_MutimesE =0; //double tot_O_gtimesE =0; double tot_O_C1timesE =0; double tot_OtimesO[3][3]; for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { tot_OtimesO[i][j]=0; } } double tot_E_sqr =0; double tot_doub2 =0; ///////////////////////////////// //**the monte carlo procedure**// ///////////////////////////////// int sample=20000/numnodes; int interval=30; int warmup=3000; int totsteps=sample*interval+warmup; /////////// Using OpenMP //////// //int num_threads=omp_get_max_threads() ; ////////////////////////////////// //#pragma omp parallel for //for (int prl_seed=0; prl_seed<numnodes; prl_seed++) { //// all possible a_ij //// consider all possible r_i - r_j //// This generate a 2S-1 X 2S-1 matrix //// We shall call the matrix by giving the displacement vector double ** a_ij = new double*[2*SIZE-1]; for (int k=0; k < (2*SIZE-1); k++) { a_ij[k] =new double[2*SIZE-1]; } //we set(update) a_ij in each iteration of the variation for-loop. /*try { config* config_level = new config[LEV]; }catch (bad_alloc xa) { cout << "Allocation Failure\n"; return 1; }*/ int lvl=LEV+1; config* config_level = new config[lvl]; for (int i=0; i<lvl; i++) { ; //config_level[i]=config(SIZE,DELTA); } //config config_level[3]={config(SIZE,DELTA),config(SIZE,DELTA),config(SIZE,DELTA)}; double *** slater; slater = new double**[lvl]; for (int i=0; i<lvl; i++) { slater[i] = new double*[num_e/2]; for (int k=0; k<num_e/2; k++) { slater[i][k] =new double[num_e/2]; } } double *** inv_slater; inv_slater = new double**[lvl]; for (int i=0; i<lvl; i++) { inv_slater[i] = new double*[num_e/2]; for (int k=0; k<num_e/2; k++) { inv_slater[i][k] =new double[num_e/2]; } } // SET a_ij matrix update_aij(a_ij,kk); config_level[0].rand_init_no_d(); config_level[0].printconfig(); // int takeInv=500; for (int steps=0;steps<=totsteps;steps++){ //Random //Generating a new config from config_level[0] ! // int flipped=0; int idx = rand()%(SIZE*SIZE); //choose electron int move = rand()%4; int overbound=0; config_level[0].swap(&config_level[1], int(idx/SIZE),idx%SIZE, move,&flipped,&overbound); /////////////////////////////////////// /// Metropolis algorithm /////// /////////////////////////////////////// /// Given the random probability 0<p<1 /// double p=0; while (p==0){ p=(rand()+1)/(double)(RAND_MAX); } if (flipped==1) { int num_d_a = config_level[0].num_doublon(); int num_d_b = config_level[1].num_doublon(); counttotal+=2; double deter_0; long long number=tonumber(config_level[0]); k = kh_get(kMap, khashMap, number); if ( k == kh_end(khashMap) ){ config_level[0].set_slater(a_ij,slater[0]); deter_0 = determinant(slater[0]); k = kh_put(kMap, khashMap, number, &ret); kh_value(khashMap, k) = deter_0; } else{ countaccept+=1; deter_0 = kh_value(khashMap, k); } double deter_1; number =tonumber(config_level[1]); k = kh_get(kMap, khashMap, number); if ( k == kh_end(khashMap) ){ config_level[1].set_slater(a_ij,slater[1]); deter_1 = determinant(slater[1]); k = kh_put(kMap, khashMap, number, &ret); kh_value(khashMap, k) = deter_1; } else{ countaccept+=1; deter_1 = kh_value(khashMap, k); } if (p<pow(deter_1/deter_0,2) *pow(g,2*(num_d_b-num_d_a))|| abs(deter_0)<0.00001){ //updated config. config_level[1].copy_config_to( &config_level[0] ); tot_accept+=1; } } //////////////////////////////////////////////////////////////// /////////// guys, Time to Sampling ~~ ///////////// ////////////////////////////////////////// if (steps%interval==0 && steps>warmup){ config_level[0].set_slater(a_ij,slater[0]); //if (std::abs(determinant(slater[0]))<0.000001) cout<<"small_deter!!!\n"; //createInverse(slater[0],inv_slater[0],num_e/2); /////////////////// /////optimization// /////////////////// //Calculating the derivative O_i double deter_origin = determinant(slater[0])*config_level[0].Sign; D+=differStep; update_aij(a_ij,kk); config_level[0].set_slater(a_ij,slater[0]); double deter_D = determinant(slater[0])*config_level[0].Sign; D-=differStep; Mu+=differStep; update_aij(a_ij,kk); config_level[0].set_slater(a_ij,slater[0]); double deter_Mu = determinant(slater[0])*config_level[0].Sign; Mu-=differStep; update_aij(a_ij,kk); config_level[0].set_slater(a_ij,slater[0]); double deriv_D = (deter_D-deter_origin)/(differStep*deter_origin); double deriv_Mu = (deter_Mu-deter_origin)/(differStep*deter_origin); //double deriv_g = ( pow(g,num_d_a) - pow((g+0.001),num_d_a) )/0.001; tot_O[0] += deriv_D; tot_O[1] += deriv_Mu; tot_OtimesO[0][1] += (deriv_D*deriv_Mu); tot_OtimesO[1][0] += (deriv_D*deriv_Mu); tot_OtimesO[0][0] += (deriv_D*deriv_D); tot_OtimesO[1][1] += (deriv_Mu*deriv_Mu); //tot_O_g += deriv_g; ////////// ////////////////// // t-J // /////////// /////// // config_level[0], config_level[1], a_ij, slater[1],deter_origin, // tot_E_sqr, tot_E, tot_O_DtimesE, tot_O_MutimesE // deriv_D, deriv_Mu double temp_EperSample=0; int N=1; double Energy_level[LEV]; for (int i=0; i<LEV; i++) { Energy_level[i]=0; } Traversal(0,LEV, config_level, a_ij, slater, deter_origin, deriv_D, deriv_Mu, &tot_E, &tot_O_DtimesE, &tot_O_MutimesE, &tot_O_C1timesE, &temp_EperSample,Energy_level,tot_E_power, khashMap); //get the value of tot_E, tot_O_DtimesE, tot_O_MutimesE, tot_O_C1timesE, temp_EperSample, Energy_level, tot_E_power tot_E_sqr += pow(temp_EperSample,2); }//End of Sampling. }//end of monte carlo loop //}; //end of parallel #openmp //end of parallel // double SUM_tot_E=0; double SUM_tot_O_DtimesE, SUM_tot_O_MutimesE, SUM_tot_O_C1timesE, SUM_tot_E_sqr; double SUM_tot_E_power[LEV]; for (int i=0; i <LEV; i++) { SUM_tot_E_power[i]=0; } double SUM_tot_O[3]={0,0,0}; double SUM_tot_OO[4]={0,0,0,0}; double local_tot_OO[4]={tot_OtimesO[0][0],tot_OtimesO[0][1],tot_OtimesO[1][0],tot_OtimesO[1][1]}; MPI_Reduce(&tot_E,&SUM_tot_E,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD); MPI_Reduce(&tot_O_DtimesE,&SUM_tot_O_DtimesE,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD); MPI_Reduce(&tot_O_MutimesE,&SUM_tot_O_MutimesE,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD); MPI_Reduce(&tot_O_C1timesE,&SUM_tot_O_C1timesE,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD); MPI_Reduce(&tot_E_sqr,&SUM_tot_E_sqr,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD); MPI_Reduce(tot_E_power,SUM_tot_E_power,LEV,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD); MPI_Reduce(tot_O,SUM_tot_O,3,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD); MPI_Reduce(local_tot_OO,SUM_tot_OO,4,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD); if (mynode==0) {//This is the master branch sample=sample*numnodes; tot_E =SUM_tot_E; tot_O_DtimesE =SUM_tot_O_DtimesE; tot_O_MutimesE =SUM_tot_O_MutimesE; tot_O_C1timesE =SUM_tot_O_C1timesE; tot_E_sqr =SUM_tot_E_sqr; for (int i=0; i<LEV; i++) { tot_E_power[i] =SUM_tot_E_power[i]; } for (int i=0; i<3; i++) { tot_O[i] =SUM_tot_O[i]; } tot_OtimesO[0][0]=SUM_tot_OO[0]; tot_OtimesO[1][0]=SUM_tot_OO[1]; tot_OtimesO[0][1]=SUM_tot_OO[2]; tot_OtimesO[1][1]=SUM_tot_OO[3]; cout<<" D = "<<D<<" Mu = "<<Mu<<" g = "<<g<<"\n"; double avg_E= tot_E/sample; Energy_log.push_back(avg_E); D_log.push_back(D); Mu_log.push_back(Mu); double num_doub = double(tot_doub)/double(sample); double err_E=std::pow( double((tot_E_sqr/sample-pow(avg_E,2))/sample) , 0.5)/pow(double(SIZE),2); double err_doub=pow( (tot_doub2/sample-pow(num_doub,2))/sample,0.5)/pow(double(SIZE),2); //cout<<"tot_E = "<<tot_E<<", tot_doub = "<<tot_doub<<endl; cout<<"sample = "<<sample<<"\n"; cout<<"avg_E = "<<avg_E /SIZE/SIZE<<" err: "<<err_E<<endl; for (int i=0; i<LEV; i++) { cout<<"Epower"<<i<<" = "<<tot_E_power[i]/pow(SIZE,double((i+1)*2))/sample <<endl; } //cout<<"E_variance = "<<pow((std::abs(pow(avg_E,2)-tot_Esquare/sample))/sample,0.5)/pow(SIZE,2)<<endl; cout<<"doublon number="<<num_doub/SIZE/SIZE<<" err: "<<err_doub<<endl; cout<<"acceptance ratio:" <<tot_accept/totsteps<<endl; // adjust the order, avoiding the round off error.// double grad_D = 2*(tot_O_DtimesE - (tot_O[0]*tot_E/sample)) /sample; double grad_Mu = 2*(tot_O_MutimesE - (tot_O[1]*tot_E/sample)) /sample; double grad_C1 = 2*(tot_O_C1timesE - (tot_O[2]*tot_E/sample)) /sample; //double grad_g = 2*(tot_O_gtimesE/sample - (tot_O_g/sample)*(tot_E/sample)); double Smatrix[2][2]; for (int i=0; i<2; i++) { for (int j=0; j<2; j++) { Smatrix[i][j] = (tot_OtimesO[i][j]-tot_O[i]*tot_O[j]/sample)/sample; cout<<"i,j:"<<i<<" "<<j<<" --> "<<Smatrix[i][j]<<endl; } } double inverse_Smatrix[2][2]; double deter_Smatrix = (Smatrix[0][0]*Smatrix[1][1]-Smatrix[0][1]*Smatrix[1][0]); inverse_Smatrix[0][0]= Smatrix[1][1]/deter_Smatrix; inverse_Smatrix[0][1]= -Smatrix[1][0]/deter_Smatrix; inverse_Smatrix[1][0]= -Smatrix[0][1]/deter_Smatrix; inverse_Smatrix[1][1]= Smatrix[0][0]/deter_Smatrix; cout<<"\n"; cout<<"D = "<<D<<" , grad_D = "<<grad_D<<endl; cout<<"Mu = "<<Mu<<" , grad_Mu = "<<grad_Mu<<endl; //cout<<"g = "<<g <<" , grad_g = "<<grad_g<<endl; cout<<"\n"; double dD0= inverse_Smatrix[0][0]*grad_D+inverse_Smatrix[0][1]*grad_Mu; double dD1= inverse_Smatrix[1][0]*grad_D+inverse_Smatrix[1][1]*grad_Mu; cout<<"\n"; cout<<"dD0 = "<<dD0<<endl; cout<<"dD1 = "<<dD1<<endl; //cout<<"g = "<<g <<" , grad_g = "<<grad_g<<endl; cout<<"\n"; // The Variational method // /////////////////////////////////////// /// Optimization is hard T______T //// /////////////////////////////////////// //del_t define in the beginning //////////////////////////////////// // The Steepest Decend(SD) method // //////////////////////////////////// //D -= del_t*grad_D*5; //Mu -= del_t*grad_Mu*5; //g -= del_t*grad_g; //////////////////////////////////// // Th SR method // ///////////////////////////////////// D -= del_t*dD0; Mu -= del_t*dD1; //g -= del_t*grad_g; /////////////////////////// // Preparing Broadcast /// /////////////////////////// buffer[0]=D; buffer[1]=Mu; } ////////////////// // Broadcast /// //////////////// MPI_Bcast(buffer,3,MPI_DOUBLE,0,MPI_COMM_WORLD); //int MPI_Bcast( void *buffer, int count, MPI_Datatype datatype, int root, MPI_Comm comm ) D = buffer[0]; Mu = buffer[1]; }//end of variational loop; if (mynode==0) { // Output the log // cout<<"log:"<<endl; for (int i=0; i<Energy_log.size(); i++) { cout<<"E: "<<Energy_log[i]<<",D: "<<D_log[i]<<",Mu: "<<Mu_log[i]<<endl; } cout<<"hash_map_efficiency:"<<endl; cout<<"total = "<<counttotal<< " accept = "<<countaccept<<"ratio"<<double(countaccept)/counttotal<<endl; } MPI::Finalize(); return 0; } void Traversal(int lvl_now, int bound, config* config_level, double ** a_ij, double *** slater, const double& deter_origin, const double& deriv_D, const double& deriv_Mu,double* ptr_tot_E, double* ptr_tot_O_DtimesE, double* ptr_tot_O_MutimesE,double* ptr_tot_O_C1timesE, double* ptr_temp_EperSample, double *Energy_level, double * tot_E_power, kh_kMap_t* khashMap){ double deter[ (bound+1) ]; khiter_t k; int ret; if (lvl_now==bound) { return; } for (int x=0; x<SIZE; x++) { for (int y=0; y<SIZE; y++) { for (int move=0; move<3; move++) { if (move==1) continue; //cout<<"move:"<<move<<"x:"<<x<<"y:"<<y<<endl; double ratio=0; int flipped=0; int overbound=0 ; int tJ = config_level[lvl_now].swap(&config_level[lvl_now+1], x,y,move,&flipped,&overbound); if (flipped==1) { counttotal+=1; long long number =tonumber(config_level[lvl_now+1]); k = kh_get(kMap, khashMap, number); if ( k == kh_end(khashMap) ){ config_level[lvl_now+1].set_slater(a_ij,slater[lvl_now+1]); deter[lvl_now+1] = determinant(slater[lvl_now+1]); k = kh_put(kMap, khashMap, number, &ret); kh_value(khashMap, k) = deter[lvl_now+1]; } else{ countaccept+=1; deter[lvl_now+1] = kh_value(khashMap, k); } //for (int i=0; i<num_e/2; i++) { // ratio += slater[1][idx_1][i]*inv_slater[0][i][idx_1]; //} //Ek=-t*ratio *pow(g,num_d_b-num_d_a); if (tJ==1) {// ele -- empty if (not overbound) { //Traversal. //New config generate //Energy get. Energy_level[lvl_now] = -t; Traversal(lvl_now+1,bound, config_level, a_ij, slater, deter_origin, deriv_D,deriv_Mu, ptr_tot_E, ptr_tot_O_DtimesE, ptr_tot_O_MutimesE, ptr_tot_O_C1timesE, ptr_temp_EperSample,Energy_level,tot_E_power, khashMap); if (lvl_now==0) { Energy_level[lvl_now]*=(deter[lvl_now+1]/deter_origin*config_level[lvl_now+1].Sign); //Energy_level[lvl_now]*=(determinant(slater[lvl_now+1])/deter_origin*config_level[lvl_now+1].Sign); (*ptr_tot_E) += Energy_level[0]; (*ptr_tot_O_DtimesE) += Energy_level[0]*deriv_D; (*ptr_tot_O_MutimesE) += Energy_level[0]*deriv_Mu; //(*ptr_tot_O_C1timesE) += Energy_level[0]*deriv_C1; //tot_O_gtimesE += E*deriv_g; (*ptr_temp_EperSample) += Energy_level[0]; } else{ double temp=1.0; for (int i=0; i<=lvl_now; i++) { temp*=Energy_level[i]; } temp*=(deter[lvl_now+1]/deter_origin*config_level[lvl_now+1].Sign); //temp*=(determinant(slater[lvl_now+1])/deter_origin*config_level[lvl_now+1].Sign); tot_E_power[lvl_now] += temp; } } else{ //In the case of overbound //Energy_level[lvl_now] = t*determinant(slater[lvl_now+1])/deter_origin*config_level[lvl_now+1].Sign; Energy_level[lvl_now] = t; Traversal(lvl_now+1,bound, config_level, a_ij, slater, deter_origin, deriv_D,deriv_Mu, ptr_tot_E, ptr_tot_O_DtimesE, ptr_tot_O_MutimesE, ptr_tot_O_C1timesE, ptr_temp_EperSample,Energy_level,tot_E_power, khashMap); if (lvl_now==0) { Energy_level[lvl_now]*=(deter[lvl_now+1]/deter_origin*config_level[lvl_now+1].Sign); //Energy_level[lvl_now]*=(determinant(slater[lvl_now+1])/deter_origin*config_level[lvl_now+1].Sign); (*ptr_tot_E) += Energy_level[0]; (*ptr_tot_O_DtimesE) += Energy_level[0]*deriv_D; (*ptr_tot_O_MutimesE) += Energy_level[0]*deriv_Mu; //tot_O_gtimesE += E*deriv_g; (*ptr_temp_EperSample) += Energy_level[0]; } else{ double temp=1.0; for (int i=0; i<=lvl_now; i++) { temp*=Energy_level[i]; } temp*=(deter[lvl_now+1]/deter_origin*config_level[lvl_now+1].Sign); //temp*=(determinant(slater[lvl_now+1])/deter_origin*config_level[lvl_now+1].Sign); tot_E_power[lvl_now] += temp; } } } else if(tJ==2){// eleup -- eledown {// contri from the superexchange. //Energy_level[lvl_now] = +J/2*determinant(slater[lvl_now+1])/deter_origin*config_level[lvl_now+1].Sign; Energy_level[lvl_now] = +J/2; Traversal(lvl_now+1,bound, config_level, a_ij, slater, deter_origin, deriv_D,deriv_Mu, ptr_tot_E, ptr_tot_O_DtimesE, ptr_tot_O_MutimesE, ptr_tot_O_C1timesE, ptr_temp_EperSample,Energy_level,tot_E_power, khashMap); if (lvl_now==0) { Energy_level[lvl_now]*=(deter[lvl_now+1]/deter_origin*config_level[lvl_now+1].Sign); //Energy_level[lvl_now]*=(determinant(slater[lvl_now+1])/deter_origin*config_level[lvl_now+1].Sign); (*ptr_tot_E) += Energy_level[0]; (*ptr_tot_O_DtimesE) += Energy_level[0]*deriv_D; (*ptr_tot_O_MutimesE) += Energy_level[0]*deriv_Mu; //tot_O_gtimesE += E*deriv_g; (*ptr_temp_EperSample) += Energy_level[0]; } else{ double temp=1.0; for (int i=0; i<=lvl_now; i++) { temp*=Energy_level[i]; } temp*=(deter[lvl_now+1]/deter_origin*config_level[lvl_now+1].Sign); //temp*=(determinant(slater[lvl_now+1])/deter_origin*config_level[lvl_now+1].Sign); tot_E_power[lvl_now] += temp; } } // contribution from the n_up*n_down term {// giving the identical configuration in the next level. Energy_level[lvl_now] = (-J/4*2); // contribution from the S1Z S2Z term config_level[lvl_now].copy_config_to(&config_level[lvl_now+1]); config_level[lvl_now+1].set_slater(a_ij,slater[lvl_now+1]); counttotal+=1; number= tonumber(config_level[lvl_now+1]); k = kh_get(kMap, khashMap, number); if ( k == kh_end(khashMap) ){ config_level[lvl_now+1].set_slater(a_ij,slater[lvl_now+1]); deter[lvl_now+1] = determinant(slater[lvl_now+1]); k = kh_put(kMap, khashMap, number, &ret); kh_value(khashMap, k) = deter[lvl_now+1]; } else{ countaccept+=1; deter[lvl_now+1] = kh_value(khashMap, k); } Traversal(lvl_now+1,bound, config_level, a_ij, slater, deter_origin, deriv_D,deriv_Mu, ptr_tot_E, ptr_tot_O_DtimesE, ptr_tot_O_MutimesE, ptr_tot_O_C1timesE, ptr_temp_EperSample,Energy_level,tot_E_power, khashMap); if (lvl_now==0) { (*ptr_tot_E) += Energy_level[0]; (*ptr_tot_O_DtimesE) += Energy_level[0]*deriv_D; (*ptr_tot_O_MutimesE) += Energy_level[0]*deriv_Mu; //tot_O_gtimesE += E*deriv_g; (*ptr_temp_EperSample) += Energy_level[0]; } else{ double temp=1.0; for (int i=0; i<=lvl_now; i++) { temp*=Energy_level[i]; } temp*=(deter[lvl_now+1]/deter_origin*config_level[lvl_now+1].Sign); //temp*=(determinant(slater[lvl_now+1])/deter_origin*config_level[lvl_now+1].Sign); tot_E_power[lvl_now] += temp; } } } else cout<<"GG\n"; }//end if flipped==1 else{//if flipped==0 if (tJ==0) { ; //emtpy -- empty } else if(tJ==3){ ; //ele -- ele } //E=0; } }// endfor move }//endfor y }//endfor x } // better data structure --> memory cost rather than speed cost // parallel computing in openMP // // complexity is about // ( Interval(30) + 32^LEV(5) )*SAMPLE( 30000 )*order(N^3)
[ "impossibleisnothing21121@gmail.com" ]
impossibleisnothing21121@gmail.com
77685c0fc72a90f4d1e53126a772afcce80582e9
c2c976a38135ce14497d5bdd55a79bef97d8119f
/Min Cut Max Flow.cpp
8ef1cdaab0dad1fe36767210fd0559d58b213e78
[]
no_license
vntshh/ACM-Notebook
668515172c6a0b497a514513b60da1a9384bfda8
459963dbad992bbe19e0a92d87954c58666f48a8
refs/heads/master
2021-01-13T14:38:37.732350
2019-06-11T11:11:01
2019-06-11T11:11:01
76,723,249
3
1
null
2017-10-31T15:16:15
2016-12-17T12:37:29
C++
UTF-8
C++
false
false
1,862
cpp
Min Cost Max Flow (My Code for Building String : Codeforces) #define MAXN 3005 struct MCMF { typedef lld ctype; struct Edge { lld x, y; lld cap, cost; }; vector<Edge> E; vector<lld> adj[MAXN]; lld N, prev[MAXN]; ctype dist[MAXN], phi[MAXN]; MCMF(lld NN) : N(NN) {} void add(lld x,lld y,ctype cap,ctype cost) { // cost >= 0 cost += EPS; // printf("Adding (%d, %d) having (%d, %d)\n", x, y, cap, cost); Edge e1={x,y,cap,cost}, e2={y,x,0,-cost}; adj[e1.x].push_back(E.size()); E.push_back(e1); adj[e2.x].push_back(E.size()); E.push_back(e2); } void mcmf(lld s,lld t, ctype &flowVal, ctype &flowCost) { lld x; flowVal = flowCost = 0; memset(phi, 0, sizeof(phi)); while (true) { for (x = 0; x < N; x++) prev[x] = -1; for (x = 0; x < N; x++) dist[x] = INF; dist[s] = prev[s] = 0; set< pair<ctype, lld> > Q; Q.insert(make_pair(dist[s], s)); while (!Q.empty()) { x = Q.begin()->second; Q.erase(Q.begin()); tr(it,adj[x]) { const Edge &e = E[*it]; if (e.cap <= 0) continue; ctype cc = e.cost + phi[x] - phi[e.y]; // *** if (dist[x] + cc + EPS < dist[e.y]) { Q.erase(make_pair(dist[e.y], e.y)); dist[e.y] = dist[x] + cc; prev[e.y] = *it; Q.insert(make_pair(dist[e.y], e.y)); } } } if (prev[t] == -1) break; ctype z = INF; for (x = t; x != s; x = E[prev[x]].x) z = min(z, E[prev[x]].cap); for (x = t; x != s; x = E[prev[x]].x) { E[prev[x]].cap -= z; E[prev[x]^1].cap += z; } flowVal += z; flowCost += z * (dist[t] - phi[s] + phi[t]); for (x = 0; x < N; x++) if (prev[x] != -1) phi[x] += dist[x]; // *** } } };
[ "noreply@github.com" ]
vntshh.noreply@github.com
5fb91a40843cd50710c41f35a47697a58ae25087
625a46bcc34374650f6fdb67c6bfd252e7911fc8
/Programming/C++/Copies/TicTacToe - Template/TicTacToe/Source/window.h
f29c1e383e206b81c5d985101a0da70c37883be9
[]
no_license
balderdash117/All-programming
bbe208c5239d7a57ddc707c87324f95c4c28fedf
10508d4dbf38bf37c53dc85c120f52f0d056c1ec
refs/heads/master
2021-01-23T05:25:07.432951
2017-09-05T10:47:32
2017-09-05T10:47:32
102,467,018
0
0
null
null
null
null
UTF-8
C++
false
false
1,967
h
//////////////////////////////////////////////////////////////////////////////////////////////////////////// //// //// Name: Window Class //// //// Purpose: Defines the characteristics of the window and functions applied to it //// //// Authors: Roger Keating //// //////////////////////////////////////////////////////////////////////////////////////////////////////////// // the old way of making sure this is accessed only once #ifndef WINDOW_H_ // 1.. is WINDOW_H_ defined ... if it is do not do this #define WINDOW_H_ // 2.. define WINDOW_H_ #include <iostream> #include <Windows.h> #include <wincon.h> #include <conio.h> #include <string> #include <vector> #include "window.h" // specify a couple of std fuctions so that they are easier to read in the program using std::cout; using std::endl; // colors used by the console system enum eColor { BLACK, DARKBLUE, DARKGREEN, DARKCYAN, DARKRED, DARKMAGENTA, DARKYELLOW, LIGHTGRAY, GRAY, BLUE, GREEN, CYAN, RED, MAGENTA, YELLOW, WHITE, ORANGE }; //POSITION AND SIZE OF THE 2D SHAPE struct Rect { int x, y, width, height; }; class Window { public: bool Initialise(int a_width, int a_height, char *name); void SetCursorVisibility(bool pShow); void SetTextColor(eColor pColor); BOOL SetXY(int pX, int pY); void DrawChar(int pX, int pY, unsigned char pLine); void DrawTextLine(int pX, int pY, eColor pColor, char *pChar, int p_max); void ClearScreen(); void ClearSection(Rect pLocation); void DrawBorder(Rect pLocation, eColor pColor); // getters COORD getMousePos(); int getRoomHeight() { return mScreenHeight; } int getRoomWidth() { return mScreenWidth; } private: //static COORD mBuffer; int mScreenWidth; int mScreenHeight; eColor mCurrentColor; //static COORD mBuffer; HANDLE mhSTDOut; }; #endif // 3.. close out the header for WINDOW_H_
[ "ben@maithsc.com.au" ]
ben@maithsc.com.au