blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
ec6c32227484f2c097ffae5214cfea757b0247c5
f5d39ca7dbc65f1fbd5a9eac10ebac3dc937fcde
/src/bit_stream.cpp
86da72fedb82ffa0b49eb7676694b45ff23df657
[ "Apache-2.0" ]
permissive
magnusl/libgif
0f2a49c2336257baeb485500e90eabb76ecbff2f
eb9cc8bdfadfb49e50f9fa769a830d8b4513f46f
refs/heads/master
2021-03-24T12:59:35.419518
2018-12-06T14:55:56
2018-12-06T14:55:56
121,938,282
0
0
null
null
null
null
UTF-8
C++
false
false
1,773
cpp
#include <gif/bit_stream.h> #include <gif/gif.h> #include <assert.h> namespace gif { BitStream::BitStream( std::basic_string_view<uint8_t>::const_iterator it, std::basic_string_view<uint8_t>::const_iterator end) : iterator_(it), end_(end), byte_(0), bitsLeftInByte_(0) { bytesInBlock_ = ParseByte(iterator_, end_); } unsigned BitStream::GetBits(size_t count) { unsigned result = 0; for(size_t i = 0; i < count; ++i) { if (bitsLeftInByte_ == 0) { if (iterator_ == end_) { throw std::runtime_error( "Reached EOF, can't read any more bytes from input."); } if (bytesInBlock_ > 0) { // there are still data in the block --bytesInBlock_; } else { bytesInBlock_ = ParseByte(iterator_, end_); if (!bytesInBlock_) { throw std::runtime_error("Reached null terminator block."); } --bytesInBlock_; } byte_ = *iterator_; bitsLeftInByte_ = 8; ++iterator_; } --bitsLeftInByte_; result |= (byte_ & 0x01) << i; byte_ >>= 1; } return result; } std::basic_string_view<uint8_t>::const_iterator BitStream::readDataTerminator() { // skip any remaining bytes in the current block while(bytesInBlock_ > 0) { ++iterator_; --bytesInBlock_; } // now read the null terminator block if (ParseByte(iterator_, end_) != 0x00) { throw std::runtime_error("Expected null terminator block"); } // return a iterator to the data that folloes the terminator block return iterator_; } } // namespace gif
[ "magnus586@hotmail.com" ]
magnus586@hotmail.com
0638c8503e218ce4bbaa0646c6ab04dffaed1eb1
a39896b2a1212edc23646bdde57c8e7cf1423393
/turbulance/include/coord.h
882cb619c06f2c4151804deab3e041a43e49f562
[]
no_license
dekdekbaloo/turbulance
eca4b743f331e22568a0f4bde4c0423896c59877
78fe67c7c28703eeafb7cf8c434733677cbbb62c
refs/heads/master
2020-12-24T13:36:09.142374
2015-05-21T15:56:16
2015-05-21T15:56:16
35,752,714
0
0
null
null
null
null
UTF-8
C++
false
false
425
h
#ifndef COORD_H_INCLUDED #define COORD_H_INCLUDED struct coord { public: float x, y, z; bool operator==(const coord &o) const { return x == o.x && y == o.y && z == o.z; } bool operator<(const coord &o) const { return x < o.x || (x == o.x && y < o.y) || (x == o.x && y == o.y && z < o.z); } coord(float a, float b, float c) : x(a) , y(b) , z(c) {} }; #endif // COORD_H_INCLUDED
[ "Bankde@hotmail.com" ]
Bankde@hotmail.com
feacaddc47a3d97d5a178ead53b6c92c136fd758
7266b663078cdc1ed0db72589e078af28ecc98d8
/Project1/Project1/SceneInstitute3.cpp
a085cbffe49c3e35b988b7d16816d14ef80e5edb
[]
no_license
Tanaka1228/ankokusinsidan
bd09cd73e7092770570edb5379fc1321fbe085b1
ccac38f3177159fe508fca3d8b42439ecf5d725c
refs/heads/main
2023-01-25T05:09:45.849278
2020-12-09T00:07:37
2020-12-09T00:07:37
304,493,182
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,524
cpp
//STLのデバック機能をOFFにする #define _SECURE_SCL (0); #define _HAS_ITERATOR_DEBUGGING (0); //GameLで使用するヘッダー #include"GameL\SceneObjManager.h" #include"GameL\DrawFont.h" #include"GameL/DrawTexture.h" //使用するネームスペース using namespace GameL; //使用するヘッダー #include"GameHead.h" #include"ObjInstitute3.h" //コンストラクタ CSceneInstitute3::CSceneInstitute3() { } //デストラクタ CSceneInstitute3::~CSceneInstitute3() { } //ゲームステージ初期化メソッド void CSceneInstitute3::InitScene() { //外部グラフィックファイルを読み込み0番に登録(512×512ピクセル)あまり関係ないらしい Draw::LoadImage(L"Hero.png", 0, TEX_SIZE_512);//主人公グラフィック //外部グラフィックファイルを読み込み1番に登録(512×512ピクセル)あまり関係ないらしい Draw::LoadImage(L"ハンドガン.png", 2, TEX_SIZE_512);//ハンドガングラフィック //外部グラフィックファイルを読み込み3番に登録(512×512ピクセル)あまり関係ないらしい Draw::LoadImage(L"弾丸_右.png", 3, TEX_SIZE_512);//弾丸グラフィック //外部グラフィックファイルを読み込み5番に登録(512×512ピクセル)あまり関係ないらしい Draw::LoadImage(L"研究所地下そざ.png", 5, TEX_SIZE_512);//弾丸グラフィック//外部グラフィックファイルを読み込み5番に登録(512×512ピクセル)あまり関係ないらしい //外部グラフィックファイルを読み込み6番に登録(512×512ピクセル)あまり関係ないらしい Draw::LoadImage(L"研究所床.png", 30, TEX_SIZE_512);//弾丸グラフィック//外部グラフィックファイルを読み込み5番に登録(512×512ピクセル)あまり関係ないらしい //主人公オブジェクト作成 CObjHero* obj = new CObjHero(400, 280); //主人公オブジェクト作成 Objs::InsertObj(obj, OBJ_HERO, 4); //作った主人公オブジェクトをオブジェクトマネージャーに登録 //銃オブジェクト作成 CObjGun* objg = new CObjGun(); Objs::InsertObj(objg, OBJ_GUN, 5); //研究所オブジェクト作成 CObjInstitute3* obji = new CObjInstitute3(); //研究所オブジェクト作成 Objs::InsertObj(obji, OBJ_INSTITUTE1, 3); //作った研究所オブジェクトをオブジェクトマネージャーに登録 } //ゲームステージ実行中メソッド void CSceneInstitute3::Scene() { }
[ "h1202016013@hiratagakuen.onmicrosoft.com" ]
h1202016013@hiratagakuen.onmicrosoft.com
f69adc19405d0062f7df85407a0e8e76e9b8cd2d
031f7354f569f118d73b5bf9ce0d4f860fb5eabf
/libkroll/utils/linux/platform_utils_linux.cpp
6fa3014d3857e9736ab452e7b35bcc9a56f73388
[ "Apache-2.0" ]
permissive
psycho-pas/kroll
706e3a55bf390e3f447d619ad158c840ff176506
12fc8ead138984a84681b7d7a526d58f5b44e3bc
refs/heads/master
2020-05-24T08:15:08.637812
2019-05-19T09:29:16
2019-05-19T09:29:16
187,138,484
0
0
NOASSERTION
2019-05-17T03:12:14
2019-05-17T03:12:14
null
UTF-8
C++
false
false
3,144
cpp
/** * Appcelerator Kroll - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved. */ // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "../utils.h" #include <cstdio> #include <cstdlib> #include <cstring> #include <unistd.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <net/if.h> namespace UTILS_NS { namespace PlatformUtils { void GetFirstMACAddressImpl(MACAddress& address) { //Based on code from: //http://adywicaksono.wordpress.com/2007/11/08/detecting-mac-address-using-c-application/ struct ifreq ifr; struct ifconf ifc; char buf[1024]; u_char addr[6] = {'\0','\0','\0','\0','\0','\0'}; int s,a; s = socket(AF_INET, SOCK_DGRAM, 0); if (s != -1) { ifc.ifc_len = sizeof(buf); ifc.ifc_buf = buf; ioctl(s, SIOCGIFCONF, &ifc); struct ifreq* IFR = ifc.ifc_req; bool success = false; for (a = ifc.ifc_len / sizeof(struct ifreq); --a >= 0; IFR++) { strcpy(ifr.ifr_name, IFR->ifr_name); if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0 && (!(ifr.ifr_flags & IFF_LOOPBACK)) && (ioctl(s, SIOCGIFHWADDR, &ifr) == 0)) { success = true; bcopy(ifr.ifr_hwaddr.sa_data, addr, 6); break; } } close(s); if (success) { memcpy(&address, addr, sizeof(address)); } } } std::string GetUsername() { char* loginName = getlogin(); if (loginName != NULL) { return loginName; } else if (EnvironmentUtils::Has("USER")) { return EnvironmentUtils::Get("USER"); } else { return "unknown"; } } int GetProcessorCount() { return sysconf(_SC_NPROCESSORS_ONLN); } } }
[ "mrobinson@appcelerator.com" ]
mrobinson@appcelerator.com
9d0b5fdbefe4d0d8eeae9bc49493f711b0f291dd
f1c01a3b5b35b59887bf326b0e2b317510deef83
/SDK/SoT_BP_Pig_Mythical_classes.hpp
ed82c40e89a89c128aa609c6d78f89e72410f03a
[]
no_license
codahq/SoT-SDK
0e4711e78a01f33144acf638202d63f573fa78eb
0e6054dddb01a83c0c1f3ed3e6cdad5b34b9f094
refs/heads/master
2023-03-02T05:00:26.296260
2021-01-29T13:03:35
2021-01-29T13:03:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
681
hpp
#pragma once // Sea of Thieves (2.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_Pig_Mythical_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_Pig_Mythical.BP_Pig_Mythical_C // 0x0000 (0x0BB8 - 0x0BB8) class ABP_Pig_Mythical_C : public ABP_Pig_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_Pig_Mythical.BP_Pig_Mythical_C")); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "30532128+pubgsdk@users.noreply.github.com" ]
30532128+pubgsdk@users.noreply.github.com
8aed5da785d449c50a3a6289377bc7cedfb97cd0
0dc20516079aaae4756d28e67db7cae9c0d33708
/jxy/jxy_src/jxysvr/src/server/gameserver/net/recharge/rcclient.h
65f5b54a449f57b534ef593f9b55431c8a6d73ac
[]
no_license
psymicgit/dummy
149365d586f0d4083a7a5719ad7c7268e7dc4bc3
483f2d410f353ae4c42abdfe4c606ed542186053
refs/heads/master
2020-12-24T07:48:56.132871
2017-08-05T07:20:18
2017-08-05T07:20:18
32,851,013
3
8
null
null
null
null
GB18030
C++
false
false
4,658
h
#ifndef __RC_CLIENT_CHANNEL_H #define __RC_CLIENT_CHANNEL_H #include <sdframework.h> #include <sdtype.h> #include <sdnet.h> #include "logic/base/basedefine.h" #include "deal/gmdealframe.h" using namespace SGDP; using namespace InterfaceDealBase; class CPlayer; class CRCClient: public ISDSession { public: CRCClient(); virtual ~CRCClient(); public: virtual VOID SDAPI SetConnection(ISDConnection* poConnection); virtual bool SDAPI OnError(INT32 nSDError, INT32 nSysError); virtual VOID SDAPI OnEstablish(); virtual VOID SDAPI OnTerminate(); virtual VOID SDAPI OnRecv(const CHAR* pBuf, UINT32 nLen); virtual VOID SDAPI Release(); ISDConnection* GetConnection(); VOID SetCliSessionID(UINT32 dwCliSessionID); UINT32 GetCliSessionID(); VOID Disconnect(); BOOL SDAPI Send(const CHAR* pBuf, INT32 nLen); BOOL SDAPI Send(UINT16 wMsgID, const CHAR* pBuf, INT32 nLen); BOOL SDAPI SendMsg(UINT16 wMsgID , const CHAR* pData); UINT64 GetLastTime() { return m_qwLastTime; } VOID SetTimeOutCloseFlag(BOOL bTimeOutClose = TRUE) { m_bTimeOutClose = bTimeOutClose; } BOOL GetTimeOutCloseFlag() { return m_bTimeOutClose; } VOID SDAPI SetPacketProcessor(CSDPacketProcessor* pPacketProcessor); inline UINT32 GetRemoteIP() { if(m_poConnection) return m_poConnection->GetRemoteIP(); return 0; } VOID SendPayRet(string strOrderID, UINT16 wErrCode, CPlayer* poPlayer, UINT32 dwExchangeGold); VOID Rspone(string strRet, string strOrderID = ""); public: VOID RspPlayerRes(CPlayer* poPlayer); VOID RspPlayerRes2(CPlayer* poPlayer); protected: VOID DealHttpRechargeReq(const CHAR* pBuf, UINT32 nLen); VOID DealHttpMyRechargeReq(const CHAR* pBuf, UINT32 nLen); VOID DealHttpGmReq(const CHAR* pBuf, UINT32 nLen); VOID DealHttpGmReq2(const CHAR* pBuf, UINT32 nLen,string strCmdInfo);//解析命令 VOID DealHttpCenterRechargeReq(const CHAR* pBuf, UINT32 nLen); VOID NtfPlayer(CPlayer* poPlayer, UINT32 dwExchangeGold); VOID DealHttpInterface(const CHAR* pBuf, UINT32 nLen); private: ISDConnection* m_poConnection; /** 与client之间的连接 */ CSDPacketProcessor* m_poPacketProcessor; UINT32 m_dwCliSessionID; /** Gate Server给client分配的事务ID */ UINT64 m_qwLastTime;//上次收到包的时间 BOOL m_bTimeOutClose;//是否是长时间未收到包而关闭的 }; /////////////////////////////////////////////////////其他方法 string GetACTEItemKindTypeName(UINT8 byKindType); string GetACTEItemKindValueName(UINT8 byKindType, UINT16 wKindID); class CRCCliProcessor : public CSDPacketProcessor { public: CRCCliProcessor() {}; ~CRCCliProcessor() {}; public: static CRCCliProcessor* Instance() { static CRCCliProcessor oProcessor; return &oProcessor; } public: virtual BOOL Init() { return TRUE; } virtual CSDProtocol* GetProtocol() { return NULL; } }; class CRCClientMgr: public ISDSessionFactory { public: typedef HashMap<UINT32, CRCClient*> CRCClientMap; typedef CRCClientMap::iterator CRCClientMapItr; CRCClientMgr(); ~CRCClientMgr(); virtual ISDSession* SDAPI CreateSession(ISDConnection* poConnection); public: BOOL Init(UINT32 nMaxClient = 1000); VOID UnInit(); VOID ReleaseCliSession(CRCClient* pSession); VOID AddCliSession(CRCClient* poSession); VOID RemoveCliSession(CRCClient* poSession); CRCClient* FindCliSession(UINT32 dwClientID); UINT32 GenerateClientID(); UINT32 GetCliSessionCount(); VOID ChkSessionOnTimer(); VOID GSDisConnect(UINT32 dwServerID); inline UINT32 GetSessionNum() { return m_mapCliSession.size(); } CGmManager & GetManager(){return m_oManager;} BOOL AddGmSerial(UINT64 qwSerialID); //TRUE则说明不是重复请求,FALSE为重复请求 private: CSDObjectPool<CRCClient, CSDMutex>* m_poCliSessionPool; CRCClientMap m_mapCliSession; CSDMutex* m_poLock; UINT32 m_dwCurClientID; CRCClientMapItr m_itrCurDeal; CRCCliProcessor m_oCliProcessor; C6464Map m_mapGmSerial2Time; //同一个序号3天过期 CGmManager m_oManager; }; #endif
[ "wuzili1234@gmail.com" ]
wuzili1234@gmail.com
ee89d372b09a2248f5154d0720a814dfa8801736
66c655a05d79ecfbc104b9b40a147c90b9efe242
/Client/Accessory.cpp
2e26e022b032cb279857cf626b8393ef4bd1488c
[]
no_license
a110b1110/MapleStory
244cdb3a98aed43244341b1b815b86cd1b0c0f15
03d627fad6224ac41ac9d92a2243d1caa05a6b35
refs/heads/master
2021-01-01T06:29:04.838321
2017-08-15T09:10:24
2017-08-15T09:10:24
97,435,142
0
0
null
2017-07-17T04:26:52
2017-07-17T04:26:52
null
UTF-8
C++
false
false
1,086
cpp
#include "stdafx.h" #include "Accessory.h" #include "BitMapMgr.h" #include "BitMap.h" CAccessory::CAccessory(void) { m_tItem.m_eType = ITEM_END; } CAccessory::CAccessory(TCHAR * pName, eItemType _eType) { m_tItem.m_eType = _eType; lstrcpy(m_tItem.m_szName, pName); } CAccessory::~CAccessory(void) { Release(); } void CAccessory::SetAccessory_Data(int _iStr, int _iDex, int _iInt, int _iLuk, int _iHp, int _iMp, int _iPrice, DWORD _dwOption) { m_tItem.m_iStr = _iStr; m_tItem.m_iDex = _iDex; m_tItem.m_iInt = _iInt; m_tItem.m_iLuk = _iLuk; m_tItem.m_iHp = _iHp; m_tItem.m_iMp = _iMp; m_tItem.m_iPrice = _iPrice; m_tItem.m_dwOption = _dwOption; } void CAccessory::Initialize(void) { m_tInfo.fcx = 32.f; m_tInfo.fcy = 32.f; } int CAccessory::Update(void) { return 0; } void CAccessory::Render(HDC _dc) { TransparentBlt(_dc, int(m_tInfo.fx), int(m_tInfo.fy), int(m_tInfo.fcx), int(m_tInfo.fcy), GETS(CBitMapMgr)->FindImage(m_tItem.m_szName)->GetMemDC(), 0, 0, int(m_tInfo.fcx), int(m_tInfo.fcy), RGB(255, 255, 255)); } void CAccessory::Release(void) { }
[ "ygchoi2001@naver.com" ]
ygchoi2001@naver.com
13bdfa3b931338551879ebcaf6683b9b17ee64e5
b7d3ac6d8eb63af8669375a1eabe153d3eef7d07
/Tarea1_B47835/Electric.h
4d014d2ecb8d83b69cce788996b57fac604f117a
[]
no_license
CursosIE/IE-0217-III-16-G2
e7707b7a9729c98215307118bd2bb374570d5e71
c3457bad72b30594d413bdafc358c1395c2de805
refs/heads/master
2021-01-11T23:19:38.683426
2017-03-07T06:38:37
2017-03-07T06:38:37
78,567,750
0
0
null
null
null
null
UTF-8
C++
false
false
1,464
h
#ifndef ELECTRIC_H #define ELECTRIC_H #include <iostream> #include "Pokemon.h" /** * Esta clase modela el comportamiento de un pokemon de tipo electrico por lo que provee metodos para mostrar las ventajas * y desventajas de un pokemon perteneciente a dicho grupo. El hecho de ser electrico es una caracteristica propia de los pokemones * por lo que se hereda todo el comportamiento que hace a un objeto ser Pokemon. * * @author Ericka Zuñiga Calvo */ class Electric : virtual public Pokemon{ public: /** * Constructor de Electric. */ Electric(); /** * Destructor de Electric. */ virtual ~Electric(); /** * Metodo para obtener la cadena de caracteres que describe dicho tipo. * * @return El tipo de esta clase. */ static std::string getType(); /** * Metodo para obtener las fortalezas de Electric contra el resto de tipos. * * @return Una cadena de caracteres que detalla sobre que tipos se impone Electric . */ static std::string getStrongVs(); /** * Metodo para obtener las debilidades de Electric contra el resto de tipos. * * @return Una cadena de caracteres que detalla que tipos debilitan Electric . */ static std::string getWeakVs(); } ; #endif /* ELECTRIC_H */
[ "cuchazc96@gmail.com" ]
cuchazc96@gmail.com
5ff757f6d2341fe4f0748961aeba035ac1e4af61
aecb4915544f1b669d3dc2ca0916245e39de4de8
/opencv_beginners/test/basicImgOpsTests/testRot.cpp
7d71aa1f24a70849bcc584c566957d3174184759
[ "MIT" ]
permissive
ratnadeepb/OpenCVProjects
bd83201ee5fc0f06b032f7f81899e9d1fa9f4f88
538e1a0bd9c6895f7f730db736767a213d140476
refs/heads/master
2021-05-06T04:25:40.018654
2018-01-04T12:14:03
2018-01-04T12:14:03
114,995,013
0
0
null
null
null
null
UTF-8
C++
false
false
193
cpp
#include "../../source/basicImgOps/rotation.hpp" int main(int argc, char** argv) { int retVal = rotate(argv[1]); std::cout << "The return value is " << retVal << std::endl; }
[ "ratnadeep.bhattacharya1983@gmail.com" ]
ratnadeep.bhattacharya1983@gmail.com
1e71259e8ccdd1e74fc88e7da0adca23e1b6408a
a09400aa22a27c7859030ec470b5ddee93e0fdf0
/stalkercop/include/smart_cover_transition_animation.hpp
94c29d88c0126a7e6c10f7cf56048a64eb7f0f80
[]
no_license
BearIvan/Stalker
4f1af7a9d6fc5ed1597ff13bd4a34382e7fdaab1
c0008c5103049ce356793b37a9d5890a996eed23
refs/heads/master
2022-04-04T02:07:11.747666
2020-02-16T10:51:57
2020-02-16T10:51:57
160,668,112
1
1
null
null
null
null
UTF-8
C++
false
false
1,518
hpp
//////////////////////////////////////////////////////////////////////////// // Module : smart_cover_transition_animation.hpp // Created : 20.12.2007 // Author : Alexander Dudin // Description : Animation transition class for smart_cover //////////////////////////////////////////////////////////////////////////// #ifndef SMART_COVER_TRANSITION_ANIMATION_HPP_INCLUDED #define SMART_COVER_TRANSITION_ANIMATION_HPP_INCLUDED #include "debug_make_final.hpp" #include "ai_monster_space.h" namespace smart_cover { namespace transitions { class animation_action : private debug::make_final<animation_action>, private boost::noncopyable { private: Fvector m_position; shared_str m_animation_id; MonsterSpace::EBodyState m_body_state; MonsterSpace::EMovementType m_movement_type; public: animation_action( Fvector const& position, shared_str const& animation_id, MonsterSpace::EBodyState const& body_state, MonsterSpace::EMovementType const& movement_type ); ~animation_action(){} IC bool has_animation () const; IC Fvector const& position () const; IC shared_str const& animation_id () const; IC MonsterSpace::EBodyState const& body_state () const; IC MonsterSpace::EMovementType const& movement_type () const; }; } // namespace transitions } // namespace smart_cover #include "smart_cover_transition_animation_inline.hpp" #endif // SMART_COVER_TRANSITION_ANIMATION_HPP_INCLUDED
[ "i-sobolevskiy@mail.ru" ]
i-sobolevskiy@mail.ru
ae3ab0668aeac1c854fc6b63882205430ff1df11
bda4ec81244344895fb3a1f8c49e095d47555104
/Arduino/SharpSensorCm/SharpSensorCm.ino
f2a54771b02f4b7cd3cdb3ae7487593944f5b3b1
[ "MIT" ]
permissive
chapellu/pekee2.0
08db3d27abf28c00eecdbb96fd29e7251f287706
d714022c037c1c63ae12534feead32db7eb14b51
refs/heads/master
2021-05-16T11:22:24.510753
2018-02-19T13:40:28
2018-02-19T13:40:28
104,994,439
0
0
null
null
null
null
UTF-8
C++
false
false
929
ino
#include <SharpIR.h> #define ir A0 #define model 430 // ir: the pin where your sensor is attached // model: an int that determines your sensor: 1080 for GP2Y0A21Y // 20150 for GP2Y0A02Y // (working distance range according to the datasheets) SharpIR SharpIR(ir, model); void setup() { // put your setup code here, to run once: Serial.begin(9600); } void loop() { delay(2000); unsigned long pepe1=millis(); // takes the time before the loop on the library begins int dis=SharpIR.distance(); // this returns the distance to the object you're measuring Serial.print("Mean distance: "); // returns it to the serial monitor Serial.println(dis); unsigned long pepe2=millis()-pepe1; // the following gives you the time taken to get the measurement Serial.print("Time taken (ms): "); Serial.println(pepe2); }
[ "ar.mignotte@orange.fr" ]
ar.mignotte@orange.fr
b5d890473273745bf6fb5850345d254f7a5b0f86
b1cedd57be15eb9a9a1727c7f09dff4d8df942b5
/PredefenceSuggestions/scratch/collision_radio_feedback.cc
e491b05a74a167823c04f278aaedb7a5e4a2c8e5
[]
no_license
takhandipu/MSThesisBook
2d00deb88d8033164a3520b94f1d3409bf202831
936b0a3102f75b8820558250d3480aab01e89873
refs/heads/master
2020-06-03T04:44:41.158733
2017-08-12T20:13:06
2017-08-12T20:13:06
94,115,774
0
0
null
null
null
null
UTF-8
C++
false
false
23,559
cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2016,2016 BUET * * 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; * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Tanvir Ahmed Khan <takhandipu@gmail.com> */ #include "ns3/wifi-net-device.h" #include "ns3/yans-wifi-channel.h" #include "ns3/yans-wifi-phy.h" #include "ns3/propagation-loss-model.h" #include "ns3/propagation-delay-model.h" #include "ns3/error-rate-model.h" #include "ns3/yans-error-rate-model.h" #include "ns3/ptr.h" #include "ns3/mobility-model.h" #include "ns3/constant-position-mobility-model.h" #include "ns3/vector.h" #include "ns3/packet.h" #include "ns3/simulator.h" #include "ns3/nstime.h" #include "ns3/command-line.h" #include "ns3/flow-id-tag.h" #include "ns3/core-module.h" #include "ns3/delay-jitter-estimation.h" #include "ns3/pu-model.h" using namespace ns3; using namespace std; NS_LOG_COMPONENT_DEFINE ("Base"); #define MAX_CHANNELS 11 #define BACKUP 0 #define FRAGMENTED 1 #define CHANNEL_DISTRIBUTED 2 #define RADIO_UTILIZATION_RATIO 4 #define CHANNEL_UTILIZATION_RATIO 8 int packetSize = 1024; //packet Size 1KB double packetInterval = 1.0/128.0; //data injection 128 KBps, 1Mbps int totalPacketsPerSU = 1024 * 20; //per SU 20 MB data string txMode = "OfdmRate18Mbps"; uint8_t txPowerLevel = 0; bool alwaysSwitch=true; double sourceSinkDistance = 80.0; double puArrivalMean = 5.0; double puArrivalBound = 10.0; double puDepartureMean = 2.0; double puDepartureBound = 4.0; double endTime = 50.0; double width = 500.0; double senseTime = 0.01; double switchTime = 0.005; double transmissionTime = 0.001; unsigned int mode = 0; unsigned int seed=1; double wakeUpRadioProbability = 0.2; Ptr<UniformRandomVariable> positionAllocator = CreateObject<UniformRandomVariable>(); Ptr<UniformRandomVariable> randomChannelAllocator = CreateObject<UniformRandomVariable>(); Ptr<UniformRandomVariable> randomRadioAllocator = CreateObject<UniformRandomVariable>(); Ptr<ExponentialRandomVariable> primaryUserArrivalAllocator = CreateObject<ExponentialRandomVariable> (); Ptr<ExponentialRandomVariable> primaryUserDepartureAllocator = CreateObject<ExponentialRandomVariable> (); Ptr<YansWifiChannel> channels[MAX_CHANNELS]; Ptr<PUModel> puModel; int SUNodeCount = 0; bool isBackup() { unsigned backupBit=mode&1; if(backupBit==0)return true; return false; } bool isFragmented() { return !isBackup(); } class MySUNode { public: int nodeId; int numberOfRadios; Ptr<YansWifiPhy> *m_txes; Ptr<YansWifiPhy> *m_rxes; Ptr<MobilityModel> posTx; Ptr<MobilityModel> posRx; int *currentChannel; uint32_t *m_flowIds; int *packetsQueuedPerRadio; int *packetsSentPerRadio; int *packetsReceivedPerRadio; Time delaySum; Time timeFirstRxPacket; Time timeLastRxPacket; bool isFirst; double perNodeAvgThroughput; double perPacketAvgDelay; double packetDropRatio; int totalPacketsQueued; int totalPacketsSent; int totalPacketsReceived; int maxPacketsReceived; int effectivePacketsReceived; int channelAllcoation[MAX_CHANNELS]; bool *radioOnStatus; void transmitPacketInChannel(int radioIndex, Ptr<Packet> p) { /**/ m_txes[radioIndex]->SendPacket (p, WifiMode (txMode), WIFI_PREAMBLE_SHORT, txPowerLevel); packetsSentPerRadio[radioIndex]++; } void startSwitching(int radioIndex, Ptr<Packet> p) { if(alwaysSwitch) { vector<int> freeChannelIndexes; for(int i=0; i<MAX_CHANNELS; i++) { if(channelAllcoation[i]==true)continue; freeChannelIndexes.push_back(i); } if(freeChannelIndexes.size()==0) { //Simulator::Schedule (Seconds (switchTime), &MySUNode::startSwitching, this, radioIndex, p); radioOnStatus[radioIndex]=false; return; } int randValue = randomChannelAllocator->GetInteger() % freeChannelIndexes.size(); int changedChannelIndex = freeChannelIndexes[randValue]; char debugString[80]; sprintf(debugString, "Node %d Radio %d is switching to channel %d",nodeId,radioIndex,changedChannelIndex); NS_LOG_DEBUG(debugString); bool notused=true; for(int i=0; i<numberOfRadios; i++) { if(i==radioIndex)continue; if(currentChannel[i]==currentChannel[radioIndex])notused=false; } if(notused)channelAllcoation[currentChannel[radioIndex]]=false; currentChannel[radioIndex] = changedChannelIndex; m_txes[radioIndex]->SetChannel(channels[changedChannelIndex]); m_rxes[radioIndex]->SetChannel(channels[changedChannelIndex]); channelAllcoation[changedChannelIndex]=true; } Simulator::Schedule (Seconds (switchTime), &MySUNode::startSensing, this, radioIndex, p); } void startSensing(int radioIndex, Ptr<Packet> p) { radioOnStatus[radioIndex]=true; bool senseResult=false; bool txSenseResult = puModel->IsPuActive(Now(),Time(senseTime),posTx->GetPosition().x,posTx->GetPosition().y,currentChannel[radioIndex]); bool rxSenseResult = puModel->IsPuActive(Now(),Time(senseTime),posRx->GetPosition().x,posRx->GetPosition().y,currentChannel[radioIndex]); senseResult = txSenseResult || rxSenseResult; if(senseResult==true) { //PU is present //schedule switching Simulator::Schedule (Seconds (senseTime), &MySUNode::startSwitching, this, radioIndex, p); } else { //PU is not present //schedule transmission Simulator::Schedule (Seconds(senseTime), &MySUNode::transmitPacketInChannel, this, radioIndex, p); } } void sendPacketInRadio(int radioIndex) { radioOnStatus[radioIndex]=true; Ptr<Packet> p = Create<Packet> (packetSize); p->AddByteTag (FlowIdTag (m_flowIds[radioIndex])); DelayJitterEstimationTimestampTag timeTag; p->AddPacketTag(timeTag); packetsQueuedPerRadio[radioIndex]++; if(isFirst == true) { timeFirstRxPacket = Now(); isFirst = false; } Simulator::Schedule (Seconds (0.0), &MySUNode::startSensing, this, radioIndex, p); } DelayJitterEstimationTimestampTag* getDelayJitterEstimationTimestampTag(Ptr<Packet> p) { PacketTagIterator i = p->GetPacketTagIterator (); DelayJitterEstimationTimestampTag *tag; while(i.HasNext ()) { PacketTagIterator::Item item = i.Next (); //NS_ASSERT (item.GetTypeId ().HasConstructor ()); if(!item.GetTypeId ().HasConstructor ())break; Callback<ObjectBase *> constructor = item.GetTypeId ().GetConstructor (); //NS_ASSERT (!constructor.IsNull ()); if(constructor.IsNull ())break; ObjectBase *instance = constructor (); tag = dynamic_cast<DelayJitterEstimationTimestampTag *> (instance); //NS_ASSERT (tag != 0); if(tag==0)break; item.GetTag (*tag); break; } return tag; } void receivePacketInRadio(Ptr<Packet> p, double snr, WifiMode mode, enum WifiPreamble preamble) { FlowIdTag tag; p->FindFirstMatchingByteTag (tag); for(int i = 0; i < numberOfRadios; i++) { if(tag.GetFlowId () == m_flowIds[i]) { packetsReceivedPerRadio[i]++; DelayJitterEstimationTimestampTag *timeTag = getDelayJitterEstimationTimestampTag(p); if(timeTag==0) { // } else { Time txTime = timeTag->GetTxTime(); delaySum += Now()-txTime; // timeLastRxPacket = Now(); } break; } } } MySUNode(int nRadios=1) { this->nodeId = SUNodeCount++; for(int i=0; i<MAX_CHANNELS; i++) { channelAllcoation[i]=false; } char debugString[80]; sprintf(debugString, "Creating %d-th SU node with %d radios.",this->nodeId,nRadios); NS_LOG_DEBUG(debugString); numberOfRadios=nRadios; m_txes = new Ptr<YansWifiPhy>[numberOfRadios]; m_rxes = new Ptr<YansWifiPhy>[numberOfRadios]; currentChannel = new int[numberOfRadios]; double x = positionAllocator->GetValue(); double y = positionAllocator->GetValue(); posTx = CreateObject<ConstantPositionMobilityModel> (); posTx->SetPosition (Vector (x, y, 0.0)); posRx = CreateObject<ConstantPositionMobilityModel> (); posRx->SetPosition (Vector (x+sourceSinkDistance, y, 0.0)); Ptr<ErrorRateModel> error = CreateObject<YansErrorRateModel> (); // for(int i = 0; i < numberOfRadios; i++) { Ptr<YansWifiPhy> tx = CreateObject<YansWifiPhy> (); Ptr<YansWifiPhy> rx = CreateObject<YansWifiPhy> (); tx->SetErrorRateModel(error); rx->SetErrorRateModel(error); int initialChannelIndex; vector<int> freeChannelIndexes; for(int j=0; j<MAX_CHANNELS; j++) { if(channelAllcoation[j]==true)continue; freeChannelIndexes.push_back(j); } if(freeChannelIndexes.size()==0) { initialChannelIndex = randomChannelAllocator->GetInteger() % MAX_CHANNELS; } else { int randValue = randomChannelAllocator->GetInteger() % freeChannelIndexes.size(); initialChannelIndex = freeChannelIndexes[randValue]; } char debugString[80]; sprintf(debugString, "Node %d Radio %d got channel %d",this->nodeId,i, initialChannelIndex); NS_LOG_DEBUG(debugString); currentChannel[i] = initialChannelIndex; channelAllcoation[initialChannelIndex]=true; tx->SetChannel(channels[initialChannelIndex]); rx->SetChannel(channels[initialChannelIndex]); tx->SetMobility(posTx); rx->SetMobility(posRx); m_txes[i]=tx; m_rxes[i]=rx; } packetsQueuedPerRadio = new int[numberOfRadios]; packetsSentPerRadio = new int[numberOfRadios]; packetsReceivedPerRadio = new int[numberOfRadios]; m_flowIds = new uint32_t[numberOfRadios]; for(int i = 0; i < numberOfRadios; i++) { packetsQueuedPerRadio[i] = 0; packetsSentPerRadio[i] = 0; packetsReceivedPerRadio[i] = 0; m_flowIds[i] = FlowIdTag::AllocateFlowId (); } delaySum=Time(0.0); perNodeAvgThroughput=0.0; perPacketAvgDelay=0.0; packetDropRatio=0.0; totalPacketsQueued=0; totalPacketsSent=0; totalPacketsReceived=0; maxPacketsReceived=0; for(int i = 0; i < numberOfRadios; i++) { m_rxes[i]->SetReceiveOkCallback ( MakeCallback ( &MySUNode::receivePacketInRadio, this ) ); } radioOnStatus=new bool[numberOfRadios]; for(int i = 0; i < numberOfRadios; i++) { radioOnStatus[i]=true; } isFirst = true; timeFirstRxPacket = Now(); timeLastRxPacket = Now(); /*if(isBackup())startBackup(); else startFragmented();*/ // startFeedback(); } void startBackup() { double currentTime = 0.0; for(int i = 0; i < totalPacketsPerSU; i++) { for(int j = 0; j < numberOfRadios; j++) { Simulator::Schedule (Seconds (currentTime), &MySUNode::sendPacketInRadio, this, j); } currentTime += packetInterval; } } void startFragmented() { double currentTime = 0.0; int effectivePacketsPerRadio=totalPacketsPerSU/numberOfRadios; for(int i = 0; i < effectivePacketsPerRadio; i++) { for(int j = 0; j < numberOfRadios; j++) { Simulator::Schedule (Seconds (currentTime), &MySUNode::sendPacketInRadio, this, j); } currentTime += packetInterval; } } void startFeedback() { double currentTime = 0.0; Simulator::Schedule (Seconds (currentTime), &MySUNode::giveFeedback, this, totalPacketsPerSU); } void giveFeedback(int packetsToSend) { if(packetsToSend == 0) { return; } double *sentToQueuedRatios=new double[numberOfRadios]; double total=0.0; for(int i=0; i<numberOfRadios; i++) { sentToQueuedRatios[i]=(1.0+packetsSentPerRadio[i])/(1.0+packetsQueuedPerRadio[i]); if(radioOnStatus[i]==false) { sentToQueuedRatios[i]*=wakeUpRadioProbability; } total+=sentToQueuedRatios[i]; } for(int i=0; i<numberOfRadios; i++) { sentToQueuedRatios[i]/=total; } double randValue = randomRadioAllocator->GetValue(); double current = 0.0; int selectedRadioIndex = 0; for(int i=0; i<numberOfRadios; i++) { current += sentToQueuedRatios[i]; if(randValue < current) { selectedRadioIndex=i; break; } } Simulator::Schedule (Seconds (0.0), &MySUNode::sendPacketInRadio, this, selectedRadioIndex); Simulator::Schedule (Seconds (packetInterval), &MySUNode::giveFeedback, this, packetsToSend-1); } void saveStatistics() { for(int i = 0; i < numberOfRadios; i++) { totalPacketsQueued += packetsQueuedPerRadio[i]; totalPacketsSent += packetsSentPerRadio[i]; totalPacketsReceived += packetsReceivedPerRadio[i]; if(packetsReceivedPerRadio[i]>maxPacketsReceived) { maxPacketsReceived = packetsReceivedPerRadio[i]; } } double delayInSecond = delaySum.GetDouble() /1000000000; if(totalPacketsReceived!=0)perPacketAvgDelay=(delayInSecond/totalPacketsReceived); if(totalPacketsSent!=0)packetDropRatio=(1.0*(totalPacketsSent-totalPacketsReceived)/totalPacketsSent); effectivePacketsReceived=totalPacketsReceived; if(isBackup())effectivePacketsReceived=maxPacketsReceived; if(timeLastRxPacket==timeFirstRxPacket) { perNodeAvgThroughput=0.0; } else { Time difference = timeLastRxPacket - timeFirstRxPacket;//in ns double diff = difference.GetDouble()/1000000000;//in s //packetCount = effectivePacketsReceived; double byteCount = effectivePacketsReceived * packetSize; double bitps = byteCount * 8; perNodeAvgThroughput = bitps/diff; } } void printSimulationResults() { saveStatistics(); // NS_LOG_DEBUG("Node "<<nodeId); for(int i = 0; i < numberOfRadios; i++) { NS_LOG_DEBUG("Radio "<<i); NS_LOG_DEBUG("Packets Sent "<<packetsSentPerRadio[i]); NS_LOG_DEBUG("Packets Received "<<packetsReceivedPerRadio[i]); } NS_LOG_DEBUG("Delay Sum (in seconds) "<<delaySum/1000000000); NS_LOG_DEBUG("Per Node Avg. Throughput (Mbps) "<<perNodeAvgThroughput/(1024*1024)); NS_LOG_DEBUG("Per Packet Avg. Delay (Seconds) "<<perPacketAvgDelay); NS_LOG_DEBUG("Packet Drop Ratio "<<packetDropRatio); } }; class MyExperiment { public: Ptr<WifiPhy> m_puTxes[MAX_CHANNELS]; int numberOfSUs; int numberOfRadios; MySUNode *sus[20]; double avgNetworkThroughput;//bps double perNodeAvgThroughput;//bps double perPacketAvgDelay; double packetDropRatio; void sendPacketInPU(int puIndex, Time endTime) { if(Now()>endTime){ double nextTime = primaryUserArrivalAllocator->GetValue(); Simulator::Schedule (Seconds (nextTime), &MyExperiment::startPUActivity, this, puIndex); } else { Ptr<Packet> p = Create<Packet> (packetSize); m_puTxes[puIndex]->SendPacket (p, WifiMode (txMode), WIFI_PREAMBLE_SHORT, txPowerLevel); char debugString[80]; sprintf(debugString, "PU %d is sending a packet",puIndex); NS_LOG_DEBUG(Now()/1000000000<<" "<<debugString); Simulator::Schedule (Seconds (packetInterval), &MyExperiment::sendPacketInPU, this, puIndex, endTime); } } void startPUActivity(int puIndex) { double nextTime = primaryUserDepartureAllocator->GetValue(); Simulator::Schedule (Seconds (0.0), &MyExperiment::sendPacketInPU, this, puIndex, Now()+Seconds(nextTime)); } MyExperiment(int numberOfSUs=4, int numberOfRadios=1) { avgNetworkThroughput=0.0;//bps perNodeAvgThroughput=0.0;//bps perPacketAvgDelay=0.0; packetDropRatio=0.0; SUNodeCount = 0; this->numberOfRadios=numberOfRadios; positionAllocator->SetAttribute ("Min", DoubleValue (0.0)); positionAllocator->SetAttribute ("Max", DoubleValue (width)); randomChannelAllocator->SetAttribute ("Min", DoubleValue (1)); randomChannelAllocator->SetAttribute ("Max", DoubleValue (MAX_CHANNELS)); randomRadioAllocator->SetAttribute ("Min", DoubleValue (0.0)); randomRadioAllocator->SetAttribute ("Max", DoubleValue (1.0)); primaryUserArrivalAllocator->SetAttribute ("Mean", DoubleValue (puArrivalMean)); primaryUserArrivalAllocator->SetAttribute ("Bound", DoubleValue (puArrivalBound)); primaryUserDepartureAllocator->SetAttribute ("Mean", DoubleValue (puDepartureMean)); primaryUserDepartureAllocator->SetAttribute ("Bound", DoubleValue (puDepartureBound)); puModel = CreateObject<PUModel>(); std::string map_file = "newPUTrace.txt";//"map_PUs_multiple.txt";// puModel->SetPuMapFile((char*)map_file.c_str()); for(int i=0; i<MAX_CHANNELS; i++) { channels[i] = CreateObject<YansWifiChannel> (); channels[i]->SetPropagationDelayModel(CreateObject<ConstantSpeedPropagationDelayModel> ()); channels[i]->SetPropagationLossModel ( CreateObject<LogDistancePropagationLossModel> () ); } Ptr<ErrorRateModel> error = CreateObject<YansErrorRateModel> (); for(int i = 0; i < MAX_CHANNELS; i++) { Ptr<YansWifiPhy> tx = CreateObject<YansWifiPhy> (); tx->SetErrorRateModel(error); tx->SetChannel(channels[i]); Ptr<MobilityModel> posTx = CreateObject<ConstantPositionMobilityModel> (); posTx->SetPosition (Vector (positionAllocator->GetValue(), positionAllocator->GetValue(), 0.0)); tx->SetMobility(posTx); m_puTxes[i]=tx; //double nextTime = primaryUserArrivalAllocator->GetValue(); //Simulator::Schedule (Seconds (nextTime), &MyExperiment::startPUActivity, this, i); } this->numberOfSUs = numberOfSUs; for(int i = 0; i<numberOfSUs; i++) { sus[i] = new MySUNode(numberOfRadios); } Simulator::Stop (Seconds (endTime+1.0)); Simulator::Run (); Simulator::Destroy(); for(int i = 0; i<numberOfSUs; i++) { sus[i]->printSimulationResults(); } saveStatistics(); printSimulationResults(); } void saveStatistics() { int totalPacketsQueued = 0; int totalPacketsReceived = 0; for(int i=0; i<numberOfSUs; i++) { totalPacketsQueued += sus[i]->totalPacketsQueued; totalPacketsReceived += sus[i]->totalPacketsReceived; } double drop = (totalPacketsQueued-totalPacketsReceived)*1.0; if(totalPacketsQueued==0) { packetDropRatio = 0.0; } else { packetDropRatio = drop/totalPacketsQueued; } for(int i=0; i<numberOfSUs; i++) { avgNetworkThroughput += sus[i]->perNodeAvgThroughput; } if(numberOfSUs!=0)perNodeAvgThroughput=(avgNetworkThroughput/(numberOfSUs*2)); Time delaySum = Seconds(0.0); for(int i = 0; i<numberOfSUs; i++) { delaySum += sus[i]->delaySum; } if(totalPacketsReceived==0) { perPacketAvgDelay = 0.0; } else { double delayInSecond = delaySum.GetDouble() /1000000000; perPacketAvgDelay=(delayInSecond/totalPacketsReceived); } NS_LOG_DEBUG("Network performance matrics"); NS_LOG_DEBUG("Avg. Network Throughput (Mbps) "<<avgNetworkThroughput/(1024*1024)); NS_LOG_DEBUG("Per Packet Avg. Delay (Seconds) "<<perPacketAvgDelay); NS_LOG_DEBUG("Per Node Avg. Throughput (Mbps) "<<perNodeAvgThroughput/(1024*1024)); NS_LOG_DEBUG("Packet Drop Ratio "<<packetDropRatio); } void printSimulationResults() { cout<<numberOfSUs*2<<", "; cout<<numberOfRadios<<", "; cout<<avgNetworkThroughput/(1024*1024)<<", "; cout<<perPacketAvgDelay<<", "; cout<<perNodeAvgThroughput/(1024*1024)<<", "; cout<<packetDropRatio<<", "; cout<<seed<<", "; cout<<(1.0/packetInterval)<<", "; cout<<endl; } }; int main (int argc, char *argv[]) { mode = 1; int numNodes = 6; int numRadios = 1; seed=1; double packetPerSecond=128.0; CommandLine cmd; cmd.AddValue ("numNodes", "Number of nodes", numNodes); cmd.AddValue ("numRadios", "Number of nodes", numRadios); cmd.AddValue ("endTime", "Total Simulation Time", endTime); cmd.AddValue ("seed", "Simulation seed", seed); cmd.AddValue ("packetPerSecond", "Packet Per Second", packetPerSecond); cmd.Parse (argc, argv); packetInterval = 1.0/packetPerSecond; SeedManager::SetSeed(seed); MyExperiment ex(numNodes,numRadios); return 0; }
[ "takhandipu@gmail.com" ]
takhandipu@gmail.com
4a3e11a0de87afa9d4aae2c18814a28f150b152d
2faa1b4e7253f75c4c7de8a07884daacf6f99620
/scroll-url.h
d58944d659e0d5498f42811fac1d7ba112622f1a
[ "MIT" ]
permissive
nnm-t/m5stickc-visiting-card
dabd8c7cb95fc758c6b48064b407e901cc723836
858a11ffa48c6d7e76d19c84cb9529a3ef3754da
refs/heads/master
2021-03-01T03:46:02.451539
2020-03-08T04:30:15
2020-03-08T04:30:15
245,751,418
4
0
null
null
null
null
UTF-8
C++
false
false
757
h
#pragma once #include <Arduino.h> #include <M5StickC.h> #include "sprite.h" class ScrollURL { static constexpr const Vector2<int32_t> position = Vector2<int32_t>(64, 56); static constexpr const Vector2<int32_t> push_position = Vector2<int32_t>(96, 0); static constexpr const Vector2<int16_t> delta = Vector2<int16_t>(-1, 0); static constexpr const Rect<int16_t> size = Rect<int16_t>(400, 16); static constexpr const Rect<int32_t> rect_size = Rect<int32_t>(400, 16); static constexpr const char* string = "Scroll_URL"; static constexpr const int16_t redraw_x = size.Width() * -1; Sprite sprite; int16_t x = 0; void DrawString(); public: ScrollURL() { } void Begin(); void Update(); };
[ "noname@kamisawa.net" ]
noname@kamisawa.net
a801015319a122807c0308f4e8de7d68099c8442
125b6ed108aa1c5cad36b4eb68d328bdcdc82669
/compare.cpp
ccccfde0d03c29e69d6c5348106b6eda24c895a0
[ "BSD-3-Clause" ]
permissive
monellz/vite
52d033fbf21220f4b94b67ccd00613dd7b092341
b9c114ae6b3b17cf23215e28afa03452c9f44b79
refs/heads/master
2023-06-16T21:50:03.777407
2021-07-16T07:41:24
2021-07-16T07:41:24
386,495,562
0
0
BSD-3-Clause
2021-07-16T03:23:14
2021-07-16T03:23:14
null
UTF-8
C++
false
false
12,192
cpp
// *********************************************************************** // // Vite: A C++ library for distributed-memory graph clustering // using MPI+OpenMP // // Daniel Chavarria (daniel.chavarria@pnnl.gov) // Antonino Tumeo (antonino.tumeo@pnnl.gov) // Mahantesh Halappanavar (hala@pnnl.gov) // Pacific Northwest National Laboratory // // Hao Lu (luhowardmark@wsu.edu) // Sayan Ghosh (sayan.ghosh@wsu.edu) // Ananth Kalyanaraman (ananth@eecs.wsu.edu) // Washington State University // // *********************************************************************** // // Copyright (2017) Battelle Memorial Institute // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // ************************************************************************ #include "compare.hpp" extern std::ofstream ofs; //Only a single process performs the cluster comparisons //Assume that clusters have been numbered in a contiguous manner //Assume that C1 is the truth data void compare_communities(std::vector<GraphElem> const& C1, std::vector<GraphElem> const& C2) { // number of vertices of two sets must match const GraphElem N1 = C1.size(); const GraphElem N2 = C2.size(); assert(N1>0 && N2>0); assert(N1 == N2); int nT; #pragma omp parallel { nT = omp_get_num_threads(); } //Compute number of communities in each set: GraphElem nC1=-1; #pragma omp parallel for reduction(max: nC1) for(GraphElem i = 0; i < N1; i++) { if (C1[i] > nC1) { nC1 = C1[i]; } } nC1++; // nC1 contains index, so need to +1 GraphElem nC2=-1; #pragma omp parallel for reduction(max: nC2) for(GraphElem i = 0; i < N2; i++) { if (C2[i] > nC2) { nC2 = C2[i]; } } nC2++; #if defined(DONT_CREATE_DIAG_FILES) std::cout << "Number of unique communities in C1 = " << nC1 << ", and C2 = " << nC2 << std::endl; #else ofs << "Number of unique communities in C1 = " << nC1 << ", and C2 = " << nC2 << std::endl; #endif //////////STEP 1: Create a CSR-like datastructure for communities in C1 GraphElem* commPtr1 = new GraphElem[nC1+1]; GraphElem* commIndex1 = new GraphElem[N1]; GraphElem* commAdded1 = new GraphElem[nC1]; GraphElem* clusterDist1 = new GraphElem[nC1]; //For Gini coefficient // Initialization #pragma omp parallel for for(GraphElem i = 0; i < nC1; i++) { commPtr1[i] = 0; commAdded1[i] = 0; } commPtr1[nC1] = 0; // Count the size of each community #pragma omp parallel for for(GraphElem i = 0; i < N1; i++) { #pragma omp atomic update commPtr1[C1[i]+1]++; } #pragma omp parallel for for(GraphElem i = 0; i < nC1; i++) { clusterDist1[i] = commPtr1[i+1]; //Zeroth position is not valid } //Prefix sum: for(GraphElem i=0; i<nC1; i++) { commPtr1[i+1] += commPtr1[i]; } //Group vertices with the same community in particular order #pragma omp parallel for for (GraphElem i=0; i<N1; i++) { long ca; #pragma omp atomic capture ca = commAdded1[C1[i]]++; GraphElem Where = commPtr1[C1[i]] + ca; commIndex1[Where] = i; //The vertex id } delete []commAdded1; #ifdef DEBUG_PRINTF ofs << "Done building structure for C1..." << std::endl; #endif //////////STEP 2: Create a CSR-like datastructure for communities in C2 GraphElem* commPtr2 = new GraphElem[nC2+1]; GraphElem* commIndex2 = new GraphElem[N2]; GraphElem* commAdded2 = new GraphElem[nC2]; GraphElem* clusterDist2 = new GraphElem[nC2]; //For Gini coefficient // Initialization #pragma omp parallel for for(GraphElem i = 0; i < nC2; i++) { commPtr2[i] = 0; commAdded2[i] = 0; } commPtr2[nC2] = 0; // Count the size of each community #pragma omp parallel for for(GraphElem i = 0; i < N2; i++) { #pragma omp atomic update commPtr2[C2[i]+1]++; } #pragma omp parallel for for(GraphElem i = 0; i < nC2; i++) { clusterDist2[i] = commPtr2[i+1]; //Zeroth position is not valid } //Prefix sum: for(GraphElem i=0; i<nC2; i++) { commPtr2[i+1] += commPtr2[i]; } //Group vertices with the same community in particular order #pragma omp parallel for for (GraphElem i=0; i<N2; i++) { long ca; #pragma omp atomic capture ca = commAdded2[C2[i]]++; GraphElem Where = commPtr2[C2[i]] + ca; commIndex2[Where] = i; //The vertex id } delete []commAdded2; #ifdef DEBUG_PRINTF ofs << "Done building structure for C2..." << std::endl; #endif //////////STEP 3: Compute statistics: // thread-private vars GraphElem tSameSame[nT], tSameDiff[nT], tDiffSame[nT], nAgree[nT]; #pragma omp parallel for for (int i=0; i < nT; i++) { tSameSame[i] = 0; tSameDiff[i] = 0; tDiffSame[i] = 0; nAgree[i] = 0; } //Compare all pairs of vertices from the perspective of C1 (ground truth): #pragma omp parallel { int tid = omp_get_thread_num(); #pragma omp for for(GraphElem ci = 0; ci < nC1; ci++) { GraphElem adj1 = commPtr1[ci]; GraphElem adj2 = commPtr1[ci+1]; for(GraphElem i = adj1; i < adj2; i++) { for(GraphElem j = i+1; j < adj2; j++) { //Check if the two vertices belong to the same community in C2 if(C2[commIndex1[i]] == C2[commIndex1[j]]) { tSameSame[tid]++; } else { tSameDiff[tid]++; } }//End of for(j) }//End of for(i) }//End of for(ci) }//End of parallel region #ifdef DEBUG_PRINTF ofs << "Done parsing C1..." << std::endl; #endif //Compare all pairs of vertices from the perspective of C2: #pragma omp parallel { int tid = omp_get_thread_num(); #pragma omp for for(GraphElem ci = 0; ci < nC2; ci++) { GraphElem adj1 = commPtr2[ci]; GraphElem adj2 = commPtr2[ci+1]; for(GraphElem i = adj1; i < adj2; i++) { for(GraphElem j = i+1; j < adj2; j++) { //Check if the two vertices belong to the same community in C2 if(C1[commIndex2[i]] == C1[commIndex2[j]]) { nAgree[tid]++; } else { tDiffSame[tid]++; } }//End of for(j) }//End of for(i) }//End of for(ci) }//End of parallel region #ifdef DEBUG_PRINTF ofs << "Done parsing C2..." << std::endl; #endif GraphElem SameSame = 0, SameDiff = 0, DiffSame = 0, Agree = 0; #pragma omp parallel for reduction(+:SameSame) reduction(+:SameDiff) \ reduction(+:DiffSame) reduction(+:Agree) for (int i=0; i < nT; i++) { SameSame += tSameSame[i]; SameDiff += tSameDiff[i]; DiffSame += tDiffSame[i]; Agree += nAgree[i]; } assert(SameSame == Agree); double precision = (double)SameSame / (double)(SameSame + DiffSame); double recall = (double)SameSame / (double)(SameSame + SameDiff); //F-score (F1 score) is the harmonic mean of precision and recall -- //multiplying the constant of 2 scales the score to 1 when both recall and precision are 1 double fScore = 2.0*((precision * recall) / (precision + recall)); //Compute Gini coefficient for each cluster: double Gini1 = compute_gini_coeff(clusterDist1, nC1); double Gini2 = compute_gini_coeff(clusterDist2, nC2); std::cout << "*******************************************" << std::endl; std::cout << "Communities comparison statistics:" << std::endl; std::cout << "*******************************************" << std::endl; std::cout << "|C1| (truth) : " << N1 << std::endl; std::cout << "#communities in C1 : " << nC1 << std::endl; std::cout << "|C2| (output) : " << N2 << std::endl; std::cout << "#communities in C2 : " << nC2 << std::endl; std::cout << "-------------------------------------------" << std::endl; std::cout << "Same-Same (True positive) : " << SameSame << std::endl; std::cout << "Same-Diff (False negative) : " << SameDiff << std::endl; std::cout << "Diff-Same (False positive) : " << DiffSame << std::endl; std::cout << "-------------------------------------------" << std::endl; std::cout << "Precision : " << precision << " (" << (precision*100) << ")" << std::endl; std::cout << "Recall : " << recall << " (" << (recall*100) << ")" << std::endl; std::cout << "F-score : " << fScore << std::endl; std::cout << "-------------------------------------------" << std::endl; std::cout << "Gini coefficient, C1 : " << Gini1 << std::endl; std::cout << "Gini coefficient, C2 : " << Gini2 << std::endl; std::cout << "*******************************************" << std::endl; //Cleanup: delete []commPtr1; delete []commIndex1; delete []commPtr2; delete []commIndex2; delete []clusterDist1; delete []clusterDist2; } //End of compare_communities(...) //WARNING: Assume that colorSize is populated with the frequency for each color //Will sort the array within the function double compute_gini_coeff(GraphElem *colorSize, int numColors) { //Step 1: Sort the color size vector -- use STL sort function #ifdef DEBUG_PRINTF double time1 = omp_get_wtime(); #endif std::sort(colorSize, colorSize+numColors); #ifdef DEBUG_PRINTF double time2 = omp_get_wtime(); ofs << "Time for sorting (in compute_gini_coeff): " << time2-time1 << std::endl; #endif //Step 2: Compute Gini coefficient double numFunc=0.0, denFunc=0.0; #pragma omp parallel for reduction(+:numFunc,denFunc) for (GraphElem i=0; i < numColors; i++) { numFunc = numFunc + ((i+1)*colorSize[i]); denFunc = denFunc + colorSize[i]; } #ifdef DEBUG_PRINTF ofs << "(Gini coeff) Numerator = " << numFunc << " Denominator = " << denFunc << std::endl; ofs << "(Gini coeff) Negative component = " << ((double)(numColors+1)/(double)numColors) << std::endl; #endif double giniCoeff = ((2*numFunc)/(numColors*denFunc)) - ((double)(numColors+1)/(double)numColors); return giniCoeff; //Return the Gini coefficient }//End of compute_gini_coeff(...)
[ "sghosh1@eecs.wsu.edu" ]
sghosh1@eecs.wsu.edu
8001ae8f7c50da67d6f9174f1f88c401a0f52752
aed2c24f8767d6d9a05b573ca97539f6c0c352a1
/cpp-第二次作业/Q87/code.cpp
8a1596bc1d776909ee1d9a20b0ac263a7424599f
[]
no_license
NJUSE58/CPP
3437a76abaf190211ef26f7c450f7c1e2c9e5aa2
b5b8aa2073e4f3a777ef654d23e5159799fe7a72
refs/heads/master
2021-05-07T17:13:59.029302
2017-11-02T12:19:27
2017-11-02T12:19:27
108,662,749
2
0
null
null
null
null
UTF-8
C++
false
false
584
cpp
#include<iostream> #include<algorithm> using namespace std; #define MAX 101 int main() { int n; int num[MAX][MAX], sum[MAX][MAX]; cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { cin >> num[i][j]; } } for (int i = 1; i <= n; i++) { sum[n][i] = num[n][i]; } for (int i = n; i > 1; i--) { for (int j = 1; j < i; j++) { if (sum[i][j] < sum[i][j + 1]) { sum[i - 1][j] = sum[i][j] + num[i - 1][j]; } else { sum[i - 1][j] = sum[i][j + 1] + num[i - 1][j]; } } } cout << sum[1][1]; cin.get(); cin.get(); return 0; }
[ "161250058@smail.nju.edu.cn" ]
161250058@smail.nju.edu.cn
d4e9821cf5ea0eb1e41abb6836312948b9154c63
e077aaaa60a39ba40855f36bc3a53f8adfc8fc08
/tensorflow-master-tensorflow/stream_executor/cuda/cuda_gpu_executor.h
2a0c6dc456dc76cd0c707c8fef9e621bf8bca989
[ "MIT" ]
permissive
xijunlee/tensorflow-learning
fe9dd1d9b0d3e79b7ed3cad16c4d25073ab14483
936c384667632c43ccd3d536b8136d46a978d5aa
refs/heads/master
2022-11-01T13:27:22.423217
2018-12-05T07:19:34
2018-12-05T07:19:34
88,263,357
1
1
MIT
2022-10-11T19:19:53
2017-04-14T11:48:26
C++
UTF-8
C++
false
false
10,718
h
/* Copyright 2015 Google Inc. 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. ==============================================================================*/ // The CUDA implementation of the StreamExecutorInterface functionality. // CUDA inclusions are ideally confined to this implementation file. // // The notions from the StreamExecutor basically correspond to the CUDA streams // programming model provided by the libcuda.so driver APIs, so we don't have // to do much more than wrap the calls to the libraries appropriately. #ifndef TENSORFLOW_STREAM_EXECUTOR_CUDA_CUDA_GPU_EXECUTOR_H_ #define TENSORFLOW_STREAM_EXECUTOR_CUDA_CUDA_GPU_EXECUTOR_H_ #include <map> #include <set> #include "tensorflow/stream_executor/cuda/cuda_kernel.h" #include "tensorflow/stream_executor/event.h" #include "tensorflow/stream_executor/lib/status.h" #include "tensorflow/stream_executor/lib/statusor.h" #include "tensorflow/stream_executor/platform.h" #include "tensorflow/stream_executor/platform/mutex.h" #include "tensorflow/stream_executor/platform/port.h" #include "tensorflow/stream_executor/platform/thread_annotations.h" #include "tensorflow/stream_executor/stream_executor_internal.h" namespace perftools { namespace gputools { namespace blas { class BlasSupport; } namespace internal { class RngSupport; } // namespace internal } // namespace gputools } // namespace perftools namespace perftools { namespace gputools { namespace cuda { // CUDA-platform implementation of the platform-agnostic // StreamExecutorInferface. class CUDAExecutor : public internal::StreamExecutorInterface { public: // sub_platform indicates the subplatform used in this executor; it must // be a CUDA type. explicit CUDAExecutor(const PluginConfig &plugin_config) : device_(0), context_(nullptr), device_ordinal_(0), cc_major_(0), cc_minor_(0), plugin_config_(plugin_config) {} // See the corresponding StreamExecutor methods for method comments on the // following overrides. ~CUDAExecutor() override; port::Status Init(int device_ordinal, DeviceOptions device_options) override; bool GetKernel(const MultiKernelLoaderSpec &spec, KernelBase *kernel) override; bool Launch(Stream *stream, const ThreadDim &thread_dims, const BlockDim &block_dims, const KernelBase &k, const std::vector<KernelArg> &args) override; void *Allocate(uint64 size) override; void *AllocateSubBuffer(DeviceMemoryBase *mem, uint64 offset_bytes, uint64 size_bytes) override; void Deallocate(DeviceMemoryBase *mem) override; // CUDA allocation/registration functions are necessary because the driver // internally sets up buffers for DMA operations (and page locks them). // There's no external interface for us to otherwise control these DMA // settings. void *HostMemoryAllocate(uint64 size) override { return CUDADriver::HostAllocate(context_, size); } void HostMemoryDeallocate(void *location) override { return CUDADriver::HostDeallocate(context_, location); } bool HostMemoryRegister(void *location, uint64 size) override; bool HostMemoryUnregister(void *location) override; bool SynchronizeAllActivity() override; bool SynchronousMemZero(DeviceMemoryBase *location, uint64 size) override; bool SynchronousMemSet(DeviceMemoryBase *location, int value, uint64 size) override; bool SynchronousMemcpy(DeviceMemoryBase *gpu_dst, const void *host_src, uint64 size) override; bool SynchronousMemcpy(void *host_dst, const DeviceMemoryBase &gpu_src, uint64 size) override; bool SynchronousMemcpyDeviceToDevice(DeviceMemoryBase *gpu_dst, const DeviceMemoryBase &gpu_src, uint64 size) override; bool MemZero(Stream *stream, DeviceMemoryBase *location, uint64 size) override; bool Memset32(Stream *stream, DeviceMemoryBase *location, uint32 pattern, uint64 size) override; bool Memcpy(Stream *stream, void *host_dst, const DeviceMemoryBase &gpu_src, uint64 size) override; bool Memcpy(Stream *stream, DeviceMemoryBase *gpu_dst, const void *host_src, uint64 size) override; bool MemcpyDeviceToDevice(Stream *stream, DeviceMemoryBase *gpu_dst, const DeviceMemoryBase &gpu_src, uint64 size) override; bool HostCallback(Stream *stream, std::function<void()> callback) override; bool AllocateStream(Stream *stream) override; void DeallocateStream(Stream *stream) override; bool CreateStreamDependency(Stream *dependent, Stream *other) override; bool AllocateTimer(Timer *timer) override; void DeallocateTimer(Timer *timer) override; bool StartTimer(Stream *stream, Timer *timer) override; bool StopTimer(Stream *stream, Timer *timer) override; port::Status AllocateEvent(Event *event) override; port::Status DeallocateEvent(Event *event) override; port::Status RecordEvent(Stream *stream, Event *event) override; port::Status WaitForEvent(Stream *stream, Event *event) override; Event::Status PollForEventStatus(Event *event) override; bool BlockHostUntilDone(Stream *stream) override; int PlatformDeviceCount() override { return CUDADriver::GetDeviceCount(); } port::Status EnablePeerAccessTo(StreamExecutorInterface *other) override; bool CanEnablePeerAccessTo(StreamExecutorInterface *other) override; SharedMemoryConfig GetDeviceSharedMemoryConfig() override; port::Status SetDeviceSharedMemoryConfig(SharedMemoryConfig config) override; bool DeviceMemoryUsage(int64 *free, int64 *total) const override; // Search for the symbol and returns a device pointer and size. // Returns false if symbol does not exist. bool GetSymbol(const string& symbol_name, void **mem, size_t *bytes) override; DeviceDescription *PopulateDeviceDescription() const override; // Populates the block_dim_limit by querying the device driver API. If an // error occurs at any point while asking the driver for block dim limits, it // will be only partially populated as a result, and an error will be logged. bool FillBlockDimLimit(BlockDim *block_dim_limit) const; KernelArg DeviceMemoryToKernelArg( const DeviceMemoryBase &gpu_mem) const override; bool SupportsBlas() const override; blas::BlasSupport *CreateBlas() override; bool SupportsFft() const override; fft::FftSupport *CreateFft() override; bool SupportsRng() const override; rng::RngSupport *CreateRng() override; bool SupportsDnn() const override; dnn::DnnSupport *CreateDnn() override; std::unique_ptr<internal::EventInterface> CreateEventImplementation() override; std::unique_ptr<internal::KernelInterface> CreateKernelImplementation() override; std::unique_ptr<internal::StreamInterface> GetStreamImplementation() override; std::unique_ptr<internal::TimerInterface> GetTimerImplementation() override; void *CudaContextHack() override; CUcontext cuda_context(); private: // Attempts to find a more specific version of the file indicated by // filename by looking for compute-capability-specific suffixed versions; i.e. // looking for "foo.ptx" will check to see if "foo.ptx.cc30.ptx" is present if // we're on a compute capability 3.0 machine. bool FindOnDiskForComputeCapability(port::StringPiece filename, port::StringPiece canonical_suffix, string *found_filename) const; // Host callback landing routine invoked by CUDA. // data: User-provided callback provided to HostCallback() above, captured // as a std::function<void()>. Allocated/initialized inside // HostCallback() and owned and deleted by this call. static void InternalHostCallback(CUstream stream, CUresult status, void *data); // Collects metadata for the specified kernel. bool GetKernelMetadata(CUDAKernel *cuda_kernel, KernelMetadata *kernel_metadata); // Determines if the given kernel's occupancy could be improved by only // slightly reducing its register usage. If so, a message is emitted to the // INFO log. The warning threshold is controlled by the flag // register_occupancy_warning_threshold. void OccupancyCheck(const KernelBase &kernel, const ThreadDim &thread_dims, const BlockDim &block_dims); // Guards the on-disk-module mapping. mutex disk_modules_mu_; // Mapping from filename to CUmodule, if it was already retrieved. // Multiple CUfunctions are usually obtained from a single CUmodule so we // attempt to hit in this mapping first, before retrieving it. std::map<string, CUmodule> disk_modules_ GUARDED_BY(disk_modules_mu_); // Guards the in-memory-module mapping. mutex in_memory_modules_mu_; std::map<const char *, CUmodule> in_memory_modules_ GUARDED_BY(in_memory_modules_mu_); // Guards the launched kernel set. mutex launched_kernels_mu_; // Keeps track of the set of launched kernels. Currently used to suppress the // occupancy check on subsequent launches. std::set<CUfunction> launched_kernels_ GUARDED_BY(launched_kernels_mu_); // Handle for the CUDA device being operated on. Immutable // post-initialization. CUdevice device_; // Handle for session with the library/driver. Immutable post-initialization. CUcontext context_; // The device ordinal value that this executor was initialized with; recorded // for use in getting device metadata. Immutable post-initialization. int device_ordinal_; // The major verion of the compute capability for device_. int cc_major_; // The minor verion of the compute capability for device_. int cc_minor_; // The plugin configuration associated with this instance. PluginConfig plugin_config_; SE_DISALLOW_COPY_AND_ASSIGN(CUDAExecutor); }; } // namespace cuda } // namespace gputools } // namespace perftools #endif // TENSORFLOW_STREAM_EXECUTOR_CUDA_CUDA_GPU_EXECUTOR_H_
[ "xijun.lee@hotmail.com" ]
xijun.lee@hotmail.com
0fa6ca2df938a9b20ede4b36f50fac4508b03705
5f1828ff9a44a2c922080773df8bb24c0b79168a
/src/HexView/HexViewInternal.h
97eb3fcace4e193abda782d1dcd7ca8ef5ea4bbf
[ "MIT" ]
permissive
McNeight/x64lab.hexview64
84af13e400a25272ebeed56cad16b49f72cf7b33
414a167df992af428663c99a3c6571a9842edf73
refs/heads/master
2021-01-10T16:20:00.510994
2013-01-20T04:30:04
2013-01-20T04:30:04
52,145,026
0
0
null
null
null
null
UTF-8
C++
false
false
11,182
h
// // HexViewInternal.h // // www.catch22.net // // Copyright (C) 2012 James Brown // Please refer to the file LICENCE.TXT for copying permission // #ifndef HEXVIEW_INTERNAL_INCLUDED #define HEXVIEW_INTERNAL_INCLUDED #include "sequence.h" #undef HEXVIEW_64 //#define HEXVIEW_64 #ifdef HEXVIEW_64 //typedef UINT64 size_w; //#define SIZEW_BITS 64 #pragma warning(disable : 4244) #else //typedef UINT32 size_w; //#define SIZEW_BITS 32 #endif #include <uxtheme.h> #include "HexView.h" #define HV_MAX_COLS 64 //typedef sequence<BYTE> byte_seq; struct _HIGHLIGHT_LIST; // hex-hittest regions #define HVHT_NONE 0x00 #define HVHT_MAIN 0x01 //#define HVHT_ADDRESS (HVHT_MAIN | 0x02) //#define HVHT_HEXCOL (HVHT_MAIN | 0x04) //#define HVHT_ASCCOL (HVHT_MAIN | 0x08) #define HVHT_SELECTION 0x02 #define HVHT_RESIZE 0x10 #define HVHT_BOOKMARK 0x100 #define HVHT_BOOKCLOSE (HVHT_BOOKMARK | 0x200) #define HVHT_BOOKSIZE (HVHT_BOOKMARK | 0x400) #define HVHT_BOOKGRIP (HVHT_BOOKMARK | 0x800) #define HVHT_BOOKEDIT (HVHT_BOOKMARK | 0x1000) #define HVHT_BOOKEDIT1 (HVHT_BOOKEDIT | 0x2000) #define HVHT_BOOKEDIT2 (HVHT_BOOKEDIT | 0x4000) #define HVHT_BOOKEDIT3 (HVHT_BOOKEDIT | 0x8000) #define BOOKMARK_XOFFSET 30 #define BOOKMARK_GRIPWIDTH 10 class HexView; class HexSnapShot; typedef struct _BOOKNODE { _BOOKNODE() : prev(0), next(0) { memset(&bookmark, 0, sizeof(bookmark)); } BOOKMARK bookmark; _BOOKNODE *prev; _BOOKNODE *next; } BOOKNODE; enum SELMODE { SEL_NONE, SEL_NORMAL, SEL_MARGIN, SEL_DRAGDROP }; // HexEdit private clipboard formats #define CFSTR_HEX_DATALEN _T("HexDataLength") #define CFSTR_HEX_HWND _T("HexHWND") #define CFSTR_HEX_SNAPSHOTPTR _T("HexSnapshotPtr") //#define CF_PRI_RLE32 _T("RLE32HexBinary") // // Define our custom HexView class. Inherit from the IDropTarget interface // to enable this window to become an OLE drop-target // class HexView : public IDropTarget { friend class HexSnapShot; public: HexView(HWND hwnd);//, byte_seq *seq); ~HexView(); LRESULT WndProc(UINT msg, WPARAM wParam, LPARAM lParam); // // IDropTarget Interface // STDMETHODIMP QueryInterface (REFIID iid, void ** ppvObject); STDMETHODIMP_(ULONG) AddRef (void); STDMETHODIMP_(ULONG) Release (void); // IDropTarget implementation STDMETHODIMP DragEnter(IDataObject * pDataObject, DWORD grfKeyState, POINTL pt, DWORD * pdwEffect); STDMETHODIMP DragOver(DWORD grfKeyState, POINTL pt, DWORD * pdwEffect); STDMETHODIMP DragLeave(void); STDMETHODIMP Drop(IDataObject * pDataObject, DWORD grfKeyState, POINTL pt, DWORD * pdwEffect); BOOL SetCurSel(size_w selStart, size_w selEnd); // // // LRESULT OnPaint(); LRESULT OnNcPaint(HRGN hrgnUpdate); LRESULT OnSetFont(HFONT hFont); UINT HitTest(int x, int y, RECT *phirc = 0, BOOKNODE **pbn = 0); LRESULT OnRButtonDown(UINT nFlags, int x, int y); LRESULT OnLButtonDown(UINT nFlags, int x, int y); LRESULT OnLButtonDblClick(UINT nFlags, int x, int y); LRESULT OnLButtonUp(UINT nFlags, int x, int y); LRESULT OnContextMenu(HWND hwndParam, int x, int y); LRESULT OnMouseMove(UINT nFlags, int x, int y); LRESULT OnMouseWheel(int nDelta); LRESULT OnMouseActivate(HWND hwndTop, UINT nHitTest, UINT nMessage); LRESULT OnTimer(UINT_PTR Id); LRESULT OnSetFocus(); LRESULT OnKillFocus(); LRESULT OnSetCursor(WPARAM wParam, LPARAM lParam); LRESULT OnSize(UINT nFlags, int width, int height); LRESULT OnKeyDown(UINT nVirtualKey, UINT nRepeatCount, UINT nFlags); LRESULT OnChar(UINT nChar); LRESULT OnSetCurPos(size_w pos); LRESULT OnSetSelStart(size_w pos); LRESULT OnSetSelEnd(size_w pos); LRESULT OnSelectAll(); BOOL OnCopy(); BOOL OnCut(); BOOL OnPaste(); BOOL OnClear(); BOOL FindInit(BYTE *pattern, size_t length, BOOL searchback, BOOL matchcase); BOOL FindNext(size_w *result, UINT options); // internal int SearchBlock(BYTE *block, int start, int length, int *partial, bool matchcase = true); bool SearchCompile(BYTE *pat, size_t length); LRESULT QueryProgressNotify(UINT code, size_w pos, size_w len); LRESULT NotifyParent(UINT nNotifyCode, NMHDR *optional = 0); VOID FakeSize(); LRESULT OnHScroll(UINT nSBCode, UINT nPos); LRESULT OnVScroll(UINT nSBCode, UINT nPos); VOID OnLengthChange(size_w nNewLength); HMENU SetContextMenu(HMENU hMenu); VOID Scroll(int dx, int dy); HRGN ScrollRgn(int dx, int dy, bool fReturnUpdateRgn); VOID SetupScrollbars(); VOID RecalcPositions(); VOID UpdateResizeBarPos(); VOID UpdateMetrics(); HMENU CreateContextMenu(); int GetLogicalX(int nScreenX, int *pane); int GetLogicalY(int nScreenY); void PositionCaret(int x, int y, int pane); int LogToPhyXCoord(int x, int pane); void CaretPosFromOffset(size_w offset, int *x, int *y); size_w OffsetFromPhysCoord(int x, int y, int *pane = 0, int *lx = 0, int *ly = 0); void RepositionCaret(); VOID ScrollToCaret(); BOOL ScrollTo(size_w offset); BOOL ScrollTop(size_w offset); bool PinToBottomCorner(); bool Undo(); bool Redo(); bool CanUndo(); bool CanRedo(); // // // VOID InvalidateRange(size_w start, size_w finish); void RefreshWindow(); int PaintLine(HDC hdc, size_w nLineNo, BYTE *data, size_t datalen, seqchar_info *bufinfo); size_t FormatAddress(size_w addr, TCHAR *buf, size_t buflen); size_t FormatHexUnit(BYTE *data, TCHAR *buf, size_t buflen); size_t FormatLine(BYTE *data, size_t length, size_w offset, TCHAR *buf, size_t buflen, ATTR *attrList, seqchar_info *infobuf, bool fIncSelection); size_t FormatData(HEXFMT_PARAMS *fmtParams); VOID IdentifySearchPatterns(BYTE *data, size_t len, seqchar_info *infobuf); LONG Highlight(BOOL fEnable); BOOL GetHighlightCol(size_w offset, int pane, BOOKNODE * itemStart, HEXCOL *col1, HEXCOL *col2, bool fModified, bool fMatched, bool fIncSelection = true); BOOKNODE * AddBookmark(BOOKMARK * bookm); BOOL DelBookmark(BOOKNODE *); BOOL BookmarkRect(BOOKMARK *bm, RECT *rect); BOOL GetBookmark(BOOKNODE *, BOOKMARK *param); BOOKNODE * EnumBookmark(BOOKNODE *, BOOKMARK *param); BOOL SetBookmark(BOOKNODE *, BOOKMARK *param); BOOL ClearBookmarks(); BOOKNODE * FindBookmark(size_w startoff, size_w endoff); void DrawNoteStrip(HDC hdc, int nx, int ny, BOOKNODE *pbn); static LRESULT CALLBACK EditProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); WNDPROC m_oldEditProc; BOOL EditBookmark(BOOKNODE *pbn, RECT *rect, bool fTitle); BOOL ExitBookmark(); BOOL SetHexColour(UINT uIndex, COLORREF col); COLORREF GetHexColour(UINT uIndex); COLORREF RealiseColour(COLORREF cr); bool CheckStyle(UINT uStyleFlag); UINT SetStyle(UINT uMask, UINT uStyles); UINT GetStyle(UINT uMask); UINT GetStyleMask(UINT uStyleFlag); UINT SetGrouping(UINT nBytes); UINT GetGrouping(); UINT GetLineLen(); UINT SetLineLen(UINT nLineLen); BOOL SetPadding(int left, int right); size_w NumFileLines(size_w length); bool IsOverResizeBar(int x); int UnitWidth(); size_w SelectionSize(); size_w SelectionStart(); size_w SelectionEnd(); size_w Size(); size_w EnterData(BYTE *pDest, size_w nLength, bool fAdvanceCaret, bool fReplaceSelection, bool fSelectData, HexSnapShot *hss = 0); ULONG SetData(size_w offset, BYTE *buf, ULONG nLength); ULONG GetData(size_w offset, BYTE *pBuf, ULONG nLength); ULONG FillData(BYTE *buf, ULONG buflen, size_w len); bool ForwardDelete(); bool BackDelete(); void ContentChanged(size_w offset, size_w length, UINT method); //size_w nStartOffset, size_w nLength BOOL OpenFile(LPCTSTR szFileName, UINT uMethod); BOOL SaveFile(LPCTSTR szFileName, UINT uMethod); BOOL ImportFile(LPCTSTR szFileName, UINT uMethod); BOOL InitBuf(const BYTE *pBuffer, size_t nLength, bool copybuf, bool readonly); BOOL CloseFile(); BOOL ClearFile(); BOOL RevertFile(); BOOL SetRedraw(BOOL fRedraw); private: // // private helper functions // DWORD DropEffect(DWORD grfKeyState, POINTL pt, DWORD dwAllowed); bool QueryDataObject(IDataObject *pDataObject); void RegisterDropWindow(); void UnregisterDropWindow(); bool DropData(IDataObject *pDataObject, bool fReplaceSelection, bool fSelectData); void StartDrag(); bool CreateDataObject (size_w offset, size_w length, IDataObject **ppDataObject); HGLOBAL BuildHGlobal(size_w offset, size_w length); HexSnapShot *CreateSnapshot(size_w offset, size_w length); VOID ClipboardShutdown(); int CalcTotalWidth(); BOOL SetFontSpacing(int x, int y); HWND m_hWnd; HWND m_hwndEdit; HTHEME m_hTheme; TCHAR m_szFilePath[MAX_PATH]; //byte_seq *m_sequence; sequence *m_pDataSeq; UINT m_nControlStyles; // cursor size_w m_nCursorOffset; int m_nCaretX; int m_nCaretY; int m_nWhichPane; size_w m_nAddressOffset; //size_w m_nFileLength; size_w m_nSelectionStart; size_w m_nSelectionEnd; // Font specific HFONT m_hFont; int m_nFontHeight; int m_nFontWidth; // View dimensions int m_nWindowLines; int m_nWindowColumns; int m_nBytesPerLine; int m_nBytesPerColumn; // Scrollbar dimensions size_w m_nVScrollPos; size_w m_nVScrollMax; int m_nHScrollPos; int m_nHScrollMax; // Drag+Drop support long m_lRefCount; bool m_fAllowDrop; bool m_fStartDrag; bool m_fDigDragDrop; // int m_nAddressWidth; int m_nHexWidth; int m_nAddressDigits; int m_nHexPaddingLeft; int m_nHexPaddingRight; int m_nTotalWidth; int m_nResizeBarPos; BOOKNODE * m_BookHead; BOOKNODE * m_BookTail; // hexview base colours COLORREF m_ColourList[HV_MAX_COLS]; // // runtime flags // //BOOL m_fMouseDown; bool m_fRedrawChanges; SELMODE m_nSelectionMode; UINT_PTR m_nScrollTimer; LONG m_nScrollCounter; BOOL m_fCursorAdjustment; bool m_fResizeBar; UINT m_nEditMode; int m_nSubItem; HMENU m_hUserMenu; BOOKNODE *m_HighlightCurrent; UINT m_HitTestCurrent; BOOKNODE *m_HighlightHot; UINT m_HitTestHot; BOOKNODE m_HighlightGhost; IDataObject * m_pLastDataObject; BYTE m_pSearchPat[64]; ULONG m_nSearchLen; }; class HexSnapShot : public IUnknown { friend class HexView; public: HexSnapShot(HexView *hvp) { m_lRefCount = 1; m_pHexView = hvp; } ~HexSnapShot() { delete[] m_desclist; } HRESULT __stdcall QueryInterface(REFIID iid, void ** ppvObject) { if(iid == IID_IUnknown) { AddRef(); *ppvObject = this; return S_OK; } else { return E_NOINTERFACE; } } ULONG __stdcall AddRef(void) { return InterlockedIncrement(&m_lRefCount); } ULONG __stdcall Release(void) { LONG count = InterlockedDecrement(&m_lRefCount); if(count == 0) delete this; return count; } size_w Render(size_w offset, BYTE *buffer, size_w length) { return m_pHexView->m_pDataSeq->rendersnapshot(m_count, m_desclist, offset, buffer, (size_t)length); } HGLOBAL RenderAsHGlobal() { BYTE *bptr; // allocate space for the buffer, +1 for string-terminator if((bptr = (BYTE *)GlobalAlloc(GPTR, (DWORD)(m_length+1))) == 0) return 0; // render data and null-terminate Render(0, bptr, m_length); bptr[m_length] = 0; return bptr; } private: LONG m_lRefCount; HexView * m_pHexView; size_t m_count; size_w m_length; sequence::span_desc * m_desclist; }; #endif
[ "mrk@localhost" ]
mrk@localhost
d1f5e2c69018d9bf7b776aa1a923369b4b417a35
c17deea16a9dfa619967c5f5a98da3b9b87b6d65
/codesignal/math/depositProfit.cpp
f802c0d136370cff28f20a18386a1b93fc4cb5f6
[ "Apache-2.0" ]
permissive
peterlamar/cpp-cp-cheatsheet
ed00c44a3a257cfbe7f2933b493dcb03c4436634
23af2e893992141572005de7a438c3a2d376547e
refs/heads/main
2023-09-01T17:40:12.507633
2021-10-14T11:32:58
2021-10-14T11:32:58
405,108,923
1
0
null
null
null
null
UTF-8
C++
false
false
849
cpp
/* https://www.math.unl.edu/~tlai3/M119-Section16.pdf For deposit = 100, rate = 20, and threshold = 170, the output should be depositProfit(deposit, rate, threshold) = 3. Each year the amount of money in your account increases by 20%. So throughout the years, your balance would be: year 0: 100; year 1: 120; year 2: 144; year 3: 172.8 R = Threshold D = Deposit r = Rate t = time D(1+r)^t = R (1+r)^t = R/D t*ln(1+r)=ln(R/C) t = ln(R/C)/ln(1+r) */ int depositProfit(int deposit, int rate, int threshold) { return ceil(log(double(threshold) / double(deposit))/log(1 + double(rate)/100.0)); } int depositProfit(int deposit, int rate, int threshold) { int cnt = 0; float fdeposit = float(deposit); while (fdeposit < float(threshold)){ fdeposit = fdeposit * (1+float(rate)/100.0); cnt += 1; } return cnt; }
[ "peterrlamar@gmail.com" ]
peterrlamar@gmail.com
03c6532cfe2ec6f65e2503c2f5ad79142088c65b
b9888a50289f77a05a7707de42eac3aaae97008b
/-std=c++98/Creature.h
1d96492b1a5b4fac4ce492acace14d32b40dc4aa
[]
no_license
Serfati/Heroes-of-Might-and-Magic-3
a8b03a499a221d43be3bad647c6966797e17f841
3a7577c3cf08e69c6c61ba9ea129b6ca9556939c
refs/heads/master
2020-04-13T09:37:48.291482
2019-06-25T06:57:21
2019-06-25T06:57:21
163,116,270
4
0
null
null
null
null
UTF-8
C++
false
false
1,181
h
/* * Creature.h * * Created on: Dec 24, 2018 * Author: serfati */ #pragma once #ifndef CREATURE_H_ #define CREATURE_H_ #include <iostream> #include <string> #include <vector> using namespace std; enum CreatureType { zombie, archer, vampire, wizard, blackDragon, Unknown }; class Creature { public: //^^^^^^^^^^ Constructors and Destructor ^^^^^^^^^^// Creature(); Creature(Creature &another); Creature(int,int,int,CreatureType); virtual ~Creature() {} //^^^^^^^^^^^^^^^^^^ GAME LOGIC ^^^^^^^^^^^^^^^^^^// virtual double attackAnother(Creature &c); virtual void specialAbility(Creature &c); void showCreature(); virtual void reset() {}; //^^^^^^^^^^^^^^Getters and Setters^^^^^^^^^^^^^^// virtual CreatureType getType() { return cType; } string creaType(int type); int creaTypeByName(string vtype); int getPrice(); virtual int getAttackPoints() const { return attackPoints; } virtual int getDefendPoints() const { return defendPoints; } protected: int attackPoints; int defendPoints; int cost; CreatureType cType; }; #endif /* CREATURE_H_ */
[ "noreply@github.com" ]
noreply@github.com
9ed4cb349577375a0eacc6fda07c10b19c57645f
595bfb90e16ec67363fbcab836ea301fca46ff46
/Win32Project1/Win32Project1/Win32Project1.cpp
742653452729fcd89ed16306f664cc82ca89571b
[]
no_license
Arishoked/OSISP
cc087ebad7565d9324ac948969c6aef12f81eac4
0a513760b41b4e6bb174d446ed7e163001554073
refs/heads/master
2021-01-22T09:09:17.252438
2014-10-07T13:45:30
2014-10-07T13:45:30
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
20,156
cpp
#include "stdafx.h" #include <windows.h> #include <CommDlg.h> #include <stdio.h> #include <string> #include "Win32Project1.h" using namespace std; #define MAX_LOADSTRING 100 #define ID_BUTTONTEXT 1 #define ID_BUTTONPEN 2 #define ID_BUTTONLINE 3 // Глобальные переменные: HINSTANCE hInst; // текущий экземпляр TCHAR szTitle[MAX_LOADSTRING]; // Текст строки заголовка TCHAR szWindowClass[MAX_LOADSTRING]; // имя класса главного окна // Отправить объявления функций, включенных в этот модуль кода: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: разместите код здесь. MSG msg; HACCEL hAccelTable; // Инициализация глобальных строк LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_WIN32PROJECT1, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Выполнить инициализацию приложения: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WIN32PROJECT1)); // Цикл основного сообщения: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } // // ФУНКЦИЯ: MyRegisterClass() // // НАЗНАЧЕНИЕ: регистрирует класс окна. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WIN32PROJECT1)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_WIN32PROJECT1); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // // ФУНКЦИЯ: InitInstance(HINSTANCE, int) // // НАЗНАЧЕНИЕ: сохраняет обработку экземпляра и создает главное окно. // // КОММЕНТАРИИ: // // В данной функции дескриптор экземпляра сохраняется в глобальной переменной, а также // создается и выводится на экран главное окно программы. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // Сохранить дескриптор экземпляра в глобальной переменной hWnd = CreateWindow(szWindowClass, "Graphics Editor", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } HBITMAP hBitmap; HBITMAP bitmaps[5]; HBITMAP PrevBitmap; int status=3; int curBitmap=-1; bool Move=false,Cancel=false,Start=true; void CrBitmap(HDC hdc,RECT rect) { int i; HDC hdcMem = CreateCompatibleDC(hdc); HBITMAP hBitmap = CreateCompatibleBitmap(hdc, rect.right, rect.bottom); HANDLE oldBitmap = SelectObject(hdcMem, hBitmap); FillRect(hdcMem,&rect,WHITE_BRUSH); BitBlt(hdcMem, 0, 0, rect.right, rect.bottom, hdc, 0, 0, SRCCOPY); PrevBitmap=bitmaps[0]; if(curBitmap<4) { curBitmap++; bitmaps[curBitmap] = hBitmap; } else { for(i=0;i<4;i++) { bitmaps[i]=bitmaps[i+1]; } bitmaps[4] = hBitmap; } SelectObject(hdcMem, oldBitmap); DeleteObject(oldBitmap); DeleteDC(hdcMem); } void LdBitmap(HDC hdc,HWND hWnd,RECT rect) { HDC hdcMem = CreateCompatibleDC(hdc); if(Cancel) { if(curBitmap>0) { curBitmap--; } else bitmaps[0]=PrevBitmap; } hBitmap = bitmaps[curBitmap]; HGDIOBJ oldBitmap = SelectObject(hdcMem, hBitmap); BITMAP bitmap; GetObject(hBitmap,sizeof(bitmap),&bitmap); BitBlt(hdc, 0, 0, rect.right, rect.bottom, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, oldBitmap); DeleteDC(hdcMem); } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC static hdc,hdc1,hdc2; HDC static hdcFile; POINT static StartPoint,EndPoint,PrevPoint,StartPolylinePoint,PrevPolylinePoint,TextPoint; RECT static rect; BOOL static bText=false,bTextStart=false; BOOL static bPolyline=false; BOOL static bStartPolyline=false; int static Width=1; HMENU static MainMenu = CreateMenu(); HMENU static SubMenuDraw = CreateMenu(); HMENU static SubMenuAction = CreateMenu(); HMENU static SubMenuFile = CreateMenu(); HMENU static SubMenuColor = CreateMenu(); HMENU static SubMenuWidth = CreateMenu(); HDC static hdcMem,CompabitibleDC; HBITMAP static hBitmap,CompabitibleBitmap; HGDIOBJ static oldBitmap,oldBitmap1,oldPen,oldPen1; HPEN static hPen=(PS_SOLID, 1, RGB(0,0,0)); HBRUSH static hBrush; POINT static PointsPolygon[20]; int static PointsCount=0; COLORREF static crCustColor[16]; CHOOSECOLOR static ccPen,ccBrush; OPENFILENAME static ofn; char static fullpath[256],filename[256],dir[256]; HENHMETAFILE static hEnhMtf; ENHMETAHEADER static emh; PRINTDLG static pd; BOOL static bZoom; double static Delta,Scale; HANDLE static hFile; string static Text; DOCINFO di; switch (message) { case WM_CREATE: ShowWindow(hWnd,SW_SHOWMAXIMIZED); hdc=GetDC(hWnd); AppendMenu(MainMenu,MF_POPUP,(UINT_PTR)SubMenuFile,"File"); AppendMenu(MainMenu,MF_POPUP,(UINT_PTR)SubMenuDraw,"Draw"); AppendMenu(MainMenu,MF_POPUP,(UINT_PTR)SubMenuAction,"Action"); AppendMenu(MainMenu,MF_POPUP,(UINT_PTR)SubMenuColor,"Color"); AppendMenu(MainMenu,MF_POPUP,(UINT_PTR)SubMenuWidth,"Width"); AppendMenu(SubMenuDraw, MF_STRING, 3, "Pen"); AppendMenu(SubMenuDraw, MF_STRING, 4, "Line"); AppendMenu(SubMenuDraw, MF_STRING, 5, "Triangle"); AppendMenu(SubMenuDraw, MF_STRING, 6, "Rectangle"); AppendMenu(SubMenuDraw, MF_STRING, 7, "Ellipse"); AppendMenu(SubMenuDraw, MF_STRING, 8, "Polyline"); AppendMenu(SubMenuDraw, MF_STRING, 9, "Polygon"); AppendMenu(SubMenuDraw, MF_STRING, 2, "Eraser"); AppendMenu(SubMenuDraw, MF_STRING, 1, "Text"); AppendMenu(SubMenuFile, MF_STRING, 13, "New"); AppendMenu(SubMenuFile, MF_STRING, 11, "Open"); AppendMenu(SubMenuFile, MF_STRING, 10, "Save"); AppendMenu(SubMenuFile, MF_STRING, 14, "Print"); AppendMenu(SubMenuFile, MF_STRING, 12, "Exit"); AppendMenu(SubMenuAction, MF_STRING, 20, "Pan"); AppendMenu(SubMenuAction, MF_STRING, 21, "Zoom"); AppendMenu(SubMenuColor, MF_STRING, 30, "PenColor"); AppendMenu(SubMenuColor, MF_STRING, 32, "TransparentFill"); AppendMenu(SubMenuColor, MF_STRING, 31, "FillColor"); AppendMenu(SubMenuWidth, MF_STRING, 41, "1"); AppendMenu(SubMenuWidth, MF_STRING, 42, "2"); AppendMenu(SubMenuWidth, MF_STRING, 43, "3"); AppendMenu(SubMenuWidth, MF_STRING, 44, "4"); AppendMenu(SubMenuWidth, MF_STRING, 45, "5"); SetMenu(hWnd, MainMenu); break; case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Разобрать выбор в меню: if(wParam>1 && wParam<10 || wParam==20) status=wParam; if(wParam==1) { bText=true; bTextStart=false; Text=""; } else { bText=false; } if(status==8 || status==9) bPolyline=true; else { bPolyline=false; if(bStartPolyline) { bStartPolyline=false; CrBitmap(hdc,rect); SelectObject(CompabitibleDC, oldBitmap1); DeleteObject(CompabitibleBitmap); DeleteDC(CompabitibleDC); PointsCount=0; } } if(wParam==30) { ccPen.lStructSize = sizeof(CHOOSECOLOR); ccPen.hInstance = NULL; ccPen.hwndOwner = hWnd; ccPen.lpCustColors = crCustColor; ccPen.Flags = CC_RGBINIT|CC_FULLOPEN; ccPen.lCustData = 0L; ccPen.lpfnHook = NULL; ccPen.rgbResult = RGB(0x80, 0x80, 0x80); ccPen.lpTemplateName = NULL; InvalidateRect(hWnd,NULL,TRUE); UpdateWindow(hWnd); if(ChooseColor(&ccPen)) { DeleteObject(hPen); hPen=CreatePen(PS_SOLID, Width, ccPen.rgbResult); //DeleteObject(SelectObject(hdc,hPen)); } } if(wParam==31) { ccBrush.lStructSize = sizeof(CHOOSECOLOR); ccBrush.hInstance = NULL; ccBrush.hwndOwner = hWnd; ccBrush.lpCustColors = crCustColor; ccBrush.Flags = CC_RGBINIT|CC_FULLOPEN; ccBrush.lCustData = 0L; ccBrush.lpfnHook = NULL; ccBrush.rgbResult = RGB(0x80, 0x80, 0x80); ccBrush.lpTemplateName = NULL; InvalidateRect(hWnd,NULL,TRUE); UpdateWindow(hWnd); if(ChooseColor(&ccBrush)) { DeleteObject(hBrush); hBrush=CreateSolidBrush(ccBrush.rgbResult); } } if(wParam==32) { DeleteObject(hBrush); hBrush=(HBRUSH)GetStockObject(NULL_BRUSH); } if(wParam>40 && wParam<46) { Width=wParam-40;; DeleteObject(hPen); hPen=CreatePen(PS_SOLID, Width, ccPen.rgbResult); DeleteObject(SelectObject(hdc,hPen)); } if(wParam==10) { ofn.lStructSize=sizeof(OPENFILENAME); ofn.hwndOwner=hWnd; ofn.hInstance=hInst; ofn.lpstrFilter="Metafile (*.emf)\0*.emf\0Все файлы (*.*)\0*.*\0"; ofn.nFilterIndex=1; ofn.lpstrFile=fullpath; ofn.nMaxFile=sizeof(fullpath); ofn.lpstrFileTitle=filename; ofn.nMaxFileTitle=sizeof(filename); ofn.lpstrInitialDir=dir; ofn.lpstrTitle="Save file as..."; ofn.Flags=OFN_PATHMUSTEXIST|OFN_OVERWRITEPROMPT|OFN_HIDEREADONLY|OFN_EXPLORER; if(GetSaveFileName(&ofn)) { hdcFile=CreateEnhMetaFile(NULL,filename,NULL,NULL); BitBlt(hdcFile,0,0,rect.right,rect.bottom,hdc,0,0,SRCCOPY); hEnhMtf=CloseEnhMetaFile(hdcFile); DeleteEnhMetaFile(hEnhMtf); } } if(wParam==11) { ofn.lStructSize=sizeof(OPENFILENAME); ofn.hwndOwner=hWnd; ofn.hInstance=hInst; ofn.lpstrFilter="Metafile (*.emf)\0*.emf\0Все файлы (*.*)\0*.*\0"; ofn.nFilterIndex=1; ofn.lpstrFile=fullpath; ofn.nMaxFile=sizeof(fullpath); ofn.lpstrFileTitle=filename; ofn.nMaxFileTitle=sizeof(filename); ofn.lpstrInitialDir=dir; ofn.lpstrTitle="Open file..."; ofn.Flags=OFN_EXPLORER|OFN_CREATEPROMPT|OFN_ALLOWMULTISELECT; if(GetOpenFileName(&ofn)) { hEnhMtf=GetEnhMetaFile(fullpath); GetEnhMetaFileHeader(hEnhMtf,sizeof(ENHMETAHEADER),&emh); SetRect(&rect,emh.rclBounds.left,emh.rclBounds.top,emh.rclBounds.right,emh.rclBounds.bottom); //SetWindowPos(hWnd,HWND_TOP,0,0,rect.right,rect.bottom,SWP_NOMOVE); PlayEnhMetaFile(hdc,hEnhMtf,&rect); CrBitmap(hdc,rect); DeleteEnhMetaFile(hEnhMtf); } } if(wParam==12) PostQuitMessage(0); if(wParam==13) { FillRect(hdc,&rect,WHITE_BRUSH); } if(wParam==14) { ZeroMemory(&pd, sizeof(pd)); pd.lStructSize = sizeof(pd); pd.hwndOwner = hWnd; pd.hDevMode = NULL; // Не забудьте освободить или сохранить hDevMode pd.hDevNames = NULL; // Не забудьте освободить или сохранить hDevNames pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC; pd.nCopies = 1; pd.nFromPage = 0xFFFF; pd.nToPage = 0xFFFF; pd.nMinPage = 1; pd.nMaxPage = 0xFFFF; if (PrintDlg(&pd)==TRUE) { int Rx = GetDeviceCaps(pd.hDC, LOGPIXELSX); int Ry = GetDeviceCaps(pd.hDC, LOGPIXELSY); di.cbSize=sizeof(DOCINFO); di.lpszDocName="Print Picture"; di.fwType=NULL; di.lpszDatatype=NULL; di.lpszOutput=NULL; StartDoc(pd.hDC,&di); StartPage(pd.hDC); GetClientRect(hWnd,&rect); int Rx1 = GetDeviceCaps(hdc, LOGPIXELSX); int Ry1 = GetDeviceCaps(hdc, LOGPIXELSY); StretchBlt(pd.hDC, 0, 0,(int)((float)(0.91*rect.right*Rx/Rx1)), (int)((float)(0.91*rect.bottom*Ry/Ry1)), hdc, 0, 0, rect.right, rect.bottom, SRCCOPY); EndPage(pd.hDC); EndDoc(pd.hDC); DeleteDC(pd.hDC); } } if(wParam==21) { bZoom=true; Scale=1; } switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_MOUSEWHEEL: if(bZoom) { GetClientRect(hWnd,&rect); CompabitibleDC = CreateCompatibleDC(hdc); CompabitibleBitmap = CreateCompatibleBitmap(hdc,rect.right,rect.bottom); oldBitmap1 = SelectObject(CompabitibleDC, CompabitibleBitmap); FillRect(CompabitibleDC,&rect,WHITE_BRUSH); LdBitmap(CompabitibleDC,hWnd,rect); Delta = GET_WHEEL_DELTA_WPARAM(wParam); if(Delta>0)Scale=Scale+0.03; if(Delta<0) Scale=Scale-0.03; FillRect(hdc,&rect,WHITE_BRUSH); StretchBlt(hdc,0,0,rect.right*Scale,rect.bottom*Scale,CompabitibleDC,0,0,rect.right,rect.bottom,SRCCOPY); SelectObject(CompabitibleDC, oldBitmap1); DeleteObject(CompabitibleBitmap); DeleteDC(CompabitibleDC); } break; case WM_LBUTTONDOWN: if(bZoom) { bZoom=false; LdBitmap(hdc,hWnd,rect); } if(bText) if(!bTextStart) { TextPoint.x=LOWORD(lParam); TextPoint.y=HIWORD(lParam); bTextStart=true; } StartPoint.x=LOWORD(lParam); StartPoint.y=HIWORD(lParam); if(bStartPolyline) { MoveToEx(hdc,PrevPolylinePoint.x,PrevPolylinePoint.y,NULL); LineTo(hdc,StartPoint.x,StartPoint.y); } if(!bStartPolyline) { CompabitibleDC = CreateCompatibleDC(hdc); CompabitibleBitmap = CreateCompatibleBitmap(hdc,rect.right,rect.bottom); oldBitmap1 = SelectObject(CompabitibleDC, CompabitibleBitmap); FillRect(CompabitibleDC,&rect,WHITE_BRUSH); BitBlt(CompabitibleDC,0,0,rect.right-5,rect.bottom-5,hdc,0,0,SRCCOPY); } Move=true; if(bPolyline) { PointsPolygon[PointsCount].x=StartPoint.x; PointsPolygon[PointsCount].y=StartPoint.y; PointsCount++; bStartPolyline=true; bPolyline=false; StartPolylinePoint.x=LOWORD(lParam); StartPolylinePoint.y=HIWORD(lParam); PrevPolylinePoint.x=LOWORD(lParam); PrevPolylinePoint.y=HIWORD(lParam); } break; case WM_RBUTTONDOWN: if(bStartPolyline) { bStartPolyline=false; bPolyline=true; if(status==9) { HPEN hPen1=CreatePen(PS_SOLID, Width, ccPen.rgbResult); HANDLE oldPen=SelectObject(CompabitibleDC,hPen1); SelectObject(CompabitibleDC,hBrush); Polygon(CompabitibleDC,PointsPolygon,PointsCount); DeleteObject(oldPen); } PointsCount=0; BitBlt(hdc,0,0,rect.right,rect.bottom,CompabitibleDC,0,0,SRCCOPY); CrBitmap(hdc,rect); SelectObject(CompabitibleDC, oldBitmap1); DeleteObject(CompabitibleBitmap); DeleteDC(CompabitibleDC); } break; case WM_LBUTTONUP: Move=false; if(!bStartPolyline && !bTextStart) { CrBitmap(hdc,rect); SelectObject(CompabitibleDC, oldBitmap1); DeleteObject(CompabitibleBitmap); DeleteDC(CompabitibleDC); } else { HPEN hPen1=CreatePen(PS_SOLID, Width, ccPen.rgbResult); HANDLE oldPen=SelectObject(CompabitibleDC,hPen1); SelectObject(CompabitibleDC,hBrush); MoveToEx(CompabitibleDC,PrevPolylinePoint.x,PrevPolylinePoint.y,NULL); LineTo(CompabitibleDC,EndPoint.x,EndPoint.y); PrevPolylinePoint=EndPoint; PointsPolygon[PointsCount].x=EndPoint.x; PointsPolygon[PointsCount].y=EndPoint.y; PointsCount++; DeleteObject(oldPen); } break; case WM_KEYDOWN: if ((GetAsyncKeyState(VK_CONTROL)) && (GetAsyncKeyState(0x5A))) { Cancel = true; InvalidateRect(hWnd,NULL,TRUE); UpdateWindow(hWnd); } break; case WM_CHAR: if(bText) { char c=(char)wParam; if(c==VK_RETURN) { bText=false; bTextStart=false; CrBitmap(hdc,rect); } else if(c==VK_BACK) Text.pop_back(); else Text+=c; LdBitmap(hdc,hWnd,rect); TextOut(hdc,TextPoint.x,TextPoint.y,Text.c_str(),strlen(Text.c_str())); } break; case WM_MOUSEMOVE: EndPoint.x=LOWORD(lParam); EndPoint.y=HIWORD(lParam); GetClientRect(hWnd,&rect); if(Move && !bTextStart) { if(status==2) { DeleteObject(hPen); hPen=CreatePen(PS_SOLID,15,RGB(255,255,255)); HANDLE oldPen=SelectObject(hdc,hPen); MoveToEx(hdc,PrevPoint.x,PrevPoint.y,NULL); LineTo(hdc,EndPoint.x,EndPoint.y); DeleteObject(oldPen); DeleteObject(hPen); hPen=CreatePen(PS_SOLID, Width, ccPen.rgbResult); DeleteObject(SelectObject(hdc,hPen)); } if(status==3) { HANDLE oldPen=SelectObject(hdc,hPen); MoveToEx(hdc,PrevPoint.x,PrevPoint.y,NULL); LineTo(hdc,EndPoint.x,EndPoint.y); DeleteObject(oldPen); } if(status>3 && status<10) { hdcMem = CreateCompatibleDC(hdc); hBitmap = CreateCompatibleBitmap(hdc,rect.right,rect.bottom); oldBitmap = SelectObject(hdcMem, hBitmap); FillRect(hdcMem,&rect,hBrush); DeleteObject(SelectObject(hdcMem,hPen)); DeleteObject(SelectObject(hdcMem,hBrush)); BitBlt(hdcMem, 0, 0, rect.right, rect.bottom, CompabitibleDC, 0, 0, SRCCOPY); } switch(status) { case 4: MoveToEx(hdcMem,StartPoint.x,StartPoint.y,NULL); LineTo(hdcMem,EndPoint.x,EndPoint.y); break; case 5: POINT Points[3]; Points[1].x=StartPoint.x-(StartPoint.x-EndPoint.x); Points[1].y=StartPoint.y; Points[2].x=StartPoint.x-(StartPoint.x-EndPoint.x)/2; Points[2].y=StartPoint.y-(StartPoint.y-EndPoint.y); Points[0].x=StartPoint.x; Points[0].y=StartPoint.y; Polygon(hdcMem,Points,3); break; case 6: Rectangle(hdcMem,StartPoint.x-(StartPoint.x-EndPoint.x),StartPoint.y,StartPoint.x,StartPoint.y-(StartPoint.y-EndPoint.y)); break; case 7: Ellipse(hdcMem,StartPoint.x,StartPoint.y,StartPoint.x-(StartPoint.x-EndPoint.x),StartPoint.y-(StartPoint.y-EndPoint.y)); break; case 8: MoveToEx(hdcMem,PrevPolylinePoint.x,PrevPolylinePoint.y,NULL); LineTo(hdcMem,EndPoint.x,EndPoint.y); break; case 9: MoveToEx(hdcMem,PrevPolylinePoint.x,PrevPolylinePoint.y,NULL); LineTo(hdcMem,EndPoint.x,EndPoint.y); break; case 20: BitBlt(hdc,EndPoint.x-StartPoint.x, EndPoint.y-StartPoint.y, rect.right-1, rect.bottom, CompabitibleDC, 0, 0, SRCCOPY); break; default: break; } if(status>3 && status<10) { BitBlt(hdc, 0, 0, rect.right, rect.bottom, hdcMem, 0, 0, SRCCOPY); SelectObject(hdcMem, oldBitmap); DeleteObject(hBitmap); DeleteDC(hdcMem); } } PrevPoint=EndPoint; //SetCapture(hWnd); break; case WM_PAINT: hdc1 = BeginPaint(hWnd, &ps); // TODO: добавьте любой код отрисовки... LdBitmap(hdc1, hWnd,rect); Cancel=false; EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Обработчик сообщений для окна "О программе". INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
[ "sergey,yermakovich@gmail.com" ]
sergey,yermakovich@gmail.com
bb493b987f1af1b39c8cafcf63426f3030f44d68
749d58e176968d14eba768d4fdb2a0721cd36d8d
/saturation.cpp
25cee3f72238f2b336a74d705dc937c99b69790c
[ "BSD-2-Clause" ]
permissive
hn-88/SoftwareLockin
aa55186c0b58afe957c87dcf4b82970f8a7baa76
1aa76265cb77e62ee09420fb94028dc7787eaed3
refs/heads/master
2020-03-07T04:11:40.729258
2018-04-18T11:03:53
2018-04-18T11:03:53
127,259,039
0
0
null
null
null
null
UTF-8
C++
false
false
5,367
cpp
/* -------------------------------------------------------------------------- PCSC-Lockin Copyright (c) 2011, EPFL LESO-PB, research group nanotechnology for solar energy conversion, Mario Geiger André Kostro Andreas Schüler 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. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by Mario Geiger, André Kostro and Andreas Schüler in LESO-PB lab, research group nanotechnology for solar energy conversion, at EPFL. 4. Neither the name of the EPFL LESO-PB 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 EPFL LESO-PB ''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 EPFL LESO-PB 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. DESCRIPTION: ---------------------------------------------------------------------------- */ #include "saturation.h" Saturation::Saturation(MStreamReader<float> *input, int bufferSize, QObject *parent) : QThread(parent), enabled(true), input(input), bufferSize(bufferSize) { currentRange = -1; autogain = false; if (bufferSize != 0) buffer = new float[bufferSize]; else buffer = 0; timer = new QTimer(this); timer->setSingleShot(true); connect(timer, SIGNAL(timeout()), this, SLOT(sendFactor())); } Saturation::~Saturation() { stop(); wait(2000); } void Saturation::setBufferSize(int newBufferSize) { mutex.lock(); if (bufferSize != 0 && newBufferSize != 0) { delete[] buffer; buffer = 0; bufferSize = 0; } if (newBufferSize != 0) { buffer = new float[newBufferSize]; bufferSize = newBufferSize; } mutex.unlock(); } void Saturation::setAutoRange(bool enable) { autogain = enable; } void Saturation::setRanges(QList<struct Range> list) { mutex.lock(); ranges = list; currentRange = -1; mutex.unlock(); } QList<struct Saturation::Range> Saturation::getRanges() const { return ranges; } void Saturation::setRange(int id) { if (id < ranges.size()) { currentRange = id; emit perdiodOutputChanged(1.0 / ranges[currentRange].f); emit rangeChanged(currentRange); ampfactorasync = 1.0 / ranges[currentRange].g; timer->start(100); } } void Saturation::setEnabled(bool yes) { enabled = yes; } void Saturation::sendFactor() { emit ampliFactorChanged(ampfactorasync); } void Saturation::stop() { stopnext = true; } void Saturation::run() { stopnext = false; int upLastTime = 1; mutex.lock(); while (stopnext == false) { int size = input->size(); if (bufferSize != 0 && size >= bufferSize) { input->read(buffer, bufferSize); float peak = 0.0; for (int i = 0; i < bufferSize; ++i) { const float va = qAbs(buffer[i]); if (va > peak) peak = va; } emit saturationValueChanged(peak); if (enabled && autogain) { // qDebug("%d", __LINE__); if (upLastTime > 0) { // qDebug("%d", __LINE__); upLastTime--; } else if (!ranges.isEmpty()) { // qDebug("%d", __LINE__); if (peak >= 0.99) { if (currentRange > 0) { currentRange--; setRange(currentRange); upLastTime = 1; } } if (peak <= 0.05) { if (currentRange < ranges.size() - 1) { currentRange++; setRange(currentRange); upLastTime = 1; } } if (currentRange == -1) { currentRange = 0; setRange(currentRange); } } } } else { mutex.unlock(); msleep(50); mutex.lock(); } } mutex.unlock(); }
[ "noreply@github.com" ]
noreply@github.com
94c4bf09f65ce0d89685152ca98460a3f6887d51
985b6c4517a1abfc914a8887ab35c677b9d03a56
/study/cppprimerplus_1.cpp
652733602408d2f9ecc22c407b8960f6ca170278
[]
no_license
furyParrot/leetcode
29fe15302b0a6b5e08c59c8bb7f580454221d3d2
f30605e595221da4ca6aa404b153f1e3e45e7482
refs/heads/master
2022-12-18T08:32:43.863839
2020-09-07T15:09:10
2020-09-07T15:09:10
293,539,005
0
0
null
null
null
null
UTF-8
C++
false
false
238
cpp
#include <iostream> using namespace std; int main(){ int mm[] = {1233,1,1,11,1,1,1,2}; cout<<sizeof(mm)/sizeof(int); cout<<"输入名字:\n"; char a[20]; cin.getline(a,10); cout<<"你的名字是:"<<a<<endl; }
[ "418396075@qq.com" ]
418396075@qq.com
1b199644e9c9b878c0519d62978f31dcef35bf88
22fdb70949ba7a1f9aac8197236b1864f65b29a3
/include/cryptobase/Extension.hpp
833d70dbab009a600fdc89426894c22a602453d9
[]
no_license
giovani-milanez/cryptobase
1a744add9d3c21181c28590a8dc1721c306a5045
a5dfe25d921d2790a19f76d7e34b5306f76e7eba
refs/heads/master
2021-01-10T20:10:33.169048
2015-01-22T12:55:29
2015-01-22T12:55:29
29,673,662
1
0
null
null
null
null
UTF-8
C++
false
false
1,004
hpp
/* * Extension.hpp * * Author: Giovani Milanez Espindola * Contact: giovani.milanez@gmail.com * Created on: 17/09/2013 */ #ifndef EXTENSION_HPP_ #define EXTENSION_HPP_ #include "cryptobase/Asn1Class.hpp" #include "cryptobase/ObjectIdentifier.hpp" #include <vector> typedef struct X509_extension_st X509_EXTENSION; namespace cryptobase { ASN1_DECLARE_CLASS(ExtensionAsn1, X509_EXTENSION) class CRYPTOBASE_API Extension : public ExtensionAsn1 { public: explicit Extension(X509_EXTENSION *p); Extension(const cryptobase::ObjectIdentifier oid, const std::string& value, bool critical); Extension(const cryptobase::ObjectIdentifier oid, bool critical); virtual ~Extension(); bool isCritical() const; ObjectIdentifier getOid() const; ByteArray getValue() const; static Extension createDistPoint(const std::vector<std::string>& distPoints); static Extension createNoRevAvail(); }; } /* namespace cryptobase */ #endif /* EXTENSION_HPP_ */
[ "giovani.milanez@gmail.com" ]
giovani.milanez@gmail.com
3e9dcdda7cffee7b39cc5cd202744a4ad934c906
6fc32a1afc588f9c588d74b5ab2f14e364bdd876
/test.cpp
d825c4674816305704f681ebd774b6c4274ce752
[]
no_license
kritik-sharma/Rubiks_Cube_OpenCV
2572833be3985e4333c6825a81e004ba6ae12e92
4ccd6e309a2d16f945e644744402b28059806b40
refs/heads/master
2022-11-29T14:35:12.859123
2020-08-04T09:10:52
2020-08-04T09:10:52
284,931,073
0
0
null
null
null
null
UTF-8
C++
false
false
22,577
cpp
#include "data.h" #define INC_VAL 2.0f #define SAFE_DELETE_ARRAY(x) { if( x ){ delete [] x; x = NULL; } } #ifndef M_PI #define M_PI 3.14159265359 #endif #ifndef GL_UNSIGNED_INT_8_8_8_8 #define GL_UNSIGNED_INT_8_8_8_8 GL_UNSIGNED_INT #endif // width and height of the window GLsizei g_width = 500; GLsizei g_height = 500; // whether to animate GLboolean g_rotate = GL_TRUE; // light 0 position GLfloat g_light_pos[4] = { 2.0f, 2.0f, 2.0f, 100.0f }; // clipping planes //GLdouble eqn1[4] = { 0.0, 0.0, 1.0, 0.0 }; GLfloat g_inc = 0.0f; // depth buffer GLfloat * g_depth_light = NULL; GLfloat * g_depth_view = NULL; // keep track of the number of frames per second int theFrameCount = 0; int theLastFrameTime = 0; void render(); void shadows(); void *font = GLUT_BITMAP_TIMES_ROMAN_24; char defaultMessage[] = "Rotation Speed:"; char *message = defaultMessage; void output(int x, int y, char *string) { int len, i; glRasterPos2f(x, y); len = (int) strlen(string); for (i = 0; i < len; i++) { glutBitmapCharacter(font, string[i]); } } GLuint texture; void gentexture(){ glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_NEAREST); //to the edge of our shape. glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); // load and generate the texture int width, height, nrChannels; unsigned char *data = stbi_load("apple.jpg", &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); //glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture\n"; } stbi_image_free(data); } int w1 = 0; int h1 = 0; void orthogonalStart() { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(-w1/2, w1/2, -h1/2, h1/2); glMatrixMode(GL_MODELVIEW); } void orthogonalEnd() { glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); } //GLuint texture = 0; void background() { glBindTexture( GL_TEXTURE_2D, texture ); orthogonalStart(); // texture width/height const int iw = 500; const int ih = 500; glPushMatrix(); glTranslatef( -iw/2, -ih/2, 0 ); glBegin(GL_QUADS); glTexCoord2i(0,0); glVertex2i(0, 0); glTexCoord2i(1,0); glVertex2i(iw, 0); glTexCoord2i(1,1); glVertex2i(iw, ih); glTexCoord2i(0,1); glVertex2i(0, ih); glEnd(); glPopMatrix(); orthogonalEnd(); } void shadows( ) { GLdouble mv_mat[16], proj_mat[16]; GLint viewport[4]; GLdouble objx, objy, objz; GLdouble depth; GLfloat * p = g_light_pos; GLdouble mv_light[16]; GLdouble winx, winy, winz; GLdouble depth_2; // color of pixels in shadow GLuint pixel[2] = { 0x00000000 }; glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); // get the modelview, project, and viewport glGetDoublev( GL_MODELVIEW_MATRIX, mv_mat ); glGetDoublev( GL_PROJECTION_MATRIX, proj_mat ); glGetIntegerv( GL_VIEWPORT, viewport ); // get the current depth buffer glReadPixels( 0, 0, g_width, g_height, GL_DEPTH_COMPONENT, GL_FLOAT, g_depth_view ); // get the transformation from light view glPushMatrix(); glLoadIdentity( ); gluLookAt( p[1], p[0], p[2], 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 ); glGetDoublev( GL_MODELVIEW_MATRIX, mv_light ); glPopMatrix(); // set the project matrix to orthographic glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0.0, (GLfloat)g_width, 0.0, (GLfloat)g_height); // set the modelview matrix to identity glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); // go through every pixel in frame buffer for( GLint y = 0; y < g_height; y++ ) for( GLint x = 0; x < g_width; x++ ) { // depth at pixel //std::cout <<g_depth_view[0]<<"\n"; //std::cout <<"ab\n"; depth = g_depth_view[ y * g_width + x ]; // on the far plane of frustum - don't calculate if( depth > .99 ) continue; // get world coordinate from x, y, depth gluUnProject( x, y, depth, mv_mat, proj_mat, viewport, &objx, &objy, &objz ); // get light view screen coordinate and depth gluProject( objx, objy, objz, mv_light, proj_mat, viewport, &winx, &winy, &winz ); // make sure within the screen if( winx >= g_width || winy >= g_height || winx < 0 || winy < 0 ) continue; // get the depth value from the light depth_2 = g_depth_light[ GLint(winy) * g_width + GLint(winx) ]; // is something between the light and the pixel? if( (winz - depth_2) > .01 ) { glRasterPos2i( x, y ); glDrawPixels( 1, 1, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &pixel ); } } // restore modelview transformation glPopMatrix(); // restore projection glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); } void render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glEnable( GL_TEXTURE_2D ); glColor3fv(color[0]); glPushMatrix(); glRotatef(25.0+p,1.0,0.0,0.0); glRotatef(-30.0+q,0.0,1.0,0.0); glRotatef(0.0+r,0.0,0.0,1.0); if(rotation==0) { colorcube1(); colorcube2(); colorcube3(); colorcube4(); colorcube5(); colorcube6(); colorcube7(); colorcube8(); colorcube9(); colorcube10(); colorcube11(); colorcube12(); colorcube13(); colorcube14(); colorcube15(); colorcube16(); colorcube17(); colorcube18(); colorcube19(); colorcube20(); colorcube21(); colorcube22(); colorcube23(); colorcube24(); colorcube25(); colorcube26(); colorcube27(); } if(rotation==1) { colorcube1(); colorcube2(); colorcube3(); colorcube4(); colorcube6(); colorcube7(); colorcube12(); colorcube13(); colorcube14(); colorcube15(); colorcube20(); colorcube21(); colorcube22(); colorcube23(); colorcube24(); colorcube25(); colorcube26(); colorcube27(); if(inverse==0) {glPushMatrix(); glColor3fv(color[0]); output(-11,6,"Top"); glPopMatrix(); glRotatef(-theta,0.0,1.0,0.0); } else {glPushMatrix(); glColor3fv(color[0]); output(-11,6,"TopInverted"); glPopMatrix(); glRotatef(theta,0.0,1.0,0.0); } colorcube5(); colorcube8(); colorcube9(); colorcube10(); colorcube11(); colorcube16(); colorcube17(); colorcube18(); colorcube19(); } if(rotation==2) { colorcube1(); colorcube2(); colorcube3(); colorcube5(); colorcube6(); colorcube7(); colorcube8(); colorcube10(); colorcube11(); colorcube12(); colorcube14(); colorcube15(); colorcube16(); colorcube17(); colorcube20(); colorcube21(); colorcube24(); colorcube25(); if(inverse==0) { glPushMatrix(); glColor3fv(color[0]); output(-11,6,"Right"); glPopMatrix(); glRotatef(-theta,1.0,0.0,0.0); } else { glPushMatrix(); glColor3fv(color[0]); output(-11,6,"RightInverted"); glPopMatrix(); glRotatef(theta,1.0,0.0,0.0); } colorcube4(); colorcube9(); colorcube13(); colorcube18(); colorcube19(); colorcube22(); colorcube23(); colorcube26(); colorcube27(); } if(rotation==3) { colorcube1(); colorcube2(); colorcube3(); colorcube4(); colorcube5(); colorcube7(); colorcube8(); colorcube9(); colorcube11(); colorcube12(); colorcube13(); colorcube15(); colorcube16(); colorcube18(); colorcube20(); colorcube22(); colorcube24(); colorcube26(); if(inverse==0) { glPushMatrix(); glColor3fv(color[0]); output(-11,6,"Front"); glPopMatrix(); glRotatef(-theta,0.0,0.0,1.0); } else { glPushMatrix(); glColor3fv(color[0]); output(-11,6,"FrontInverted"); glPopMatrix(); glRotatef(theta,0.0,0.0,1.0); } colorcube6(); colorcube10(); colorcube14(); colorcube17(); colorcube19(); colorcube21(); colorcube23(); colorcube25(); colorcube27(); } if(rotation==4) { colorcube1(); colorcube2(); colorcube4(); colorcube5(); colorcube6(); colorcube7(); colorcube9(); colorcube10(); colorcube11(); colorcube13(); colorcube14(); colorcube15(); colorcube18(); colorcube19(); colorcube22(); colorcube23(); colorcube26(); colorcube27(); if(inverse==0) {glPushMatrix(); glColor3fv(color[0]); output(-11,6,"Left"); glPopMatrix(); glRotatef(theta,1.0,0.0,0.0); } else {glPushMatrix(); glColor3fv(color[0]); output(-11,6,"LeftInverted"); glPopMatrix(); glRotatef(-theta,1.0,0.0,0.0); } colorcube3(); colorcube8(); colorcube12(); colorcube16(); colorcube17(); colorcube20(); colorcube21(); colorcube24(); colorcube25(); } if(rotation==5) { colorcube1(); colorcube2(); colorcube3(); colorcube4(); colorcube5(); colorcube6(); colorcube8(); colorcube9(); colorcube10(); colorcube12(); colorcube13(); colorcube14(); colorcube17(); colorcube19(); colorcube21(); colorcube23(); colorcube25(); colorcube27(); if(inverse==0) {glPushMatrix(); glColor3fv(color[0]); output(-11,6,"Back"); glPopMatrix(); glRotatef(theta,0.0,0.0,1.0); } else { glPushMatrix(); glColor3fv(color[0]); output(-11,6,"BackInverted"); glPopMatrix(); glRotatef(-theta,0.0,0.0,1.0); } colorcube7(); colorcube11(); colorcube15(); colorcube16(); colorcube18(); colorcube20(); colorcube22(); colorcube24(); colorcube26(); } if(rotation==6) { colorcube1(); colorcube3(); colorcube4(); colorcube5(); colorcube6(); colorcube7(); colorcube8(); colorcube9(); colorcube10(); colorcube11(); colorcube16(); colorcube17(); colorcube18(); colorcube19(); colorcube20(); colorcube21(); colorcube22(); colorcube23(); if(inverse==0) {glPushMatrix(); glColor3fv(color[0]); output(-11,6,"Bottom"); glPopMatrix(); glRotatef(theta,0.0,1.0,0.0); } else {glPushMatrix(); glColor3fv(color[0]); output(-11,6,"BottomInverted"); glPopMatrix(); glRotatef(-theta,0.0,1.0,0.0); } colorcube2(); colorcube12(); colorcube13(); colorcube14(); colorcube15(); colorcube24(); colorcube25(); colorcube26(); colorcube27(); } glPopMatrix(); /*glPushMatrix(); glTranslatef(-.5,-4,0); glScalef(speed/4.5,1.0,1.0); glTranslatef(0.5,4,0); polygon(5,216,217,218,219); glPopMatrix(); */ } void display( ) { static GLfloat angle = 0.0; GLint buffer = GL_NONE; GLfloat * p = g_light_pos; glGetIntegerv( GL_DRAW_BUFFER, &buffer ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glPushMatrix( ); glRotatef( angle += g_inc, 0.0f, 1.0f, 0.0f ); glLightfv( GL_LIGHT0, GL_POSITION, g_light_pos ); //GL_DIFFUSE glPushMatrix(); glDrawBuffer( GL_NONE ); glLoadIdentity(); gluLookAt( p[0], p[1], p[2], 0, 0, 0, 0, 1, 0 ); render(); glReadPixels( 0, 0, g_width, g_height, GL_DEPTH_COMPONENT, GL_FLOAT, g_depth_light ); glDrawBuffer( (GLenum)buffer ); glPopMatrix( ); glClear( GL_DEPTH_BUFFER_BIT ); render( ); glPopMatrix( ); glFlush( ); glutSwapBuffers( ); } void transpose(char a) { if(a=='r') { int temp; temp=right[0][0]; right[0][0]=right[2][0]; right[2][0]=right[2][2]; right[2][2]=right[0][2]; right[0][2]=temp; temp=right[1][0]; right[1][0]=right[2][1]; right[2][1]=right[1][2]; right[1][2]=right[0][1]; right[0][1]=temp; } if(a=='t') { int temp; temp=top[0][0]; top[0][0]=top[2][0]; top[2][0]=top[2][2]; top[2][2]=top[0][2]; top[0][2]=temp; temp=top[1][0]; top[1][0]=top[2][1]; top[2][1]=top[1][2]; top[1][2]=top[0][1]; top[0][1]=temp; } if(a=='f') { int temp; temp=front[0][0]; front[0][0]=front[2][0]; front[2][0]=front[2][2]; front[2][2]=front[0][2]; front[0][2]=temp; temp=front[1][0]; front[1][0]=front[2][1]; front[2][1]=front[1][2]; front[1][2]=front[0][1]; front[0][1]=temp; } if(a=='l') { int temp; temp=left[0][0]; left[0][0]=left[2][0]; left[2][0]=left[2][2]; left[2][2]=left[0][2]; left[0][2]=temp; temp=left[1][0]; left[1][0]=left[2][1]; left[2][1]=left[1][2]; left[1][2]=left[0][1]; left[0][1]=temp; } if(a=='k') { int temp; temp=back[0][0]; back[0][0]=back[2][0]; back[2][0]=back[2][2]; back[2][2]=back[0][2]; back[0][2]=temp; temp=back[1][0]; back[1][0]=back[2][1]; back[2][1]=back[1][2]; back[1][2]=back[0][1]; back[0][1]=temp; } if(a=='b') { int temp; temp=bottom[0][0]; bottom[0][0]=bottom[2][0]; bottom[2][0]=bottom[2][2]; bottom[2][2]=bottom[0][2]; bottom[0][2]=temp; temp=bottom[1][0]; bottom[1][0]=bottom[2][1]; bottom[2][1]=bottom[1][2]; bottom[1][2]=bottom[0][1]; bottom[0][1]=temp; } } void topc() { transpose('t'); int temp1=front[0][0]; int temp2=front[0][1]; int temp3=front[0][2]; front[0][0]=right[0][0]; front[0][1]=right[0][1]; front[0][2]=right[0][2]; right[0][0]=back[0][0]; right[0][1]=back[0][1]; right[0][2]=back[0][2]; back[0][0]=left[0][0]; back[0][1]=left[0][1]; back[0][2]=left[0][2]; left[0][0]=temp1; left[0][1]=temp2; left[0][2]=temp3; } void frontc() { transpose('f'); int temp1=left[0][2]; int temp2=left[1][2]; int temp3=left[2][2]; left[0][2]=bottom[0][0]; left[1][2]=bottom[0][1]; left[2][2]=bottom[0][2]; bottom[0][0]=right[2][0]; bottom[0][1]=right[1][0]; bottom[0][2]=right[0][0]; right[2][0]=top[2][2]; right[1][0]=top[2][1]; right[0][0]=top[2][0]; top[2][2]=temp1; top[2][1]=temp2; top[2][0]=temp3; } void rightc() { transpose('r'); int temp1=top[0][2]; int temp2=top[1][2]; int temp3=top[2][2]; top[0][2]=front[0][2]; top[1][2]=front[1][2]; top[2][2]=front[2][2]; front[0][2]=bottom[0][2]; front[1][2]=bottom[1][2]; front[2][2]=bottom[2][2]; bottom[0][2]=back[2][0]; bottom[1][2]=back[1][0]; bottom[2][2]=back[0][0]; back[2][0]=temp1; back[1][0]=temp2; back[0][0]=temp3; } void leftc() { transpose('l'); int temp1=front[0][0]; int temp2=front[1][0]; int temp3=front[2][0]; front[0][0]=top[0][0]; front[1][0]=top[1][0]; front[2][0]=top[2][0]; top[0][0]=back[2][2]; top[1][0]=back[1][2]; top[2][0]=back[0][2]; back[2][2]=bottom[0][0]; back[1][2]=bottom[1][0]; back[0][2]=bottom[2][0]; bottom[0][0]=temp1; bottom[1][0]=temp2; bottom[2][0]=temp3; } void backc() { transpose('k'); int temp1=top[0][0]; int temp2=top[0][1]; int temp3=top[0][2]; top[0][0]=right[0][2]; top[0][1]=right[1][2]; top[0][2]=right[2][2]; right[0][2]=bottom[2][2]; right[1][2]=bottom[2][1]; right[2][2]=bottom[2][0]; bottom[2][2]=left[2][0]; bottom[2][1]=left[1][0]; bottom[2][0]=left[0][0]; left[2][0]=temp1; left[1][0]=temp2; left[0][0]=temp3; } void bottomc() { transpose('b'); int temp1=front[2][0]; int temp2=front[2][1]; int temp3=front[2][2]; front[2][0]=left[2][0]; front[2][1]=left[2][1]; front[2][2]=left[2][2]; left[2][0]=back[2][0]; left[2][1]=back[2][1]; left[2][2]=back[2][2]; back[2][0]=right[2][0]; back[2][1]=right[2][1]; back[2][2]=right[2][2]; right[2][0]=temp1; right[2][1]=temp2; right[2][2]=temp3; } void spincube() { theta+=0.5+speed; if(theta==360.0) theta-=360.0; if(theta>=90.0) { rotationcomplete=1; glutIdleFunc(NULL); if(rotation==1&&inverse==0) { topc(); } if(rotation==1&&inverse==1) { topc(); topc(); topc(); } if(rotation==2&&inverse==0) { rightc(); } if(rotation==2&&inverse==1) { rightc(); rightc(); rightc(); } if(rotation==3&&inverse==0) { frontc(); } if(rotation==3&&inverse==1) { frontc(); frontc(); frontc(); } if(rotation==4&&inverse==0) { leftc(); } if(rotation==4&&inverse==1) { leftc(); leftc(); leftc(); } if(rotation==5&&inverse==0) { backc(); } if(rotation==5&&inverse==1) { backc(); backc(); backc(); } if(rotation==6&&inverse==0) { bottomc(); } if(rotation==6&&inverse==1) { bottomc(); bottomc(); bottomc(); } rotation=0; theta=0; } glutPostRedisplay(); } void motion(int x, int y) { if (moving) { q=q + (x - beginx); beginx = x; p=p + (y - beginy); beginy=y; glutPostRedisplay(); } } void mouse(int btn,int state,int x,int y) { if(btn==GLUT_LEFT_BUTTON && state==GLUT_DOWN) { moving = 1; beginx = x; beginy=y; } } static void keyboard(unsigned char key,int x,int y) { if(key=='a'&&rotationcomplete==1) { rotationcomplete=0; rotation=1; inverse=0; solve[++count]=1; glutIdleFunc(spincube); } if(key=='q'&&rotationcomplete==1) { rotationcomplete=0; rotation=1; inverse=1; solve[++count]=-1; glutIdleFunc(spincube); } if(key=='s'&&rotationcomplete==1) {rotationcomplete=0; rotation=2; inverse=0; solve[++count]=2; glutIdleFunc(spincube); } if(key=='w'&&rotationcomplete==1) {rotationcomplete=0; rotation=2; inverse=1; solve[++count]=-2; glutIdleFunc(spincube); } if(key=='d'&&rotationcomplete==1) {rotationcomplete=0; rotation=3; inverse=0; solve[++count]=3; glutIdleFunc(spincube); } if(key=='e'&&rotationcomplete==1) {rotationcomplete=0; rotation=3; inverse=1; solve[++count]=-3; glutIdleFunc(spincube); } if(key=='f'&&rotationcomplete==1) {rotationcomplete=0; rotation=4; inverse=0; solve[++count]=4; glutIdleFunc(spincube); } if(key=='r'&&rotationcomplete==1) {rotationcomplete=0; rotation=4; inverse=1; solve[++count]=-4; glutIdleFunc(spincube); } if(key=='g'&&rotationcomplete==1) {rotationcomplete=0; rotation=5; inverse=0; solve[++count]=5; glutIdleFunc(spincube); } if(key=='t'&&rotationcomplete==1) {rotationcomplete=0; rotation=5; inverse=1; solve[++count]=-5; glutIdleFunc(spincube); } if(key=='h'&&rotationcomplete==1) {rotationcomplete=0; rotation=6; inverse=0; solve[++count]=6; glutIdleFunc(spincube); } if(key=='y'&&rotationcomplete==1) {rotationcomplete=0; rotation=6; inverse=1; solve[++count]=-6; glutIdleFunc(spincube); } if(key=='2'&&rotationcomplete==1) { p=p+2.0; glutIdleFunc(spincube); } if(key=='8'&&rotationcomplete==1) { p=p-2.0; glutIdleFunc(spincube); } if(key=='6'&&rotationcomplete==1) { q=q+2.0; glutIdleFunc(spincube); } if(key=='4'&&rotationcomplete==1) { q=q-2.0; glutIdleFunc(spincube); } if(key=='9'&&rotationcomplete==1) { r=r+2.0; glutIdleFunc(spincube); } if(key=='1'&&rotationcomplete==1) { r=r-2.0; glutIdleFunc(spincube); } if(key=='5'&&rotationcomplete==1) { p=0.0; q=0.0; r=0.0; glutIdleFunc(spincube); } if(key=='n'&&rotationcomplete==1) { if(speed>=0.3) { speed=speed-0.3; speedmetercolor[speedmetercount--]=0; } glutPostRedisplay(); } if(key=='o'&&rotationcomplete==1) { rotationcomplete=0; if(count>=0) { if(solve[count]<0) { rotation=-1*solve[count]; inverse=0; glutIdleFunc(spincube); } if(solve[count]>0) { rotation=solve[count]; inverse=1; glutIdleFunc(spincube); } --count; } glutIdleFunc(spincube); } } void myreshape(int w,int h){ g_width = w; g_height = h; glViewport(0,0,w,h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (w <= h) glOrtho(-10.0,10.0,-10.0*(GLfloat)h/(GLfloat)w, 10.0*(GLfloat)h/(GLfloat)w,-10.0,10.0); else glOrtho(-10.0*(GLfloat)w/(GLfloat)h, 10.0*(GLfloat)w/(GLfloat)h,-10.0,10.0,-10.0,10.0); glMatrixMode(GL_MODELVIEW); SAFE_DELETE_ARRAY( g_depth_light ); SAFE_DELETE_ARRAY( g_depth_view ); g_depth_light = new GLfloat[g_width * g_height]; g_depth_view = new GLfloat[g_width * g_height]; } void mymenu(int id){ if(rotationcomplete==1){ rotationcomplete=0; switch(id) { case 1: rotation=1; inverse=0; solve[++count]=1; glutIdleFunc(spincube); break; case 2: rotation=1; inverse=1; solve[++count]=-1; glutIdleFunc(spincube); break; case 3: rotation=2; inverse=0; solve[++count]=2; glutIdleFunc(spincube); break; case 4: rotation=2; inverse=1; solve[++count]=-2; glutIdleFunc(spincube); break; case 5: rotation=3; inverse=0; solve[++count]=3; glutIdleFunc(spincube); break; case 6: rotation=3; inverse=1; solve[++count]=-3; glutIdleFunc(spincube); break; case 7: rotation=4; inverse=0; solve[++count]=4; glutIdleFunc(spincube); break; case 8: rotation=4; inverse=1; solve[++count]=-4; glutIdleFunc(spincube); break; case 9: rotation=5; inverse=0; solve[++count]=5; glutIdleFunc(spincube); break; case 10: rotation=5; inverse=1; solve[++count]=-5; glutIdleFunc(spincube); break; case 11: rotation=6; inverse=0; solve[++count]=6; glutIdleFunc(spincube); break; case 12: rotation=6; inverse=1; solve[++count]=-6; glutIdleFunc(spincube); break; case 13: exit(0); break; } } } void init() { glClearColor( 0.0f, 0.0f,0.0f, 1.0f ); glShadeModel( GL_SMOOTH ); glEnable( GL_DEPTH_TEST ); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glEnable( GL_LIGHTING ); glLightModeli( GL_FRONT, GL_TRUE ); glColorMaterial( GL_FRONT, GL_AMBIENT_AND_DIFFUSE ); glEnable( GL_COLOR_MATERIAL ); glEnable( GL_LIGHT0 ); } int main(int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize (g_width, g_height); glutInitWindowPosition( 100, 100 ); glutCreateWindow ("RUBIK'S CUBE"); glutReshapeFunc (myreshape); glutIdleFunc(spincube); glutMouseFunc(mouse); glutMotionFunc(motion); glutCreateMenu(mymenu); glutAddMenuEntry("Top :a",1); glutAddMenuEntry("Top Inverted :q",2); glutAddMenuEntry("Right :s",3); glutAddMenuEntry("Right Inverted :w",4); glutAddMenuEntry("Front :d",5); glutAddMenuEntry("Front Inverted :e",6); glutAddMenuEntry("Left :f",7); glutAddMenuEntry("Left Inverted :r",8); glutAddMenuEntry("Back :g",9); glutAddMenuEntry("Back Inverted :t",10); glutAddMenuEntry("Bottom :h",11); glutAddMenuEntry("Bottom Inverted :y",12); gentexture(); init(); glutAddMenuEntry("Exit",13); glutAttachMenu(GLUT_RIGHT_BUTTON); glutKeyboardFunc(keyboard); glutDisplayFunc (display); glEnable(GL_DEPTH_TEST); glutMainLoop(); }
[ "noreply@github.com" ]
noreply@github.com
c59a02065daf3b63639d51efbf48b45ce659f60c
17814ec599354da725769ad375f0d6d2c0e561a3
/src/third_party/Snap/snap-adv/agmfit.cpp
9d9f74418853768a3125a891ed81389ad263eac0
[ "BSD-3-Clause", "BSD-2-Clause-Views" ]
permissive
lstopar/qminer
be01188ae4227c54da51fd433e2ba8b1397cc38b
65bcb297f7eb69c37f42f7b999faf6a57d97819c
refs/heads/master
2020-12-25T10:16:15.370577
2020-03-23T20:19:43
2020-03-23T20:19:43
20,472,715
0
1
BSD-2-Clause
2018-01-22T12:55:58
2014-06-04T06:32:21
C++
UTF-8
C++
false
false
24,022
cpp
#include "stdafx.h" #include "agmfit.h" #include "agm.h" ///////////////////////////////////////////////// // AGM fitting void TAGMFit::Save(TSOut& SOut) { G->Save(SOut); CIDNSetV.Save(SOut); EdgeComVH.Save(SOut); NIDComVH.Save(SOut); ComEdgesV.Save(SOut); PNoCom.Save(SOut); LambdaV.Save(SOut); NIDCIDPrH.Save(SOut); NIDCIDPrS.Save(SOut); MinLambda.Save(SOut); MaxLambda.Save(SOut); RegCoef.Save(SOut); BaseCID.Save(SOut); } void TAGMFit::Load(TSIn& SIn, const int& RndSeed) { G = TUNGraph::Load(SIn); CIDNSetV.Load(SIn); EdgeComVH.Load(SIn); NIDComVH.Load(SIn); ComEdgesV.Load(SIn); PNoCom.Load(SIn); LambdaV.Load(SIn); NIDCIDPrH.Load(SIn); NIDCIDPrS.Load(SIn); MinLambda.Load(SIn); MaxLambda.Load(SIn); RegCoef.Load(SIn); BaseCID.Load(SIn); Rnd.PutSeed(RndSeed); } // Randomly initialize bipartite community affiliation graph. void TAGMFit::RandomInitCmtyVV(const int InitComs, const double ComSzAlpha, const double MemAlpha, const int MinComSz, const int MaxComSz, const int MinMem, const int MaxMem) { TVec<TIntV> InitCmtyVV(InitComs, 0); TAGMUtil::GenCmtyVVFromPL(InitCmtyVV, G, G->GetNodes(), InitComs, ComSzAlpha, MemAlpha, MinComSz, MaxComSz, MinMem, MaxMem, Rnd); SetCmtyVV(InitCmtyVV); } // For each (u, v) in edges, precompute C_uv (the set of communities u and v share). void TAGMFit::GetEdgeJointCom() { ComEdgesV.Gen(CIDNSetV.Len()); EdgeComVH.Gen(G->GetEdges()); for (TUNGraph::TNodeI SrcNI = G->BegNI(); SrcNI < G->EndNI(); SrcNI++) { int SrcNID = SrcNI.GetId(); for (int v = 0; v < SrcNI.GetDeg(); v++) { int DstNID = SrcNI.GetNbrNId(v); if (SrcNID >= DstNID) { continue; } TIntSet JointCom; IAssert(NIDComVH.IsKey(SrcNID)); IAssert(NIDComVH.IsKey(DstNID)); TAGMUtil::GetIntersection(NIDComVH.GetDat(SrcNID), NIDComVH.GetDat(DstNID), JointCom); EdgeComVH.AddDat(TIntPr(SrcNID,DstNID),JointCom); for (int k = 0; k < JointCom.Len(); k++) { ComEdgesV[JointCom[k]]++; } } } IAssert(EdgeComVH.Len() == G->GetEdges()); } // Set epsilon by the default value. void TAGMFit::SetDefaultPNoCom() { PNoCom = 1.0 / (double) G->GetNodes() / (double) G->GetNodes(); } double TAGMFit::Likelihood(const TFltV& NewLambdaV, double& LEdges, double& LNoEdges) { IAssert(CIDNSetV.Len() == NewLambdaV.Len()); IAssert(ComEdgesV.Len() == CIDNSetV.Len()); LEdges = 0.0; LNoEdges = 0.0; for (int e = 0; e < EdgeComVH.Len(); e++) { TIntSet& JointCom = EdgeComVH[e]; double LambdaSum = SelectLambdaSum(NewLambdaV, JointCom); double Puv = 1 - exp(- LambdaSum); if (JointCom.Len() == 0) { Puv = PNoCom; } IAssert(! _isnan(log(Puv))); LEdges += log(Puv); } for (int k = 0; k < NewLambdaV.Len(); k++) { int MaxEk = CIDNSetV[k].Len() * (CIDNSetV[k].Len() - 1) / 2; int NotEdgesInCom = MaxEk - ComEdgesV[k]; if(NotEdgesInCom > 0) { if (LNoEdges >= TFlt::Mn + double(NotEdgesInCom) * NewLambdaV[k]) { LNoEdges -= double(NotEdgesInCom) * NewLambdaV[k]; } } } double LReg = 0.0; if (RegCoef > 0.0) { LReg = - RegCoef * TLinAlg::SumVec(NewLambdaV); } return LEdges + LNoEdges + LReg; } double TAGMFit::Likelihood() { return Likelihood(LambdaV); } // Step size search for updating P_c (which is parametarized by lambda). double TAGMFit::GetStepSizeByLineSearchForLambda(const TFltV& DeltaV, const TFltV& GradV, const double& Alpha, const double& Beta) { double StepSize = 1.0; double InitLikelihood = Likelihood(); IAssert(LambdaV.Len() == DeltaV.Len()); TFltV NewLambdaV(LambdaV.Len()); for (int iter = 0; ; iter++) { for (int i = 0; i < LambdaV.Len(); i++) { NewLambdaV[i] = LambdaV[i] + StepSize * DeltaV[i]; if (NewLambdaV[i] < MinLambda) { NewLambdaV[i] = MinLambda; } if (NewLambdaV[i] > MaxLambda) { NewLambdaV[i] = MaxLambda; } } if (Likelihood(NewLambdaV) < InitLikelihood + Alpha * StepSize * TLinAlg::DotProduct(GradV, DeltaV)) { StepSize *= Beta; } else { break; } } return StepSize; } // Gradient descent for p_c while fixing community affiliation graph (CAG). int TAGMFit::MLEGradAscentGivenCAG(const double& Thres, const int& MaxIter, const TStr PlotNm) { int Edges = G->GetEdges(); TExeTm ExeTm; TFltV GradV(LambdaV.Len()); int iter = 0; TIntFltPrV IterLV, IterGradNormV; double GradCutOff = 1000; for (iter = 0; iter < MaxIter; iter++) { GradLogLForLambda(GradV); //if gradient is going out of the boundary, cut off for (int i = 0; i < LambdaV.Len(); i++) { if (GradV[i] < -GradCutOff) { GradV[i] = -GradCutOff; } if (GradV[i] > GradCutOff) { GradV[i] = GradCutOff; } if (LambdaV[i] <= MinLambda && GradV[i] < 0) { GradV[i] = 0.0; } if (LambdaV[i] >= MaxLambda && GradV[i] > 0) { GradV[i] = 0.0; } } double Alpha = 0.15, Beta = 0.2; if (Edges > Kilo(100)) { Alpha = 0.00015; Beta = 0.3;} double LearnRate = GetStepSizeByLineSearchForLambda(GradV, GradV, Alpha, Beta); if (TLinAlg::Norm(GradV) < Thres) { break; } for (int i = 0; i < LambdaV.Len(); i++) { double Change = LearnRate * GradV[i]; LambdaV[i] += Change; if(LambdaV[i] < MinLambda) { LambdaV[i] = MinLambda;} if(LambdaV[i] > MaxLambda) { LambdaV[i] = MaxLambda;} } if (! PlotNm.Empty()) { double L = Likelihood(); IterLV.Add(TIntFltPr(iter, L)); IterGradNormV.Add(TIntFltPr(iter, TLinAlg::Norm(GradV))); } } if (! PlotNm.Empty()) { TGnuPlot::PlotValV(IterLV, PlotNm + ".likelihood_Q"); TGnuPlot::PlotValV(IterGradNormV, PlotNm + ".gradnorm_Q"); printf("MLE for Lambda completed with %d iterations(%s)\n",iter,ExeTm.GetTmStr()); } return iter; } void TAGMFit::RandomInit(const int& MaxK) { CIDNSetV.Clr(); for (int c = 0; c < MaxK; c++) { CIDNSetV.Add(); int NC = Rnd.GetUniDevInt(G -> GetNodes()); TUNGraph::TNodeI NI = G -> GetRndNI(); CIDNSetV.Last().AddKey(NI.GetId()); for (int v = 0; v < NC; v++) { NI = G->GetNI(NI.GetNbrNId(Rnd.GetUniDevInt(NI.GetDeg()))); CIDNSetV.Last().AddKey(NI.GetId()); } } InitNodeData(); SetDefaultPNoCom(); } // Initialize node community memberships using best neighborhood communities (see D. Gleich et al. KDD'12). void TAGMFit::NeighborComInit(const int InitComs) { CIDNSetV.Gen(InitComs); const int Edges = G->GetEdges(); TFltIntPrV NIdPhiV(G->GetNodes(), 0); TIntSet InvalidNIDS(G->GetNodes()); TIntV ChosenNIDV(InitComs, 0); //FOR DEBUG TExeTm RunTm; //compute conductance of neighborhood community TIntV NIdV; G->GetNIdV(NIdV); for (int u = 0; u < NIdV.Len(); u++) { TIntSet NBCmty(G->GetNI(NIdV[u]).GetDeg() + 1); double Phi; if (G->GetNI(NIdV[u]).GetDeg() < 5) { //do not include nodes with too few degree Phi = 1.0; } else { TAGMUtil::GetNbhCom(G, NIdV[u], NBCmty); IAssert(NBCmty.Len() == G->GetNI(NIdV[u]).GetDeg() + 1); Phi = TAGMUtil::GetConductance(G, NBCmty, Edges); } NIdPhiV.Add(TFltIntPr(Phi, NIdV[u])); } NIdPhiV.Sort(true); printf("conductance computation completed [%s]\n", RunTm.GetTmStr()); fflush(stdout); //choose nodes with local minimum in conductance int CurCID = 0; for (int ui = 0; ui < NIdPhiV.Len(); ui++) { int UID = NIdPhiV[ui].Val2; fflush(stdout); if (InvalidNIDS.IsKey(UID)) { continue; } ChosenNIDV.Add(UID); //FOR DEBUG //add the node and its neighbors to the current community CIDNSetV[CurCID].AddKey(UID); TUNGraph::TNodeI NI = G->GetNI(UID); fflush(stdout); for (int e = 0; e < NI.GetDeg(); e++) { CIDNSetV[CurCID].AddKey(NI.GetNbrNId(e)); } //exclude its neighbors from the next considerations for (int e = 0; e < NI.GetDeg(); e++) { InvalidNIDS.AddKey(NI.GetNbrNId(e)); } CurCID++; fflush(stdout); if (CurCID >= InitComs) { break; } } if (InitComs > CurCID) { printf("%d communities needed to fill randomly\n", InitComs - CurCID); } //assign a member to zero-member community (if any) for (int c = 0; c < CIDNSetV.Len(); c++) { if (CIDNSetV[c].Len() == 0) { int ComSz = 10; for (int u = 0; u < ComSz; u++) { int UID = G->GetRndNI().GetId(); CIDNSetV[c].AddKey(UID); } } } InitNodeData(); SetDefaultPNoCom(); } // Add epsilon community (base community which includes all nodes) into community affiliation graph. It means that we fit for epsilon. void TAGMFit::AddBaseCmty() { TVec<TIntV> CmtyVV; GetCmtyVV(CmtyVV); TIntV TmpV = CmtyVV[0]; CmtyVV.Add(TmpV); G->GetNIdV(CmtyVV[0]); IAssert(CIDNSetV.Len() + 1 == CmtyVV.Len()); SetCmtyVV(CmtyVV); InitNodeData(); BaseCID = 0; PNoCom = 0.0; } void TAGMFit::InitNodeData() { TSnap::DelSelfEdges(G); NIDComVH.Gen(G->GetNodes()); for (TUNGraph::TNodeI NI = G->BegNI(); NI < G->EndNI(); NI++) { NIDComVH.AddDat(NI.GetId()); } TAGMUtil::GetNodeMembership(NIDComVH, CIDNSetV); GetEdgeJointCom(); LambdaV.Gen(CIDNSetV.Len()); for (int c = 0; c < CIDNSetV.Len(); c++) { int MaxE = (CIDNSetV[c].Len()) * (CIDNSetV[c].Len() - 1) / 2; if (MaxE < 2) { LambdaV[c] = MaxLambda; } else{ LambdaV[c] = -log((double) (MaxE - ComEdgesV[c]) / MaxE); } if (LambdaV[c] > MaxLambda) { LambdaV[c] = MaxLambda; } if (LambdaV[c] < MinLambda) { LambdaV[c] = MinLambda; } } NIDCIDPrS.Gen(G->GetNodes() * 10); for (int c = 0; c < CIDNSetV.Len(); c++) { for (TIntSet::TIter SI = CIDNSetV[c].BegI(); SI < CIDNSetV[c].EndI(); SI++) { NIDCIDPrS.AddKey(TIntPr(SI.GetKey(), c)); } } } // After MCMC, NID leaves community CID. void TAGMFit::LeaveCom(const int& NID, const int& CID) { TUNGraph::TNodeI NI = G->GetNI(NID); for (int e = 0; e < NI.GetDeg(); e++) { int VID = NI.GetNbrNId(e); if (NIDComVH.GetDat(VID).IsKey(CID)) { TIntPr SrcDstNIDPr = TIntPr(TMath::Mn(NID,VID), TMath::Mx(NID,VID)); EdgeComVH.GetDat(SrcDstNIDPr).DelKey(CID); ComEdgesV[CID]--; } } CIDNSetV[CID].DelKey(NID); NIDComVH.GetDat(NID).DelKey(CID); NIDCIDPrS.DelKey(TIntPr(NID, CID)); } // After MCMC, NID joins community CID. void TAGMFit::JoinCom(const int& NID, const int& JoinCID) { TUNGraph::TNodeI NI = G->GetNI(NID); for (int e = 0; e < NI.GetDeg(); e++) { int VID = NI.GetNbrNId(e); if (NIDComVH.GetDat(VID).IsKey(JoinCID)) { TIntPr SrcDstNIDPr = TIntPr(TMath::Mn(NID,VID), TMath::Mx(NID,VID)); EdgeComVH.GetDat(SrcDstNIDPr).AddKey(JoinCID); ComEdgesV[JoinCID]++; } } CIDNSetV[JoinCID].AddKey(NID); NIDComVH.GetDat(NID).AddKey(JoinCID); NIDCIDPrS.AddKey(TIntPr(NID, JoinCID)); } // Sample transition: Choose among (join, leave, switch), and then sample (NID, CID). void TAGMFit::SampleTransition(int& NID, int& JoinCID, int& LeaveCID, double& DeltaL) { int Option = Rnd.GetUniDevInt(3); //0:Join 1:Leave 2:Switch if (NIDCIDPrS.Len() <= 1) { Option = 0; } //if there is only one node membership, only join is possible. int TryCnt = 0; const int MaxTryCnt = G->GetNodes(); DeltaL = TFlt::Mn; if (Option == 0) { do { JoinCID = Rnd.GetUniDevInt(CIDNSetV.Len()); NID = G->GetRndNId(); } while (TryCnt++ < MaxTryCnt && NIDCIDPrS.IsKey(TIntPr(NID, JoinCID))); if (TryCnt < MaxTryCnt) { //if successfully find a move DeltaL = SeekJoin(NID, JoinCID); } } else if (Option == 1) { do { TIntPr NIDCIDPr = NIDCIDPrS.GetKey(NIDCIDPrS.GetRndKeyId(Rnd)); NID = NIDCIDPr.Val1; LeaveCID = NIDCIDPr.Val2; } while (TryCnt++ < MaxTryCnt && LeaveCID == BaseCID); if (TryCnt < MaxTryCnt) {//if successfully find a move DeltaL = SeekLeave(NID, LeaveCID); } } else{ do { TIntPr NIDCIDPr = NIDCIDPrS.GetKey(NIDCIDPrS.GetRndKeyId(Rnd)); NID = NIDCIDPr.Val1; LeaveCID = NIDCIDPr.Val2; } while (TryCnt++ < MaxTryCnt && (NIDComVH.GetDat(NID).Len() == CIDNSetV.Len() || LeaveCID == BaseCID)); do { JoinCID = Rnd.GetUniDevInt(CIDNSetV.Len()); } while (TryCnt++ < G->GetNodes() && NIDCIDPrS.IsKey(TIntPr(NID, JoinCID))); if (TryCnt < MaxTryCnt) {//if successfully find a move DeltaL = SeekSwitch(NID, LeaveCID, JoinCID); } } } /// MCMC fitting void TAGMFit::RunMCMC(const int& MaxIter, const int& EvalLambdaIter, const TStr& PlotFPrx) { TExeTm IterTm, TotalTm; double PrevL = Likelihood(), DeltaL = 0; double BestL = PrevL; printf("initial likelihood = %f\n",PrevL); TIntFltPrV IterTrueLV, IterJoinV, IterLeaveV, IterAcceptV, IterSwitchV, IterLBV; TIntPrV IterTotMemV; TIntV IterV; TFltV BestLV; TVec<TIntSet> BestCmtySetV; int SwitchCnt = 0, LeaveCnt = 0, JoinCnt = 0, AcceptCnt = 0, ProbBinSz; int Nodes = G->GetNodes(), Edges = G->GetEdges(); TExeTm PlotTm; ProbBinSz = TMath::Mx(1000, G->GetNodes() / 10); //bin to compute probabilities IterLBV.Add(TIntFltPr(1, BestL)); for (int iter = 0; iter < MaxIter; iter++) { IterTm.Tick(); int NID = -1; int JoinCID = -1, LeaveCID = -1; SampleTransition(NID, JoinCID, LeaveCID, DeltaL); //sample a move double OptL = PrevL; if (DeltaL > 0 || Rnd.GetUniDev() < exp(DeltaL)) { //if it is accepted IterTm.Tick(); if (LeaveCID > -1 && LeaveCID != BaseCID) { LeaveCom(NID, LeaveCID); } if (JoinCID > -1 && JoinCID != BaseCID) { JoinCom(NID, JoinCID); } if (LeaveCID > -1 && JoinCID > -1 && JoinCID != BaseCID && LeaveCID != BaseCID) { SwitchCnt++; } else if (LeaveCID > -1 && LeaveCID != BaseCID) { LeaveCnt++;} else if (JoinCID > -1 && JoinCID != BaseCID) { JoinCnt++;} AcceptCnt++; if ((iter + 1) % EvalLambdaIter == 0) { IterTm.Tick(); MLEGradAscentGivenCAG(0.01, 3); OptL = Likelihood(); } else{ OptL = PrevL + DeltaL; } if (BestL <= OptL && CIDNSetV.Len() > 0) { BestCmtySetV = CIDNSetV; BestLV = LambdaV; BestL = OptL; } } if (iter > 0 && (iter % ProbBinSz == 0) && PlotFPrx.Len() > 0) { IterLBV.Add(TIntFltPr(iter, OptL)); IterSwitchV.Add(TIntFltPr(iter, (double) SwitchCnt / (double) AcceptCnt)); IterLeaveV.Add(TIntFltPr(iter, (double) LeaveCnt / (double) AcceptCnt)); IterJoinV.Add(TIntFltPr(iter, (double) JoinCnt / (double) AcceptCnt)); IterAcceptV.Add(TIntFltPr(iter, (double) AcceptCnt / (double) ProbBinSz)); SwitchCnt = JoinCnt = LeaveCnt = AcceptCnt = 0; } PrevL = OptL; if ((iter + 1) % 10000 == 0) { printf("\r%d iterations completed [%.2f]", iter, (double) iter / (double) MaxIter); } } // plot the likelihood and acceptance probabilities if the plot file name is given if (PlotFPrx.Len() > 0) { TGnuPlot GP1; GP1.AddPlot(IterLBV, gpwLinesPoints, "likelihood"); GP1.SetDataPlotFNm(PlotFPrx + ".likelihood.tab", PlotFPrx + ".likelihood.plt"); TStr TitleStr = TStr::Fmt(" N:%d E:%d", Nodes, Edges); GP1.SetTitle(PlotFPrx + ".likelihood" + TitleStr); GP1.SavePng(PlotFPrx + ".likelihood.png"); TGnuPlot GP2; GP2.AddPlot(IterSwitchV, gpwLinesPoints, "Switch"); GP2.AddPlot(IterLeaveV, gpwLinesPoints, "Leave"); GP2.AddPlot(IterJoinV, gpwLinesPoints, "Join"); GP2.AddPlot(IterAcceptV, gpwLinesPoints, "Accept"); GP2.SetTitle(PlotFPrx + ".transition"); GP2.SetDataPlotFNm(PlotFPrx + "transition_prob.tab", PlotFPrx + "transition_prob.plt"); GP2.SavePng(PlotFPrx + "transition_prob.png"); } CIDNSetV = BestCmtySetV; LambdaV = BestLV; InitNodeData(); MLEGradAscentGivenCAG(0.001, 100); printf("\nMCMC completed (best likelihood: %.2f) [%s]\n", BestL, TotalTm.GetTmStr()); } // Returns \v QV, a vector of (1 - p_c) for each community c. void TAGMFit::GetQV(TFltV& OutV) { OutV.Gen(LambdaV.Len()); for (int i = 0; i < LambdaV.Len(); i++) { OutV[i] = exp(- LambdaV[i]); } } // Remove empty communities. int TAGMFit::RemoveEmptyCom() { int DelCnt = 0; for (int c = 0; c < CIDNSetV.Len(); c++) { if (CIDNSetV[c].Len() == 0) { CIDNSetV[c] = CIDNSetV.Last(); CIDNSetV.DelLast(); LambdaV[c] = LambdaV.Last(); LambdaV.DelLast(); DelCnt++; c--; } } return DelCnt; } // Compute the change in likelihood (Delta) if node UID leaves community CID. double TAGMFit::SeekLeave(const int& UID, const int& CID) { IAssert(CIDNSetV[CID].IsKey(UID)); IAssert(G->IsNode(UID)); double Delta = 0.0; TUNGraph::TNodeI NI = G->GetNI(UID); int NbhsInC = 0; for (int e = 0; e < NI.GetDeg(); e++) { const int VID = NI.GetNbrNId(e); if (! NIDComVH.GetDat(VID).IsKey(CID)) { continue; } TIntPr SrcDstNIDPr(TMath::Mn(UID,VID), TMath::Mx(UID,VID)); TIntSet& JointCom = EdgeComVH.GetDat(SrcDstNIDPr); double CurPuv, NewPuv, LambdaSum = SelectLambdaSum(JointCom); CurPuv = 1 - exp(- LambdaSum); NewPuv = 1 - exp(- LambdaSum + LambdaV[CID]); IAssert(JointCom.Len() > 0); if (JointCom.Len() == 1) { NewPuv = PNoCom; } Delta += (log(NewPuv) - log(CurPuv)); IAssert(!_isnan(Delta)); NbhsInC++; } Delta += LambdaV[CID] * (CIDNSetV[CID].Len() - 1 - NbhsInC); return Delta; } // Compute the change in likelihood (Delta) if node UID joins community CID. double TAGMFit::SeekJoin(const int& UID, const int& CID) { IAssert(! CIDNSetV[CID].IsKey(UID)); double Delta = 0.0; TUNGraph::TNodeI NI = G->GetNI(UID); int NbhsInC = 0; for (int e = 0; e < NI.GetDeg(); e++) { const int VID = NI.GetNbrNId(e); if (! NIDComVH.GetDat(VID).IsKey(CID)) { continue; } TIntPr SrcDstNIDPr(TMath::Mn(UID,VID), TMath::Mx(UID,VID)); TIntSet& JointCom = EdgeComVH.GetDat(SrcDstNIDPr); double CurPuv, NewPuv, LambdaSum = SelectLambdaSum(JointCom); CurPuv = 1 - exp(- LambdaSum); if (JointCom.Len() == 0) { CurPuv = PNoCom; } NewPuv = 1 - exp(- LambdaSum - LambdaV[CID]); Delta += (log(NewPuv) - log(CurPuv)); IAssert(!_isnan(Delta)); NbhsInC++; } Delta -= LambdaV[CID] * (CIDNSetV[CID].Len() - NbhsInC); return Delta; } // Compute the change in likelihood (Delta) if node UID switches from CurCID to NewCID. double TAGMFit::SeekSwitch(const int& UID, const int& CurCID, const int& NewCID) { IAssert(! CIDNSetV[NewCID].IsKey(UID)); IAssert(CIDNSetV[CurCID].IsKey(UID)); double Delta = SeekJoin(UID, NewCID) + SeekLeave(UID, CurCID); //correct only for intersection between new com and current com TUNGraph::TNodeI NI = G->GetNI(UID); for (int e = 0; e < NI.GetDeg(); e++) { const int VID = NI.GetNbrNId(e); if (! NIDComVH.GetDat(VID).IsKey(CurCID) || ! NIDComVH.GetDat(VID).IsKey(NewCID)) {continue;} TIntPr SrcDstNIDPr(TMath::Mn(UID,VID), TMath::Mx(UID,VID)); TIntSet& JointCom = EdgeComVH.GetDat(SrcDstNIDPr); double CurPuv, NewPuvAfterJoin, NewPuvAfterLeave, NewPuvAfterSwitch, LambdaSum = SelectLambdaSum(JointCom); CurPuv = 1 - exp(- LambdaSum); NewPuvAfterLeave = 1 - exp(- LambdaSum + LambdaV[CurCID]); NewPuvAfterJoin = 1 - exp(- LambdaSum - LambdaV[NewCID]); NewPuvAfterSwitch = 1 - exp(- LambdaSum - LambdaV[NewCID] + LambdaV[CurCID]); if (JointCom.Len() == 1 || NewPuvAfterLeave == 0.0) { NewPuvAfterLeave = PNoCom; } Delta += (log(NewPuvAfterSwitch) + log(CurPuv) - log(NewPuvAfterLeave) - log(NewPuvAfterJoin)); if (_isnan(Delta)) { printf("NS:%f C:%f NL:%f NJ:%f PNoCom:%f", NewPuvAfterSwitch, CurPuv, NewPuvAfterLeave, NewPuvAfterJoin, PNoCom.Val); } IAssert(!_isnan(Delta)); } return Delta; } // Get communities whose p_c is higher than 1 - QMax. void TAGMFit::GetCmtyVV(TVec<TIntV>& CmtyVV, const double QMax) { TFltV TmpQV; GetCmtyVV(CmtyVV, TmpQV, QMax); } void TAGMFit::GetCmtyVV(TVec<TIntV>& CmtyVV, TFltV& QV, const double QMax) { CmtyVV.Gen(CIDNSetV.Len(), 0); QV.Gen(CIDNSetV.Len(), 0); TIntFltH CIDLambdaH(CIDNSetV.Len()); for (int c = 0; c < CIDNSetV.Len(); c++) { CIDLambdaH.AddDat(c, LambdaV[c]); } CIDLambdaH.SortByDat(false); for (int c = 0; c < CIDNSetV.Len(); c++) { int CID = CIDLambdaH.GetKey(c); IAssert(LambdaV[CID] >= MinLambda); double Q = exp( - (double) LambdaV[CID]); if (Q > QMax) { continue; } TIntV CmtyV; CIDNSetV[CID].GetKeyV(CmtyV); if (CmtyV.Len() == 0) { continue; } if (CID == BaseCID) { //if the community is the base community(epsilon community), discard IAssert(CmtyV.Len() == G->GetNodes()); } else { CmtyVV.Add(CmtyV); QV.Add(Q); } } } void TAGMFit::SetCmtyVV(const TVec<TIntV>& CmtyVV) { CIDNSetV.Gen(CmtyVV.Len()); for (int c = 0; c < CIDNSetV.Len(); c++) { CIDNSetV[c].AddKeyV(CmtyVV[c]); for (int j = 0; j < CmtyVV[c].Len(); j++) { IAssert(G->IsNode(CmtyVV[c][j])); } // check whether the member nodes exist in the graph } InitNodeData(); SetDefaultPNoCom(); } // Gradient of likelihood for P_c. void TAGMFit::GradLogLForLambda(TFltV& GradV) { GradV.Gen(LambdaV.Len()); TFltV SumEdgeProbsV(LambdaV.Len()); for (int e = 0; e < EdgeComVH.Len(); e++) { TIntSet& JointCom = EdgeComVH[e]; double LambdaSum = SelectLambdaSum(JointCom); double Puv = 1 - exp(- LambdaSum); if (JointCom.Len() == 0) { Puv = PNoCom; } for (TIntSet::TIter SI = JointCom.BegI(); SI < JointCom.EndI(); SI++) { SumEdgeProbsV[SI.GetKey()] += (1 - Puv) / Puv; } } for (int k = 0; k < LambdaV.Len(); k++) { int MaxEk = CIDNSetV[k].Len() * (CIDNSetV[k].Len() - 1) / 2; int NotEdgesInCom = MaxEk - ComEdgesV[k]; GradV[k] = SumEdgeProbsV[k] - (double) NotEdgesInCom; if (LambdaV[k] > 0.0 && RegCoef > 0.0) { //if regularization exists GradV[k] -= RegCoef; } } } // Compute sum of lambda_c (which is log (1 - p_c)) over C_uv (ComK). It is used to compute edge probability P_uv. double TAGMFit::SelectLambdaSum(const TIntSet& ComK) { return SelectLambdaSum(LambdaV, ComK); } double TAGMFit::SelectLambdaSum(const TFltV& NewLambdaV, const TIntSet& ComK) { double Result = 0.0; for (TIntSet::TIter SI = ComK.BegI(); SI < ComK.EndI(); SI++) { IAssert(NewLambdaV[SI.GetKey()] >= 0); Result += NewLambdaV[SI.GetKey()]; } return Result; } // Compute the empirical edge probability between a pair of nodes who share no community (epsilon), based on current community affiliations. double TAGMFit::CalcPNoComByCmtyVV(const int& SamplePairs) { TIntV NIdV; G->GetNIdV(NIdV); uint64 PairNoCom = 0, EdgesNoCom = 0; for (int u = 0; u < NIdV.Len(); u++) { for (int v = u + 1; v < NIdV.Len(); v++) { int SrcNID = NIdV[u], DstNID = NIdV[v]; TIntSet JointCom; TAGMUtil::GetIntersection(NIDComVH.GetDat(SrcNID),NIDComVH.GetDat(DstNID),JointCom); if(JointCom.Len() == 0) { PairNoCom++; if (G->IsEdge(SrcNID, DstNID)) { EdgesNoCom++; } if (SamplePairs > 0 && PairNoCom >= (uint64) SamplePairs) { break; } } } if (SamplePairs > 0 && PairNoCom >= (uint64) SamplePairs) { break; } } double DefaultVal = 1.0 / (double)G->GetNodes() / (double)G->GetNodes(); if (EdgesNoCom > 0) { PNoCom = (double) EdgesNoCom / (double) PairNoCom; } else { PNoCom = DefaultVal; } printf("%s / %s edges without joint com detected (PNoCom = %f)\n", TUInt64::GetStr(EdgesNoCom).CStr(), TUInt64::GetStr(PairNoCom).CStr(), PNoCom.Val); return PNoCom; } void TAGMFit::PrintSummary() { TIntFltH CIDLambdaH(CIDNSetV.Len()); for (int c = 0; c < CIDNSetV.Len(); c++) { CIDLambdaH.AddDat(c, LambdaV[c]); } CIDLambdaH.SortByDat(false); int Coms = 0; for (int i = 0; i < LambdaV.Len(); i++) { int CID = CIDLambdaH.GetKey(i); if (LambdaV[CID] <= 0.0001) { continue; } printf("P_c : %.3f Com Sz: %d, Total Edges inside: %d \n", 1.0 - exp(- LambdaV[CID]), CIDNSetV[CID].Len(), (int) ComEdgesV[CID]); Coms++; } printf("%d Communities, Total Memberships = %d, Likelihood = %.2f, Epsilon = %f\n", Coms, NIDCIDPrS.Len(), Likelihood(), PNoCom.Val); }
[ "jan.rupnik@ijs.si" ]
jan.rupnik@ijs.si
1860f56c4415fef15220f04f801d3847458f6fa8
a14c840a1e3cf74d6594fa2b0dc2b045dc58258d
/Lab4 - Dziedziczenie/main.cpp
bb8b7e40386772b8ba561680116854a61bb3fb32
[]
no_license
AiRWIPP13/PProg
47e686fafdde988e29dba58aecec132f0206feeb
e4ce3ca83cd50b5c31f56494bad5e352ae3611af
refs/heads/master
2016-08-08T05:24:42.588734
2014-06-25T15:48:32
2014-06-25T15:48:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
723
cpp
#include "punkt.h" #include <iostream> using namespace std; int oblicz(punkt someobject) { return 2*(someobject.numer); } int main() { punkt point1d; punkt2d point2d; punkt3d point3d; point1d.nazwa = "p1"; point2d.nazwa = "p2"; point3d.nazwa = "p3"; point3d.przedstaw(); point3d.x = 3; point3d.przedstaw(); point2d.przedstaw(); int num; cout<<endl<<"Podaj numer: "<<endl; cin>>num; punkt point1dn(num); cout<<endl; cout<<oblicz (point1dn)<<endl<<endl; cout<<endl<<"Podaj numer: "<<endl; cin>>num; punkt2d point2dn(num); cout<<endl; cout<<oblicz(point2dn)<<endl; //punkt* wsk = new punkt3d; getchar(); return 0; }
[ "llukas1994@wp.pl" ]
llukas1994@wp.pl
c04a6c0b540bf93c489767c36e87343de40452bb
a5656b21c02cef5b16ee7b6868f3e8e07f01d8e0
/1059. Prime Factors.cpp
7775b71100c6196cda24b26a797ce55aca7de85f
[]
no_license
alicelh/PAT-advanced-level-
8827b0260dbe660d2c924cf498ea7f6f2a9a029c
1c7e8a96a0e709c40d7dba9cd655f15651177bf7
refs/heads/master
2021-01-01T17:29:26.331687
2017-09-16T13:22:27
2017-09-16T13:22:27
98,083,888
0
0
null
null
null
null
UTF-8
C++
false
false
838
cpp
#include<cstdio> #include<cmath> #define maxN 10000 struct pri{ int pm; int km; }factor[10]; int p[100000]; int num=0; bool isprime(int a){ int n=(int)sqrt(1.0*a); for(int i=2;i<=n;i++){ if(a%i==0) return false; } return true; } void findprime(){ for(int i=2;i<maxN;i++){ if(isprime(i)) p[num++]=i; } } int main(){ int N,i,tmp; int k=0; scanf("%d",&N); tmp=N; if(N==1){ printf("1=1"); return 0; } findprime(); for(i=0;i<num;i++){ if(N%p[i]==0){ while(1){ factor[k].pm=p[i]; factor[k].km++; N=N/p[i]; if(N%p[i]!=0) break; } k++; } if(p[i]>N) break; } if(N>1){ factor[k].pm=N; factor[k].km=1; k++; } printf("%d=",tmp); for(int i=0;i<k;i++){ printf("%d",factor[i].pm); if(factor[i].km>1){ printf("^%d",factor[i].km); } if(i!=k-1) printf("*"); } return 0; }
[ "820267577@qq.com" ]
820267577@qq.com
5052b4e3bd4590fb4ba8e8705bb9ddc9a4328fbd
cbbcfcb52e48025cb6c83fbdbfa28119b90efbd2
/codeforces/479/A.cpp
70b92fdf6ef5c548d9f9fe1cd8863025fd1cefb1
[]
no_license
dmehrab06/Time_wasters
c1198b9f2f24e06bfb2199253c74a874696947a8
a158f87fb09d880dd19582dce55861512e951f8a
refs/heads/master
2022-04-02T10:57:05.105651
2019-12-05T20:33:25
2019-12-05T20:33:25
104,850,524
0
1
null
null
null
null
UTF-8
C++
false
false
1,905
cpp
/*-------property of the half blood prince-----*/ #include <bits/stdc++.h> #include <dirent.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/detail/standard_policies.hpp> #define MIN(X,Y) X<Y?X:Y #define MAX(X,Y) X>Y?X:Y #define ISNUM(a) ('0'<=(a) && (a)<='9') #define ISCAP(a) ('A'<=(a) && (a)<='Z') #define ISSML(a) ('a'<=(a) && (a)<='z') #define ISALP(a) (ISCAP(a) || ISSML(a)) #define MXX 10000000000 #define MNN -MXX #define ISVALID(X,Y,N,M) ((X)>=1 && (X)<=(N) && (Y)>=1 && (Y)<=(M)) #define LLI long long int #define VI vector<int> #define VLLI vector<long long int> #define MII map<int,int> #define SI set<int> #define PB push_back #define MSI map<string,int> #define PII pair<int,int> #define PLLI pair<LLI,LLI> #define PDD pair<double,double> #define FREP(i,I,N) for(int (i)=(int)(I);(i)<=(int)(N);(i)++) #define eps 0.0000000001 #define RFREP(i,N,I) for(int (i)=(int)(N);(i)>=(int)(I);(i)--) #define SORTV(VEC) sort(VEC.begin(),VEC.end()) #define SORTVCMP(VEC,cmp) sort(VEC.begin(),VEC.end(),cmp) #define REVV(VEC) reverse(VEC.begin(),VEC.end()) #define INRANGED(val,l,r) (((l)<(val) || fabs((val)-(l))<eps) && ((val)<(r) || fabs((val)-(r))<eps)) #define INRANGEI(val,l,r) ((val)>=(l) && (val)<=(r)) #define MSET(a,b) memset(a,b,sizeof(a)) using namespace std; using namespace __gnu_pbds; //int dx[]={1,0,-1,0};int dy[]={0,1,0,-1}; //4 Direction //int dx[]={1,1,0,-1,-1,-1,0,1};int dy[]={0,1,1,1,0,-1,-1,-1};//8 direction //int dx[]={2,1,-1,-2,-2,-1,1,2};int dy[]={1,2,2,1,-1,-2,-2,-1};//Knight Direction //int dx[]={2,1,-1,-2,-1,1};int dy[]={0,1,1,0,-1,-1}; //Hexagonal Direction //typedef tree < int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update > ordered_set; int main(){ int n,k; scanf("%d %d",&n,&k); FREP(i,1,k){ if(n%10)n--; else n/=10; } cout<<n<<"\n"; return 0; }
[ "1205112.zm@ugrad.cse.buet.ac.bd" ]
1205112.zm@ugrad.cse.buet.ac.bd
5e350a3e892e1e6acd9a47077f688859d91cfd34
d6258ae3c0fd9f36efdd859a2c93ab489da2aa9b
/fulldocset/add/codesnippet/CPP/t-system.runtime.remotin_17_2.cpp
6c9e53f127d37a3adf799d125740ea97e2ae3f91
[ "CC-BY-4.0", "MIT" ]
permissive
OpenLocalizationTestOrg/ECMA2YamlTestRepo2
ca4d3821767bba558336b2ef2d2a40aa100d67f6
9a577bbd8ead778fd4723fbdbce691e69b3b14d4
refs/heads/master
2020-05-26T22:12:47.034527
2017-03-07T07:07:15
2017-03-07T07:07:15
82,508,764
1
0
null
2017-02-28T02:14:26
2017-02-20T02:36:59
Visual Basic
UTF-8
C++
false
false
280
cpp
using namespace System; using namespace System::Runtime::Remoting; public ref class Remotable: public MarshalByRefObject { private: int callCount; public: Remotable() : callCount( 0 ) {} int GetCount() { callCount++; return (callCount); } };
[ "tianzh@microsoft.com" ]
tianzh@microsoft.com
b7801d602b62dc4051cc85ecc4a9fe8dcf2dbb34
598899681a690d8ef928e66aa10007fde384dcf0
/BTP-Project/MS3/Good.h
76af801ac369f81e6894470b6fcafdd56c0f86ae
[]
no_license
HyperTHD/BTP200-S2019
73710b4aa8426ad464db106d09a72ceb209b21cc
7c922b4976777aafe7f807f236729da276b7a8ef
refs/heads/master
2021-02-16T03:29:06.959010
2020-03-04T17:35:57
2020-03-04T17:35:57
244,961,791
0
0
null
null
null
null
UTF-8
C++
false
false
2,288
h
/* Name: Abdulbasid Guled Student Number: 156024184 Email: aguled5@myseneca.ca Due Date: July 30, 2019 Milestone 3 */ #ifndef _AID_GOOD_H #define _AID_GOOD_H #include <iostream> #include <fstream> #include "Error.h" namespace aid { const int max_sku_length = 7; const int max_unit_length = 10; const int max_name_length = 75; const double tax_rate = 0.13; class Good { // Private Variables char m_type; // Type of the Good char m_SKU[max_sku_length + 1]; // Good's SKU char m_Unit[max_unit_length + 1]; // Good's Unit char* m_name; // Good's Name int m_onHand; // What we have int m_needed; // What we need double m_unitPrice; // Price of Good Unit before applying any taxes bool m_taxStatus; // Can the good be taxed? Error m_errorState; protected: void name(const char*); const char* name() const; const char* sku() const; const char* unit() const; bool taxed() const; double itemPrice() const; double itemCost() const; void message(const char*); bool isClear() const; public: Good(char type = 'N'); Good(const char*, const char*, const char*, int = 0, bool = true, double = 0.0, int = 0); Good(const Good& good); Good& operator=(const Good& good); ~Good(); std::fstream& store(std::fstream& file, bool newLine = true) const; std::fstream& load(std::fstream& file); std::ostream& write(std::ostream& os, bool linear) const; std::istream& read(std::istream& is); bool operator==(const char*) const; double total_cost() const; // Includes Taxes void quantity(int); // Increments onHand by number received bool isEmpty() const; int qtyNeeded() const; // Returns m_needed int quantity() const; // Returns m_onHand bool operator>(const char*) const; bool operator>(const Good&) const; int operator+=(int); // updates onHand }; // Helper Functions std::ostream& operator<<(std::ostream&, const Good&); std::istream& operator>>(std::istream&, Good&); double operator+=(double&, const Good&); } #endif
[ "aguled5@myseneca.ca" ]
aguled5@myseneca.ca
fa2671af1983820744e8b14437250aa7d494c941
297497957c531d81ba286bc91253fbbb78b4d8be
/third_party/libwebrtc/modules/audio_processing/aec3/echo_remover_metrics_unittest.cc
340ab4e20fdcae5246f2347943fc6d404f4166e6
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
marco-c/gecko-dev-comments-removed
7a9dd34045b07e6b22f0c636c0a836b9e639f9d3
61942784fb157763e65608e5a29b3729b0aa66fa
refs/heads/master
2023-08-09T18:55:25.895853
2023-08-01T00:40:39
2023-08-01T00:40:39
211,297,481
0
0
NOASSERTION
2019-09-29T01:27:49
2019-09-27T10:44:24
C++
UTF-8
C++
false
false
4,787
cc
#include "modules/audio_processing/aec3/echo_remover_metrics.h" #include <math.h> #include <cmath> #include "modules/audio_processing/aec3/aec3_fft.h" #include "modules/audio_processing/aec3/aec_state.h" #include "test/gtest.h" namespace webrtc { #if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID) TEST(UpdateDbMetricDeathTest, NullValue) { std::array<float, kFftLengthBy2Plus1> value; value.fill(0.f); EXPECT_DEATH(aec3::UpdateDbMetric(value, nullptr), ""); } #endif TEST(UpdateDbMetric, Updating) { std::array<float, kFftLengthBy2Plus1> value; std::array<EchoRemoverMetrics::DbMetric, 2> statistic; statistic.fill(EchoRemoverMetrics::DbMetric(0.f, 100.f, -100.f)); constexpr float kValue0 = 10.f; constexpr float kValue1 = 20.f; std::fill(value.begin(), value.begin() + 32, kValue0); std::fill(value.begin() + 32, value.begin() + 64, kValue1); aec3::UpdateDbMetric(value, &statistic); EXPECT_FLOAT_EQ(kValue0, statistic[0].sum_value); EXPECT_FLOAT_EQ(kValue0, statistic[0].ceil_value); EXPECT_FLOAT_EQ(kValue0, statistic[0].floor_value); EXPECT_FLOAT_EQ(kValue1, statistic[1].sum_value); EXPECT_FLOAT_EQ(kValue1, statistic[1].ceil_value); EXPECT_FLOAT_EQ(kValue1, statistic[1].floor_value); aec3::UpdateDbMetric(value, &statistic); EXPECT_FLOAT_EQ(2.f * kValue0, statistic[0].sum_value); EXPECT_FLOAT_EQ(kValue0, statistic[0].ceil_value); EXPECT_FLOAT_EQ(kValue0, statistic[0].floor_value); EXPECT_FLOAT_EQ(2.f * kValue1, statistic[1].sum_value); EXPECT_FLOAT_EQ(kValue1, statistic[1].ceil_value); EXPECT_FLOAT_EQ(kValue1, statistic[1].floor_value); } TEST(TransformDbMetricForReporting, DbFsScaling) { std::array<float, kBlockSize> x; FftData X; std::array<float, kFftLengthBy2Plus1> X2; Aec3Fft fft; x.fill(1000.f); fft.ZeroPaddedFft(x, Aec3Fft::Window::kRectangular, &X); X.Spectrum(Aec3Optimization::kNone, X2); float offset = -10.f * std::log10(32768.f * 32768.f); EXPECT_NEAR(offset, -90.3f, 0.1f); EXPECT_EQ( static_cast<int>(30.3f), aec3::TransformDbMetricForReporting( true, 0.f, 90.f, offset, 1.f / (kBlockSize * kBlockSize), X2[0])); } TEST(TransformDbMetricForReporting, Limits) { EXPECT_EQ(0, aec3::TransformDbMetricForReporting(false, 0.f, 10.f, 0.f, 1.f, 0.001f)); EXPECT_EQ(10, aec3::TransformDbMetricForReporting(false, 0.f, 10.f, 0.f, 1.f, 100.f)); } TEST(TransformDbMetricForReporting, Negate) { EXPECT_EQ(10, aec3::TransformDbMetricForReporting(true, -20.f, 20.f, 0.f, 1.f, 0.1f)); EXPECT_EQ(-10, aec3::TransformDbMetricForReporting(true, -20.f, 20.f, 0.f, 1.f, 10.f)); } TEST(DbMetric, Update) { EchoRemoverMetrics::DbMetric metric(0.f, 20.f, -20.f); constexpr int kNumValues = 100; constexpr float kValue = 10.f; for (int k = 0; k < kNumValues; ++k) { metric.Update(kValue); } EXPECT_FLOAT_EQ(kValue * kNumValues, metric.sum_value); EXPECT_FLOAT_EQ(kValue, metric.ceil_value); EXPECT_FLOAT_EQ(kValue, metric.floor_value); } TEST(DbMetric, UpdateInstant) { EchoRemoverMetrics::DbMetric metric(0.f, 20.f, -20.f); constexpr float kMinValue = -77.f; constexpr float kMaxValue = 33.f; constexpr float kLastValue = (kMinValue + kMaxValue) / 2.0f; for (float value = kMinValue; value <= kMaxValue; value++) metric.UpdateInstant(value); metric.UpdateInstant(kLastValue); EXPECT_FLOAT_EQ(kLastValue, metric.sum_value); EXPECT_FLOAT_EQ(kMaxValue, metric.ceil_value); EXPECT_FLOAT_EQ(kMinValue, metric.floor_value); } TEST(DbMetric, Constructor) { EchoRemoverMetrics::DbMetric metric; EXPECT_FLOAT_EQ(0.f, metric.sum_value); EXPECT_FLOAT_EQ(0.f, metric.ceil_value); EXPECT_FLOAT_EQ(0.f, metric.floor_value); metric = EchoRemoverMetrics::DbMetric(1.f, 2.f, 3.f); EXPECT_FLOAT_EQ(1.f, metric.sum_value); EXPECT_FLOAT_EQ(2.f, metric.floor_value); EXPECT_FLOAT_EQ(3.f, metric.ceil_value); } TEST(EchoRemoverMetrics, NormalUsage) { EchoRemoverMetrics metrics; AecState aec_state(EchoCanceller3Config{}, 1); std::array<float, kFftLengthBy2Plus1> comfort_noise_spectrum; std::array<float, kFftLengthBy2Plus1> suppressor_gain; comfort_noise_spectrum.fill(10.f); suppressor_gain.fill(1.f); for (int j = 0; j < 3; ++j) { for (int k = 0; k < kMetricsReportingIntervalBlocks - 1; ++k) { metrics.Update(aec_state, comfort_noise_spectrum, suppressor_gain); EXPECT_FALSE(metrics.MetricsReported()); } metrics.Update(aec_state, comfort_noise_spectrum, suppressor_gain); EXPECT_TRUE(metrics.MetricsReported()); } } }
[ "mcastelluccio@mozilla.com" ]
mcastelluccio@mozilla.com
e50336a9bd131eaef94830f345c26bf474d2272f
a26f2518cb58df647e142ae96bf0b45459d439f8
/WCS/13/Balanced Sequence.cpp
484fbd615a8d7e57197929cb4c1d5d6a6082fc6e
[ "MIT" ]
permissive
BlackVS/Hackerrank
ddf857fc865830b9c73c200ac004684beb3a4805
017159a2354673dbca14e409e088798c9a54d7e1
refs/heads/master
2020-03-25T23:19:54.362477
2018-08-17T09:15:49
2018-08-17T09:15:49
144,270,975
0
0
null
null
null
null
UTF-8
C++
false
false
660
cpp
#include <bits/stdc++.h> #include <stack> #include <iostream> #include <string> using namespace std; #define boost std::ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0) int solve(string s) { stack<char> stack; for (int i = 0; i<s.length(); i++) { if (s[i] == ')' && !stack.empty()) { if (stack.top() == '(' ) stack.pop(); else stack.push(s[i]); } else stack.push(s[i]); } char p = ' '; int cnt = 0; while(!stack.empty()) { char c = stack.top(); if (c != p) { cnt++; p = c; } stack.pop(); } return cnt; } int main() { int n; string s; boost; cin >> n >> s; int res=solve(s); cout << res; }
[ "vvs@polesye.com" ]
vvs@polesye.com
27772d3041abb09fd0b48bdf679c8725b0c3fabc
e7ec8d359acef8fc4483d43695aed78fff9844c1
/DrawDemo/PenWidthDialog.h
e6a67ea5fc837acb88c7f77f7f9cdea612502e1c
[ "MIT" ]
permissive
qdhqf/DrawDemo
bbc4d522035a4fbfffed945339f1bf3937b96589
339b83d73da4b2805a2cb1d1358b071f1655d8cc
refs/heads/master
2020-05-17T20:45:15.658488
2018-01-18T02:28:36
2018-01-18T02:28:36
null
0
0
null
null
null
null
GB18030
C++
false
false
778
h
#pragma once #include "afxcmn.h" #include "afxwin.h" // CPenWidthDialog 对话框 class CPenWidthDialog : public CDialogEx { DECLARE_DYNAMIC(CPenWidthDialog) public: CPenWidthDialog(unsigned short penWidthInit, CWnd* pParent = NULL); // 标准构造函数 virtual ~CPenWidthDialog(); // 变量 private: unsigned short penWidth; CSliderCtrl slider; CStatic staticText; CStatic preview; CRect previewRect; CDC *pPreviewDC; // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_PEN_WIDTH_DIALOG }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: virtual BOOL OnInitDialog(); unsigned short GetPenWidth(); afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); };
[ "samzhao0727@gmail.com" ]
samzhao0727@gmail.com
ef6c5b8e2e437f036b56f9324577fe63464458bc
bec81245f0bf2c524cda0fbca4040438ef9af64f
/firstConsole/ExpressionCalculator.cxx
78abd4bd1ee1423e77f8cb745b789165bf8956a8
[]
no_license
lyyiangang/Test_C_Plus_Plus
e607e44be8b3cb9afdb71c695f3e875f66415a33
94e8d7adeeff162c3da08ce493629a421586b678
refs/heads/master
2021-01-11T23:33:07.069703
2017-05-05T14:13:39
2017-05-05T14:13:39
78,598,548
0
0
null
null
null
null
UTF-8
C++
false
false
3,410
cxx
#include "stdafx.h" #include <vector> #include <stack> #include <functional> #include <sstream> float ExpressionCalculator(const std::string& exp) { std::unordered_map<char, int> operatorPriority{ { '(',6 }, { '*',4 }, { '/',4 }, { '+',2 }, { '-',2 }, { ')',1 }, { '#',0 } }; std::string copiedExp = exp; copiedExp.append("#"); auto opertor2Num = [](float numA, float numB, char opertorToken)->float { float result = 0.0; switch (opertorToken) { case '+': result = numA + numB; break; case '-':result = numA - numB; break; case '*':result = numA*numB; break; case '/':result = numA / numB; break; default: assert(false); break; } return result; }; std::stack<float> dataStack; std::stack<char> operatorStack; std::ostringstream iStream; for (int ii = 0; ii < copiedExp.size(); ++ii) { char curChar = copiedExp[ii]; if (curChar == ' ') continue; bool isOperator = operatorPriority.find(curChar) != operatorPriority.end(); if (!isOperator) { iStream << curChar; } if ((isOperator || ii == copiedExp.size() - 1) && !iStream.str().empty()) { dataStack.push(std::atof(iStream.str().c_str())); iStream.str(""); } if (isOperator) { if (operatorStack.empty()) { operatorStack.push(curChar); } else { char preOperator = operatorStack.top(); if (preOperator == '(' && curChar == ')') { operatorStack.pop(); continue; } if (operatorPriority[preOperator] >= operatorPriority[curChar] && preOperator != '(') { operatorStack.pop(); float numA = dataStack.top(); dataStack.pop(); float numB = dataStack.top(); dataStack.pop(); float result = opertor2Num(numB, numA, preOperator); dataStack.push(result); --ii; continue; } else { operatorStack.push(curChar); } } } } assert(dataStack.size() == 1 && operatorStack.size() == 1); return dataStack.top(); } void TestExpression() { const float epsilon = 1e-6; auto IsEqual = [&](float valA, float valB)->bool { return std::fabs(valA - valB) < epsilon; }; std::vector<std::pair<std::string, float>> testEntries{ { "(2)", 2 }, { "((2.5))", 2.5 }, { "(2+5/3)", 3.666666666666667 }, { "(3*6/5+2)-33/8*9-7", -38.525 }, { "(233)",233 }, { "22.5",22.5 } }; for (const auto& curPair : testEntries) { float result = ExpressionCalculator(curPair.first); if (!IsEqual(result, curPair.second)) std::cout << "Expression:" << curPair.first << "result is:" << result << ",want:" << curPair.second << std::endl; } std::cout << "all tests pass" << std::endl; } int _tmain(int argc, _TCHAR* argv[]) { TestExpression(); getchar(); return 0; }
[ "lyyiangang@sina.com" ]
lyyiangang@sina.com
59c1125a6b1f22e89523880400f622eabfd6e567
c2ff60b563572770748a07d6f7c872b9c989cf74
/src/CVAppEngine/InputHandlerTest/InputHandlerTest.cpp
9a5c2718b0667382d62c169f6135903a1c71b455
[]
no_license
arkarandil/Magisterka
fde8719f0d2895452626519108ec1d124c071d78
9ab6895af25abee6dbdfb929e438bd43a1fa8785
refs/heads/master
2016-09-06T09:08:20.772529
2012-01-18T06:48:56
2012-01-18T06:48:56
3,070,520
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
3,131
cpp
// OpenCVTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include "InputHandler.h" #include "InputFrame.h" #include "CameraInputHandler.h" #include "VideoInputHandler.h" #include "ITaskScheduler.h" #include "FIFOTaskQueue.h" #include "ITask.h" #include "ImgDataManager.h" #include <direct.h> void TaskShedulerTest(); using namespace std; using namespace cv; int _tmain(int argc, _TCHAR* argv[]) { TaskShedulerTest(); ImgDataManager::Instance().SetWorkingDir("temporary"); int IDs[]={0}; char* paths[]={"H:\\Dyplom\\Movies\\MVI_0195.MOV"}; VideoInputHandler*camera =new VideoInputHandler(1); if(!camera->ConnectVideos(paths)){ cout<<"Wrong camera IDs"<<endl; system("PAUSE"); return -1; } InputHandler *input=camera; camera->StartCapturing(); cvNamedWindow ("3D Webcam left", CV_WINDOW_AUTOSIZE); //cvNamedWindow ("3D Webcam right", CV_WINDOW_AUTOSIZE); InputFrame * f; int lastInputFrame=0; int key; bool paused = false; bool manualControl = false; while(true) { key=cv::waitKey(5); switch(key) { case 'q': goto finish; case 'p': input->PauseCapturing(); paused=true; break; case 'r': input->ResumeCapturing(); paused=false; break; case 'b': if(lastInputFrame>0) { lastInputFrame--; manualControl = true; } break; case 'f': if(lastInputFrame<input->GetLatestFrameCapturedIndex()-1) { lastInputFrame++; manualControl = true; } break; } if(!paused && !manualControl) { f = input->ProcessNextFrame(); if(f!=NULL) { ImgDataManager::Instance().AddNewFrame("test",f); IplImage* im = ImgDataManager::Instance().GetImage("test",lastInputFrame,0); cvShowImage ("3D Webcam left", im); //cvShowImage ("3D Webcam right", f->m_views[1]); lastInputFrame=MAX(0,input->GetLastFrameProcessedIndex()-1); } } else if(manualControl) { f=input->ProcessFrameWithIndex(lastInputFrame); if(f!=NULL) { cvShowImage ("3D Webcam left", f->_views[0]); //cvShowImage ("3D Webcam right", f->m_views[1]); } manualControl = false; } } finish: input->StopCapturing(); delete camera; return 0; } int *a,*b; class IncrementTask:public ITask { public: IncrementTask(int* i):_value(i){} void Perform() { cout<<"Increment begun"<<endl; Sleep(100); (*_value)++; cout<<"Increment finished"<<endl; } private: int* _value; }; void TaskShedulerTest() { a=new int(); *a=0; b=new int(); *b=0; ITaskScheduler* queue = new FIFOTaskQueue(); ITask* task1 = new IncrementTask(a); ITask* task2 = new IncrementTask(b); ITask* task3 = new IncrementTask(a); assert(*a==0); assert(*b==0); queue->ScheduleNewTask(&task1); queue->ScheduleNewTask(&task2); queue->ScheduleNewTask(&task3); assert(*a==0); assert(*b==0); queue->StartWork(); assert(*a==0); assert(*b==0); //zakładam że task trwa 0.1 sec Sleep(110); assert(*a==1); assert(*b==0); Sleep(110); assert(*a==1); assert(*b==1); Sleep(110); assert(*a==2); assert(*b==1); queue->StopWork(); } /* Increment after one second */
[ "piotr.czerw@gmail.com" ]
piotr.czerw@gmail.com
1cf7c587666aa3072ecbaaea8f7677f5ea1e7c69
93e5bf800dddade222c29920767eff7321147739
/LaivuMusis/LaivuMusis/Zaidimas.h
d420adcc78beee2502b5c09cdc43db3c8382a439
[]
no_license
IgnasSteponenas/laivynas
3037475a8dd0039bf9c6729c81e2c299bf34a7ce
a791748d87cb6ec7a8f471eea629fbf79ac2417c
refs/heads/master
2020-05-24T20:42:59.818122
2019-05-21T07:49:59
2019-05-21T07:49:59
187,460,489
0
0
null
null
null
null
UTF-8
C++
false
false
1,211
h
#pragma once #include<vector> using namespace std; class Zaidimas { private: const static int plotis = 10; const static int ilgis = 10; char lentele[plotis][ilgis]; char lenteleBOTmatoma[plotis][ilgis]; char lenteleBOT[plotis][ilgis]; vector<int> zmogausX; vector<int> zmogausY; vector<int> BOTX; vector<int> BOTY; public: Zaidimas(); void pradzia(); void zaidejoLaivuIvedimas(int & x, int & y, char & kryptis, bool reikia); void BOTlaivuIvedimas(); void numustoLaivoTikrinimas(int x, int y, char irasomaLentele[][10], char tikrinamaLentele[][10], vector<int>& kurpaimtiX, vector<int>& kurpaimtiY); void saudimasZmogaus(); void saudimasBOT(); void saudimas(int x, int y, char irasomaLentele[][10], char tikrinamaLentele[][10], vector<int>& kurpaimtiX, vector<int>& kurpaimtiY); bool laimejimas(vector<int>& kurX, vector<int>& kurY, char testtikrinamaLentele[][10]); bool zaidimopabaiga(); void laimejimoPranesimas(); ~Zaidimas(); void spausdinimas(); void surasymas(int x, int y, char kryptis, int vieta, vector<int>& kurIrasytiX, vector<int>& kurIrasytiY); void zaidejoPradiniaiLaivai(); bool statimoTikrinimas(int kiekVietu, char puse, int x, int y, char kurilentele[][10]); };
[ "50793829+IgnasSteponenas@users.noreply.github.com" ]
50793829+IgnasSteponenas@users.noreply.github.com
d343619d7e8dfb3e9a89f226bc0337f361a03c10
16c25858ef1e5f29f653580d4aacda69a50c3244
/hikr/build/Android/Preview/app/src/main/include/Uno.UX.PropertyObject.h
4fefd4d5faad50c4eeb70c1135723111b5ac3d7b
[]
no_license
PoliGomes/tutorialfuse
69c32ff34ba9236bc3e84e99e00eb116d6f16422
0b7fadfe857fed568a5c2899d176acf45249d2b8
refs/heads/master
2021-08-16T02:50:08.993542
2017-11-18T22:04:56
2017-11-18T22:04:56
111,242,469
0
0
null
null
null
null
UTF-8
C++
false
false
2,148
h
// This file was generated based on /usr/local/share/uno/Packages/UnoCore/1.2.2/source/uno/ux/$.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{namespace Uno{namespace Collections{struct Dictionary;}}} namespace g{namespace Uno{namespace Collections{struct List;}}} namespace g{namespace Uno{namespace UX{struct PropertyObject;}}} namespace g{namespace Uno{namespace UX{struct Selector;}}} namespace g{ namespace Uno{ namespace UX{ // public class PropertyObject :327 // { uType* PropertyObject_typeof(); void PropertyObject__ctor__fn(PropertyObject* __this); void PropertyObject__AddPropertyListener_fn(PropertyObject* __this, uObject* listener); void PropertyObject__EmulatePropertyChanged_fn(PropertyObject* obj, ::g::Uno::UX::Selector* sel, uObject* origin); void PropertyObject__GetSimulatedProperty_fn(PropertyObject* __this, uString* name, uObject** __retval); void PropertyObject__New1_fn(PropertyObject** __retval); void PropertyObject__OnPropertyChanged_fn(PropertyObject* __this, ::g::Uno::UX::Selector* property); void PropertyObject__OnPropertyChanged1_fn(PropertyObject* __this, ::g::Uno::UX::Selector* property, uObject* origin); void PropertyObject__RemovePropertyListener_fn(PropertyObject* __this, uObject* listener); void PropertyObject__SetSimulatedProperty_fn(PropertyObject* __this, uString* name, uObject* value, uObject* origin); struct PropertyObject : uObject { uStrong< ::g::Uno::Collections::List*> _propListeners; uStrong< ::g::Uno::Collections::Dictionary*> _simulatedProps; void ctor_(); void AddPropertyListener(uObject* listener); uObject* GetSimulatedProperty(uString* name); void OnPropertyChanged(::g::Uno::UX::Selector property); void OnPropertyChanged1(::g::Uno::UX::Selector property, uObject* origin); void RemovePropertyListener(uObject* listener); void SetSimulatedProperty(uString* name, uObject* value, uObject* origin); static void EmulatePropertyChanged(PropertyObject* obj, ::g::Uno::UX::Selector sel, uObject* origin); static PropertyObject* New1(); }; // } }}} // ::g::Uno::UX
[ "poliana.ph@gmail.com" ]
poliana.ph@gmail.com
350dffa81a86902c942b59d1b0e7eee9ec739630
59466a1610a8becd88b18fd6e33ab9df17fe0602
/seventh/mostcommonword.cpp
62243059f1b12b2a963f6e524d096ddb5011d1b7
[]
no_license
jiakum/leetcode
c473ea481724feb4156a087bbb266e5298e3610b
8c09ce853dc4ef373b875f82600f3bfc01368adf
refs/heads/master
2020-03-27T18:58:25.369889
2019-01-07T10:08:17
2019-01-07T10:08:17
146,956,900
0
0
null
null
null
null
UTF-8
C++
false
false
1,404
cpp
class Solution { public: string mostCommonWord(string paragraph, vector<string>& banned) { map<string, int> lmap; set<string> bset; map<string, int>::iterator iter; int i, size = paragraph.size(), j, maxfreq = 0; string bstr, result; char c; for(i = 0;i < banned.size();i++) { string &ban = banned[i]; string str; for(j = 0;j < ban.size();j++) { c = tolower(ban[j]); str.push_back(c); } bset.insert(str); } for(i = 0;i < size;i++) { string str; while(isalpha(paragraph[i])) { str.push_back(tolower(paragraph[i])); i++; } if(bset.find(str) != bset.end() || str.empty()) continue; iter = lmap.find(str); if(iter == lmap.end()) lmap[str] = 1; else iter->second++; } for(iter = lmap.begin();iter != lmap.end();iter++) { if(iter->second > maxfreq) { maxfreq = iter->second; result = iter->first; } } return result; } };
[ "jkma@actions-semi.com" ]
jkma@actions-semi.com
b7b67afbacc0df7a684c880208d20818b161917f
3872cfaed74cc34d638612d48253f949b63fb929
/src/atm_connector.hpp
8250bc30d053f51bc1f03163dd3a2bbf33f244bc
[ "MIT" ]
permissive
wuyuanyi135/Automaton
739cd118f13a879a290adcb94eb4a6c9706029a3
23772f1ad55ba5f2b11042ce638a86abacd5a659
refs/heads/master
2022-04-21T04:52:52.198514
2020-04-20T08:09:53
2020-04-20T08:09:53
255,166,619
1
0
MIT
2020-04-12T20:42:39
2020-04-12T20:42:38
null
UTF-8
C++
false
false
1,274
hpp
#pragma once #include "Arduino.h" typedef void ( *atm_cb_push_t )( int idx, int v, int up ); typedef bool ( *atm_cb_pull_t )( int idx ); class atm_connector { public: enum { MODE_NULL, MODE_PUSHCB, MODE_PULLCB, MODE_MACHINE }; // bits 0, 1, 2 - Mode enum { LOG_AND, LOG_OR, LOG_XOR }; // bits 3, 4 - Logical operator enum { REL_NULL, REL_EQ, REL_NEQ, REL_LT, REL_GT, REL_LTE, REL_GTE }; // bits 5, 6, 7 - Relational operator uint8_t mode_flags; union { struct { union { atm_cb_push_t push_callback; atm_cb_pull_t pull_callback; }; int callback_idx; // +2 = 5 bytes per connector/object }; struct { union { Machine* machine; }; int event; }; }; void set( Machine* m, int evt, int8_t logOp = 0, int8_t relOp = 0 ); void set( atm_cb_push_t callback, int idx, int8_t logOp = 0, int8_t relOp = 0 ); void set( atm_cb_pull_t callback, int idx, int8_t logOp = 0, int8_t relOp = 0 ); bool push( int v = 0, int up = 0, bool overrideCallback = false ); // returns false (only) if callback is set! int pull( int v = 0, int up = 0, bool def_value = false ); int8_t logOp( void ); int8_t relOp( void ); int8_t mode( void ); };
[ "tinkerspy@myown.mailcan.com" ]
tinkerspy@myown.mailcan.com
baf1cabc42e90b7cd600099c32005c32b765d148
2bec5a52ce1fb3266e72f8fbeb5226b025584a16
/energy/src/kgroups.cpp
eb2d837be75d8190c1c13cd4e05bb709f1aacf3c
[]
no_license
akhikolla/InformationHouse
4e45b11df18dee47519e917fcf0a869a77661fce
c0daab1e3f2827fd08aa5c31127fadae3f001948
refs/heads/master
2023-02-12T19:00:20.752555
2020-12-31T20:59:23
2020-12-31T20:59:23
325,589,503
9
2
null
null
null
null
UTF-8
C++
false
false
3,407
cpp
#include <Rcpp.h> using namespace Rcpp; int kgroups_update(NumericMatrix x, int k, IntegerVector clus, IntegerVector sizes, NumericVector within, bool distance); List kgroups_start(NumericMatrix x, int k, IntegerVector clus, int iter_max, bool distance); int kgroups_update(NumericMatrix x, int k, IntegerVector clus, IntegerVector sizes, NumericVector w, bool distance) { /* * k-groups one pass through sample moving one point at a time * x: data matrix or distance * k: number of clusters * clus: clustering vector clus(i)==j ==> x_i is in cluster j * sizes: cluster sizes * within: vector of within cluster dispersions * distance: true if x is distance matrix * update clus, sizes, and withins * return count = number of points moved */ int n = x.nrow(), d = x.ncol(); int i, j, I, J, ix, nI, nJ; NumericVector rowdst(k), e(k); int best, count = 0; double dsum, dif; for (ix = 0; ix < n; ix++) { I = clus(ix); nI = sizes(I); if (nI > 1) { // calculate the E-distances of this point to each cluster rowdst.fill(0.0); for (i = 0; i < n; i++) { J = clus(i); if (distance == true) { rowdst(J) += x(ix, i); } else { dsum = 0.0; for (j = 0; j < d; j++) { dif = x(ix, j) - x(i, j); dsum += dif * dif; } rowdst(J) += sqrt(dsum); } } for (J = 0; J < k; J++) { nJ = sizes(J); e(J) = (2.0 / (double) nJ) * (rowdst(J) - w(J)); } best = Rcpp::which_min(e); if (best != I) { // move this point and update nI = sizes(I); nJ = sizes(best); w(best) = (((double) nJ) * w(best) + rowdst(best)) / ((double) (nJ + 1)); w(I) = (((double) nI) * w(I) - rowdst(I)) / ((double) (nI - 1)); clus(ix) = best; sizes(I) = nI - 1; sizes(best) = nJ + 1; count ++; // number of moves } } } return count; } // [[Rcpp::export]] List kgroups_start(NumericMatrix x, int k, IntegerVector clus, int iter_max, bool distance) { // k-groups clustering with initial clustering vector clus // up to iter_max iterations of n possible moves each // distance: true if x is distance matrix NumericVector within(k, 0.0); IntegerVector sizes(k, 0); double dif, dsum; int I, J, h, i, j; int n = x.nrow(), d = x.ncol(); for (i = 0; i < n; i++) { I = clus(i); sizes(I)++; for (j = 0; j < i; j++) { J = clus(j); if (I == J) { if (distance == true) { within(I) += x(i, j); } else { dsum = 0.0; for (h = 0; h < d; h++) { dif = x(i, h) - x(j, h); dsum += dif * dif; } within(I) += sqrt(dsum); } } } } for (I = 0; I < k; I++) within(I) /= ((double) sizes(I)); int it = 1, count = 1; count = kgroups_update(x, k, clus, sizes, within, distance); while (it < iter_max && count > 0) { count = kgroups_update(x, k, clus, sizes, within, distance); it++; } double W = Rcpp::sum(within); return List::create( _["within"] = within, _["W"] = W, _["sizes"] = sizes, _["cluster"] = clus, _["iterations"] = it, _["count"] = count); }
[ "akhilakollasrinu424jf@gmail.com" ]
akhilakollasrinu424jf@gmail.com
020adc1f7438326314316ab2bdc35e41f34133d9
974ed2407c816b86e827baed9acabde1907cfcc2
/Pow(x,n)/Pow(x,n).cpp
c513e7cd221c6b5d1a069a46598caac3bb91cfba
[]
no_license
xuermin/leetcode
7cf9521fd7d4d0241aa95a03edac0732227c27a0
36dc8b17c3248f22098a3183e920194941e28952
refs/heads/master
2021-09-10T10:01:35.637988
2018-03-24T07:05:00
2018-03-24T07:05:00
null
0
0
null
null
null
null
GB18030
C++
false
false
820
cpp
// Pow(x,n).cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<iostream> using namespace std; double myPow(double x, int n); double fastPow(double x, long long n); int main() { cout << myPow(1, -2147483648) << endl; return 0; } //double myPow(double x, int n) { // if (n < 0) { // long long N = n; // return myPow(1 / x, -N); // } // if (n == 0) // return 1; // else { // double m = myPow(x, n / 2); // if (n % 2 == 0) // return m*m; // else // return x*m*m; // } //} double fastPow(double x, long long n) { if (n == 0) { return 1.0; } double half = fastPow(x, n / 2); if (n % 2 == 0) { return half * half; } else { return half * half * x; } } double myPow(double x, int n) { long long N = n; if (N < 0) { x = 1 / x; N = -N; } return fastPow(x, N); }
[ "xemiracle@163.com" ]
xemiracle@163.com
e42aae6b9d7f1559badb9a78c4e07f7f7c8d652d
4b2457464779c2518584f7a6dfa56a90960e0870
/Benchmark/BenchmarkCommon/BenchmarkList.hpp
529e5e9651cffce44e7d065037456394f12bef53
[ "Apache-2.0" ]
permissive
SpaceGameEngine/SpaceGameEngine
5990c02b07b621c1b18ad6c68b0ddca3aa98275e
f1a2753834c225a742f1f03572739d2abec5a9aa
refs/heads/master
2023-08-23T18:25:49.024552
2022-04-01T07:51:22
2022-04-01T07:51:22
158,053,435
4
0
Apache-2.0
2022-07-03T13:54:07
2018-11-18T05:35:56
C++
UTF-8
C++
false
false
3,150
hpp
/* Copyright 2022 creatorlxd 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. */ #pragma once #include <benchmark/benchmark.h> #include "Container/List.hpp" #include <list> #include <cassert> void BM_StdListCreate(benchmark::State& state) { for (auto _ : state) { std::list<int> l; } } void BM_SgeListCreate(benchmark::State& state) { for (auto _ : state) { SpaceGameEngine::List<int> l; } } BENCHMARK(BM_StdListCreate)->Iterations(1000000); BENCHMARK(BM_SgeListCreate)->Iterations(1000000); inline const int list_test_size = 1024; void BM_StdListPushBack(benchmark::State& state) { for (auto _ : state) { std::list<int> l; for (int i = 0; i < list_test_size; ++i) { l.push_back(i); } } } void BM_SgeListPushBack(benchmark::State& state) { for (auto _ : state) { SpaceGameEngine::List<int> l; for (int i = 0; i < list_test_size; ++i) { l.PushBack(i); } } } BENCHMARK(BM_StdListPushBack)->Iterations(1000000); BENCHMARK(BM_SgeListPushBack)->Iterations(1000000); void BM_StdListInsert(benchmark::State& state) { for (auto _ : state) { std::list<int> l{0}; for (int i = 0; i < list_test_size; ++i) { auto iter = l.begin(); ++iter; l.insert(iter, i); } } } void BM_SgeListInsert(benchmark::State& state) { for (auto _ : state) { SpaceGameEngine::List<int> l{0}; for (int i = 0; i < list_test_size; ++i) { auto iter = l.GetBegin(); ++iter; l.Insert(iter, i); } } } BENCHMARK(BM_StdListInsert)->Iterations(10000); BENCHMARK(BM_SgeListInsert)->Iterations(10000); void BM_StdListRemove(benchmark::State& state) { for (auto _ : state) { std::list<int> l(list_test_size, 1); for (int i = 0; i < list_test_size - 1; ++i) { auto iter = l.begin(); ++iter; l.erase(iter); } } } void BM_SgeListRemove(benchmark::State& state) { for (auto _ : state) { SpaceGameEngine::List<int> l(list_test_size, 1); for (int i = 0; i < list_test_size - 1; ++i) { auto iter = l.GetBegin(); ++iter; l.Remove(iter); } } } BENCHMARK(BM_StdListRemove)->Iterations(10000); BENCHMARK(BM_SgeListRemove)->Iterations(10000); void BM_StdListIteration(benchmark::State& state) { for (auto _ : state) { std::list<int> l(list_test_size, 1); int cnt = 0; for (auto i = l.begin(); i != l.end(); ++i, ++cnt) { assert(*i == cnt); } } } void BM_SgeListIteration(benchmark::State& state) { for (auto _ : state) { SpaceGameEngine::List<int> l(list_test_size, 1); int cnt = 0; for (auto i = l.GetBegin(); i != l.GetEnd(); ++i, ++cnt) { assert(*i == cnt); } } } BENCHMARK(BM_StdListIteration)->Iterations(10000); BENCHMARK(BM_SgeListIteration)->Iterations(10000);
[ "1461637345@qq.com" ]
1461637345@qq.com
3e2ae693cecc8f4a1828592ab99ef8bdaa03fc4c
a88485042673e6467c9749a32ec25aece3551913
/CGI_Run_Add_JS/CGI_SCADA/CGI_SCADA_include/CGI_SCADA_define.cpp
0c7d23ff9f51e9b1787ed1bc020992abf316f603
[]
no_license
isliulin/20160125CGI_Src
3fb8a050ece8edf3e60848c9054f8fe3c0b24867
d0ab988265aef9cfc348837ce617ab4dcd6ed71b
refs/heads/master
2021-05-30T09:33:09.166619
2016-01-25T08:48:39
2016-01-25T08:48:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
141
cpp
#include "CGI_SCADA_define.h" QByteArray CGI_SCADA_define::s_baCookie = QByteArray(); QString CGI_SCADA_define::s_strIPAddress = QString();
[ "596896768@qq.com" ]
596896768@qq.com
d0a22b580861f9d6999503aff9fc43fc8244e602
33546aee6429d5b8f19a02e14699b6ebb5b34af8
/src/ui/events/ozone/device/udev/device_manager_udev.h
7c15e3b760e9d1db89718728b0f6d89d27cca27b
[ "BSD-3-Clause" ]
permissive
mYoda/CustomBrs
bdbf992c0db0bf2fd1821fa1fd0120ac77ffc011
493fc461eb7ea7321c51c6831fe737cfb21fdd3e
refs/heads/master
2022-11-22T09:11:37.873894
2022-11-10T10:02:49
2022-11-10T10:02:49
24,951,822
0
1
null
2022-11-02T14:39:34
2014-10-08T17:22:30
C++
UTF-8
C++
false
false
1,582
h
// Copyright 2014 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. #ifndef UI_EVENTS_OZONE_DEVICE_UDEV_DEVICE_MANAGER_UDEV_H_ #define UI_EVENTS_OZONE_DEVICE_UDEV_DEVICE_MANAGER_UDEV_H_ #include "base/message_loop/message_pump_libevent.h" #include "base/observer_list.h" #include "ui/events/ozone/device/device_manager.h" #include "ui/events/ozone/device/udev/scoped_udev.h" namespace ui { class DeviceEvent; class DeviceEventObserver; class DeviceManagerUdev : public DeviceManager, base::MessagePumpLibevent::Watcher { public: DeviceManagerUdev(); virtual ~DeviceManagerUdev(); private: scoped_ptr<DeviceEvent> ProcessMessage(udev_device* device); // Creates a device-monitor to look for device add/remove/change events. void CreateMonitor(); // DeviceManager overrides: virtual void ScanDevices(DeviceEventObserver* observer) OVERRIDE; virtual void AddObserver(DeviceEventObserver* observer) OVERRIDE; virtual void RemoveObserver(DeviceEventObserver* observer) OVERRIDE; // base::MessagePumpLibevent::Watcher overrides: virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE; virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE; scoped_udev udev_; scoped_udev_monitor monitor_; base::MessagePumpLibevent::FileDescriptorWatcher controller_; ObserverList<DeviceEventObserver> observers_; DISALLOW_COPY_AND_ASSIGN(DeviceManagerUdev); }; } // namespace ui #endif // UI_EVENTS_OZONE_DEVICE_UDEV_DEVICE_MANAGER_UDEV_H_
[ "nechayukanton@gmail.com" ]
nechayukanton@gmail.com
c49da1119af3e2dbc6c2257a642744143e698328
07eac873a7d246da59ab653d7f78f2f6a1cd867d
/7_9/1541.cpp
b24b756ffc658daa2fb1a424531c153eb5a51e75
[]
no_license
MinKyungHwi/C_plus_plus
766e0b391fa7e73d40aa6e2941abeefd094c72d5
2f3bce8771080a01dc5d208fe6e998216c6453ff
refs/heads/master
2022-11-16T00:54:28.233246
2020-07-11T13:30:10
2020-07-11T13:30:10
273,224,197
0
0
null
null
null
null
UTF-8
C++
false
false
514
cpp
#include <iostream> #include <string> using namespace std; int main() { string s; string temp; int count = 0; cin >> s; int ans = 0; bool bFirst = false; for(int i = 0 ; i <= s.length(); i++) { if (s[i] == '+' || s[i] == '-' || s[i] == '\0') { if (bFirst) { ans -= stoi(temp); } else { ans += stoi(temp); } if (s[i] == '-') bFirst = true; temp.clear(); temp.shrink_to_fit(); continue; } temp += s[i]; } cout << ans << endl; return 0; }
[ "49218251+MinKyungHwi@users.noreply.github.com" ]
49218251+MinKyungHwi@users.noreply.github.com
5a5cd05a728caadc3c0e19ccf404c2b2b8aa1bd6
b1fa00e8b9e534169e5a8e1b45459ada6522bee0
/lezip0100src/CPP/7zip/UI/FileManager/PanelSplitFile.cpp
efe33f5ed4adffc247b1375ba3d912251757f01c
[]
no_license
anbeibei/lezip
84f1febeb60c5382fdb12e9f2dbecdde022cdfe2
dd1dcf24a5e982da362280090f79d7c577ac7d09
refs/heads/master
2020-11-28T23:10:47.773639
2019-04-11T15:36:25
2019-04-11T15:36:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,614
cpp
// PanelSplitFile.cpp #include "StdAfx.h" #include "../../../Common/IntToString.h" #include "../../../Windows/ErrorMsg.h" #include "../../../Windows/FileName.h" #include "../GUI/ExtractRes.h" #include "resource.h" #include "App.h" #include "CopyDialog.h" #include "FormatUtils.h" #include "LangUtils.h" #include "SplitDialog.h" #include "SplitUtils.h" #include "PropertyNameRes.h" using namespace NWindows; using namespace NFile; using namespace NDir; static const char * const g_Message_FileWriteError = "File write error"; struct CVolSeqName { UString UnchangedPart; UString ChangedPart; CVolSeqName(): ChangedPart("000") {}; void SetNumDigits(UInt64 numVolumes) { ChangedPart = "000"; while (numVolumes > 999) { numVolumes /= 10; ChangedPart += '0'; } } bool ParseName(const UString &name) { if (name.Len() < 2) return false; if (name.Back() != L'1' || name[name.Len() - 2] != L'0') return false; unsigned pos = name.Len() - 2; for (; pos > 0 && name[pos - 1] == '0'; pos--); UnchangedPart.SetFrom(name, pos); ChangedPart = name.Ptr(pos); return true; } UString GetNextName(); }; UString CVolSeqName::GetNextName() { for (int i = (int)ChangedPart.Len() - 1; i >= 0; i--) { wchar_t c = ChangedPart[i]; if (c != L'9') { ChangedPart.ReplaceOneCharAtPos(i, (wchar_t)(c + 1)); break; } ChangedPart.ReplaceOneCharAtPos(i, L'0'); if (i == 0) ChangedPart.InsertAtFront(L'1'); } return UnchangedPart + ChangedPart; } class CThreadSplit: public CProgressThreadVirt { HRESULT ProcessVirt(); public: FString FilePath; FString VolBasePath; UInt64 NumVolumes; CRecordVector<UInt64> VolumeSizes; }; class CPreAllocOutFile { UInt64 _preAllocSize; public: NIO::COutFile File; UInt64 Written; CPreAllocOutFile(): _preAllocSize(0), Written(0) {} ~CPreAllocOutFile() { SetCorrectFileLength(); } void PreAlloc(UInt64 preAllocSize) { _preAllocSize = 0; if (File.SetLength(preAllocSize)) _preAllocSize = preAllocSize; File.SeekToBegin(); } bool Write(const void *data, UInt32 size, UInt32 &processedSize) throw() { bool res = File.Write(data, size, processedSize); Written += processedSize; return res; } void Close() { SetCorrectFileLength(); Written = 0; _preAllocSize = 0; File.Close(); } void SetCorrectFileLength() { if (Written < _preAllocSize) { File.SetLength(Written); _preAllocSize = 0; } } }; static const UInt32 kBufSize = (1 << 20); HRESULT CThreadSplit::ProcessVirt() { NIO::CInFile inFile; if (!inFile.Open(FilePath)) return GetLastError(); CPreAllocOutFile outFile; CMyBuffer buffer; if (!buffer.Allocate(kBufSize)) return E_OUTOFMEMORY; CVolSeqName seqName; seqName.SetNumDigits(NumVolumes); UInt64 length; if (!inFile.GetLength(length)) return GetLastError(); CProgressSync &sync = Sync; sync.Set_NumBytesTotal(length); UInt64 pos = 0; UInt64 prev = 0; UInt64 numFiles = 0; unsigned volIndex = 0; for (;;) { UInt64 volSize; if (volIndex < VolumeSizes.Size()) volSize = VolumeSizes[volIndex]; else volSize = VolumeSizes.Back(); UInt32 needSize = kBufSize; { const UInt64 rem = volSize - outFile.Written; if (needSize > rem) needSize = (UInt32)rem; } UInt32 processedSize; if (!inFile.Read(buffer, needSize, processedSize)) return GetLastError(); if (processedSize == 0) return S_OK; needSize = processedSize; if (outFile.Written == 0) { FString name = VolBasePath; name += '.'; name += us2fs(seqName.GetNextName()); sync.Set_FilePath(fs2us(name)); if (!outFile.File.Create(name, false)) { HRESULT res = GetLastError(); AddErrorPath(name); return res; } UInt64 expectSize = volSize; if (pos < length) { const UInt64 rem = length - pos; if (expectSize > rem) expectSize = rem; } outFile.PreAlloc(expectSize); } if (!outFile.Write(buffer, needSize, processedSize)) return GetLastError(); if (needSize != processedSize) throw g_Message_FileWriteError; pos += processedSize; if (outFile.Written == volSize) { outFile.Close(); sync.Set_NumFilesCur(++numFiles); if (volIndex < VolumeSizes.Size()) volIndex++; } if (pos - prev >= ((UInt32)1 << 22) || outFile.Written == 0) { RINOK(sync.Set_NumBytesCur(pos)); prev = pos; } } } void CApp::Split() { int srcPanelIndex = GetFocusedPanelIndex(); CPanel &srcPanel = Panels[srcPanelIndex]; if (!srcPanel.Is_IO_FS_Folder()) { srcPanel.MessageBox_Error_UnsupportOperation(); return; } CRecordVector<UInt32> indices; srcPanel.GetOperatedItemIndices(indices); if (indices.IsEmpty()) return; if (indices.Size() != 1) { srcPanel.MessageBox_Error_LangID(IDS_SELECT_ONE_FILE); return; } int index = indices[0]; if (srcPanel.IsItem_Folder(index)) { srcPanel.MessageBox_Error_LangID(IDS_SELECT_ONE_FILE); return; } const UString itemName = srcPanel.GetItemName(index); UString srcPath = srcPanel.GetFsPath() + srcPanel.GetItemPrefix(index); UString path = srcPath; unsigned destPanelIndex = (NumPanels <= 1) ? srcPanelIndex : (1 - srcPanelIndex); CPanel &destPanel = Panels[destPanelIndex]; if (NumPanels > 1) if (destPanel.IsFSFolder()) path = destPanel.GetFsPath(); CSplitDialog splitDialog; splitDialog.FilePath = srcPanel.GetItemRelPath(index); splitDialog.Path = path; if (splitDialog.Create(srcPanel.GetParent()) != IDOK) return; NFind::CFileInfo fileInfo; if (!fileInfo.Find(us2fs(srcPath + itemName))) { srcPanel.MessageBox_Error(L"Can not find file"); return; } if (fileInfo.Size <= splitDialog.VolumeSizes.Front()) { srcPanel.MessageBox_Error_LangID(IDS_SPLIT_VOL_MUST_BE_SMALLER); return; } const UInt64 numVolumes = GetNumberOfVolumes(fileInfo.Size, splitDialog.VolumeSizes); if (numVolumes >= 100) { wchar_t s[32]; ConvertUInt64ToString(numVolumes, s); if (::MessageBoxW(srcPanel, MyFormatNew(IDS_SPLIT_CONFIRM_MESSAGE, s), LangString(IDS_SPLIT_CONFIRM_TITLE), MB_YESNOCANCEL | MB_ICONQUESTION) != IDYES) return; } path = splitDialog.Path; NName::NormalizeDirPathPrefix(path); if (!CreateComplexDir(us2fs(path))) { DWORD lastError = ::GetLastError(); srcPanel.MessageBox_Error_2Lines_Message_HRESULT(MyFormatNew(IDS_CANNOT_CREATE_FOLDER, path), lastError); return; } { CThreadSplit spliter; spliter.NumVolumes = numVolumes; CProgressDialog &progressDialog = spliter; UString progressWindowTitle ("leya"); // LangString(IDS_APP_TITLE, 0x03000000); UString title = LangString(IDS_SPLITTING); progressDialog.ShowCompressionInfo = false; progressDialog.MainWindow = _window; progressDialog.MainTitle = progressWindowTitle; progressDialog.MainAddTitle = title; progressDialog.MainAddTitle.Add_Space(); progressDialog.Sync.Set_TitleFileName(itemName); spliter.FilePath = us2fs(srcPath + itemName); spliter.VolBasePath = us2fs(path + srcPanel.GetItemName_for_Copy(index)); spliter.VolumeSizes = splitDialog.VolumeSizes; // if (splitDialog.VolumeSizes.Size() == 0) return; // CPanel::CDisableTimerProcessing disableTimerProcessing1(srcPanel); // CPanel::CDisableTimerProcessing disableTimerProcessing2(destPanel); if (spliter.Create(title, _window) != 0) return; } RefreshTitleAlways(); // disableNotify.Restore(); // disableNotify.Restore(); // srcPanel.SetFocusToList(); // srcPanel.RefreshListCtrlSaveFocused(); } class CThreadCombine: public CProgressThreadVirt { HRESULT ProcessVirt(); public: FString InputDirPrefix; FStringVector Names; FString OutputPath; UInt64 TotalSize; }; HRESULT CThreadCombine::ProcessVirt() { NIO::COutFile outFile; if (!outFile.Create(OutputPath, false)) { HRESULT res = GetLastError(); AddErrorPath(OutputPath); return res; } CProgressSync &sync = Sync; sync.Set_NumBytesTotal(TotalSize); CMyBuffer bufferObject; if (!bufferObject.Allocate(kBufSize)) return E_OUTOFMEMORY; Byte *buffer = (Byte *)(void *)bufferObject; UInt64 pos = 0; FOR_VECTOR (i, Names) { NIO::CInFile inFile; const FString nextName = InputDirPrefix + Names[i]; if (!inFile.Open(nextName)) { HRESULT res = GetLastError(); AddErrorPath(nextName); return res; } sync.Set_FilePath(fs2us(nextName)); for (;;) { UInt32 processedSize; if (!inFile.Read(buffer, kBufSize, processedSize)) { HRESULT res = GetLastError(); AddErrorPath(nextName); return res; } if (processedSize == 0) break; UInt32 needSize = processedSize; if (!outFile.Write(buffer, needSize, processedSize)) { HRESULT res = GetLastError(); AddErrorPath(OutputPath); return res; } if (needSize != processedSize) throw g_Message_FileWriteError; pos += processedSize; RINOK(sync.Set_NumBytesCur(pos)); } } return S_OK; } extern void AddValuePair2(UString &s, UINT resourceID, UInt64 num, UInt64 size); static void AddInfoFileName(UString &dest, const UString &name) { dest += "\n "; dest += name; } void CApp::Combine() { int srcPanelIndex = GetFocusedPanelIndex(); CPanel &srcPanel = Panels[srcPanelIndex]; if (!srcPanel.IsFSFolder()) { srcPanel.MessageBox_Error_LangID(IDS_OPERATION_IS_NOT_SUPPORTED); return; } CRecordVector<UInt32> indices; srcPanel.GetOperatedItemIndices(indices); if (indices.IsEmpty()) return; int index = indices[0]; if (indices.Size() != 1 || srcPanel.IsItem_Folder(index)) { srcPanel.MessageBox_Error_LangID(IDS_COMBINE_SELECT_ONE_FILE); return; } const UString itemName = srcPanel.GetItemName(index); UString srcPath = srcPanel.GetFsPath() + srcPanel.GetItemPrefix(index); UString path = srcPath; unsigned destPanelIndex = (NumPanels <= 1) ? srcPanelIndex : (1 - srcPanelIndex); CPanel &destPanel = Panels[destPanelIndex]; if (NumPanels > 1) if (destPanel.IsFSFolder()) path = destPanel.GetFsPath(); CVolSeqName volSeqName; if (!volSeqName.ParseName(itemName)) { srcPanel.MessageBox_Error_LangID(IDS_COMBINE_CANT_DETECT_SPLIT_FILE); return; } { CThreadCombine combiner; UString nextName = itemName; combiner.TotalSize = 0; for (;;) { NFind::CFileInfo fileInfo; if (!fileInfo.Find(us2fs(srcPath + nextName)) || fileInfo.IsDir()) break; combiner.Names.Add(us2fs(nextName)); combiner.TotalSize += fileInfo.Size; nextName = volSeqName.GetNextName(); } if (combiner.Names.Size() == 1) { srcPanel.MessageBox_Error_LangID(IDS_COMBINE_CANT_FIND_MORE_THAN_ONE_PART); return; } if (combiner.TotalSize == 0) { srcPanel.MessageBox_Error(L"No data"); return; } UString info; AddValuePair2(info, IDS_PROP_FILES, combiner.Names.Size(), combiner.TotalSize); info.Add_LF(); info += srcPath; unsigned i; for (i = 0; i < combiner.Names.Size() && i < 2; i++) AddInfoFileName(info, fs2us(combiner.Names[i])); if (i != combiner.Names.Size()) { if (i + 1 != combiner.Names.Size()) AddInfoFileName(info, L"..."); AddInfoFileName(info, fs2us(combiner.Names.Back())); } { CCopyDialog copyDialog; copyDialog.Value = path; LangString(IDS_COMBINE, copyDialog.Title); copyDialog.Title.Add_Space(); copyDialog.Title += srcPanel.GetItemRelPath(index); LangString(IDS_COMBINE_TO, copyDialog.Static); copyDialog.Info = info; if (copyDialog.Create(srcPanel.GetParent()) != IDOK) return; path = copyDialog.Value; } NName::NormalizeDirPathPrefix(path); if (!CreateComplexDir(us2fs(path))) { DWORD lastError = ::GetLastError(); srcPanel.MessageBox_Error_2Lines_Message_HRESULT(MyFormatNew(IDS_CANNOT_CREATE_FOLDER, path), lastError); return; } UString outName = volSeqName.UnchangedPart; while (!outName.IsEmpty()) { if (outName.Back() != L'.') break; outName.DeleteBack(); } if (outName.IsEmpty()) outName = "file"; NFind::CFileInfo fileInfo; UString destFilePath = path + outName; combiner.OutputPath = us2fs(destFilePath); if (fileInfo.Find(combiner.OutputPath)) { srcPanel.MessageBox_Error(MyFormatNew(IDS_FILE_EXIST, destFilePath)); return; } CProgressDialog &progressDialog = combiner; progressDialog.ShowCompressionInfo = false; UString progressWindowTitle ("leya"); // LangString(IDS_APP_TITLE, 0x03000000); UString title = LangString(IDS_COMBINING); progressDialog.MainWindow = _window; progressDialog.MainTitle = progressWindowTitle; progressDialog.MainAddTitle = title; progressDialog.MainAddTitle.Add_Space(); combiner.InputDirPrefix = us2fs(srcPath); // CPanel::CDisableTimerProcessing disableTimerProcessing1(srcPanel); // CPanel::CDisableTimerProcessing disableTimerProcessing2(destPanel); if (combiner.Create(title, _window) != 0) return; } RefreshTitleAlways(); // disableNotify.Restore(); // disableNotify.Restore(); // srcPanel.SetFocusToList(); // srcPanel.RefreshListCtrlSaveFocused(); }
[ "2305665112@qq.com" ]
2305665112@qq.com
9e932a1ace3135f85db935c542cdcb21193ec750
4579eaaeabeaa4d945ec9e0c802ec28bbb9aa8ef
/school computer copy/cse202/lab8/passwordfile.h
eb833416657f5f311cdef22cd590a1246b49c4db
[]
no_license
CircuitMonster/School
bbed854f3ff5e8ae859c68c9c5a6be609fdd14cb
e6e71ce8c0beb3791958949245a7665908caa3de
refs/heads/master
2021-01-22T19:59:52.686214
2017-03-17T04:41:06
2017-03-17T04:41:06
85,271,605
0
0
null
null
null
null
UTF-8
C++
false
false
375
h
#ifndef PASSWORDFILE_H #define PASSWORDFILE_H #include <string> #include <vector> #include "userpw.h" using namespace std; class PasswordFile { public: PasswordFile(string filename); vector<UserPW> getFile(); void addPW(UserPW newentry); bool checkPW(string user, string passwd); private: string filename; vector<UserPW> entry; void Synch(); }; #endif
[ "CircuitMonster@Turbos-MacBook-Pro.local" ]
CircuitMonster@Turbos-MacBook-Pro.local
b454fdc41b989d0a258db7dce39fbf2069888a4a
654769aff13316ffdf330e9e99846306d24289d0
/V3.2 FINALE/main.cpp
3ec3ab55f23cc4eb5abd798757b38989593f2036
[]
no_license
Giglobastre/TropicNetworks
ee584b350ee3ff76183b74730535169750c6f603
36306b037c17e5026a6d8c73e037cccbab4c828f
refs/heads/master
2020-03-08T08:50:31.652113
2018-04-08T21:47:06
2018-04-08T21:47:06
128,031,941
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,599
cpp
#include <iostream> #include <allegro.h> #include "Graphe.h" /** * * NOTRE REPO GIT : https://github.com/Giglobastre/TropicNetworks * * * */ int Quitter() { return 1; } Graphe load_Graphe(std::string nomfile, BITMAP *page) { Graphe g; g.load(nomfile); g.affiche_graphe(nomfile); //g.afficheInfos(); return g; } void Graphe(BITMAP *page) { ///declarations int var_quit_selec=0; std::string nomfile; ///allegro clear_bitmap(page); clear_bitmap(screen); ///boucle while(var_quit_selec!=1) { ///texte textprintf_centre_ex(page,font,1024/2,768/6,makecol(255,255,255),-1,"CHOIX DU GRAPHE");//titre textprintf_centre_ex(page,font,1024/2,768/3,makecol(255,255,255),-1,"Graphe 1");//graphe 1 textprintf_centre_ex(page,font,1024/2,768/2,makecol(255,255,255),-1,"Graphe 2");//graphe 2 textprintf_centre_ex(page,font,1024/2,768/1.5,makecol(255,255,255),-1,"Graphe 3");//Graphe 3 textprintf_centre_ex(page,font,1024/2,700,makecol(255,255,255),-1,"Retour au menu");//Retour ///encadrement rect(page,412,120,612,140,makecol(255,255,255));//encadrement titre rect(page,412,246,612,266,makecol(255,255,255));//premier cadre rect(page,412,374,612,394,makecol(255,255,255));//deuxieme cadre rect(page,412,502,612,522,makecol(255,255,255));//troisieme cadre rect(page,412,690,612,710,makecol(255,255,255));//cadre retour ///hitbox sur clic if(mouse_b & 1) { //Premier cadre if(mouse_x>412 && mouse_x<612 && mouse_y>246 && mouse_y<266) { nomfile="graphe_1.txt"; load_Graphe(nomfile,page); } //Deuxieme cadre if(mouse_x>412 && mouse_x<612 && mouse_y>374 && mouse_y<394) { nomfile="graphe_2.txt"; load_Graphe(nomfile,page); } //troisieme cadre if(mouse_x>412 && mouse_x<612 && mouse_y>502 && mouse_y<522) { nomfile="graphe_3.txt"; load_Graphe(nomfile,page); } //cadre retour if(mouse_x>412 && mouse_x<612 && mouse_y>690 && mouse_y<710) { var_quit_selec=Quitter(); } } show_mouse(page); blit(page,screen,0,0,0,0,1024,768); } } int main() { /// declarations int var_quit_main=0;//variable servant a quitter le programme /// initialisation allegro // Lancer allegro et le mode graphique allegro_init(); set_display_switch_mode(SWITCH_BACKGROUND); install_keyboard(); install_mouse(); set_color_depth(desktop_color_depth()); if (set_gfx_mode(GFX_AUTODETECT_WINDOWED,1024,768,0,0)!=0) { allegro_message("prb gfx mode"); allegro_exit(); exit(EXIT_FAILURE); } ///Bitmaps // BITMAP servant de buffer d'affichage BITMAP *page; // CREATION DU BUFFER D'AFFICHAGE à la taille de l'écran page=create_bitmap(SCREEN_W,SCREEN_H); clear_bitmap(page); ///Boucle while (var_quit_main!=1) { clear_bitmap(page); ///affichage menu texte textprintf_centre_ex(page,font,1024/2,768/6,makecol(0,255,122),-1,"TROPHIC NETWORKS");//titre textprintf_centre_ex(page,font,1024/2,768/2.5,makecol(255,255,255),-1,"Choisir graphe");//1er choix textprintf_centre_ex(page,font,1024/2,768/1.5,makecol(255,255,255),-1,"Quitter");//quitte le jeu si on le choisis ///affichage cadre et hitbox rect(page,412,120,612,140,makecol(0,255,0));//encadrement titre rect(page,412,297,612,317,makecol(255,255,255));//premier cadre rect(page,412,502,612,522,makecol(255,255,255));//deuxieme cadre ///si on clique dans l'une des hitbox effectue les actions correspondantes if(mouse_b & 1) { //Premier cadre if(mouse_x>412 && mouse_x<612 && mouse_y>297 && mouse_y<317) { Graphe(page); } //Deuxieme cadre if(mouse_x>412 && mouse_x<612 && mouse_y>502 && mouse_y<522) { var_quit_main=Quitter(); } } //affichage final show_mouse(page); blit(page,screen,0,0,0,0,1024,768); } return 0; } END_OF_MAIN();
[ "noreply@github.com" ]
noreply@github.com
ef8600cd827702536d56673ac2cdcd2b57bd6ff6
85c5b0ad7cd689ef9f6865af7c7b1829fc513aae
/renderer/Renderer.hpp
a0883570c7ba4c5baf70b6cd0ce9a61e98106363
[]
no_license
Busiu/Games
025433ca3f547c816ae68e8eb0d47caf8813a710
b56d01ffe1a1467e81cf6f21ce7692fdd61a4746
refs/heads/master
2020-03-28T11:35:52.989971
2019-03-06T02:27:46
2019-03-06T02:27:46
148,229,682
0
0
null
null
null
null
UTF-8
C++
false
false
744
hpp
// // Created by Busiu on 14.09.2018. // #ifndef GAMES_RENDERER_HPP #define GAMES_RENDERER_HPP #include "../Libraries.hpp" #include "../Exception.hpp" #include "Renderable.hpp" #include "../util/Types.hpp" class Renderable; class Renderer { private: SDL_Window* window; SDL_Renderer* renderer; public: explicit Renderer(Resolution windowSize); ~Renderer(); void clear(); void update(); SDL_Renderer* getRenderer(); void setResolution(Resolution resolution); void render(Renderable* renderable); private: //Constructor bool initWindow(Resolution windowSize); bool initRenderer(); //Destructor void destroyWindow(); void destroyRenderer(); }; #endif //GAMES_RENDERER_HPP
[ "busiu69@gmail.com" ]
busiu69@gmail.com
f413f740b4e6f7648714b0e7709e90e769b778d5
b1c4be5357d95a8bef78dab271189a4161ffbd2c
/Summer Practice/UVA/Graphs/Single Source Shortest Paths/BFS/Knight Moves.cpp
5f8d436f6ad7561437bf599090464134fb732f2b
[]
no_license
Shaker2001/Algorithms-Library
faa0434ce01ad55d4b335c109f4f85736a6869ed
1aa09469ca434f6138547592ce49060d4400e349
refs/heads/master
2023-03-16T04:41:27.367439
2017-11-13T00:41:55
2017-11-13T00:41:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,229
cpp
#include<stdio.h> #include<string.h> #include<vector> #include<queue> using namespace std; #define Point pair<int, pair<int, int> > #define mp(a,b,c) make_pair(a, make_pair(b, c)) #define X first #define Y second.first #define cost second.second int inside_board(int x, int y){ return x>=0&&y>=0&&x<8&&y<8; } int dx[] = {-2, -2, 1, -1, 2, 2, 1, -1}; int dy[] = {1, -1, -2, -2, 1, -1, 2, 2}; int bfs(int x, int y, int desx, int desy){ queue<Point> q; q.push(mp(x,y,0)); int vis[8][8]; memset(vis, 0, sizeof vis); while (!q.empty()){ Point p = q.front(); q.pop(); if (p.X==desx&&p.Y==desy) return p.cost; if (vis[p.X][p.Y]) continue; vis[p.X][p.Y] = 1; for (int i =0;i<8;i++){ int nx = p.X+dx[i], ny = p.Y+dy[i]; if (inside_board(nx, ny)) q.push(mp(nx, ny, p.cost+1)); } } return -1; } int main(){ char str[20], str1[20]; while (scanf("%s %s", str, str1)>0) printf("To get from %c%c to %c%c takes %d knight moves.\n", str[0], str[1], str1[0], str1[1], bfs(str[1]-'1', str[0]-'a', str1[1]-'1', str1[0]-'a')); }
[ "malatawy15@gmail.com" ]
malatawy15@gmail.com
dce36e4d5ed675407bb3b21571f4ca6bc9c9eaba
e3970b6299678aab3f553b381a78f84728f1dbdf
/boost/mpl/x11/apply.hpp
e0bba6b19e89dfc8127f12a631d235f4cf861080
[]
no_license
krzysztof-jusiak/boost
df4001f8ad50c2e3df6d4b90d5aa9eac9bcbc14c
1e33047c31d2c65493f1d858f7ce02b195cd9093
refs/heads/master
2021-01-18T09:03:54.997601
2014-06-24T10:53:13
2014-06-24T10:53:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
876
hpp
/*============================================================================= Copyright (c) 2000-2008 Aleksey Gurtovoy Copyright (c) 2013 Alex Dubov <oakad@yahoo.com> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(MPL_X11_APPLY_APR_05_2013_1410) #define MPL_X11_APPLY_APR_05_2013_1410 #include <boost/mpl/x11/lambda.hpp> #include <boost/mpl/x11/apply_wrap.hpp> namespace boost { namespace mpl { namespace x11 { template <typename...> struct apply; template <typename F> struct apply<F> : apply_wrap<typename lambda<F>::type> {}; template <typename F, typename... Tn> struct apply<F, Tn...> : apply_wrap<typename lambda<F>::type, Tn...> {}; }}} #endif
[ "oakad@yahoo.com" ]
oakad@yahoo.com
0dddb37a3e015e7f6b90cfccca67302cb17da04b
215111e92a3dfc535ce1c1ce25a35fb6003ab575
/cf/egyptian_2016/k.cpp
2bdfcc23b3a04fdcaf30e86fbf9806483a76370f
[]
no_license
emanueljuliano/Competitive_Programming
6e65aa696fb2bb0e2251e5a68657f4c79cd8f803
86fefe4d0e3ee09b5766acddc8c78ed8b60402d6
refs/heads/master
2023-06-23T04:52:43.910062
2021-06-26T11:34:42
2021-06-26T11:34:42
299,115,304
0
0
null
null
null
null
UTF-8
C++
false
false
1,565
cpp
#include <bits/stdc++.h> using namespace std; #define _ ios_base::sync_with_stdio(0);cin.tie(0); //#define endl '\n' #define f first #define s second #define pb push_back typedef long long ll; typedef pair<int, int> ii; typedef double ld; const int INF = 0x3f3f3f3f; const ll LINF = 0x3f3f3f3f3f3f3f3fll; const ld eps = 1e-12; ld P[25][25], C[25][25]; vector<int> v; ld dp[25][25]; int dest =-1; int endit; int n; ld solve(int at, int it){ ld &ret = dp[at][it]; if(ret>-3) return ret; if(dest!=-1 and it==endit-1) return ret = P[at][dest] * C[at][v[it]]; if(it==endit-1) return ret = C[at][v[it]]; ld p = 0.0; for(int i=0; i<n; i++) p += P[at][i] * solve(i, it+1); return ret = C[at][v[it]]*p; } int main(){ _ freopen("trip.in", "r", stdin); int t; cin >> t; while(t--){ for(int i=0;i <25; i++) for(int j=0; j<25; j++) dp[i][j] = -5; int m, k, q, z; cin >> n >> m >> k >> q >> z; for(int i=0;i <n; i++) for(int j=0; j<n; j++) cin >> P[i][j]; for(int i=0;i <n; i++) for(int j=0; j<m; j++) cin >> C[i][j]; v.resize(k); for(auto &i : v) cin >> i; if(q==0){ cout << setprecision(3) << fixed; if(z!=0 or C[0][v[0]] < eps) cout << 0.0 << endl; else cout << 1.0 << endl; continue; } dest = z, endit = q; ld p1 = solve(0, 0); for(int i=0;i <25; i++) for(int j=0; j<25; j++) dp[i][j] = -5; dest = -1, endit=k; ld p2 = solve(z, q); for(int i=0;i <25; i++) for(int j=0; j<25; j++) dp[i][j] = -5; ld p3 = solve(0, 0); cout << setprecision(3) << fixed; cout << p1*p2/p3 << endl; } exit(0); }
[ "emanueljulianoms@gmail.com" ]
emanueljulianoms@gmail.com
7cacf673f52671562a727738674355fd32ff4d65
dc9721b5b0610dbeb595697d5b9347295e2a662e
/ROVControl/TcpServeDlg.h
0e5aa30b16246d5b0c8fe9da2c9524d919daf405
[]
no_license
thinkexist1989/ROVControl
7e042e476a3cd51d70d0892df15f7f467a884e92
f4e86b6d10630ebdd88902698fa91e15023583b3
refs/heads/master
2021-01-20T00:53:48.901316
2017-04-24T08:52:11
2017-04-24T08:52:11
89,210,930
2
0
null
null
null
null
GB18030
C++
false
false
2,804
h
#pragma once #define THREAD_ID_DEEP 0 #define THREAD_ID_POSE 1 #define POSE_SOCKET_CONNECTED 0 #define MOTOR_SOCKET_CONNECTED 1 #define TEST_SOCKET_CONNECTED 2 #define MOTOR_VALUE_LIMIT 500 #include <fstream> #include "iswitchled_deep.h" // CTcpServeDlg 对话框 class CTcpServeDlg : public CDialogEx { DECLARE_DYNAMIC(CTcpServeDlg) public: CTcpServeDlg(CWnd* pParent = NULL); // 标准构造函数 virtual ~CTcpServeDlg(); // 对话框数据 enum { IDD = IDD_TCPSERVE_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: // TODO:套接字 static SOCKET m_socket_Deep_listen; static SOCKET m_socket_Pose_listen; static SOCKET m_sockConn_Pose; //这个SOCKET才是和下位机通讯用的 static SOCKET m_sockConn_Motor; //电机和姿态用同一个端口(port7) static SOCKET m_sockConn_Deep; static SOCKET m_sockConn_Test; //本机测试用 private: // 服务器IP地址 192.168.1.1 DWORD m_dwIP; //服务器端口 int m_portDeep; int m_portPose; // 是否已经建立连接标志 static bool m_bConnectDeep; static bool m_bConnectPose; public: afx_msg void OnBnClickedBtnConnect(); afx_msg void OnBnClickedBtnDisconnect(); virtual BOOL OnInitDialog(); CString m_showMsg; private: void SetConnect(SOCKET &sock, int &port, bool &mark); public: static bool RecvProc(int nID); static void SendMotorSpeed(); static void SendMotorN(int n1,int n2,int n3,int n4,int n5,int n6,int n7,int n8); static void SendSwitchLight(BOOL bSwitch); static void SetMotorPID(char sign, float v1, float v2, float v3, float v4, float v5, float v6, float v7, float v8); static void GetMotorValue(char sign); static DWORD WINAPI ThreadProcWaitForSocket(LPVOID lpParameter); static DWORD WINAPI ThreadProc(LPVOID lpParameter); static DWORD WINAPI ThreadProcDeep(LPVOID lpParameter); static DWORD WINAPI ThreadProcPose(LPVOID lpParameter); // 卡尔曼滤波函数 static void Kalman_Filter(float &Z, float &X, float &P, float R); // 计数,当三个欧拉角全部收到后,进行运算 static bool m_bYaw; static bool m_bPitch; static bool m_bRoll; static bool m_bPose; //在进行运算之后m_bPose标志置TRUE static bool m_bDeep; //接收到深度信号后m_bDeep标志置TRUE static int sgn(int value); static unsigned char GetDirectionBit(); //得到电机正反转位,参数为全局变量GlobalVar::motor static unsigned char GetDirectionBit(int m1,int m2,int m3,int m4,int m5,int m6,int m7,int m8);// static std::ofstream m_pitchFile; static std::ofstream m_rollFile; static std::ofstream m_yawFile; protected: afx_msg LRESULT OnSocketconnected(WPARAM wParam, LPARAM lParam); public: CIswitchled_deep m_pose_connected; CIswitchled_deep m_motor_connected; };
[ "992534544@qq.com" ]
992534544@qq.com
2d9a5b3a4edcc40a110c952c9bc14ab1f28d1151
65e9363bc4d754993fe7dc93483629e259414388
/automatsko-rezonovanje/iskazna-logika/AtomicFormula.h
856abc5cfd0d5d41d192315726af340e83c954c7
[]
no_license
miki208/Vezbanje
914be3b10bfa2f86b2cc25dbd46ed01c1139d341
cb4e7577ef7ba27497002174936771802dd89a2d
refs/heads/master
2021-01-20T11:17:29.333541
2017-06-14T11:50:59
2017-06-14T11:50:59
86,230,574
0
0
null
null
null
null
UTF-8
C++
false
false
304
h
#ifndef _ATOMIC_FORMULA_H_ #define _ATOMIC_FORMULA_H_ #include "Formula.h" class AtomicFormula : public BaseFormula { public: int complexity() const; Formula substitute(const Formula&, const Formula&); Formula simplify(); Formula nnf(); LiteralListList cnf(); LiteralListList dnf(); }; #endif
[ "miloss208@gmail.com" ]
miloss208@gmail.com
62566bbf476502a6f26ae5b4bcddb5f7c67488cd
e641c52f034a78a77498f14ed7b86b62d5af5865
/01_begin/Engine/Core/Input.h
953c88df69bd5a04c9868683dc95d340e0d7b89c
[]
no_license
BabajotaUA/01_begin
bb9250f5cc262a67d860b0157b2cf26e9cd57f7a
19766c230d8ebcab259f6064a274dc4f6e2b058d
refs/heads/master
2021-01-25T08:48:49.067720
2013-09-06T11:44:24
2013-09-06T11:44:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
631
h
#pragma once #include <vector> #include <memory> #include <Windows.h> class Input { public: Input(void); virtual ~Input(void); bool isKeyHit(unsigned char key); bool isKeyDown(unsigned char key); bool isMouseHit(unsigned char key); bool isMouseDown(unsigned char key); bool isOK() const; LRESULT CALLBACK messageInterception(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK windowProcessor(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); private: bool ok; std::vector<bool> keysDown; std::vector<bool> keysHit; }; static std::unique_ptr<Input> ApplicationHandle;
[ "yfshaolin@gmail.com" ]
yfshaolin@gmail.com
0bc61f2d65d45b5ac3faf2c6b80f7a9b09334138
2a3a5c2c49f5ae1f66ea4b2a70bb21828b47406d
/PCDMK2.7.cpp
8983e161949f2af57b33bd1a90b120b98f3b69df
[]
no_license
MSAChowdhury/ICPC-Prac
5f6d8faf92d8c8b58921ac865480e727568358e9
874665c8c99c6d985029cdb4d9777c8f55f3b9de
refs/heads/master
2021-03-04T21:33:32.670689
2020-05-19T07:39:23
2020-05-19T07:39:23
246,066,461
0
0
null
null
null
null
UTF-8
C++
false
false
297
cpp
#include <iostream> #include <math.h> using namespace std; int main() { int year; cin >> year; if(year%400 == 0 || (year%100 != 0 && year% 4 == 0) ) { cout << year << " is Leap year"; } else { cout << year << " is NOT Leap year"; } return 0; }
[ "samselarifinchowdhury@gmail.com" ]
samselarifinchowdhury@gmail.com
2abd8d9a1b2134cb5213de648d901dbef119650c
e41b03c2ef4fd330397355effc8c11788f4084eb
/Team_Polk_NoFault.cpp
32b8dfc9ac036b366459af69de84412b84012175
[]
no_license
alecmas/Roll-System
6209b2af1d83fca94f8526988dba72c455daeab3
25c9dde596a71557e2f5c7715b5a9eaaed6bddb9
refs/heads/master
2020-09-20T11:10:42.773304
2017-01-13T15:50:12
2017-01-13T15:50:12
66,852,091
0
1
null
2016-09-28T21:11:17
2016-08-29T14:40:43
C++
UTF-8
C++
false
false
21,235
cpp
//***************************************************************** // Team_Polk_NoFault.cpp // A small class-roll maintenance system // // Programmers: Ryan Binder, Constance Luong, Elin Cheung, // Wesam Ali, Alexander Mas // // This file contains the RollSystem class and all functions //***************************************************************** #include <cstdlib> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> using namespace std; //****************************************************************** // RollSystem class //****************************************************************** class RollSystem { public: struct student { // up to 40 characters string name; // 10 characters string usfId; // up to 40 characters string email; // value from 0 (F) to 4 (A) int presGrade, e1Grade, e2Grade, projGrade; }; // vector to hold students vector<student> students; bool validateStudent(string name, string usfId, string email); bool validateGrade(int grade); void addStudent(string name, string usfId, string email); void removeStudent(string usfId); void searchByName(string name); void searchById(string usfId); void searchByEmail(string email); void editInfo(int index); void editGrades(int index); void editStudent(string usfId); void displaySystem(); void displayStudent(int index); void displayMenu(); }; //****************************************************************** // validateStudent function will check to see if name, UID, // and email are all valid inputs //****************************************************************** bool RollSystem::validateStudent(string name, string usfId, string email) { // if name is not a valid length if (name.size() == 0 || name.size() > 40) { cout << endl; cout << "ERROR: invalid name. Names must contain between 1 and 40 characters" << endl; return false; } // if UID is not a valid length if (usfId.size() != 8) { cout << endl; cout << "ERROR: invalid UID. UID must be exactly 8 characters" << endl; return false; } // find if UID contains all numbers size_t numberFound = usfId.find_first_not_of("0123456789"); // if all characters are numbers, numberFound will equal npos if (numberFound != string::npos) { cout << endl; cout << "ERROR: invalid UID. UID consists of numbers only" << endl; return false; } // find if email contains '@' character size_t atFound = email.find("@"); // if @ not found, atFound will equal npos if (atFound == string::npos) { cout << endl; cout << "ERROR: invalid email. Email addresses must contain an @ symbol" << endl; return false; } // if email is not a valid length if (email.size() < 3 || email.size() > 40) { cout << endl; cout << "ERROR: invalid email. Email addresses must contain between 3 and 40 characters" << endl; return false; } return true; } //****************************************************************** // validateGrade function makes sure grade input is valid // (between 0 and 4) //****************************************************************** bool RollSystem::validateGrade(int grade) { // if newGrade is out of range, print error and fail the grade edit if (grade < 0 || grade > 4) { cout << endl; cout << "ERROR: Please enter a grade value between 0 and 4\n"; cout << endl; cout << "Grade edit failed!" << endl; return false; } else { return true; } } //****************************************************************** // addStudent function will create a student // and add that student to the system //****************************************************************** void RollSystem::addStudent(string name, string usfId, string email) { // variable to check if id is already in system bool duplicateId = false; // variable to check if email is already in system bool duplicateEmail = false; // iterate through the vector to see if there are any duplicate ids or emails for (int i = 0; i < students.size(); i++) { if (students[i].usfId == usfId) { duplicateId = true; } if (students[i].email == email) { duplicateEmail = true; } } if (duplicateId == true) { cout << endl; cout << "ERROR: a student with that UID is already in the system.\n"; return; } else if (duplicateEmail == true) { cout << endl; cout << "ERROR: a student with that email is already in the system.\n"; return; } // validate name, id, and email else if (validateStudent(name, usfId, email) == false) { return; } // else there were no errors else { // create student student newStudent; // transform user's name input to all lowercase to eliminate case-sensitivity issues transform(name.begin(), name.end(), name.begin(), ::tolower); // transform user's email input to all lowercase to eliminate case-sensitivity issues transform(email.begin(), email.end(), email.begin(), ::tolower); newStudent.name = name; newStudent.usfId = usfId; newStudent.email = email; // set initial grades to 0 newStudent.presGrade = 0; newStudent.e1Grade = 0; newStudent.e2Grade = 0; newStudent.projGrade = 0; // push new student onto the end of the students vector students.push_back(newStudent); cout << endl; cout << "Student added!\n"; } } //****************************************************************** // removeStudent function will find a student by UID // and remove that student from the system //****************************************************************** void RollSystem::removeStudent(string usfId) { // variable to make sure student is in the system bool foundStudent = false; // variable to hold index of the student to be removed int indexToRemove; // iterate through students vector to find the student to be removed for (int i = 0; i < students.size(); i++) { if (students[i].usfId == usfId) { foundStudent = true; indexToRemove = i; } } if (foundStudent == false) { cout << endl; cout << "ERROR: student you wish to remove is not in the system\n"; } else { // erase the student at the saved index students.erase(students.begin() + indexToRemove); cout << endl; cout << "Removal successful!\n"; } } //****************************************************************** // searchByName function will search system for student // by their name //****************************************************************** void RollSystem::searchByName(string name) { // variable to check if name is in system bool foundName = false; // transform user's name input to lowercase to eliminate case-sensitivity issues transform(name.begin(), name.end(), name.begin(), ::tolower); // iterate through students vector to find a matching name for (int i = 0; i < students.size(); i++) { // compare names, which are now both lowercase if (students[i].name == name) { foundName = true; displayStudent(i); } } if (foundName == false) { cout << endl; cout << "Student \"" << name << "\" not found in the system\n"; } } //****************************************************************** // searchById function will search system for student // by their UID //****************************************************************** void RollSystem::searchById(string usfId) { // variable to check if id is in system bool foundId = false; // iterate through students vector to find a matching id for (int i = 0; i < students.size(); i++) { if (students[i].usfId == usfId) { foundId = true; displayStudent(i); } } if (foundId == false) { cout << endl; cout << "UID " << usfId << " not found in the system\n"; } } //****************************************************************** // searchByEmail function will search system for student // by their email //****************************************************************** void RollSystem::searchByEmail(string email) { // variable to check if email is in system bool foundEmail = false; // transform user's email input to all lowercase to eliminate case-sensitivity issues transform(email.begin(), email.end(), email.begin(), ::tolower); // iterate through students vector to find a matching email for (int i = 0; i < students.size(); i++) { if (students[i].email == email) { foundEmail = true; displayStudent(i); } } if (foundEmail == false) { cout << endl; cout << "Email \"" << email << "\" not found in the system\n"; } } //****************************************************************** // editInfo function will edit student's information // (name, UID, email) //****************************************************************** void RollSystem::editInfo(int index) { // variables for the new information string newName, newId, newEmail; cout << "New name: "; getline(cin, newName); cout << "New UID: "; getline(cin, newId); cout << "New email: "; getline(cin, newEmail); // validate new email if (validateStudent(newName, newId, newEmail) == false) { return; } // transform user's name input to lowercase to eliminate case-sensitivity issues transform(newName.begin(), newName.end(), newName.begin(), ::tolower); // transform user's email input to all lowercase to eliminate case-sensitivity issues transform(newEmail.begin(), newEmail.end(), newEmail.begin(), ::tolower); // update information of the student at the saved index students[index].name = newName; students[index].usfId = newId; students[index].email = newEmail; cout << endl; cout << "Info edit successful!" << endl; } //****************************************************************** // editGrades function will edit student's grades //****************************************************************** void RollSystem::editGrades(int index) { // variables for new grades string newPresGrade, newE1Grade, newE2Grade, newProjGrade; // prompt user for input cout << endl; cout << "Please enter all grades as numeric values according to the following scale:" << endl; cout << "4 = A, 3 = B, 2 = C, 1 = D, 0 = F" << endl; cout << endl; cout << "New Presentation grade: "; getline(cin, newPresGrade); // convert input to int to prevent errors int presGradeInt = atoi(newPresGrade.c_str()); // if input is not valid, exit the function if (validateGrade(presGradeInt) == false) { return; } // else make the edit else { students[index].presGrade = presGradeInt; } cout << "New Essay 1 grade: "; getline(cin, newE1Grade); int e1GradeInt = atoi(newE1Grade.c_str()); if (validateGrade(e1GradeInt) == false) { return; } else { students[index].e1Grade = e1GradeInt; } cout << "New Essay 2 grade: "; getline(cin, newE2Grade); int e2GradeInt = atoi(newE2Grade.c_str()); if (validateGrade(e2GradeInt) == false) { return; } else { students[index].e2Grade = e2GradeInt; } cout << "New Project grade: "; getline(cin, newProjGrade); int projGradeInt = atoi(newProjGrade.c_str()); if (validateGrade(projGradeInt) == false) { return; } else { students[index].projGrade = projGradeInt; } // if the function makes it this far, the edit was successful cout << endl; cout << "Grades edit successful!" << endl; } //****************************************************************** // editStudent function will find student by UID and then // prompt user to editInfo or editGrades //****************************************************************** void RollSystem::editStudent(string usfId) { // variable to make sure student is in the system bool foundStudent = false; // variable to save the index of the student to be edited int indexToEdit = 0; // variable for menu system string command; // iterate through students vector to find the student to be edited for (int i = 0; i < students.size(); i++) { if (students[i].usfId == usfId) { foundStudent = true; indexToEdit = i; } } if (foundStudent == false) { cout << endl; cout << "ERROR: student you wish to edit was not found.\n"; } else { cout << endl; cout << "1. Edit student info" << endl; cout << "2. Edit student grades" << endl; cout << endl; cout << "Command number: "; getline(cin, command); cout << endl; int commandInt = atoi(command.c_str()); switch(commandInt) { case 1: editInfo(indexToEdit); break; case 2: editGrades(indexToEdit); break; default: cout << "ERROR: invalid command." << endl; break; } } } //****************************************************************** // displaySystem function will display all students currently // in the system, as well as their information //****************************************************************** void RollSystem::displaySystem() { // variable to keep count of students in system int count = 0; cout << "--------------------------------------------------------------------------------------------------\n"; cout << "| " << setw(40) << left << "Name" << "| " << setw(10) << left << "UID" << "| " << setw(40) << "Email " << " |" << endl; cout << "--------------------------------------------------------------------------------------------------\n"; // iterate through students vector and print all students for (int i = 0; i < students.size(); i++) { count++; cout << "| " << setw(40) << left << students[i].name << "| " << setw(10) << left << students[i].usfId << "| " << setw(40) << students[i].email << " |" << endl; } if (count == 0) { cout << "| System contains no students" << setw(69) << right << " |" << endl; cout << "--------------------------------------------------------------------------------------------------\n"; } else { cout << "--------------------------------------------------------------------------------------------------\n"; cout << "| TOTAL STUDENTS: " << setw(78) << count << " |" << endl; cout << "--------------------------------------------------------------------------------------------------\n"; cout << endl; cout << "NOTE: if you would like to see a student's grades, please search for them individually" << endl; } } //****************************************************************** // displayStudent function will display a single student's // information and grades //****************************************************************** void RollSystem::displayStudent(int index) { cout << "--------------------------------------------------\n"; cout << "| " << setw(45) << left << "STUDENT " << index + 1 << " |" << endl; cout << "--------------------------------------------------\n"; cout << "| " << "Name:" << setw(41) << right << students[index].name << " |" << endl; cout << "| " << "UID:" << setw(42) << right << students[index].usfId << " |" << endl; cout << "| " << "Email:" << setw(40) << right << students[index].email << " |" << endl; cout << "| " << setw(48) << " |" << endl; cout << "| " << setw(45) << left << "Presentation Grade: " << students[index].presGrade << " |" << endl; cout << "| " << setw(45) << left << "Essay 1 Grade: " << students[index].e1Grade << " |" << endl; cout << "| " << setw(45) << left << "Essay 2 Grade: " << students[index].e2Grade << " |" << endl; cout << "| " << setw(45) << left << "Project Grade: " << students[index].projGrade << " |" << endl; cout << "--------------------------------------------------\n"; } //****************************************************************** // displayMenu function will display the menu to remind // the user what commands are valid //****************************************************************** void RollSystem::displayMenu() { cout << endl; cout << "1. Display students in system" << endl; cout << "2. Add student" << endl; cout << "3. Remove student" << endl; cout << "4. Search for student by name" << endl; cout << "5. Search for student by UID" << endl; cout << "6. Search for student by email" << endl; cout << "7. Edit student" << endl; cout << "8. Exit system" << endl; } //****************************************************************** // MAIN FUNCTION //****************************************************************** int main() { // create system RollSystem classRoll; // command input for main menu string menuCommand; // variables for adding student string newName, newId, newEmail; // id of student to remove string removeId; // variables for searching student string searchName, searchId, searchEmail; // id of student to edit string editId; /* TESTING // classRoll.addStudent("Alexander Mas", "00000000", "alexanderm@mail.usf.edu"); classRoll.addStudent("Geoffrey Kohlhase", "11111111", "gk@mail.usf.edu"); classRoll.addStudent("David Cap", "22222222", "dc@mail.usf.edu"); classRoll.addStudent("Mason Wudtke", "33333333", "mw@mail.usf.edu"); // END TESTING */ cout << endl; cout << "Welcome to the Class Roll Maintenance System!" << endl; classRoll.displayMenu(); cout << endl; cout << "Command number: "; getline(cin, menuCommand); // variable for string converted to int // fool-proofs menu so user can't break program int menuCommandInt = atoi(menuCommand.c_str()); // loop menu until user wants to exit while (menuCommandInt != 8) { // switch statement for menu command switch (menuCommandInt) { // display students case 1: cout << endl; cout << "Displaying system..." << endl; cout << endl; classRoll.displaySystem(); cout << endl; cout << "Press ENTER to continue..."; // cin.ignore() makes user have to hit enter to continue cin.ignore(); // display the menu after whatever the user does to remind them of commands classRoll.displayMenu(); // always ask for new command after each case to see what the user wants to do next cout << endl; cout << "Command number: "; getline(cin, menuCommand); menuCommandInt = atoi(menuCommand.c_str()); break; // add student case 2: cout << endl; cout << "Adding student..." << endl; cout << endl; cout << "Name: "; getline(cin, newName); cout << "UID: "; getline(cin, newId); cout << "Email: "; getline(cin, newEmail); classRoll.addStudent(newName, newId, newEmail); cout << endl; cout << "Press ENTER to continue..."; cin.ignore(); classRoll.displayMenu(); cout << endl; cout << "Command number: "; getline(cin, menuCommand); menuCommandInt = atoi(menuCommand.c_str()); break; // remove student case 3: cout << endl; cout << "Removing student..." << endl; cout << endl; cout << "UID of student you'd like to remove: "; getline(cin, removeId); classRoll.removeStudent(removeId); cout << endl; cout << "Press ENTER to continue..."; cin.ignore(); classRoll.displayMenu(); cout << endl; cout << "Command number: "; getline(cin, menuCommand); menuCommandInt = atoi(menuCommand.c_str()); break; // search student by name case 4: cout << endl; cout << "Searching for student by name..." << endl; cout << endl; cout << "Name: "; getline(cin, searchName); classRoll.searchByName(searchName); cout << endl; cout << "Press ENTER to continue..."; cin.ignore(); classRoll.displayMenu(); cout << endl; cout << "Command number: "; getline(cin, menuCommand); menuCommandInt = atoi(menuCommand.c_str()); break; // search student by id case 5: cout << endl; cout << "Searching for student by UID..." << endl; cout << endl; cout << "UID: "; getline(cin, searchId); classRoll.searchById(searchId); cout << endl; cout << "Press ENTER to continue..."; cin.ignore(); classRoll.displayMenu(); cout << endl; cout << "Command number: "; getline(cin, menuCommand); menuCommandInt = atoi(menuCommand.c_str()); break; // search student by email case 6: cout << endl; cout << "Searching by email..." << endl; cout << endl; cout << "Email: "; getline(cin, searchEmail); classRoll.searchByEmail(searchEmail); cout << endl; cout << "Press ENTER to continue..."; cin.ignore(); classRoll.displayMenu(); cout << endl; cout << "Command number: "; getline(cin, menuCommand); menuCommandInt = atoi(menuCommand.c_str()); break; // edit student case 7: cout << endl; cout << "Editing student..." << endl; cout << endl; cout << "UID of student you'd like to edit: "; getline(cin, editId); classRoll.editStudent(editId); cout << endl; cout << "Press ENTER to continue..."; cin.ignore(); classRoll.displayMenu(); cout << endl; cout << "Command number: "; getline(cin, menuCommand); menuCommandInt = atoi(menuCommand.c_str()); break; // error message default: cout << endl; cout << "ERROR: invalid command." << endl; cout << endl; cout << "Press ENTER to continue..."; cin.ignore(); classRoll.displayMenu(); cout << endl; cout << "Command number: "; getline(cin, menuCommand); menuCommandInt = atoi(menuCommand.c_str()); break; } } cout << endl; cout << "Exiting system..."; cin.ignore(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
f88f72faf6b59fc1e194c40bd6b20a62f0012beb
785f542387f302225a8a95af820eaccb50d39467
/codeforces/1-A/1-A-12397424.cpp
ad401b078998438f384c3295fdbb9a46762c07ff
[]
no_license
anveshi/Competitive-Programming
ce33b3f0356beda80b50fee48b0c7b0f42c44b0c
9a719ea3a631320dfa84c60300f45e370694b378
refs/heads/master
2016-08-12T04:27:13.078738
2015-01-19T17:30:00
2016-03-08T17:44:36
51,570,689
0
0
null
null
null
null
UTF-8
C++
false
false
1,001
cpp
#include <bits/stdc++.h> using namespace std; #define mp make_pair #define pb push_back #define ff first #define ss second #define all(c) (c).begin(),(c).end() #define tr(c,it) for(auto it = (c).begin(); it != (c).end(); it++) #define __ ios_base::sync_with_stdio(false);cin.tie(NULL); #define TRACE #ifdef TRACE #define trace1(x) cerr << #x << ": " << x << endl; #define trace2(x, y) cerr << #x << ": " << x << " | " << #y << ": " << y << endl; #define trace3(x, y, z) cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl; #define trace4(a, b, c, d) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl; #else #define trace1(x) #define trace2(x, y) #define trace3(x, y, z) #define trace4(a, b, c, d) #endif typedef long long LL; const LL MOD = 1000000007; int main(){ LL n,m,a; cin >> n >> m >> a; n%a==0?n/=a:n=n/a+1; m%a==0?m/=a:m=m/a+1; cout << n*m << endl; return 0; }
[ "anveshishukla@gmail.com" ]
anveshishukla@gmail.com
6ee6a6e351aaba83774b6378d41e361c17d205df
a816e8ab3043f8775f20776e0f48072c379dbbc3
/dopy/dz_3/variant_1/E.cpp
19a3ea4c8cf706cccd1cd942c23c04bcbdf01a8c
[]
no_license
AruzhanBazarbai/pp1
1dee51b6ef09a094072f89359883600937faf558
317d488a1ffec9108d71e8bf976a9a1c0896745e
refs/heads/master
2023-07-16T14:37:20.131167
2021-08-25T17:08:41
2021-08-25T17:08:41
399,890,781
0
0
null
null
null
null
UTF-8
C++
false
false
962
cpp
//Using a vector. the user writes a command such as push after that he should keep the number and so on. #include <iostream> #include <vector> using namespace std; int main(){ vector<int> v; string s; while(cin >> s){ if(s=="end"){ cout << "Black Devil" << endl; break; }else{ if(s=="push"){ int x; cin >> x; v.push_back(x); cout << "OK" << endl; }else if(s=="size"){ cout << v.size() << endl; }else if(s=="back"){ cout << v.back() << endl; }else if(s=="front"){ cout << v.front() << endl; }else if(s=="pop"){ cout << "OK" << endl; v.pop_back(); }else if(s=="clear"){ cout << "OK" << endl; v.clear(); } } } return 0; }
[ "aruzhanart2003@mail.ru" ]
aruzhanart2003@mail.ru
bd48e4c9d04a7bbae851be2b512428ca3e0a5600
bed3c9bb3502750de3d03e9971b29072b6e26f18
/ProjectPANG/ProjectPANG/Time_Count.cpp
55c5505d66971821b199c057c45b84ad891a478a
[]
no_license
The4Bros/ANGRY_PANGS
1f89b6f10b69b71b038e3d8c9a92562b7b378928
ea56d01a2ed8c00d8c3b2dc40e84f7fd7bfb1c0a
refs/heads/master
2021-09-08T16:14:03.899488
2015-06-24T18:54:03
2015-06-24T18:54:03
31,953,420
0
0
null
null
null
null
UTF-8
C++
false
false
1,663
cpp
#include "Time_Count.h" Time_Count::Time_Count(Application* app) { this->app = app; current_time = 100; time(&timer); rect[0] = { 334 * app->windowModule->scale, 9 * app->windowModule->scale, 13 * app->windowModule->scale, 13 * app->windowModule->scale }; rect[1] = { 348 * app->windowModule->scale, 9 * app->windowModule->scale, 13 * app->windowModule->scale, 13 * app->windowModule->scale }; rect[2] = { 362 * app->windowModule->scale, 9 * app->windowModule->scale, 13 * app->windowModule->scale, 13 * app->windowModule->scale }; rect[3] = { 271 * app->windowModule->scale, 9 * app->windowModule->scale, 62 * app->windowModule->scale, 13 * app->windowModule->scale }; for (int i = 0; i < 10; i ++){ source_rect[i] = {62 + (i * 13), 0, 13, 13}; } source_rect[10] = {0, 0, 62, 13}; Update_Source_Index(); } void Time_Count::Update() { if (current_time > 0) { current_time--; time(&timer); Update_Source_Index(); } } void Time_Count::Update_Source_Index() { source_index[0] = (current_time / 100) % 10; source_index[1] = (current_time / 10) % 10; source_index[2] = current_time % 10; } void Time_Count::Reset(unsigned int seconds) { current_time = seconds; time(&timer); Update_Source_Index(); } void Time_Count::Print_Timer() { app->renderModule->Print(app->texturesModule->timer_sprite, &source_rect[10], &rect[3]); app->renderModule->Print(app->texturesModule->timer_sprite, &source_rect[source_index[0]], &rect[0]); app->renderModule->Print(app->texturesModule->timer_sprite, &source_rect[source_index[1]], &rect[1]); app->renderModule->Print(app->texturesModule->timer_sprite, &source_rect[source_index[2]], &rect[2]); }
[ "ec4who@hotmail.com" ]
ec4who@hotmail.com
88f0a70e69b707b02abd8dc20fa12a667fa6b024
b43d21897e2e89697b9a2416d1f74f1ae89ce858
/Analysis/lib/include/ModuleIterator.hpp
8be3cb9f1e193fcb5f819719634ba948bad1ae7a
[]
no_license
ZhenghengLi/POLAR_DATA
a9ed9d71cee9f1527941624d27028af6e80d485b
60ae443d4bdd8967d637da5f19d3dd9f93fb2a7c
refs/heads/master
2020-03-19T13:27:28.837344
2019-07-13T14:35:35
2019-07-13T14:35:35
136,580,337
2
0
null
null
null
null
UTF-8
C++
false
false
2,012
hpp
#ifndef MODULEITERATOR_H #define MODULEITERATOR_H #include <cstdio> #include "SciType.hpp" using namespace std; class ModuleIterator: private SciType { private: TFile* t_file_in_; TTree* t_trigger_; TTree* t_modules_; TTree* t_ped_trigger_; TTree* t_ped_modules_; bool cur_is_1P_; int cur_ct_num_; string cur_filter_; Long64_t cur_seq_num_; Long64_t pre_seq_num_; bool ped_trigg_reach_end_; bool ped_event_reach_end_; bool phy_trigg_reach_end_; bool phy_event_reach_end_; bool trigg_start_flag_; bool event_start_flag_; TEventList* ped_trigg_elist_; Int_t ped_trigg_cur_index_; TEventList* ped_event_elist_; Int_t ped_event_cur_index_; TEventList* phy_trigg_elist_; Int_t phy_trigg_cur_index_; TEventList* phy_event_elist_; Int_t phy_event_cur_index_; Trigger_T phy_trigg_; Trigger_T ped_trigg_; Modules_T phy_event_; Modules_T ped_event_; public: Trigger_T cur_trigg; Modules_T cur_event; private: bool ped_trigg_next_(); bool phy_trigg_next_(); bool ped_event_next_(); bool phy_event_next_(); public: ModuleIterator(); ~ModuleIterator(); bool open(const char* filename); void close(); bool trigg_next(); bool event_next(); bool set_module(int ct_num, string filter = ""); bool set_trigger(string filter = ""); void set_start(); Int_t get_tot_N(); int get_cur_seq(); int get_bad_cnt(); int get_cur_ct_num(); string get_cur_filter(); bool cur_is_ped(); Modules_T get_first_event(); Modules_T get_last_event(); Trigger_T get_first_trigg(); Trigger_T get_last_trigg(); TTree* get_trigger_tree(); TTree* get_modules_tree(); TTree* get_ped_trigger_tree(); TTree* get_ped_modules_tree(); bool is_1P() { return cur_is_1P_; } }; #endif
[ "zhenghenge@gmail.com" ]
zhenghenge@gmail.com
2118da178a4bdb28bae5c471d1929389b6b2b04c
d26099a38bec290e18bd2c25b5795243a69b9d31
/src/qt/transactiontablemodel.cpp
e973be75b12656b9f790faf08cb4511b723920f8
[ "MIT" ]
permissive
microcoinsource/microCoin_V3.0
a074ffa3c23c3bace3b5575fef5b5317d87cf02b
2dccfd13a77d45a7adaf9c1bc01f54821474da07
refs/heads/master
2021-01-15T16:53:28.806532
2016-02-21T14:44:28
2016-02-21T14:44:28
37,809,498
4
3
null
null
null
null
UTF-8
C++
false
false
20,412
cpp
#include "transactiontablemodel.h" #include "guiutil.h" #include "transactionrecord.h" #include "guiconstants.h" #include "transactiondesc.h" #include "walletmodel.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "wallet.h" #include "ui_interface.h" #include <QLocale> #include <QList> #include <QColor> #include <QTimer> #include <QIcon> #include <QDateTime> #include <QtAlgorithms> // Amount column is right-aligned it contains numbers static int column_alignments[] = { Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignRight|Qt::AlignVCenter }; // Comparison operator for sort/binary search of model tx list struct TxLessThan { bool operator()(const TransactionRecord &a, const TransactionRecord &b) const { return a.hash < b.hash; } bool operator()(const TransactionRecord &a, const uint256 &b) const { return a.hash < b; } bool operator()(const uint256 &a, const TransactionRecord &b) const { return a < b.hash; } }; // Private implementation class TransactionTablePriv { public: TransactionTablePriv(CWallet *wallet, TransactionTableModel *parent): wallet(wallet), parent(parent) { } CWallet *wallet; TransactionTableModel *parent; /* Local cache of wallet. * As it is in the same order as the CWallet, by definition * this is sorted by sha256. */ QList<TransactionRecord> cachedWallet; /* Query entire wallet anew from core. */ void refreshWallet() { OutputDebugStringF("refreshWallet\n"); cachedWallet.clear(); { LOCK(wallet->cs_wallet); for(std::map<uint256, CWalletTx>::iterator it = wallet->mapWallet.begin(); it != wallet->mapWallet.end(); ++it) { if(TransactionRecord::showTransaction(it->second)) cachedWallet.append(TransactionRecord::decomposeTransaction(wallet, it->second)); } } } /* Update our model of the wallet incrementally, to synchronize our model of the wallet with that of the core. Call with transaction that was added, removed or changed. */ void updateWallet(const uint256 &hash, int status) { OutputDebugStringF("updateWallet %s %i\n", hash.ToString().c_str(), status); { LOCK(wallet->cs_wallet); // Find transaction in wallet std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash); bool inWallet = mi != wallet->mapWallet.end(); // Find bounds of this transaction in model QList<TransactionRecord>::iterator lower = qLowerBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); QList<TransactionRecord>::iterator upper = qUpperBound( cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan()); int lowerIndex = (lower - cachedWallet.begin()); int upperIndex = (upper - cachedWallet.begin()); bool inModel = (lower != upper); // Determine whether to show transaction or not bool showTransaction = (inWallet && TransactionRecord::showTransaction(mi->second)); if(status == CT_UPDATED) { if(showTransaction && !inModel) status = CT_NEW; /* Not in model, but want to show, treat as new */ if(!showTransaction && inModel) status = CT_DELETED; /* In model, but want to hide, treat as deleted */ } OutputDebugStringF(" inWallet=%i inModel=%i Index=%i-%i showTransaction=%i derivedStatus=%i\n", inWallet, inModel, lowerIndex, upperIndex, showTransaction, status); switch(status) { case CT_NEW: if(inModel) { OutputDebugStringF("Warning: updateWallet: Got CT_NEW, but transaction is already in model\n"); break; } if(!inWallet) { OutputDebugStringF("Warning: updateWallet: Got CT_NEW, but transaction is not in wallet\n"); break; } if(showTransaction) { // Added -- insert at the right position QList<TransactionRecord> toInsert = TransactionRecord::decomposeTransaction(wallet, mi->second); if(!toInsert.isEmpty()) /* only if something to insert */ { parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex+toInsert.size()-1); int insert_idx = lowerIndex; foreach(const TransactionRecord &rec, toInsert) { cachedWallet.insert(insert_idx, rec); insert_idx += 1; } parent->endInsertRows(); } } break; case CT_DELETED: if(!inModel) { OutputDebugStringF("Warning: updateWallet: Got CT_DELETED, but transaction is not in model\n"); break; } // Removed -- remove entire transaction from table parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedWallet.erase(lower, upper); parent->endRemoveRows(); break; case CT_UPDATED: // Miscellaneous updates -- nothing to do, status update will take care of this, and is only computed for // visible transactions. break; } } } int size() { return cachedWallet.size(); } TransactionRecord *index(int idx) { if(idx >= 0 && idx < cachedWallet.size()) { TransactionRecord *rec = &cachedWallet[idx]; // If a status update is needed (blocks came in since last check), // update the status of this transaction from the wallet. Otherwise, // simply re-use the cached status. if(rec->statusUpdateNeeded()) { { LOCK(wallet->cs_wallet); std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash); if(mi != wallet->mapWallet.end()) { rec->updateStatus(mi->second); } } } return rec; } else { return 0; } } QString describe(TransactionRecord *rec) { { LOCK(wallet->cs_wallet); std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash); if(mi != wallet->mapWallet.end()) { return TransactionDesc::toHTML(wallet, mi->second); } } return QString(""); } }; TransactionTableModel::TransactionTableModel(CWallet* wallet, WalletModel *parent): QAbstractTableModel(parent), wallet(wallet), walletModel(parent), priv(new TransactionTablePriv(wallet, this)), cachedNumBlocks(0) { columns << QString() << tr("Date") << tr("Type") << tr("Address") << tr("Reference") << tr("Amount"); priv->refreshWallet(); QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updateConfirmations())); timer->start(MODEL_UPDATE_DELAY); connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); } TransactionTableModel::~TransactionTableModel() { delete priv; } void TransactionTableModel::updateTransaction(const QString &hash, int status) { uint256 updated; updated.SetHex(hash.toStdString()); priv->updateWallet(updated, status); } void TransactionTableModel::updateConfirmations() { if(nBestHeight != cachedNumBlocks) { cachedNumBlocks = nBestHeight; // Blocks came in since last poll. // Invalidate status (number of confirmations) and (possibly) description // for all rows. Qt is smart enough to only actually request the data for the // visible rows. emit dataChanged(index(0, Status), index(priv->size()-1, Status)); emit dataChanged(index(0, ToAddress), index(priv->size()-1, ToAddress)); } } int TransactionTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int TransactionTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QString TransactionTableModel::formatTxStatus(const TransactionRecord *wtx) const { QString status; switch(wtx->status.status) { case TransactionStatus::OpenUntilBlock: status = tr("Open for %n more block(s)","",wtx->status.open_for); break; case TransactionStatus::OpenUntilDate: status = tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx->status.open_for)); break; case TransactionStatus::Offline: status = tr("Offline"); break; case TransactionStatus::Unconfirmed: status = tr("Unconfirmed"); break; case TransactionStatus::Confirming: status = tr("Confirming (%1 of %2 recommended confirmations)").arg(wtx->status.depth).arg(TransactionRecord::RecommendedNumConfirmations); break; case TransactionStatus::Confirmed: status = tr("Confirmed (%1 confirmations)").arg(wtx->status.depth); break; case TransactionStatus::Conflicted: status = tr("Conflicted"); break; case TransactionStatus::Immature: status = tr("Immature (%1 confirmations, will be available after %2)").arg(wtx->status.depth).arg(wtx->status.depth + wtx->status.matures_in); break; case TransactionStatus::MaturesWarning: status = tr("This block was not received by any other nodes and will probably not be accepted!"); break; case TransactionStatus::NotAccepted: status = tr("Generated but not accepted"); break; } return status; } QString TransactionTableModel::formatTxDate(const TransactionRecord *wtx) const { if(wtx->time) { return GUIUtil::dateTimeStr(wtx->time); } else { return QString(); } } /* Look up address in address book, if found return label (address) otherwise just return (address) */ QString TransactionTableModel::lookupAddress(const std::string &address, bool tooltip) const { QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(address)); QString description; if(!label.isEmpty()) { description += label + QString(" "); } if(label.isEmpty() || walletModel->getOptionsModel()->getDisplayAddresses() || tooltip) { description += QString("(") + QString::fromStdString(address) + QString(")"); } return description; } QString TransactionTableModel::formatTxType(const TransactionRecord *wtx) const { switch(wtx->type) { case TransactionRecord::RecvWithAddress: return tr("Received with"); case TransactionRecord::RecvFromOther: return tr("Received from"); case TransactionRecord::SendToAddress: case TransactionRecord::SendToOther: return tr("Sent to"); case TransactionRecord::SendToSelf: return tr("Payment to yourself"); case TransactionRecord::Generated: return tr("Mined"); default: return QString(); } } QVariant TransactionTableModel::txAddressDecoration(const TransactionRecord *wtx) const { switch(wtx->type) { case TransactionRecord::Generated: return QIcon(":/icons/tx_mined"); case TransactionRecord::RecvWithAddress: case TransactionRecord::RecvFromOther: return QIcon(":/icons/tx_input"); case TransactionRecord::SendToAddress: case TransactionRecord::SendToOther: return QIcon(":/icons/tx_output"); default: return QIcon(":/icons/tx_inout"); } return QVariant(); } QString TransactionTableModel::formatTxToAddress(const TransactionRecord *wtx, bool tooltip) const { switch(wtx->type) { case TransactionRecord::RecvFromOther: return QString::fromStdString(wtx->address); case TransactionRecord::RecvWithAddress: case TransactionRecord::SendToAddress: case TransactionRecord::Generated: return lookupAddress(wtx->address, tooltip); case TransactionRecord::SendToOther: return QString::fromStdString(wtx->address); case TransactionRecord::SendToSelf: default: return tr("(n/a)"); } } QString TransactionTableModel::formatTxReference(const TransactionRecord *wtx) const { return QString::fromStdString(wtx->reference); } QVariant TransactionTableModel::addressColor(const TransactionRecord *wtx) const { // Show addresses without label in a less visible color switch(wtx->type) { case TransactionRecord::RecvWithAddress: case TransactionRecord::SendToAddress: case TransactionRecord::Generated: { QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(wtx->address)); if(label.isEmpty()) return COLOR_BAREADDRESS; } break; case TransactionRecord::SendToSelf: return COLOR_BAREADDRESS; default: break; } return QVariant(); } QString TransactionTableModel::formatTxAmount(const TransactionRecord *wtx, bool showUnconfirmed) const { QString str = BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), wtx->credit + wtx->debit); if(showUnconfirmed) { if(!wtx->status.countsForBalance) { str = QString("[") + str + QString("]"); } } return QString(str); } QVariant TransactionTableModel::txStatusDecoration(const TransactionRecord *wtx) const { switch(wtx->status.status) { case TransactionStatus::OpenUntilBlock: case TransactionStatus::OpenUntilDate: return QColor(64,64,255); case TransactionStatus::Offline: return QColor(192,192,192); case TransactionStatus::Unconfirmed: return QIcon(":/icons/transaction_0"); case TransactionStatus::Confirming: switch(wtx->status.depth) { case 1: return QIcon(":/icons/transaction_1"); case 2: return QIcon(":/icons/transaction_2"); case 3: return QIcon(":/icons/transaction_3"); case 4: return QIcon(":/icons/transaction_4"); default: return QIcon(":/icons/transaction_5"); }; case TransactionStatus::Confirmed: return QIcon(":/icons/transaction_confirmed"); case TransactionStatus::Conflicted: return QIcon(":/icons/transaction_conflicted"); case TransactionStatus::Immature: { int total = wtx->status.depth + wtx->status.matures_in; int part = (wtx->status.depth * 4 / total) + 1; return QIcon(QString(":/icons/transaction_%1").arg(part)); } case TransactionStatus::MaturesWarning: case TransactionStatus::NotAccepted: return QIcon(":/icons/transaction_0"); } return QColor(0,0,0); } QString TransactionTableModel::formatTooltip(const TransactionRecord *rec) const { QString tooltip = formatTxStatus(rec) + QString("\n") + formatTxType(rec); if(rec->type==TransactionRecord::RecvFromOther || rec->type==TransactionRecord::SendToOther || rec->type==TransactionRecord::SendToAddress || rec->type==TransactionRecord::RecvWithAddress) { tooltip += QString(" ") + formatTxToAddress(rec, true); } return tooltip; } QVariant TransactionTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); TransactionRecord *rec = static_cast<TransactionRecord*>(index.internalPointer()); switch(role) { case Qt::DecorationRole: switch(index.column()) { case Status: return txStatusDecoration(rec); case ToAddress: return txAddressDecoration(rec); } break; case Qt::DisplayRole: switch(index.column()) { case Date: return formatTxDate(rec); case Type: return formatTxType(rec); case ToAddress: return formatTxToAddress(rec, false); case Amount: return formatTxAmount(rec); case Reference: return formatTxReference(rec); } break; case Qt::EditRole: // Edit role is used for sorting, so return the unformatted values switch(index.column()) { case Status: return QString::fromStdString(rec->status.sortKey); case Date: return rec->time; case Type: return formatTxType(rec); case ToAddress: return formatTxToAddress(rec, true); case Amount: return rec->credit + rec->debit; } break; case Qt::ToolTipRole: return formatTooltip(rec); case Qt::TextAlignmentRole: return column_alignments[index.column()]; case Qt::ForegroundRole: // Non-confirmed (but not immature) as transactions are grey if(!rec->status.countsForBalance && rec->status.status != TransactionStatus::Immature) { return COLOR_UNCONFIRMED; } if(index.column() == Amount && (rec->credit+rec->debit) < 0) { return COLOR_NEGATIVE; } if(index.column() == ToAddress) { return addressColor(rec); } break; case TypeRole: return rec->type; case DateRole: return QDateTime::fromTime_t(static_cast<uint>(rec->time)); case LongDescriptionRole: return priv->describe(rec); case AddressRole: return QString::fromStdString(rec->address); case LabelRole: return walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(rec->address)); case AmountRole: return rec->credit + rec->debit; case TxIDRole: return QString::fromStdString(rec->getTxID()); case ConfirmedRole: return rec->status.countsForBalance; case FormattedAmountRole: return formatTxAmount(rec, false); case StatusRole: return rec->status.status; } return QVariant(); } QVariant TransactionTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } else if (role == Qt::TextAlignmentRole) { return column_alignments[section]; } else if (role == Qt::ToolTipRole) { switch(section) { case Status: return tr("Transaction status. Hover over this field to show number of confirmations."); case Date: return tr("Date and time that the transaction was received."); case Type: return tr("Type of transaction."); case ToAddress: return tr("Destination address of transaction."); case Amount: return tr("Amount removed from or added to balance."); } } } return QVariant(); } QModelIndex TransactionTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); TransactionRecord *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void TransactionTableModel::updateDisplayUnit() { // emit dataChanged to update Amount column with the current unit emit dataChanged(index(0, Amount), index(priv->size()-1, Amount)); }
[ "office@alcurex.info" ]
office@alcurex.info
672cc4fc0c01fdcad42318a51b25d01aad63a476
db97e3e6643f6d674032e6d6ae3cc03b8ceedb8d
/support/macOS/xerces-c/src/xercesc/validators/datatype/DatatypeValidatorFactory.cpp
973e01a646156cabfc5b178030732f0a27554669
[ "Apache-2.0", "MIT" ]
permissive
audio-dsp/Max-Live-Environment
ddb302a1c945da7cea2cc62a17e0c5c2c7935a07
e0622c899c55ac9a73bcfce5aecdf99cc2618ed0
refs/heads/master
2020-06-12T08:32:06.458685
2019-06-07T02:15:17
2019-06-07T02:15:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
36,815
cpp
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/validators/datatype/DatatypeValidatorFactory.hpp> #include <xercesc/validators/schema/SchemaSymbols.hpp> #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/validators/datatype/StringDatatypeValidator.hpp> #include <xercesc/validators/datatype/BooleanDatatypeValidator.hpp> #include <xercesc/validators/datatype/DecimalDatatypeValidator.hpp> #include <xercesc/validators/datatype/HexBinaryDatatypeValidator.hpp> #include <xercesc/validators/datatype/Base64BinaryDatatypeValidator.hpp> #include <xercesc/validators/datatype/IDDatatypeValidator.hpp> #include <xercesc/validators/datatype/IDREFDatatypeValidator.hpp> #include <xercesc/validators/datatype/NOTATIONDatatypeValidator.hpp> #include <xercesc/validators/datatype/ENTITYDatatypeValidator.hpp> #include <xercesc/validators/datatype/QNameDatatypeValidator.hpp> #include <xercesc/validators/datatype/NameDatatypeValidator.hpp> #include <xercesc/validators/datatype/NCNameDatatypeValidator.hpp> #include <xercesc/validators/datatype/ListDatatypeValidator.hpp> #include <xercesc/validators/datatype/UnionDatatypeValidator.hpp> #include <xercesc/validators/datatype/DoubleDatatypeValidator.hpp> #include <xercesc/validators/datatype/FloatDatatypeValidator.hpp> #include <xercesc/validators/datatype/AnyURIDatatypeValidator.hpp> #include <xercesc/validators/datatype/AnySimpleTypeDatatypeValidator.hpp> #include <xercesc/validators/datatype/DateTimeDatatypeValidator.hpp> #include <xercesc/validators/datatype/DateDatatypeValidator.hpp> #include <xercesc/validators/datatype/TimeDatatypeValidator.hpp> #include <xercesc/validators/datatype/DayDatatypeValidator.hpp> #include <xercesc/validators/datatype/MonthDatatypeValidator.hpp> #include <xercesc/validators/datatype/MonthDayDatatypeValidator.hpp> #include <xercesc/validators/datatype/YearDatatypeValidator.hpp> #include <xercesc/validators/datatype/YearMonthDatatypeValidator.hpp> #include <xercesc/validators/datatype/DurationDatatypeValidator.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/XMLInitializer.hpp> #include <xercesc/internal/XTemplateSerializer.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // DatatypeValidatorFactory: Local const data // --------------------------------------------------------------------------- const XMLCh fgTokPattern[] = { chBackSlash, chLatin_c, chPlus, chNull }; //E2-43 //[+\-]?[0-9]+ const XMLCh fgIntegerPattern[] = { chOpenSquare, chPlus, chBackSlash, chDash, chCloseSquare, chQuestion, chOpenSquare, chDigit_0, chDash, chDigit_9, chCloseSquare, chPlus, chNull }; // --------------------------------------------------------------------------- // DatatypeValidatorFactory: Static member data // --------------------------------------------------------------------------- RefHashTableOf<DatatypeValidator>* DatatypeValidatorFactory::fBuiltInRegistry = 0; RefHashTableOf<XMLCanRepGroup, PtrHasher>* DatatypeValidatorFactory::fCanRepRegistry = 0; void XMLInitializer::initializeDatatypeValidatorFactory() { // @@ This is ugly. Need to make expandRegistryToFullSchemaSet // static. // DatatypeValidatorFactory *dvFactory = new DatatypeValidatorFactory(); if (dvFactory) { dvFactory->expandRegistryToFullSchemaSet(); delete dvFactory; } } void XMLInitializer::terminateDatatypeValidatorFactory() { delete DatatypeValidatorFactory::fBuiltInRegistry; DatatypeValidatorFactory::fBuiltInRegistry = 0; delete DatatypeValidatorFactory::fCanRepRegistry; DatatypeValidatorFactory::fCanRepRegistry = 0; } // --------------------------------------------------------------------------- // DatatypeValidatorFactory: Constructors and Destructor // --------------------------------------------------------------------------- DatatypeValidatorFactory::DatatypeValidatorFactory(MemoryManager* const manager) : fUserDefinedRegistry(0) , fMemoryManager(manager) { } DatatypeValidatorFactory::~DatatypeValidatorFactory() { cleanUp(); } // --------------------------------------------------------------------------- // DatatypeValidatorFactory: Reset methods // --------------------------------------------------------------------------- void DatatypeValidatorFactory::resetRegistry() { if (fUserDefinedRegistry != 0) { fUserDefinedRegistry->removeAll(); } } // --------------------------------------------------------------------------- // DatatypeValidatorFactory: Registry initialization methods // --------------------------------------------------------------------------- void DatatypeValidatorFactory::expandRegistryToFullSchemaSet() { //Initialize common Schema/DTD Datatype validator set fBuiltInRegistry = new RefHashTableOf<DatatypeValidator>(29); DatatypeValidator *dv = new StringDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_STRING, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_STRING, dv); dv = new NOTATIONDatatypeValidator(); dv->setTypeName(XMLUni::fgNotationString, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) XMLUni::fgNotationString, dv); dv = new AnySimpleTypeDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_ANYSIMPLETYPE, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_ANYSIMPLETYPE, dv); dv = new BooleanDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_BOOLEAN, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_BOOLEAN, dv); dv = new DecimalDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_DECIMAL, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_DECIMAL, dv); dv = new HexBinaryDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_HEXBINARY, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_HEXBINARY, dv); dv = new Base64BinaryDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_BASE64BINARY, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_BASE64BINARY, dv); dv = new DoubleDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_DOUBLE, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_DOUBLE, dv); dv = new FloatDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_FLOAT, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_FLOAT, dv); dv = new AnyURIDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_ANYURI, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_ANYURI, dv); dv = new QNameDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_QNAME, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_QNAME, dv); dv = new DateTimeDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_DATETIME, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_DATETIME, dv); dv = new DateDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_DATE, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_DATE, dv); dv = new TimeDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_TIME, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_TIME, dv); dv = new DayDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_DAY, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_DAY, dv); dv = new MonthDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_MONTH, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_MONTH, dv); dv = new MonthDayDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_MONTHDAY, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_MONTHDAY, dv); dv = new YearDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_YEAR, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_YEAR, dv); dv = new YearMonthDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_YEARMONTH, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_YEARMONTH, dv); dv = new DurationDatatypeValidator(); dv->setTypeName(SchemaSymbols::fgDT_DURATION, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_DURATION, dv); // REVISIT // We are creating a lot of Hashtables for the facets of the different // validators. It's better to have some kind of a memory pool and ask // the pool to give us a new instance of the hashtable. RefHashTableOf<KVStringPair>* facets = new RefHashTableOf<KVStringPair>(3); // Create 'normalizedString' datatype validator facets->put((void*) SchemaSymbols::fgELT_WHITESPACE, new KVStringPair(SchemaSymbols::fgELT_WHITESPACE, SchemaSymbols::fgWS_REPLACE)); createDatatypeValidator(SchemaSymbols::fgDT_NORMALIZEDSTRING, getDatatypeValidator(SchemaSymbols::fgDT_STRING), facets, 0, false, 0, false); // Create 'token' datatype validator facets = new RefHashTableOf<KVStringPair>(3); facets->put((void*) SchemaSymbols::fgELT_WHITESPACE, new KVStringPair(SchemaSymbols::fgELT_WHITESPACE, SchemaSymbols::fgWS_COLLAPSE)); createDatatypeValidator(SchemaSymbols::fgDT_TOKEN, getDatatypeValidator(SchemaSymbols::fgDT_NORMALIZEDSTRING), facets, 0, false, 0, false); dv = new NameDatatypeValidator(getDatatypeValidator(SchemaSymbols::fgDT_TOKEN), 0, 0, 0); dv->setTypeName(SchemaSymbols::fgDT_NAME, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_NAME, dv); dv = new NCNameDatatypeValidator(getDatatypeValidator(SchemaSymbols::fgDT_NAME), 0, 0, 0); dv->setTypeName(SchemaSymbols::fgDT_NCNAME, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) SchemaSymbols::fgDT_NCNAME, dv); // Create 'NMTOKEN' datatype validator facets = new RefHashTableOf<KVStringPair>(3); facets->put((void*) SchemaSymbols::fgELT_PATTERN , new KVStringPair(SchemaSymbols::fgELT_PATTERN,fgTokPattern)); facets->put((void*) SchemaSymbols::fgELT_WHITESPACE, new KVStringPair(SchemaSymbols::fgELT_WHITESPACE, SchemaSymbols::fgWS_COLLAPSE)); createDatatypeValidator(XMLUni::fgNmTokenString, getDatatypeValidator(SchemaSymbols::fgDT_TOKEN),facets, 0, false, 0, false); // Create 'NMTOKENS' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MINLENGTH, new KVStringPair(SchemaSymbols::fgELT_MINLENGTH, XMLUni::fgValueOne)); createDatatypeValidator(XMLUni::fgNmTokensString, getDatatypeValidator(XMLUni::fgNmTokenString), facets, 0, true, 0, false); // Create 'language' datatype validator facets = new RefHashTableOf<KVStringPair>(3); facets->put((void*) SchemaSymbols::fgELT_PATTERN, new KVStringPair(SchemaSymbols::fgELT_PATTERN, XMLUni::fgLangPattern)); createDatatypeValidator(SchemaSymbols::fgDT_LANGUAGE, getDatatypeValidator(SchemaSymbols::fgDT_TOKEN), facets, 0, false, 0, false); // Create 'integer' datatype validator facets = new RefHashTableOf<KVStringPair>(3); facets->put((void*) SchemaSymbols::fgELT_FRACTIONDIGITS, new KVStringPair(SchemaSymbols::fgELT_FRACTIONDIGITS, XMLUni::fgValueZero)); facets->put((void*) SchemaSymbols::fgELT_PATTERN, new KVStringPair(SchemaSymbols::fgELT_PATTERN, fgIntegerPattern)); createDatatypeValidator(SchemaSymbols::fgDT_INTEGER, getDatatypeValidator(SchemaSymbols::fgDT_DECIMAL), facets, 0, false, 0, false); // Create 'nonPositiveInteger' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgValueZero)); createDatatypeValidator(SchemaSymbols::fgDT_NONPOSITIVEINTEGER, getDatatypeValidator(SchemaSymbols::fgDT_INTEGER), facets, 0, false, 0, false); // Create 'negativeInteger' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgNegOne)); createDatatypeValidator(SchemaSymbols::fgDT_NEGATIVEINTEGER, getDatatypeValidator(SchemaSymbols::fgDT_NONPOSITIVEINTEGER), facets, 0, false, 0, false); // Create 'long' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgLongMaxInc)); facets->put((void*) SchemaSymbols::fgELT_MININCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MININCLUSIVE, XMLUni::fgLongMinInc)); createDatatypeValidator(SchemaSymbols::fgDT_LONG, getDatatypeValidator(SchemaSymbols::fgDT_INTEGER), facets, 0, false, 0, false); // Create 'int' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgIntMaxInc)); facets->put((void*) SchemaSymbols::fgELT_MININCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MININCLUSIVE, XMLUni::fgIntMinInc)); createDatatypeValidator(SchemaSymbols::fgDT_INT, getDatatypeValidator(SchemaSymbols::fgDT_LONG), facets, 0, false, 0, false); // Create 'short' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgShortMaxInc)); facets->put((void*) SchemaSymbols::fgELT_MININCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MININCLUSIVE, XMLUni::fgShortMinInc)); createDatatypeValidator(SchemaSymbols::fgDT_SHORT, getDatatypeValidator(SchemaSymbols::fgDT_INT), facets, 0, false, 0 ,false); // Create 'byte' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgByteMaxInc)); facets->put((void*) SchemaSymbols::fgELT_MININCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MININCLUSIVE, XMLUni::fgByteMinInc)); createDatatypeValidator(SchemaSymbols::fgDT_BYTE, getDatatypeValidator(SchemaSymbols::fgDT_SHORT), facets, 0, false, 0, false); // Create 'nonNegativeInteger' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MININCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MININCLUSIVE, XMLUni::fgValueZero)); createDatatypeValidator(SchemaSymbols::fgDT_NONNEGATIVEINTEGER, getDatatypeValidator(SchemaSymbols::fgDT_INTEGER), facets, 0, false, 0, false); // Create 'unsignedLong' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgULongMaxInc)); createDatatypeValidator(SchemaSymbols::fgDT_ULONG, getDatatypeValidator(SchemaSymbols::fgDT_NONNEGATIVEINTEGER), facets, 0, false, 0, false); // Create 'unsignedInt' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgUIntMaxInc)); createDatatypeValidator(SchemaSymbols::fgDT_UINT, getDatatypeValidator(SchemaSymbols::fgDT_ULONG), facets, 0, false, 0, false); // Create 'unsignedShort' datatypeValidator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgUShortMaxInc)); createDatatypeValidator(SchemaSymbols::fgDT_USHORT, getDatatypeValidator(SchemaSymbols::fgDT_UINT), facets, 0, false, 0, false); // Create 'unsignedByte' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MAXINCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MAXINCLUSIVE, XMLUni::fgUByteMaxInc)); createDatatypeValidator(SchemaSymbols::fgDT_UBYTE, getDatatypeValidator(SchemaSymbols::fgDT_USHORT), facets, 0, false, 0, false); // Create 'positiveInteger' datatype validator facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MININCLUSIVE, new KVStringPair(SchemaSymbols::fgELT_MININCLUSIVE, XMLUni::fgValueOne)); createDatatypeValidator(SchemaSymbols::fgDT_POSITIVEINTEGER, getDatatypeValidator(SchemaSymbols::fgDT_NONNEGATIVEINTEGER), facets, 0, false, 0, false); // Create 'ID', 'IDREF' and 'ENTITY' datatype validator dv = new IDDatatypeValidator(getDatatypeValidator(SchemaSymbols::fgDT_NCNAME), 0, 0, 0); dv->setTypeName(XMLUni::fgIDString, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) XMLUni::fgIDString, dv); dv = new IDREFDatatypeValidator(getDatatypeValidator(SchemaSymbols::fgDT_NCNAME), 0, 0, 0); dv->setTypeName(XMLUni::fgIDRefString, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) XMLUni::fgIDRefString, dv); dv = new ENTITYDatatypeValidator(getDatatypeValidator(SchemaSymbols::fgDT_NCNAME), 0, 0, 0); dv->setTypeName(XMLUni::fgEntityString, SchemaSymbols::fgURI_SCHEMAFORSCHEMA); fBuiltInRegistry->put((void*) XMLUni::fgEntityString, dv); facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MINLENGTH, new KVStringPair(SchemaSymbols::fgELT_MINLENGTH, XMLUni::fgValueOne)); // Create 'IDREFS' datatype validator createDatatypeValidator ( XMLUni::fgIDRefsString , getDatatypeValidator(XMLUni::fgIDRefString) , facets , 0 , true , 0 , false ); facets = new RefHashTableOf<KVStringPair>(2); facets->put((void*) SchemaSymbols::fgELT_MINLENGTH, new KVStringPair(SchemaSymbols::fgELT_MINLENGTH, XMLUni::fgValueOne)); // Create 'ENTITIES' datatype validator createDatatypeValidator ( XMLUni::fgEntitiesString , getDatatypeValidator(XMLUni::fgEntityString) , facets , 0 , true , 0 , false ); initCanRepRegistory(); } /*** * * For Decimal-derivated, an instance of DecimalDatatypeValidator * can be used by the primitive datatype, decimal, or any one of * the derivated datatypes, such as int, long, unsighed short, just * name a few, or any user-defined datatypes, which may derivate from * either the primitive datatype, decimal, or from any one of those * decimal derivated datatypes, or other user-defined datatypes, which * in turn, indirectly derivate from decimal or decimal-derived. * * fCanRepRegisty captures deciaml dv and its derivatives. * ***/ void DatatypeValidatorFactory::initCanRepRegistory() { /*** * key: dv * data: XMLCanRepGroup ***/ fCanRepRegistry = new RefHashTableOf<XMLCanRepGroup, PtrHasher>(29, true); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_DECIMAL), new XMLCanRepGroup(XMLCanRepGroup::Decimal)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_INTEGER), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derived_signed)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_LONG), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derived_signed)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_INT), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derived_signed)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_SHORT), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derived_signed)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_BYTE), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derived_signed)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_NONNEGATIVEINTEGER), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derived_signed)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_POSITIVEINTEGER), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derived_signed)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_NEGATIVEINTEGER), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derived_unsigned)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_ULONG), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derived_unsigned)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_UINT), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derived_unsigned)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_USHORT), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derived_unsigned)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_UBYTE), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derived_unsigned)); fCanRepRegistry->put((void*) getDatatypeValidator(SchemaSymbols::fgDT_NONPOSITIVEINTEGER), new XMLCanRepGroup(XMLCanRepGroup::Decimal_Derived_npi)); } /*** * * For any dv other than Decimaldv, return String only. * Later on if support to dv other than Decimaldv arise, we may * add them fCanRepRegistry during DatatypeValidatorFactory::initCanRepRegistory() * ***/ XMLCanRepGroup::CanRepGroup DatatypeValidatorFactory::getCanRepGroup(const DatatypeValidator* const dv) { if (!dv) return XMLCanRepGroup::String; DatatypeValidator *curdv = (DatatypeValidator*) dv; while (curdv) { if (fCanRepRegistry->containsKey(curdv)) return fCanRepRegistry->get(curdv)->getGroup(); else curdv = curdv->getBaseValidator(); } return XMLCanRepGroup::String; } DatatypeValidator* DatatypeValidatorFactory::getBuiltInBaseValidator(const DatatypeValidator* const dv) { DatatypeValidator *curdv = (DatatypeValidator*)dv; while (curdv) { if (curdv == getBuiltInRegistry()->get(curdv->getTypeLocalName())) return curdv; else curdv = curdv->getBaseValidator(); } return 0; } // --------------------------------------------------------------------------- // DatatypeValidatorFactory: factory methods // --------------------------------------------------------------------------- DatatypeValidator* DatatypeValidatorFactory::createDatatypeValidator ( const XMLCh* const typeName , DatatypeValidator* const baseValidator , RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , const bool isDerivedByList , const int finalSet , const bool isUserDefined , MemoryManager* const userManager ) { if (baseValidator == 0) { if (facets) { Janitor<KVStringPairHashTable> janFacets(facets); } if (enums) { Janitor<XMLChRefVector> janEnums(enums); } return 0; } DatatypeValidator* datatypeValidator = 0; MemoryManager* const manager = (isUserDefined) ? userManager : XMLPlatformUtils::fgMemoryManager; if (isDerivedByList) { datatypeValidator = new (manager) ListDatatypeValidator(baseValidator, facets, enums, finalSet, manager); // Set PSVI information for Ordered, Numeric, Bounded & Finite datatypeValidator->setOrdered(XSSimpleTypeDefinition::ORDERED_FALSE); datatypeValidator->setNumeric(false); if (facets && ((facets->get(SchemaSymbols::fgELT_LENGTH) || (facets->get(SchemaSymbols::fgELT_MINLENGTH) && facets->get(SchemaSymbols::fgELT_MAXLENGTH))))) { datatypeValidator->setBounded(true); datatypeValidator->setFinite(true); } else { datatypeValidator->setBounded(false); datatypeValidator->setFinite(false); } } else { if ((baseValidator->getType() != DatatypeValidator::String) && facets) { KVStringPair* value = facets->get(SchemaSymbols::fgELT_WHITESPACE); if (value != 0) { facets->removeKey(SchemaSymbols::fgELT_WHITESPACE); } } datatypeValidator = baseValidator->newInstance ( facets , enums , finalSet , manager ); // Set PSVI information for Ordered, Numeric, Bounded & Finite datatypeValidator->setOrdered(baseValidator->getOrdered()); datatypeValidator->setNumeric(baseValidator->getNumeric()); RefHashTableOf<KVStringPair>* baseFacets = baseValidator->getFacets(); if (facets && ((facets->get(SchemaSymbols::fgELT_MININCLUSIVE) || facets->get(SchemaSymbols::fgELT_MINEXCLUSIVE) || (baseFacets && (baseFacets->get(SchemaSymbols::fgELT_MININCLUSIVE) || baseFacets->get(SchemaSymbols::fgELT_MINEXCLUSIVE))))) && (facets->get(SchemaSymbols::fgELT_MAXINCLUSIVE) || facets->get(SchemaSymbols::fgELT_MAXEXCLUSIVE) || (baseFacets && ((baseFacets->get(SchemaSymbols::fgELT_MAXINCLUSIVE) || baseFacets->get(SchemaSymbols::fgELT_MAXEXCLUSIVE)))))) { datatypeValidator->setBounded(true); } else { datatypeValidator->setBounded(false); } if (baseValidator->getFinite()) { datatypeValidator->setFinite(true); } else if (!facets) { datatypeValidator->setFinite(false); } else if (facets->get(SchemaSymbols::fgELT_LENGTH) || facets->get(SchemaSymbols::fgELT_MAXLENGTH) || facets->get(SchemaSymbols::fgELT_TOTALDIGITS)) { datatypeValidator->setFinite(true); } //for efficiency use this instead of rechecking... //else if ((facets->get(SchemaSymbols::fgELT_MININCLUSIVE) || facets->get(SchemaSymbols::fgELT_MINEXCLUSIVE)) && // (facets->get(SchemaSymbols::fgELT_MAXINCLUSIVE) || facets->get(SchemaSymbols::fgELT_MAXEXCLUSIVE))) else if (datatypeValidator->getBounded() || datatypeValidator->getType() == DatatypeValidator::Date || datatypeValidator->getType() == DatatypeValidator::YearMonth || datatypeValidator->getType() == DatatypeValidator::Year || datatypeValidator->getType() == DatatypeValidator::MonthDay || datatypeValidator->getType() == DatatypeValidator::Day || datatypeValidator->getType() == DatatypeValidator::Month) { if (facets->get(SchemaSymbols::fgELT_FRACTIONDIGITS)) { datatypeValidator->setFinite(true); } else { datatypeValidator->setFinite(false); } } else { datatypeValidator->setFinite(false); } } if (datatypeValidator != 0) { if (isUserDefined) { if (!fUserDefinedRegistry) { fUserDefinedRegistry = new (userManager) RefHashTableOf<DatatypeValidator>(29, userManager); } fUserDefinedRegistry->put((void *)typeName, datatypeValidator); } else { fBuiltInRegistry->put((void *)typeName, datatypeValidator); } datatypeValidator->setTypeName(typeName); } return datatypeValidator; } static DatatypeValidator::ValidatorType getPrimitiveDV(DatatypeValidator::ValidatorType validationDV) { if (validationDV == DatatypeValidator::ID || validationDV == DatatypeValidator::IDREF || validationDV == DatatypeValidator::ENTITY) { return DatatypeValidator::String; } return validationDV; } DatatypeValidator* DatatypeValidatorFactory::createDatatypeValidator ( const XMLCh* const typeName , RefVectorOf<DatatypeValidator>* const validators , const int finalSet , const bool userDefined , MemoryManager* const userManager ) { if (validators == 0) return 0; DatatypeValidator* datatypeValidator = 0; MemoryManager* const manager = (userDefined) ? userManager : XMLPlatformUtils::fgMemoryManager; datatypeValidator = new (manager) UnionDatatypeValidator(validators, finalSet, manager); if (datatypeValidator != 0) { if (userDefined) { if (!fUserDefinedRegistry) { fUserDefinedRegistry = new (userManager) RefHashTableOf<DatatypeValidator>(29, userManager); } fUserDefinedRegistry->put((void *)typeName, datatypeValidator); } else { fBuiltInRegistry->put((void *)typeName, datatypeValidator); } datatypeValidator->setTypeName(typeName); // Set PSVI information for Ordered, Numeric, Bounded & Finite XMLSize_t valSize = validators->size(); if (valSize) { DatatypeValidator::ValidatorType ancestorId = getPrimitiveDV(validators->elementAt(0)->getType()); // For a union the ORDERED {value} is partial unless one of the following: // 1. If every member of {member type definitions} is derived from a common ancestor other than the simple ur-type, then {value} is the same as that ancestor's ordered facet. // 2. If every member of {member type definitions} has a {value} of false for the ordered facet, then {value} is false. bool allOrderedFalse = true; bool commonAnc = ancestorId != DatatypeValidator::AnySimpleType; bool allNumeric = true; bool allBounded = true; bool allFinite = true; for(XMLSize_t i = 0 ; (i < valSize) && (commonAnc || allOrderedFalse || allNumeric || allBounded || allFinite); i++) { // for the other member types, check whether the value is false // and whether they have the same ancestor as the first one if (commonAnc) commonAnc = ancestorId == getPrimitiveDV(validators->elementAt(i)->getType()); if (allOrderedFalse) allOrderedFalse = validators->elementAt(i)->getOrdered() == XSSimpleTypeDefinition::ORDERED_FALSE; if (allNumeric && !validators->elementAt(i)->getNumeric()) { allNumeric = false; } if (allBounded && (!validators->elementAt(i)->getBounded() || ancestorId != getPrimitiveDV(validators->elementAt(i)->getType()))) { allBounded = false; } if (allFinite && !validators->elementAt(i)->getFinite()) { allFinite = false; } } if (commonAnc) { datatypeValidator->setOrdered(validators->elementAt(0)->getOrdered()); } else if (allOrderedFalse) { datatypeValidator->setOrdered(XSSimpleTypeDefinition::ORDERED_FALSE); } else { datatypeValidator->setOrdered(XSSimpleTypeDefinition::ORDERED_PARTIAL); } datatypeValidator->setNumeric(allNumeric); datatypeValidator->setBounded(allBounded); datatypeValidator->setFinite(allFinite); } else // size = 0 { datatypeValidator->setOrdered(XSSimpleTypeDefinition::ORDERED_PARTIAL); datatypeValidator->setNumeric(true); datatypeValidator->setBounded(true); datatypeValidator->setFinite(true); } } return datatypeValidator; } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_TOCREATE(DatatypeValidatorFactory) void DatatypeValidatorFactory::serialize(XSerializeEngine& serEng) { // Need not to serialize static data member, fBuiltInRegistry if (serEng.isStoring()) { /*** * Serialize RefHashTableOf<DatatypeValidator> ***/ XTemplateSerializer::storeObject(fUserDefinedRegistry, serEng); } else { /*** * Deserialize RefHashTableOf<DatatypeValidator> ***/ XTemplateSerializer::loadObject(&fUserDefinedRegistry, 29, true, serEng); } } XERCES_CPP_NAMESPACE_END /** * End of file DatatypeValidatorFactory.cpp */
[ "jdm7dv@gmail.com" ]
jdm7dv@gmail.com
3ea36dcab3c0be03305818f45421263cdd586378
447b8067c23805d594f927bd0e6e8d2bae9ba0e9
/device/device.cpp
dd3d1cf54dad245bdde1f59cf5165d0ac3766e2e
[]
no_license
paulfitz/cycles_hack
24d61b3d0a8adc679ae4f6edde9006b83e321cd7
a65852f0d5974f958bfa372a68090e68d54ddc53
refs/heads/master
2020-06-12T11:22:36.487405
2012-04-19T22:25:03
2012-04-19T22:25:03
4,011,796
1
1
null
null
null
null
UTF-8
C++
false
false
7,453
cpp
/* * Copyright 2011, Blender Foundation. * * 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 2 * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdlib.h> #include <string.h> #include "device.h" #include "device_intern.h" //#include "util_cuda.h" #include "util_debug.h" #include "util_foreach.h" #include "util_math.h" #include "util_opencl.h" #include "util_opengl.h" #include "util_types.h" #include "util_vector.h" #ifdef USE_SDL #include <SDL/SDL.h> #endif CCL_NAMESPACE_BEGIN /* Device Task */ DeviceTask::DeviceTask(Type type_) : type(type_), x(0), y(0), w(0), h(0), rng_state(0), rgba(0), buffer(0), sample(0), resolution(0), shader_input(0), shader_output(0), shader_eval_type(0), shader_x(0), shader_w(0) { } void DeviceTask::split_max_size(list<DeviceTask>& tasks, int max_size) { int num; if(type == SHADER) { num = (shader_w + max_size - 1)/max_size; } else { max_size = max(1, max_size/w); num = (h + max_size - 1)/max_size; } split(tasks, num); } void DeviceTask::split(ThreadQueue<DeviceTask>& queue, int num) { list<DeviceTask> tasks; split(tasks, num); foreach(DeviceTask& task, tasks) queue.push(task); } void DeviceTask::split(list<DeviceTask>& tasks, int num) { if(type == SHADER) { num = min(shader_w, num); for(int i = 0; i < num; i++) { int tx = shader_x + (shader_w/num)*i; int tw = (i == num-1)? shader_w - i*(shader_w/num): shader_w/num; DeviceTask task = *this; task.shader_x = tx; task.shader_w = tw; tasks.push_back(task); } } else { num = min(h, num); for(int i = 0; i < num; i++) { int ty = y + (h/num)*i; int th = (i == num-1)? h - i*(h/num): h/num; DeviceTask task = *this; task.y = ty; task.h = th; tasks.push_back(task); } } } /* Device */ void Device::pixels_alloc(device_memory& mem) { mem_alloc(mem, MEM_READ_WRITE); } void Device::pixels_copy_from(device_memory& mem, int y, int w, int h) { mem_copy_from(mem, y, w, h, sizeof(uint8_t)*4); } void Device::pixels_free(device_memory& mem) { mem_free(mem); } void Device::draw_pixels(device_memory& rgba, int y, int w, int h, int dy, int width, int height, bool transparent) { pixels_copy_from(rgba, y, w, h); uint8_t *pixels = (uint8_t*)rgba.data_pointer; /* for multi devices, this assumes the ineffecient method that we allocate all pixels on the device even though we only render to a subset */ pixels += 4*y*w; printf("I think we have an image of size %d %d\n", w, h); #ifdef USE_SDL SDL_Surface *screen = SDL_SetVideoMode(w,h, 32, SDL_SWSURFACE); if (SDL_MUSTLOCK(screen)) SDL_LockSurface(screen); for (int i = 0; i < h; i++) { char *target = (char*)screen->pixels + i*w*4; char *src = (char *)pixels + ((h-i-1)*w*4); for (int j = 0; j < w; j++) { target[0] = src[2]; target[1] = src[1]; target[2] = src[0]; target[3] = src[3]; target += 4; src += 4; } } if (SDL_MUSTLOCK(screen)) SDL_UnlockSurface(screen); SDL_Flip(screen); #else #ifndef NO_FILE_OUTPUT static int ct = 0; char buf[1000]; sprintf(buf,"test_%06d.ppm",ct); ct++; FILE *fp = fopen(buf, "wb"); if (!fp) { printf("cannot open file for writing\n"); return; } else { const int inc = w*4; fprintf(fp, "P6\n%d %d\n%d\n", w, h, 255); for (int yy = 0; yy < h; yy++) { char *src = (char *)pixels + ((h-yy-1)*w*4); for (int xx = 0; xx < w; xx++) { fwrite((void *) src, 1, (size_t) (3), fp); src += 4; } } fclose(fp); } printf("wrote to %s (hacked in %s)\n", buf, __FILE__); #endif if (w<200) { for (int yy = 0; yy < h; yy++) { printf("993 "); char *src = (char*)rgba.device_pointer + ((h-yy-1)*w*4); for (int xx = 0; xx < w; xx++) { printf("%d ", (unsigned char)src[0]); printf("%d ", (unsigned char)src[1]); printf("%d ", (unsigned char)src[2]); src += 4; } printf("\n"); } } printf("999 \n"); exit(0); #endif #ifndef NO_VIEWER if(transparent) { glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } glPixelZoom((float)width/(float)w, (float)height/(float)h); glRasterPos2f(0, dy); glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels); glRasterPos2f(0.0f, 0.0f); glPixelZoom(1.0f, 1.0f); if(transparent) glDisable(GL_BLEND); #endif } Device *Device::create(DeviceInfo& info, bool background, int threads) { Device *device; switch(info.type) { case DEVICE_CPU: device = device_cpu_create(info, threads); break; #ifdef WITH_CUDA case DEVICE_CUDA: if(cuLibraryInit()) device = device_cuda_create(info, background); else device = NULL; break; #endif #ifdef WITH_MULTI case DEVICE_MULTI: device = device_multi_create(info, background); break; #endif #ifdef WITH_NETWORK case DEVICE_NETWORK: device = device_network_create(info, "127.0.0.1"); break; #endif #ifdef WITH_OPENCL case DEVICE_OPENCL: if(clLibraryInit()) device = device_opencl_create(info, background); else device = NULL; break; #endif default: return NULL; } if(device) device->info = info; return device; } DeviceType Device::type_from_string(const char *name) { if(strcmp(name, "cpu") == 0) return DEVICE_CPU; else if(strcmp(name, "cuda") == 0) return DEVICE_CUDA; else if(strcmp(name, "opencl") == 0) return DEVICE_OPENCL; else if(strcmp(name, "network") == 0) return DEVICE_NETWORK; else if(strcmp(name, "multi") == 0) return DEVICE_MULTI; return DEVICE_NONE; } string Device::string_from_type(DeviceType type) { if(type == DEVICE_CPU) return "cpu"; else if(type == DEVICE_CUDA) return "cuda"; else if(type == DEVICE_OPENCL) return "opencl"; else if(type == DEVICE_NETWORK) return "network"; else if(type == DEVICE_MULTI) return "multi"; return ""; } vector<DeviceType>& Device::available_types() { static vector<DeviceType> types; static bool types_init = false; if(!types_init) { types.push_back(DEVICE_CPU); #ifdef WITH_CUDA if(cuLibraryInit()) types.push_back(DEVICE_CUDA); #endif #ifdef WITH_OPENCL if(clLibraryInit()) types.push_back(DEVICE_OPENCL); #endif #ifdef WITH_NETWORK types.push_back(DEVICE_NETWORK); #endif #ifdef WITH_MULTI types.push_back(DEVICE_MULTI); #endif types_init = true; } return types; } vector<DeviceInfo>& Device::available_devices() { static vector<DeviceInfo> devices; static bool devices_init = false; if(!devices_init) { #ifdef WITH_CUDA if(cuLibraryInit()) device_cuda_info(devices); #endif #ifdef WITH_OPENCL if(clLibraryInit()) device_opencl_info(devices); #endif #ifdef WITH_MULTI device_multi_info(devices); #endif device_cpu_info(devices); #ifdef WITH_NETWORK device_network_info(devices); #endif devices_init = true; } return devices; } CCL_NAMESPACE_END
[ "paulfitz@alum.mit.edu" ]
paulfitz@alum.mit.edu
196497c688a5c2f1294a1a7a7491d4249c3c4088
60fa2eef5ae796507f5ecf9cea519fa10a945f08
/swig/omnipod.i
b117016ac57255775358cd635f5bb9cea48d190d
[]
no_license
hackjealousy/omnipod
dea258cc585f61db7901b0ee0162d6058935e1be
687e05bda76658371e77a21b9b3f2d987c0c5b01
refs/heads/master
2020-04-22T12:58:46.484477
2019-02-12T21:17:44
2019-02-12T21:17:44
170,392,804
0
0
null
null
null
null
UTF-8
C++
false
false
103
i
/* -*- c++ -*- */ %include "gnuradio.i" %{ #include "omnipod_demod.h" %} %include "omnipod_demod.i"
[ "jl@thre.at" ]
jl@thre.at
be06850db14c959d2a8a8c36303404bbd9488fe6
d1250816ef08e75669aa5c786684e94aa4f334fa
/experimental/graphite/src/CommandBuffer.cpp
df984ba1fb916acbcfd4fbca85bb0057c470e984
[ "BSD-3-Clause" ]
permissive
boundaryfree/skia
c5958e83defef659bfef6659db6095982be0a812
54a5744ac9d9530c79d42431dee7edf7678432b8
refs/heads/main
2023-08-22T18:21:17.618446
2021-10-11T07:42:35
2021-10-11T07:42:35
392,546,972
0
0
BSD-3-Clause
2021-08-04T04:25:38
2021-08-04T04:25:38
null
UTF-8
C++
false
false
273
cpp
/* * Copyright 2021 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "experimental/graphite/src/CommandBuffer.h" namespace skgpu { CommandBuffer::CommandBuffer() {} } // namespace skgpu
[ "skcq-be@skia-corp.google.com.iam.gserviceaccount.com" ]
skcq-be@skia-corp.google.com.iam.gserviceaccount.com
1f35c2ca598a6cfd964eac877393de7df641ff41
bfe5cfbf99700c2e42dc5b1e55c2f3207fd96aed
/src/libmeasurement_kit/common/worker.cpp
f69643c955b160e7520053f1eb6286805bbebdd5
[ "Zlib", "MIT", "curl", "BSD-2-Clause", "BSD-3-Clause" ]
permissive
joelanders/measurement-kit
84f3158928ae2c5b0a2d4a7d9039cd489634ee0f
9e1a500cfee81cec24966bf5201ecbc0f9549eb6
refs/heads/master
2020-12-31T07:11:55.046527
2017-09-15T10:58:32
2017-09-15T10:58:32
80,559,960
0
0
null
2017-01-31T20:39:05
2017-01-31T20:39:05
null
UTF-8
C++
false
false
2,724
cpp
// Part of measurement-kit <https://measurement-kit.github.io/>. // Measurement-kit is free software under the BSD license. See AUTHORS // and LICENSE for more information on the copying conditions. #include <measurement_kit/common/callback.hpp> #include <measurement_kit/common/detail/worker.hpp> #include <measurement_kit/common/logger.hpp> #include <measurement_kit/common/non_copyable.hpp> #include <measurement_kit/common/non_movable.hpp> #include <measurement_kit/common/shared_ptr.hpp> #include <cassert> #include <chrono> #include <functional> #include <list> #include <memory> #include <mutex> #include <thread> #include <utility> namespace mk { void Worker::call_in_thread(Callback<> &&func) { std::unique_lock<std::mutex> _{state->mutex}; // Move function such that the running-in-background thread // has unique ownership and controls its lifecycle. state->queue.push_back(std::move(func)); if (state->active >= state->parallelism) { return; } // Note: pass only the internal state, so that the thread can possibly // continue to work even when the external object is gone. auto task = [S = state]() { for (;;) { Callback<> func = [&]() { std::unique_lock<std::mutex> _{S->mutex}; // Initialize inside the lock such that there is only // one critical section in which we could be if (S->queue.size() <= 0) { --S->active; return Callback<>{}; } auto front = S->queue.front(); S->queue.pop_front(); return front; }(); if (!func) { break; } try { func(); } catch (...) { mk::warn("worker thread: unhandled exception"); } } }; std::thread{task}.detach(); ++state->active; } unsigned short Worker::parallelism() const { std::unique_lock<std::mutex> _{state->mutex}; return state->parallelism; } void Worker::set_parallelism(unsigned short newval) const { std::unique_lock<std::mutex> _{state->mutex}; state->parallelism = newval; } unsigned short Worker::concurrency() const { std::unique_lock<std::mutex> _{state->mutex}; return state->active; } void Worker::wait_empty_() const { while (concurrency() > 0) { std::this_thread::sleep_for(std::chrono::seconds(1)); } std::this_thread::sleep_for(std::chrono::seconds(1)); } /*static*/ SharedPtr<Worker> Worker::default_tasks_queue() { static SharedPtr<Worker> worker = SharedPtr<Worker>::make(); return worker; } } // namespace mk
[ "bassosimone@gmail.com" ]
bassosimone@gmail.com
0bd2e0ec053faa73a719a44bec29794c5d15cfcf
d236b2844cb53f07a0bd327087bded09fbaa3eef
/OperationHelp.cpp
2ce9f83aeec416187d4df64fcea9a53a7bc20d54
[]
no_license
wyrover/Repacls
ae37d333f78407e9856b92c0eb7f1f3f9d8f22a9
c08256a593747fdafe2f50afa81da97a50104689
refs/heads/master
2021-01-22T20:21:32.744992
2017-05-09T00:16:10
2017-05-09T00:16:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,810
cpp
#include "OperationHelp.h" #include <iostream> ClassFactory<OperationHelp> * OperationHelp::RegisteredFactory = new ClassFactory<OperationHelp>(GetCommand()); ClassFactory<OperationHelp> * OperationHelp::RegisteredFactoryAltOne = new ClassFactory<OperationHelp>(GetCommandAltOne()); ClassFactory<OperationHelp> * OperationHelp::RegisteredFactoryAltTwo = new ClassFactory<OperationHelp>(GetCommandAltTwo()); OperationHelp::OperationHelp(std::queue<std::wstring> & oArgList) : Operation(oArgList) { std::wcout << LR"( repacls.exe /Path <Absolute Path> ... other options .... Repacls was developed to address large scale migrations, transitions, health checks, and access control optimizations. Repacls is multi-threaded and employs account name caching to accelerate operation on large file servers with millions of files. It was developed to address a variety of platform limitations, resource consumption concerns, and bugs within xcacls, icacls, setacl, and subinacl. Important: Unless otherwise specified, all repacls commands are recursive. Repacls must be executed with administrator permissions and will attempt to acquire the backup, restore, and take ownership privileges during its execution. Any command line parameter that accepts an account or domain name can also use a SID string instead of the name. This may be necessary if working with an account or domain that is no longer resolvable. Global Options ============== Global Options affect the entire command regardless of where they appear in the passed command line. It is recommended to include them at the very beginning or end of your command as to not confuse them with ordered parameters. /Path <Path> Specifies the file or directory to process. If a directory, the directory is processed recursively; all operations specified affect the directory and all files and folders under the directory (unless otherwise specified). This parameter is mandatory. This command can be specified multiple times. /SharePaths <ComputerName>[:AdminOnly|IncludeHidden|Match=<Str>|NoMatch=<Str>] Specifies a server that has one or more shares to process. This command is equivalent to specifying /Path for every share on a particular file server. By default, only non-administrative, non-hidden shares are scanned. To only scan administrative shares (e.g. C$), append :AdminOnly to the computer name. To include hidden, non-administrative shares, append :IncludeHidden to the computer name. By appending :Match= or :NoMatch= with a literal string or regular expression, any share name that does not match or mismatch the specified string, respectively, will be excluded. /DomainPaths <DomainName>[:StopOnError|<See /SharePaths>] Specifies a domain to scan for member servers that should be processed. For each server that is found, a /SharePaths command is processed for that particular server. This takes the same extra parameters as /SharePaths including another option StopOnError to stop processing if the shares of any particular computer can not be read; if not specified an error will be shown on the screen but processing will continue. /Quiet Hides all non-error output. This option will greatly enhance performance if a large number of changes are being processed. Alternatively, it is advisable to redirect console output to a file (using the > redirector) if /Quiet cannot be specified. /Threads <NumberOfThreads> Specifies the number of threads to use while processing. The default value of '5' is usually adequate, but can be increased if performing changes over a higher-latency connection. Since changes to a parent directory often affect the inherited security on children, the security of children objects are always processed after the security on their parent objects are fully processed. /WhatIf This option will analyze security and report on any potential changes without actually committing the data. Use of /WhatIf is recommended for those first using the tool. /NoHiddenSystem Use this option to avoid processing any file marked as both 'hidden' and 'system'. These are what Windows refers to 'operating system protected files' in Windows Explorer. Ordered Options =============== Ordered Options are executed on each SID encountered in the security descriptor in the order they are specified on the command line. Executing commands in this way is preferable to multiple commands because the security descriptor is only read and written once for the entire command which is especially helpful for large volumes. Commands That Do Not Alter Security ----------------------------------- /PrintDescriptor Prints out the security descriptor to the screen. This is somewhat useful for seeing the under-the-cover changes to the security descriptor before and after a particular command. /CheckCanonical This command inspects the DACL and SACL for canonical order compliance (i.e., the rules in the ACL are ordered as explicitly deny, explicitly allow, inherited deny, inherited allow). If non-canonical entries are detected, it is recommended to inspect the ACL with icacls.exe or Windows Explorer to ensure the ACL is not corrupted in a more significant way. /BackupSecurity <FileName> Export the security descriptor to the file specified. The file is outputted in the format of file|descriptor on each line. The security descriptor is formatted as specified in the documentation for ConvertDescriptorToStringSecurityDescriptor(). This command does not print informational messages other than errors. /FindAccount <Name|Sid> Reports any instance of an account specified. /FindDomain <Name|Sid> Reports any instance of an account matching the specified domain. /FindNullAcl Reports any instance of a null ACL. A null ACL, unlike an empty ACL, allows all access (i.e., similar to an ACE with 'Everyone' with 'Full Control') Commands That Can Alter Security (When /WhatIf Is Not Present) -------------------------------- /AddAccountIfMissing <Name|Sid> This command will ensure the account specified has full control access to path and all directories/files under the path either via explicit or inherited permissions. This command does not take into account any permissions that would be granted to the specified user via group membership. If the account does not have access, access is granted. This command is useful to correct issues where a user or administrator has mistakenly removed an administrative group from some directories. /Compact This command will look for mergeable entires in the security descriptor and merge them. For example, running icacls.exe <file> /grant Everyone:R followed by icacls.exe <file> /grant Everyone:(CI)(OI)(R) will produce two entries even those the second command supersedes the first one. Windows Explorer automatically merges these entries when display security information so you have to use other utilities to detect these inefficiencies. While these's nothing inherently wrong with these entires, it possible for them to result file system is performance degradation. /CopyDomain <SourceDomainName>:<TargetDomainName> This command is identical to /MoveDomain except that the original entry referring the SourceDomainName is retained instead of replaced. This command only applies to the SACL and the DACL. If this command is used multiple times, it is recommended to use /Compact to ensure there are not any redundant access control entries. /MoveDomain <SourceDomainName>:<TargetDomainName> This command will look to see whether any account in <SourceDomain> has an identically-named account in <TargetDomain>. If so, any entires are converted to use the new domain. For example, 'OldDomain\Domain Admins' would become 'NewDomain\Domain Admins'. Since this operation relies on the names being resolvable, specifying a SID instead of domain name for this command does not work. )"; std::wcout << LR"( /RemoveAccount <Name|Sid> Will remove <Name> from the security descriptor. If the specified name is found as the file owner, the owner is replaced by the builtin Administrators group. If the specified name is found as the group owner (a defunct attribute that has no function in terms of security), it is also replace with the built-in Administrators group. /RemoveOrphans <Domain|Sid> Remove any account whose SID is derived from the <Domain> specified and can no longer be resolved to a valid name /RemoveRedundant This command will remove any explicit permission that is redundant of of the permissions its already given through inheritance. This option helps recovered from the many individual explicit permissions that may have been littered from the old cacls.exe command that didn't understand how to set up inheritance. /ReplaceAccount <SearchAccount>:<ReplaceAccount> Search for an account and replace it with another account. /Report <FileName> <RegularExpression> This command will write a comma separated value file with the fields of filename, security descriptor part (e.g., DACL), account name, permissions, and inheritance flags. The regular expression will perform a case insensitive regular expression search against the account name in DOMAIN\user format. To report all data, pass .* as the regular expression. An optional qualifier after regular expression can be specified after the regular expression to refine what part of the security descriptor to scan. See Other Notes & Limitations section for more information. /RestoreSecurity <FileName> The reverse operation of /BackupSecurity. Takes the file name and security descriptors specified in the file specified and applies them to the file system. This command does not print informational messages other than errors. /SetOwner <Name|Sid> Will set the owner of the file to the name specified. /UpdateHistoricalSids Will update any SIDs that present in the security descriptor and are part of a SID history with the primary SID that is associated an account. This is especially useful after a domain migration and prior to removing excess SID history on accounts. Exclusive Options ================= Exclusive options cannot be combined with any other security operations. /Help or /? or /H Shows this information. /ResetChildren This will reset all children of path to the to inherit from the parent. It will not affect the security of the parent. This command does not affect the security the root directory as specified by the /Path argument. /InheritChildren This will cause any parent that is currently set to block inheritance to start allowing inheritance. Any explicit entries on the children are preserved. This command does not will not affect the security the root directory as specified by the /Path argument. Other Notes & Limitations ========================= - To only affect a particular part of a security descriptor, you can add on an optional ':X' parameter after the end of the account name where X is a comma separated list of DACL,SACL, OWNER, or GROUP. For example, '/RemoveAccount "DOM\joe:DACL,OWNER"' will only cause the designated account to be removed from the DACL and OWNER parts of the security descriptor. - Since repacls is multi-threaded, any file output shown on the screen or written to an output file may appear differently between executions. In this is problematic for your needs, you can turn off multi-threading by setting /Threads to '1' or, in the case of comparing files between runs, sort the output before comparing with your favorite text editor. - Antivirus applications can degrade performance tremendously if active while running repacls. If performance is a concern and you are processing a large volume, you may want to consider temporarily disabling realtime virus scanning. Antivirus status is noted when executing repacls. Examples ======== - Replace all instances of DOM\jack to DOM\jill in C:\test: repacls.exe /Path C:\Test /ReplaceAccount "DOM\jack:DOM\jill" - Migrate all permissions for all accounts with matching names in DOMA with DOMB: repacls.exe /Path C:\Test /MoveDomain DOMA:DOMB - Update old SID references, remove any explicit permissions that are already granted by inherited permissions, and compact all ACLs if not compacted: repacls.exe /Path C:\Test /UpdateHistoricalSids /RemoveRedundant /Compact Type 'repacls.exe /? | more' to scroll this documentation. )"; exit(0); }
[ "berns@uwalumni.com" ]
berns@uwalumni.com
297d09b5687fe574ab7143b65d730714ac600e8c
e8cec014c373a8599f9ac5d3768d87662528b28e
/meeting-qt/setup/UnInstall/src/setup/window/async_modal_runner.cpp
f368fa4da9494df89292b47c785b7e0ffb3159fb
[ "MIT" ]
permissive
xiaoge136/Meeting
ee69e309666b3132449476217033d34b92eb975d
0b85c53ee3df6d5611c84dc2b9fe564590874563
refs/heads/main
2023-07-21T14:39:03.158711
2021-08-31T14:13:18
2021-08-31T14:13:18
401,727,185
0
1
MIT
2021-08-31T14:10:04
2021-08-31T14:10:04
null
UTF-8
C++
false
false
3,072
cpp
/** * @copyright Copyright (c) 2021 NetEase, Inc. All rights reserved. * Use of this source code is governed by a MIT license that can be found in the LICENSE file. */ // Copyright (c) 2013, NetEase Inc. All rights reserved. // // Wang Rongtao <rtwang@corp.netease.com> // 2013/10/11 // // Aysnc modal dialog runner // #include "async_modal_runner.h" static const char kModalThreadName[] = "AsyncModalRunner"; AsyncModalRunner::AsyncModalRunner(Delegate *delegate) : event_(true, false), is_running_(false), quit_posted_(false), delegate_(delegate) { } AsyncModalRunner::~AsyncModalRunner() { CancelModalThenExit(); } void AsyncModalRunner::CancelModalThenExit() { if (!is_running_ || quit_posted_) return; quit_posted_ = true; PostThreadMessage(thread_id(), WM_QUIT, 0, 0); } bool AsyncModalRunner::DoModal(ModalWndBase *dlg) { DCHECK(!is_running_); modal_dlg_.reset(dlg); if (!Create()) return false; is_running_ = event_.Wait(); return is_running_; } void AsyncModalRunner::Run() { #ifndef NDEBUG #if defined(OS_WIN) && defined(COMPILER_MSVC) nbase::SetThreadName(GetCurrentThreadId(), kModalThreadName); #endif #endif event_.Signal(); if (modal_dlg_ != nullptr) { modal_dlg_->SyncShowModal(); } if (delegate_ != nullptr) { delegate_->OnThreadWillExit(this); } } AsyncModalRunnerManager* AsyncModalRunnerManager::GetInstance() { return nbase::Singleton<AsyncModalRunnerManager>::get(); } AsyncModalRunnerManager::AsyncModalRunnerManager() { } AsyncModalRunnerManager::~AsyncModalRunnerManager() { CancelAllThreads(); } bool AsyncModalRunnerManager::DoModal(ModalWndBase *dlg) { if (dlg == nullptr) return false; std::shared_ptr<AsyncModalRunner> runner = std::make_shared<AsyncModalRunner>(this); { nbase::NAutoLock lock(&threads_lock_); runners_.push_back(runner); } if (runner->DoModal(std::move(dlg))) return true; return false; } void AsyncModalRunnerManager::CancelAllThreads() { std::list<std::shared_ptr<AsyncModalRunner> > threads; { nbase::NAutoLock lock(&threads_lock_); threads.swap(runners_); } // First, we notify the modal dialogs to quit the modal loop std::for_each(threads.begin(), threads.end(), [](std::shared_ptr<AsyncModalRunner> runner) { runner->CancelModalThenExit(); } ); // Then, we wait util all modal runner exited std::for_each(threads.begin(), threads.end(), [](std::shared_ptr<AsyncModalRunner> runner) { runner->Close(); } ); } void AsyncModalRunnerManager::OnThreadWillExit(AsyncModalRunner *runner) { nbase::ThreadManager::PostTask( threading::kThreadUI,std::bind(&AsyncModalRunnerManager::Deregister,this,runner)); } void AsyncModalRunnerManager::Deregister(AsyncModalRunner *runner) { std::shared_ptr<AsyncModalRunner> found; { nbase::NAutoLock lock(&threads_lock_); for (auto iter = runners_.begin(); iter != runners_.end(); iter++) { if ((*iter).get() == runner) { found = *iter; runners_.erase(iter); break; } } } // If the runner is found, // it will be destroyed out of the scope of the lock }
[ "wangjianzhong@corp.netease.com" ]
wangjianzhong@corp.netease.com
d44b1aeac2d2e71654eff8142f97106840641a05
0b070626740788d5af23fcd1cd095e56033308de
/1085.cpp
3c60e05fe5d10e898a82ec03b3e780854d7ea6fb
[]
no_license
xis19/leetcode
71cb76c5764f8082155d31abcb024b25fd90bc75
fb35fd050d69d5d8abf6794ae4bed174aaafb001
refs/heads/master
2021-03-24T12:53:34.379480
2020-02-24T04:25:36
2020-02-24T04:25:36
76,006,015
0
0
null
null
null
null
UTF-8
C++
false
false
253
cpp
#include <algorithm> #include <vector> int sumOfDigits(const std::vector<int>& A) { int min = *std::min_element(A.begin(), A.end()); int sum = 0; while(min > 0) { sum += min % 10; min /= 10; } return sum % 2 == 0; }
[ "magichp@gmail.com" ]
magichp@gmail.com
900ed065da72ccd9234079f481c907946a93d5ba
e7148b971a0d3a722356d20b5b6c5fbfb0678b72
/nvr/src/device_discovery.cpp
4edddb73bafda9f480d38948dfe4b2d59f1a547f
[ "MIT" ]
permissive
houbin/recipes
ec4b7f47b01c8b0502873584b9ddedad56f94bcb
2ca4008ae2409bfbc79fd6b664d492a616e745a8
refs/heads/master
2021-01-10T10:08:35.022404
2019-06-05T02:42:04
2019-06-05T02:42:04
44,296,558
0
0
null
null
null
null
UTF-8
C++
false
false
2,933
cpp
#include "common.h" #include "device_discovery.h" #include "inc/JVNSDKDef.h" #include "inc/JvClient.h" #include "src/yst_usedef.h" #include <time.h> DeviceDiscovery::DeviceDiscovery(QWidget *parent, bool use_yst, bool use_onvif) : QWidget(parent), use_yst_(use_yst), use_onvif_(use_onvif) { if (use_yst_) { yst_discovery_ = new YstDiscovery(this); } } DeviceDiscovery::~DeviceDiscovery() { if (yst_discovery_ && yst_discovery_->IsSearching()) { yst_discovery_->StopSearch(); delete yst_discovery_; } } void DeviceDiscovery::Init() { if(yst_discovery_) { yst_discovery_->Init(); } } void DeviceDiscovery::StartSearch() { if (yst_discovery_) { yst_discovery_->StartSearch(); } return; } void DeviceDiscovery::StopSearch() { if(yst_discovery_ && yst_discovery_->IsSearching()) { yst_discovery_->StopSearch(); } return; } /* yst discovery * */ YstDiscovery::YstDiscovery(DeviceDiscovery *parent) : parent_(parent), bc_id_(-1), if_searching_(false) { } YstDiscovery::~YstDiscovery() { } void YstDiscovery::Init() { int local_port; #if defined(Q_OS_WIN32) bool r; #elif defined(Q_OS_LINUX) int r; #endif for (local_port = 9400; local_port < 9500; local_port++) { r = JVC_StartLANSerchServer(local_port, 6666, YST_ClientLanSearchCallBack); if (r == true) { logger->debug("start lan search, local port is %1, ret is %2", local_port, r); break; } logger->debug("lan: local port %1 was used, and try %2", local_port, local_port + 1); } if (r == 0) { logger->warn("search lan error"); } for (local_port = 9500; local_port < 9600; local_port++) { #if defined(Q_OS_WIN32) bool r; #elif defined(Q_OS_LINUX) int r; #endif r = JVC_StartBroadcastServer(local_port, 9106, YST_ClientBcCallBack); if (r == true) { logger->debug("start bc search, local port is %1, ret is %2", local_port, r); break; } logger->debug("bc: local port %1 was used, and try %2", local_port, local_port + 1); } if (r == 0) { logger->warn("search bc error"); } return; } bool YstDiscovery::IsSearching() { return if_searching_; } void YstDiscovery::StartSearch() { // search lan srand(time(NULL)); this->bc_id_ = rand() + rand() + 1; BCPACKET packet = {0}; packet.nCmd = BC_SEARCH; JVC_BroadcastOnce(this->bc_id_, (unsigned char *)(&packet), sizeof(BCPACKET), 1000); // search vlan //JVC_LANSerchDevice("", 0, 0xE71A, 3, "", 6000, 3600); // TODO: search by onvif if_searching_ = true; return; } void YstDiscovery::StopSearch() { if (if_searching_) { JVC_StopLANSerchServer(); JVC_StopBroadcastServer(); } return; }
[ "houbin0504@163.com" ]
houbin0504@163.com
ba51c4fa63f6cfa4f0fe11f0530afb9c488cc778
6d3f21c737a4c84c2ae9229696141d2a4370b925
/src/common.cpp
b57b2213462ce552eae622a9ceb5fad87cf81776
[ "MIT" ]
permissive
lrxjason/Face-Landmark-Detection
2211f40180a4b54519a2b2b9c1fca74811ece9fa
27f6d7c489cc2897f28a86f874671658b53e881c
refs/heads/master
2021-09-07T02:48:10.988357
2018-02-16T04:23:07
2018-02-16T04:23:07
121,572,458
0
0
null
null
null
null
UTF-8
C++
false
false
7,240
cpp
#include <cmath> #include <ctime> #include <cstdio> #include <cassert> #include <cstdarg> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "common.hpp" using namespace cv; using namespace std; namespace lbf { BBox::BBox() {} BBox::~BBox() {} //BBox::BBox(const BBox &other) { // BBox(other.x, other.y, other.width, other.height); //} //BBox &BBox::operator=(const BBox &other) { // if (this == &other) return *this; // BBox(other.x, other.y, other.width, other.height); // return *this; //} BBox::BBox(double x, double y, double w, double h) { this->x = x; this->y = y; this->width = w; this->height = h; this->x_center = x + w / 2.; this->y_center = y + h / 2.; this->x_scale = w / 2.; this->y_scale = h / 2.; } // Project absolute shape to relative shape binding to this bbox Mat BBox::Project(const Mat &shape) const { Mat_<double> res(shape.rows, shape.cols); const Mat_<double> &shape_ = (Mat_<double>)shape; for (int i = 0; i < shape.rows; i++) { res(i, 0) = (shape_(i, 0) - x_center) / x_scale; res(i, 1) = (shape_(i, 1) - y_center) / y_scale; } return res; } // Project relative shape to absolute shape binding to this bbox Mat BBox::ReProject(const Mat &shape) const { Mat_<double> res(shape.rows, shape.cols); const Mat_<double> &shape_ = (Mat_<double>)shape; for (int i = 0; i < shape.rows; i++) { res(i, 0) = shape_(i, 0)*x_scale + x_center; res(i, 1) = shape_(i, 1)*y_scale + y_center; } return res; } // Similarity Transform, project shape2 to shape1 // p1 ~= scale * rotate * p2, p1 and p2 are vector in math void calcSimilarityTransform(const Mat &shape1, const Mat &shape2, double &scale, Mat &rotate) { Mat_<double> rotate_(2, 2); double x1_center, y1_center, x2_center, y2_center; x1_center = cv::mean(shape1.col(0))[0]; y1_center = cv::mean(shape1.col(1))[0]; x2_center = cv::mean(shape2.col(0))[0]; y2_center = cv::mean(shape2.col(1))[0]; Mat temp1(shape1.rows, shape1.cols, CV_64FC1); Mat temp2(shape2.rows, shape2.cols, CV_64FC1); temp1.col(0) = shape1.col(0) - x1_center; temp1.col(1) = shape1.col(1) - y1_center; temp2.col(0) = shape2.col(0) - x2_center; temp2.col(1) = shape2.col(1) - y2_center; Mat_<double> covar1, covar2; Mat_<double> mean1, mean2; calcCovarMatrix(temp1, covar1, mean1, CV_COVAR_COLS); calcCovarMatrix(temp2, covar2, mean2, CV_COVAR_COLS); double s1 = sqrt(cv::norm(covar1)); double s2 = sqrt(cv::norm(covar2)); scale = s1 / s2; temp1 /= s1; temp2 /= s2; double num = temp1.col(1).dot(temp2.col(0)) - temp1.col(0).dot(temp2.col(1)); double den = temp1.col(0).dot(temp2.col(0)) + temp1.col(1).dot(temp2.col(1)); double normed = sqrt(num*num + den*den); double sin_theta = num / normed; double cos_theta = den / normed; rotate_(0, 0) = cos_theta; rotate_(0, 1) = -sin_theta; rotate_(1, 0) = sin_theta; rotate_(1, 1) = cos_theta; rotate = rotate_; } double calcVariance(const Mat &vec) { double m1 = cv::mean(vec)[0]; double m2 = cv::mean(vec.mul(vec))[0]; double variance = m2 - m1*m1; return variance; } double calcVariance(const vector<double> &vec) { if (vec.size() == 0) return 0.; Mat_<double> vec_(vec); double m1 = cv::mean(vec_)[0]; double m2 = cv::mean(vec_.mul(vec_))[0]; double variance = m2 - m1*m1; return variance; } double calcMeanError(vector<Mat> &gt_shapes, vector<Mat> &current_shapes) { int N = gt_shapes.size(); Config &config = Config::GetInstance(); int landmark_n = config.landmark_n; vector<int> &left = config.pupils[0]; vector<int> &right = config.pupils[1]; double e = 0; // every train data for (int i = 0; i < N; i++) { const Mat_<double> &gt_shape = (Mat_<double>)gt_shapes[i]; const Mat_<double> &current_shape = (Mat_<double>)current_shapes[i]; double x1, y1, x2, y2; x1 = x2 = y1 = y2 = 0; for (int j = 0; j < left.size(); j++) { x1 += gt_shape(left[j], 0); y1 += gt_shape(left[j], 1); } for (int j = 0; j < right.size(); j++) { x2 += gt_shape(right[j], 0); y2 += gt_shape(right[j], 1); } x1 /= left.size(); y1 /= left.size(); x2 /= right.size(); y2 /= right.size(); double pupils_distance = sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)); // every landmark double e_ = 0; for (int i = 0; i < landmark_n; i++) { e_ += norm(gt_shape.row(i) - current_shape.row(i)); } e += e_ / pupils_distance; } e /= N*landmark_n; return e; } // Get mean_shape over all dataset Mat getMeanShape(vector<Mat> &gt_shapes, vector<BBox> &bboxes) { int N = gt_shapes.size(); Mat mean_shape = Mat::zeros(gt_shapes[0].rows, 2, CV_64FC1); for (int i = 0; i < N; i++) { mean_shape += bboxes[i].Project(gt_shapes[i]); } mean_shape /= N; return mean_shape; } // Get relative delta_shapes for predicting target vector<Mat> getDeltaShapes(vector<Mat> &gt_shapes, vector<Mat> &current_shapes, \ vector<BBox> &bboxes, Mat &mean_shape) { vector<Mat> delta_shapes; int N = gt_shapes.size(); delta_shapes.resize(N); double scale; Mat_<double> rotate; for (int i = 0; i < N; i++) { delta_shapes[i] = bboxes[i].Project(gt_shapes[i]) - bboxes[i].Project(current_shapes[i]); calcSimilarityTransform(mean_shape, bboxes[i].Project(current_shapes[i]), scale, rotate); delta_shapes[i] = scale * delta_shapes[i] * rotate.t(); } return delta_shapes; } // Draw landmarks with bbox on image Mat drawShapeInImage(const Mat &img, const Mat &shape, const BBox &bbox) { Mat img_ = img.clone(); //rectangle(img_, Rect(bbox.x, bbox.y, bbox.width, bbox.height), Scalar(0, 0, 255), 2); for (int i = 0; i < shape.rows; i++) { circle(img_, Point(shape.at<double>(i, 0), shape.at<double>(i, 1)), 2, Scalar(0, 255, 0), -1); } return img_; } // Logging with timestamp, message sholdn't be too long void LOG(const char *fmt, ...) { va_list args; va_start(args, fmt); char msg[256]; vsprintf(msg, fmt, args); va_end(args); char buff[256]; time_t t = time(NULL); strftime(buff, sizeof(buff), "[%x - %X]", localtime(&t)); printf("%s %s\n", buff, msg); } Config::Config() { dataset = "/mnt/nfs/wenge/data/CelebA/Anno/trainset"; saved_file_name = "../model/celbea.model"; stages_n = 6; tree_n = 12; tree_depth = 5; landmark_n = 5; initShape_n = 10; bagging_overlap = 0.4; int pupils[][1] = { { 0 }, { 1 } }; int feats_m[] = { 500, 500, 500, 300, 300, 300, 200, 200, 200, 100 }; double radius_m[] = { 0.3, 0.2, 0.15, 0.12, 0.10, 0.10, 0.08, 0.06, 0.06, 0.05 }; for (int i = 0; i < 1; i++) { this->pupils[0].push_back(pupils[0][i]); this->pupils[1].push_back(pupils[1][i]); } for (int i = 0; i < 10; i++) { this->feats_m.push_back(feats_m[i]); this->radius_m.push_back(radius_m[i]); } } } // namespace lbf
[ "noreply@github.com" ]
noreply@github.com
9a1ee510ed54c2a3f2d8750f125775884f41ce26
eb61436e6225d46e30c2b6c1d718f28cb81f202e
/SimpleAnalysis/SimpleAnalysis.cc
fc3553b7fb6ee878a6b6c589915eb4fcf48e081b
[]
no_license
miguelignacio/delphes_EIC
3f1796bf769e2d8d086cd4223ae59e06df1e9dc9
5eac861b88ac7a9181075ebd861ef296be57b16b
refs/heads/master
2021-05-17T22:11:03.788507
2021-04-15T22:37:01
2021-04-15T22:37:01
250,973,430
4
2
null
2021-04-11T22:23:25
2020-03-29T07:02:24
Jupyter Notebook
UTF-8
C++
false
false
6,337
cc
#include <TROOT.h> #include <TFile.h> #include <TChain.h> #include <TTree.h> #include <TString.h> #include <TObjString.h> #include "TInterpreter.h" #include <unistd.h> #include <stdlib.h> #include <iostream> #include <stdio.h> #include <getopt.h> #include <glob.h> #include <vector> #include <map> #include <any> #include "classes/DelphesClasses.h" #include "external/ExRootAnalysis/ExRootTreeReader.h" #include "ModuleHandler.h" #include "TreeHandler.h" static std::string input_dir = ""; static std::string output_file = ""; static std::string module_sequence = ""; static int nevents = -1; ModuleHandler *ModuleHandler::instance = 0; TreeHandler *TreeHandler::instance = 0; // HELPER METHODS void PrintHelp() { std::cout << "--input_dir <i>: Directory containing all the ROOT files you want to process\n" "--output_file <o>: Output ROOT file to store results\n" "--module_sequence <s>: A string comma-separated list of modules to load; order is preserved in execution.\n" "--nevents <n>: The total number of events to process, starting from the zeroth event in the input.\n" "--help: Show this helpful message!\n"; exit(1); } std::vector<std::string> fileVector(const std::string& pattern){ glob_t glob_result; glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result); std::vector<std::string> files; for(unsigned int i=0;i<glob_result.gl_pathc;++i){ files.push_back(std::string(glob_result.gl_pathv[i])); } globfree(&glob_result); return files; } // MAIN FUNCTION int main(int argc, char *argv[]) { std::cout << "===================== SIMPLEANALYSIS =====================" << std::endl; // Handle complex TTree data storage types by defining them for ROOT gInterpreter->GenerateDictionary("std::vector<std::vector<float>>","vector"); if (argc <= 1) { PrintHelp(); } const char* const short_opts = "i:o:h"; const option long_opts[] = { {"input_dir", required_argument, nullptr, 'i'}, {"output_file", required_argument, nullptr, 'o'}, {"module_sequence", required_argument, nullptr, 's'}, {"nevents", optional_argument, nullptr, 'n'}, {"help", no_argument, nullptr, 'h'}, {nullptr, no_argument, nullptr, 0} }; while (true) { const auto opt = getopt_long(argc, argv, short_opts, long_opts, nullptr); if (-1 == opt) break; switch (opt) { case 'i': input_dir = optarg; std::cout << "Input Directory: " << input_dir << std::endl; break; case 'o': output_file = optarg; std::cout << "Output File: " << output_file << std::endl; break; case 's': module_sequence = optarg; std::cout << "Module sequence: " << module_sequence << std::endl; break; case 'n': nevents = std::stoi(optarg); std::cout << "Number of events to process: " << nevents << std::endl; break; case 'h': // -h or --help case '?': // Unrecognized option PrintHelp(); break; default: PrintHelp(); break; } } auto data = new TChain("Delphes"); auto files = fileVector(input_dir); for (auto file : files) { data->Add(file.c_str()); } ExRootTreeReader *treeReader = new ExRootTreeReader(data); int n_entries = data->GetEntries(); std::cout << "The provided data set contains the following number of events: " << std::endl << n_entries << std::endl; // Load object pointers TClonesArray *branchJet = treeReader->UseBranch("Jet"); TClonesArray *branchElectron = treeReader->UseBranch("Electron"); TClonesArray *branchPhoton = treeReader->UseBranch("EFlowPhoton"); TClonesArray *branchNeutralHadron = treeReader->UseBranch("EFlowNeutralHadron"); TClonesArray *branchGenJet = treeReader->UseBranch("GenJet"); TClonesArray *branchGenParticle = treeReader->UseBranch("Particle"); TClonesArray *branchRawTrack = treeReader->UseBranch("Track"); TClonesArray *branchEFlowTrack = treeReader->UseBranch("EFlowTrack"); TClonesArray *branchMET = treeReader->UseBranch("MissingET"); // Setup the module handler ModuleHandler *module_handler = module_handler->getInstance(treeReader); auto module_list = TString(module_sequence).Tokenize(","); // Setup the output storage TreeHandler *tree_handler = tree_handler->getInstance(output_file.c_str(), "tree"); tree_handler->initialize(); for (int i = 0; i < module_list->GetEntries(); i++) { auto name = static_cast<TObjString*>(module_list->At(i))->GetString().Data(); std::cout << " Appending module " << name << std::endl; module_handler->addModule(name); } for (auto module : module_handler->getModules()) { module->initialize(); } if (nevents < 0) { std::cout << "Processing all events in the sample..." << std::endl; } else { std::cout << "Processing "<< nevents << " events in the sample..." << std::endl; } for(int i=0; i < n_entries; ++i) { // event number printout if(i%1000==0) { std::cout << "Processing Event " << i << std::endl; } if (nevents >= 0 && i >= nevents) break; // read the data for i-th event // data->GetEntry(i); // Load selected branches with data from specified event treeReader->ReadEntry(i); std::map<std::string, std::any> DataStore; for (auto module : module_handler->getModules()) { module->setJets(branchJet); module->setGenJets(branchGenJet); module->setEFlowTracks(branchEFlowTrack); module->setTracks(branchRawTrack); module->setGenParticles(branchGenParticle); module->setPhotons(branchPhoton); module->setElectrons(branchElectron); module->setNeutralHadrons(branchNeutralHadron); module->setMET(branchMET); bool result = module->execute(&DataStore); if (result == false) break; } tree_handler->execute(); // if (DataStore.find("CharmJets") != DataStore.end()) { // std::vector<Jet*> charm_jets = std::any_cast<std::vector<Jet*>>(DataStore["CharmJets"]); // } } for (auto module : module_handler->getModules()) { module->finalize(); } tree_handler->finalize(); std::cout << "========================== FINIS =========================" << std::endl; exit(EXIT_SUCCESS); }
[ "sekula@CERN.CH" ]
sekula@CERN.CH
ce01694d6e6c8b7c2fa4e9fdc871b5fd30e2d4c9
53fa1201e74c83799b2dc94260d70bb1b0eb67e2
/283. Move Zeroes.cpp
d96759aede61733446eeb949f1aab60736ebe3b3
[]
no_license
duanmao/leetcode
82bc193bc229a4813106ccd9679c6b9bff197edb
2c563c007dbad87a3d0d939130470e7eecad64e9
refs/heads/master
2020-05-29T17:59:05.528518
2020-04-20T18:07:41
2020-04-20T18:07:41
189,290,892
0
0
null
null
null
null
UTF-8
C++
false
false
732
cpp
class Solution { public: void moveZeroes(vector<int>& nums) { int nonzero = 0; for (int i = 0; i < nums.size(); ++i) { if (nums[i] != 0) { // Indispensable!!! if (nonzero != i) { nums[nonzero] = nums[i]; nums[i] = 0; } ++nonzero; } } } }; class Solution { public: void moveZeroes(vector<int>& nums) { int count = 0; for (int i = 0; i < nums.size(); ++i) { if (nums[i] == 0) { ++count; } else if (count) { nums[i - count] = nums[i]; nums[i] = 0; } } } };
[ "zhengjunlin515@gmail.com" ]
zhengjunlin515@gmail.com
62dd3b8bcfd8213cb7bca3e12b0063281003ae7f
cb015b0e378c17ec90c76289a53e246e69ef0566
/util/ping.cpp
101dfbfb0c3884fb8a2e093404b281693f1e6fbe
[]
no_license
hakwolf/oneproxy-monitor
a1d9e08573f09d2ce135745790f9874378a2f1cf
474f43eb154c9e587ed3dd65a6b94003059474de
refs/heads/master
2020-09-14T13:01:09.948006
2017-10-18T14:15:21
2017-10-18T14:15:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,200
cpp
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * * @FileName: ping.cpp * @Description: TODO * All rights Reserved, Designed By huih * @Company: onexsoft * @Author: hui * @Version: V1.0 * @Date: 2016年9月8日 * */ #include "ping.h" #include "systemapi.h" #include "memmanager.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> Ping::Ping() { // TODO Auto-generated constructor stub } Ping::~Ping() { // TODO Auto-generated destructor stub } int Ping::decode_response(char *buf, int bytes, struct sockaddr_in *from) { IpHeader *iphdr; IcmpHeader *icmphdr; unsigned short iphdrlen; iphdr = (IpHeader *)buf; //获取IP报文首地址 iphdrlen = (iphdr->ip_hl) * 4 ; //因为h_len是32位word,要转换成bytes必须*4 if (bytes < iphdrlen + ICMP_MIN) { //回复报文长度小于IP首部长度与ICMP报文最小长度之和,此时ICMP报文长不含 icmp_data logs(Logger::DEBUG, "Too few bytes from %s\n", inet_ntoa(from->sin_addr)); } icmphdr = (IcmpHeader*)(buf + iphdrlen); //越过ip报头,指向ICMP报头 //确保所接收的是我所发的ICMP的回应 if (icmphdr->icmp_type != ICMP_ECHOREPLY) { //回复报文类型不是请求回显 logs(Logger::DEBUG, "non-echo type %d recvd\n",icmphdr->icmp_type); return -1; } if (icmphdr->icmp_id != (u_uint16)SystemApi::get_pid()) { //回复报文进程号是否匹配 logs(Logger::DEBUG,"someone else's packet!\n"); return -1; } return 0;//ping success. } //计算ICMP首部校验和 u_uint16 Ping::checksum(u_uint16 *buffer, int size) { unsigned long cksum=0; //把ICMP报头二进制数据以2字节(16bit)为单位累加起来 while(size >1) { cksum+=*buffer++; size -= 2; } //若ICMP报头为奇数个字节,会剩下最后一字节。把最后一个字节视为一个2字节数据的高字节,这个2字节数据的低字节为0,继续累加 if(size) { cksum += *(u_uint8*)buffer; } cksum = (cksum >> 16) + (cksum & 0xffff); //高16bit和低16bit相加 cksum += (cksum >>16); //可能有进位情况,高16bit和低16bit再加1次 return (u_uint16)(~cksum); //将该16bit的值取反,存入校验和字段 } // //设置ICMP报头 // void Ping::fill_icmpData(char * icmp_data, int datasize){ IcmpHeader *icmp_hdr; char *datapart; icmp_hdr = (IcmpHeader*)icmp_data; icmp_hdr->icmp_type = ICMP_ECHO; // ICMP报文类型为请求回显 icmp_hdr->icmp_code = 0; icmp_hdr->icmp_id = (u_uint16)SystemApi::get_pid(); //获取当前的进程id icmp_hdr->icmp_cksum = 0; icmp_hdr->icmp_seq = 0; datapart = icmp_data + sizeof(IcmpHeader); //跳过IcmpHeader // // Place some junk in the buffer. // memset(datapart,'E', datasize - sizeof(IcmpHeader)); //填充datapart中的所有字节为"E",长度为ICMP报文数据段长度 } int Ping::ping(const char* pingAddress, int tryTimes, int packetSize) { SystemSocket sockRaw = 0; struct sockaddr_in dest,from; struct hostent * hp; int bread, datasize; int fromlen = sizeof(from); char *icmp_data; char *recvbuf; unsigned int addr=0; u_uint16 seq_no = 0; int ret = 0; do { sockRaw = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); ////创建套接字 if ((int)sockRaw <= 0) { logs(Logger::ERR, "create socket error(%s)", SystemApi::system_strerror()); sockRaw = 0; ret = -1; break; } //set receve timeout if(SystemApi::system_setSocketRcvTimeo(sockRaw, 1, 0)) { logs(Logger::ERR,"failed to set recv timeout: %s\n", SystemApi::system_strerror()); ret = -1; break; } //set send timeout if(SystemApi::system_setSocketSndTimeo(sockRaw, 1, 0)) { logs(Logger::ERR,"failed to set send timeout: %s\n", SystemApi::system_strerror()); ret = -1; break; } memset(&dest,0,sizeof(dest)); //用0来填充一块大小为sizeof(dest)的内存区域 hp = gethostbyname(pingAddress); if (!hp){ addr = inet_addr(pingAddress); //inet_addr将IP地址从点数字符格式转换成网络字节格式整型。网络字节 7f 00 00 01 /主机字节 01 00 00 7f } if ((!hp) && (addr == INADDR_NONE) ) { logs(Logger::ERR, "Unable to resolve %s\n", SystemApi::system_strerror()); ret = -1; break; } if (hp != NULL) memcpy(&(dest.sin_addr),hp->h_addr,hp->h_length); else dest.sin_addr.s_addr = addr; if (hp) dest.sin_family = hp->h_addrtype; else dest.sin_family = AF_INET; //AF_INET表示在Internet中通信 datasize = packetSize; // //创建ICMP报文 // datasize += sizeof(IcmpHeader);//发送数据包大小 + Icmp头大小 icmp_data = (char*)MemManager::malloc(MAX_PACKET); //分配发包内存 recvbuf = (char*)MemManager::malloc(MAX_PACKET); //分配收包内存 if (!icmp_data) { logs(Logger::ERR, "HeapAlloc failed %s\n", SystemApi::system_strerror()); //创建失败,打印提示信息 ret = -1; break; } memset(icmp_data,0,MAX_PACKET); //把一个char a[20]清零, 就是 memset(a, 0, 20) fill_icmpData(icmp_data, datasize); ////初始化ICMP首部 //send packet int i = 0; for(i = 0; i < tryTimes; i++){ int bwrote; //初始化ICMP首部 ((IcmpHeader*)icmp_data)->icmp_cksum = 0; //校验和置零 ((IcmpHeader*)icmp_data)->icmp_data = SystemApi::system_millisecond(); ((IcmpHeader*)icmp_data)->icmp_seq = seq_no++; //序列号++ ((IcmpHeader*)icmp_data)->icmp_cksum = checksum((u_uint16*)icmp_data,datasize); //计算校验和 do { bwrote = sendto(sockRaw, icmp_data, datasize, 0, (struct sockaddr*)&dest, sizeof(dest)); //发送数据 if (bwrote != datasize){ //发送失败 logs(Logger::ERR, "sendto failed: %s\n", SystemApi::system_strerror()); ret = -1; break; } bread = recvfrom(sockRaw, recvbuf, MAX_PACKET, 0, (struct sockaddr*)&from, (socklen_t*)&fromlen); if (bread < 0){ // logs(Logger::ERR, "recvfrom failed: %s\n", SystemApi::system_strerror()); ret = -1; break; } if(decode_response(recvbuf,bread, &from)) { logs(Logger::DEBUG, "decode response error"); ret = -1; break; } } while(0); if (ret < 0) ret = 0; else break; } if (i >= tryTimes) { ret = -1; } MemManager::free(icmp_data); MemManager::free(recvbuf); }while(0); if (sockRaw > 0) { SystemApi::close(sockRaw); } return ret; }
[ "1173811163@qq.com" ]
1173811163@qq.com
daeac89df87b9e8a2773926b89ff24f2232f576c
f57a583d41ddf3bf4e8a96e32f38de9d83ff6ae8
/gtk+3/entry.cpp
f45e61b9a0f5b942d38ab7143230941ce11d7b7c
[]
no_license
sansajn/test
5bc34a7e8ef21ba600f22ea258f6c75e42ce4c4e
c1bed95984123d90ced1376a6de93e3bb37fac76
refs/heads/master
2023-09-01T00:04:48.222555
2023-08-22T15:14:34
2023-08-22T15:14:34
224,257,205
2
3
null
null
null
null
UTF-8
C++
false
false
690
cpp
#include <gtk/gtk.h> void activate(GtkApplication * app, gpointer user_data) { GtkWidget * win = gtk_application_window_new(app); gtk_window_set_title(GTK_WINDOW(win), "entry-sample"); GtkWidget * hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5); gtk_container_add(GTK_CONTAINER(win), hbox); GtkWidget * entry = gtk_entry_new(); gtk_container_add(GTK_CONTAINER(hbox), entry); gtk_widget_show_all(win); } int main(int argc, char * argv[]) { GtkApplication * app = gtk_application_new("enty.sample", G_APPLICATION_FLAGS_NONE); g_signal_connect(app, "activate", G_CALLBACK(activate), NULL); g_application_run(G_APPLICATION(app), argc, argv); g_object_unref(app); return 0; }
[ "adam.hlavatovic@protonmail.ch" ]
adam.hlavatovic@protonmail.ch
bfd1b41108eb4413253fe2bb89aca8af1d0af787
a621cc1dcbdbafab73905753c9c54fb69aa46c9b
/cpu/Addressing.cpp
35687e94c3304531804a8ddb2df80cca9e0eee41
[]
no_license
FrancescoRigoni/SNES-Emulator
57f838cee3f229a19125e39bdc8abea1f2208a41
c306aa130c2f7e69465db3ba6a9e4b36584962d8
refs/heads/master
2021-01-19T17:22:58.920614
2017-06-05T17:03:39
2017-06-05T17:06:06
88,323,233
0
0
null
null
null
null
UTF-8
C++
false
false
10,162
cpp
#include "Cpu65816.hpp" #define LOG_TAG "Addressing" bool Cpu65816::opCodeAddressingCrossesPageBoundary(OpCode &opCode) { switch(opCode.getAddressingMode()) { case AddressingMode::AbsoluteIndexedWithX: { Address initialAddress(mDB, mMemoryMapper.readTwoBytes(mProgramAddress.newWithOffset(1))); // TODO: figure out when to wrap around and when not to, it should not matter in this case // but it matters when fetching data Address finalAddress = Address::sumOffsetToAddress(initialAddress, indexWithXRegister()); return Address::offsetsAreOnDifferentPages(initialAddress.getOffset(), finalAddress.getOffset()); } case AddressingMode::AbsoluteIndexedWithY: { Address initialAddress(mDB, mMemoryMapper.readTwoBytes(mProgramAddress.newWithOffset(1))); // TODO: figure out when to wrap around and when not to, it should not matter in this case // but it matters when fetching data Address finalAddress = Address::sumOffsetToAddress(initialAddress, indexWithYRegister()); return Address::offsetsAreOnDifferentPages(initialAddress.getOffset(), finalAddress.getOffset()); } case AddressingMode::DirectPageIndirectIndexedWithY: { uint16_t firstStageOffset = mD + mMemoryMapper.readByte(mProgramAddress.newWithOffset(1)); Address firstStageAddress(0x00, firstStageOffset); uint16_t secondStageOffset = mMemoryMapper.readTwoBytes(firstStageAddress); Address thirdStageAddress(mDB, secondStageOffset); // TODO: figure out when to wrap around and when not to, it should not matter in this case // but it matters when fetching data Address finalAddress = Address::sumOffsetToAddress(thirdStageAddress, indexWithYRegister()); return Address::offsetsAreOnDifferentPages(thirdStageAddress.getOffset(), finalAddress.getOffset()); } default: { Log::err(LOG_TAG).str("!!! Unsupported opCodeAddressingCrossesPageBoundary for opCode: ").hex(opCode.getCode(), 2).show(); } } return false; } Address Cpu65816::getAddressOfOpCodeData(OpCode &opCode) { uint8_t dataAddressBank; uint16_t dataAddressOffset; switch(opCode.getAddressingMode()) { case AddressingMode::Interrupt: case AddressingMode::Accumulator: case AddressingMode::Implied: case AddressingMode::StackImplied: // Not really used, doesn't make any sense since these opcodes do not have operands return mProgramAddress; case AddressingMode::Immediate: case AddressingMode::BlockMove: // Blockmove OpCodes have two bytes following them directly case AddressingMode::StackAbsolute: // Stack absolute is used to push values following the op code onto the stack case AddressingMode::ProgramCounterRelative: // Program counter relative OpCodes such as all branch instructions have an 8 bit operand // following the op code case AddressingMode::ProgramCounterRelativeLong: // StackProgramCounterRelativeLong is only used by the PER OpCode, it has 16 bit operand case AddressingMode::StackProgramCounterRelativeLong: mProgramAddress.newWithOffset(1).getBankAndOffset(&dataAddressBank, &dataAddressOffset); break; case AddressingMode::Absolute: dataAddressBank = mDB; dataAddressOffset = mMemoryMapper.readTwoBytes(mProgramAddress.newWithOffset(1)); break; case AddressingMode::AbsoluteLong: mMemoryMapper.readAddressAt(mProgramAddress.newWithOffset(1)).getBankAndOffset(&dataAddressBank, &dataAddressOffset); break; case AddressingMode::AbsoluteIndirect: { dataAddressBank = mProgramAddress.getBank(); Address addressOfOffset(0x00, mMemoryMapper.readTwoBytes(mProgramAddress.newWithOffset(1))); dataAddressOffset = mMemoryMapper.readTwoBytes(addressOfOffset); } break; case AddressingMode::AbsoluteIndirectLong: { Address addressOfEffectiveAddress(0x00, mMemoryMapper.readTwoBytes(mProgramAddress.newWithOffset(1))); mMemoryMapper.readAddressAt(addressOfEffectiveAddress).getBankAndOffset(&dataAddressBank, &dataAddressOffset); } break; case AddressingMode::AbsoluteIndexedIndirectWithX: { Address firstStageAddress(mProgramAddress.getBank(), mMemoryMapper.readTwoBytes(mProgramAddress.newWithOffset(1))); Address secondStageAddress = firstStageAddress.newWithOffsetNoWrapAround(indexWithXRegister()); dataAddressBank = mProgramAddress.getBank(); dataAddressOffset = mMemoryMapper.readTwoBytes(secondStageAddress); } break; case AddressingMode::AbsoluteIndexedWithX: { Address firstStageAddress(mDB, mMemoryMapper.readTwoBytes(mProgramAddress.newWithOffset(1))); Address::sumOffsetToAddressNoWrapAround(firstStageAddress, indexWithXRegister()) .getBankAndOffset(&dataAddressBank, &dataAddressOffset);; } break; case AddressingMode::AbsoluteLongIndexedWithX: { Address firstStageAddress = mMemoryMapper.readAddressAt(mProgramAddress.newWithOffset(1)); Address::sumOffsetToAddressNoWrapAround(firstStageAddress, indexWithXRegister()) .getBankAndOffset(&dataAddressBank, &dataAddressOffset);; } break; case AddressingMode::AbsoluteIndexedWithY: { Address firstStageAddress(mDB, mMemoryMapper.readTwoBytes(mProgramAddress.newWithOffset(1))); Address::sumOffsetToAddressNoWrapAround(firstStageAddress, indexWithYRegister()) .getBankAndOffset(&dataAddressBank, &dataAddressOffset);; } break; case AddressingMode::DirectPage: { // Direct page/Zero page always refers to bank zero dataAddressBank = 0x00; if (mCpuStatus.emulationFlag()) { // 6502 uses zero page dataAddressOffset = mMemoryMapper.readByte(mProgramAddress.newWithOffset(1)); } else { // 65816 uses direct page dataAddressOffset = mD + mMemoryMapper.readByte(mProgramAddress.newWithOffset(1)); } } break; case AddressingMode::DirectPageIndexedWithX: { dataAddressBank = 0x00; dataAddressOffset = mD + indexWithXRegister() + mMemoryMapper.readByte(mProgramAddress.newWithOffset(1)); } break; case AddressingMode::DirectPageIndexedWithY: { dataAddressBank = 0x00; dataAddressOffset = mD + indexWithYRegister() + mMemoryMapper.readByte(mProgramAddress.newWithOffset(1)); } break; case AddressingMode::DirectPageIndirect: { Address firstStageAddress(0x00, mD + mMemoryMapper.readByte(mProgramAddress.newWithOffset(1))); dataAddressBank = mDB; dataAddressOffset = mMemoryMapper.readTwoBytes(firstStageAddress); } break; case AddressingMode::DirectPageIndirectLong: { Address firstStageAddress(0x00, mD + mMemoryMapper.readByte(mProgramAddress.newWithOffset(1))); mMemoryMapper.readAddressAt(firstStageAddress) .getBankAndOffset(&dataAddressBank, &dataAddressOffset);; } break; case AddressingMode::DirectPageIndexedIndirectWithX: { Address firstStageAddress(0x00, mD + mMemoryMapper.readByte(mProgramAddress.newWithOffset(1)) + indexWithXRegister()); dataAddressBank = mDB; dataAddressOffset = mMemoryMapper.readTwoBytes(firstStageAddress); } break; case AddressingMode::DirectPageIndirectIndexedWithY: { Address firstStageAddress(0x00, mD + mMemoryMapper.readByte(mProgramAddress.newWithOffset(1))); uint16_t secondStageOffset = mMemoryMapper.readTwoBytes(firstStageAddress); Address thirdStageAddress(mDB, secondStageOffset); Address::sumOffsetToAddressNoWrapAround(thirdStageAddress, indexWithYRegister()) .getBankAndOffset(&dataAddressBank, &dataAddressOffset); } break; case AddressingMode::DirectPageIndirectLongIndexedWithY: { Address firstStageAddress(0x00, mD + mMemoryMapper.readByte(mProgramAddress.newWithOffset(1))); Address secondStageAddress = mMemoryMapper.readAddressAt(firstStageAddress); Address::sumOffsetToAddressNoWrapAround(secondStageAddress, indexWithYRegister()) .getBankAndOffset(&dataAddressBank, &dataAddressOffset); } break; case AddressingMode::StackRelative: { dataAddressBank = 0x00; dataAddressOffset = mStack.getStackPointer() + mMemoryMapper.readByte(mProgramAddress.newWithOffset(1)); } break; case AddressingMode::StackDirectPageIndirect: { dataAddressBank = 0x00; dataAddressOffset = mD + mMemoryMapper.readByte(mProgramAddress.newWithOffset(1)); } break; case AddressingMode::StackRelativeIndirectIndexedWithY: { Address firstStageAddress(0x00, mStack.getStackPointer() + mMemoryMapper.readByte(mProgramAddress.newWithOffset(1))); uint16_t secondStageOffset = mMemoryMapper.readTwoBytes(firstStageAddress); Address thirdStageAddress(mDB, secondStageOffset); Address::sumOffsetToAddressNoWrapAround(thirdStageAddress, indexWithYRegister()) .getBankAndOffset(&dataAddressBank, &dataAddressOffset); } break; } return Address(dataAddressBank, dataAddressOffset); }
[ "francesco.rigoni@gmail.com" ]
francesco.rigoni@gmail.com
d14aa4c628d32c4eeb5732026ecd91e77fbed9d3
9ddbbc876049a70db8cd4019eee0f8de95f53187
/Http/HttpServer.h
247c58f2e0107c414a9522b1375af112cb32de23
[]
no_license
MarekM25/TIN_iptables
af46d08060f0113b172b50a71361e4d4b55a5c73
5bb7be83a2d5b68d483d7f7082d7b8341731d405
refs/heads/master
2021-01-10T17:01:28.125175
2015-12-22T15:02:22
2015-12-22T15:02:22
46,950,725
0
1
null
null
null
null
UTF-8
C++
false
false
2,287
h
// // Created by anowikowski on 10.12.15. // #ifndef TIN_IPTABLES_HTTPSERVER_H #define TIN_IPTABLES_HTTPSERVER_H #include <string> #include <thread> #include <netinet/in.h> #include "HttpResponse.h" #include "HttpRequest.h" #include "HttpRequestContext.h" class HttpServerRequestHandlerInterface { public: virtual HttpResponse HandleHttpRequest(HttpRequestContext httpRequestContext) = 0; }; class HttpServer { public: HttpServer(); ~HttpServer(); void SetPort(unsigned short port); void SetListeningIpAddress(std::string ipAddress); void Start(); void Stop(); bool IsRunning(); void SetMaxConnectionQueueLength(int maxConnectionQueueLength); void SetSendTimeout(int sendTimeout); void SetReceiveTimeout(int receiveTimeout); void SetHttpRequestHandlerContextObject(HttpServerRequestHandlerInterface *pHttpServerRequestHandlerContextObject); private: sockaddr_in m_localAddress; std::thread m_serverThread; void ServerThreadWork(int iSocket); void ClientConnectionThreadWork(int clientSocket); int m_iMaxConnectionQueueLength; int m_iSendTimeout; int m_iReceiveTimeout; bool m_bIsRunning; bool m_bIsServerStopRequested; std::string ReadAvailableString(int socket); std::string ReadString(int socket, int length); void SendResponse(int socket, HttpResponse &httpResponse); void SendString(int socket, const std::string &str); void SetSocketNonBlocking(int iSocket); int InitializeListeningSocket(); static const std::string m_sNewLineString; static const std::string m_sHttpRequestHeadersDataSeparator; static const std::string m_sHttpRequestHeaderNameValueSeparator; static const std::string m_sHttpContentLengthHttpHeaderName; static const std::size_t m_bufferSize; static std::vector<HttpHeader> m_staticHttpResponseHeaders; HttpServerRequestHandlerInterface *m_pHttpServerRequestHandlerContextObject; void SendBadRequestResponse(int iSocket); void SendInternalServerErrorResponse(int iSocket); void AddStaticHttpResponseHeadersToHttpResponse(HttpResponse &httpResponse); void SetHttpResponseContentLengthHeader(HttpResponse &httpResponse); std::string GetClientIpAddress(int iSocket); }; #endif //TIN_IPTABLES_HTTPSERVER_H
[ "nowikowski22@hotmail.com" ]
nowikowski22@hotmail.com
a94d0ea3f536b15515c8cb784953d6888b86500d
a9642579bb7ddd2e671d5ade73ee540a5c053925
/src/Engine/Primitives/CharacterMesh.h
6857f5b4e6df0377403943fc21ba2e3f3e836742
[]
no_license
BobDeng1974/OpenGLEngine
bd8417fc572f5631010cd1f686559166af831bd2
9770c95a51e102a087d098e002a84f50279e551e
refs/heads/master
2020-04-29T01:45:29.158464
2019-03-14T23:12:40
2019-03-14T23:12:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
915
h
#ifndef OPENGL_TEXT_H #define OPENGL_TEXT_H #include "Mesh.h" #include "../CharacterTextureGenerator.h" class CharacterMesh : public Mesh { public: Character ch; CharacterMesh(char c, std::map<GLchar, Character> & characters) : Mesh() { ch = characters[c]; textureId = ch.TextureID; vertices = { 0.0f, 1.0f, 0.0, 0.0f, 0.0f, 0.0, 1.0f, 0.0f, 0.0, 0.0f, 1.0f, 0.0, 1.0f, 0.0f, 0.0, 1.0f, 1.0f, 0.0 }; indices = { 0, 1, 2, 3, 4, 5 }; uvs = { 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0 }; } }; #endif //OPENGL_TEXT_H
[ "krzysiekkucharski7@gmail.com" ]
krzysiekkucharski7@gmail.com
063b534a5733fc5079be72afc0c534b1fa7223f7
d10f52a94a61edc1c8be594977c13de984013494
/004-Median-of-Two-Sorted-Arrays-non-recursive/solution.cpp
1a39b50659fdbca02ce23c07ed8f9c7f3ee03040
[ "Apache-2.0" ]
permissive
johnhany/leetcode
1248e4c9b9e511d5dda3b4e970b4b2fda05d3a29
1948c6a517f3552f667df0c673198a12e5ea99b8
refs/heads/master
2023-05-14T01:03:19.608452
2023-05-05T12:43:56
2023-05-05T12:43:56
136,358,094
7
5
null
null
null
null
UTF-8
C++
false
false
1,005
cpp
#include "solution.hpp" static auto x = []() { // turn off sync std::ios::sync_with_stdio(false); // untie in/out streams cin.tie(NULL); return 0; }(); double Solution::findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { if (nums1.size() > nums2.size()) { std::swap(nums1, nums2); } int m = nums1.size(), n = nums2.size(); int low = 0, high = m, mid = (m+n+1)/2; int int_max = int((~(unsigned int)0) >> 1); int int_min = int(~int_max); while (low <= high) { int cut1 = (low+high)/2; int cut2 = mid-cut1; int left1 = (cut1==0)?int_min:nums1[cut1-1]; int left2 = (cut2==0)?int_min:nums2[cut2-1]; int right1 = (cut1==m)?int_max:nums1[cut1]; int right2 = (cut2==n)?int_max:nums2[cut2]; if (left1 <= right2 && left2 <= right1) { return (m+n)%2==0 ? (std::max(left1,left2)+std::min(right1,right2))/2.0 : std::max(left1,left2); } else if (right1 < left2) { low = cut1+1; } else { high = cut1-1; } } return 0.0; }
[ "johnhany@163.com" ]
johnhany@163.com
18f2a0b4d54ad0f48815294a5f9057dce84a5e4c
822febebbf0213bf144f6532ae428a5050beb4d8
/VS Code Cpp/DP_Aditya_Verma/7_MCM_&_Its_6_Variations/MCM_Memoization.cpp
11c9b958e60362db87a86d5c17bfe127757dfa5b
[]
no_license
roushan-raj/Codes
bf5d5ffe438285556635fe8b2879048c37df11cf
96e0c54e4dbc679ea5c32c3aec72e80197b334d8
refs/heads/master
2023-05-13T22:10:08.333235
2021-06-09T17:19:29
2021-06-09T17:19:29
333,555,263
0
0
null
null
null
null
UTF-8
C++
false
false
631
cpp
#include<iostream> #include<bits/stdc++.h> using namespace std; int static dp[1001][1001]; int mcm(int arr[], int i, int j){ if(i>=j){ return 0; } if(dp[i][j] != -1){ return dp[i][j]; } int mn = INT_MAX; for(int k=i; k<=j-1; k++){ int temp = mcm(arr, i, k) + mcm(arr, k+1, j) + (arr[i-1]*arr[k]*arr[j]); if(temp < mn){ mn = temp; } } return dp[i][j] = mn; } int main() { int arr [] = {40, 20, 30, 10, 30}; int n = sizeof(arr) / sizeof(arr[0]); memset(dp, -1, sizeof(dp)); cout<<mcm(arr, 1, n-1); return 0; }
[ "rraa1.raushan@gmail.com" ]
rraa1.raushan@gmail.com
e0c3d54e4c69d332e3fb7bf32b7907c33e4e4769
2e1dd69084d07f9c0f71e1b446b59f9d3a96af9d
/Extras/bi_directional/bi_directional.ino
bee9f315666370f792cf2de3e89fc3a6e5b45736
[]
no_license
Rakin7/Coal-Mining-Safety-System
c319e158f7b2cad9992df9183d9a125d0f17439d
af1755943cbbba74f48a897bb5bc90f01760128a
refs/heads/master
2023-01-06T14:14:50.818431
2020-11-01T14:07:53
2020-11-01T14:07:53
288,236,792
0
0
null
null
null
null
UTF-8
C++
false
false
636
ino
#include <SPI.h> #include <nRF24L01.h> #include <RF24.h> char text[32] = ""; RF24 radio(8,9); // CE, CSN const byte addresses[][6] = {"00001", "00002"}; void setup() { Serial.begin(9600); radio.begin(); radio.openWritingPipe(addresses[1]); // 00002 radio.openReadingPipe(0, addresses[0]); // 00001 radio.setPALevel(RF24_PA_MIN); } void loop() { radio.startListening(); if ( radio.available()) { while (radio.available()) { radio.read(&text, sizeof(text)); Serial.println(text); } delay(5); radio.stopListening(); radio.write(&text, sizeof(text)); } }
[ "noreply@github.com" ]
noreply@github.com
7bd2b4cbad11d632fb8ecd43c889dee4d03ccc19
b9f26ea33f6b983ed18b4c9cb670ab71938fd5bc
/TopApps/os_win.cpp
c698981f10b75c0451800aca7e2eaba55ce8c2a6
[]
no_license
korha/TopApps
e899d269f56f9b26f289de1ee6de97ec3cbedd2d
cc2a6ac627e474ee0f2e3c068ada3fd6d7dcdc03
refs/heads/master
2021-01-21T20:24:05.271608
2017-09-08T01:16:06
2017-09-08T01:16:06
92,232,895
0
0
null
null
null
null
UTF-8
C++
false
false
18,731
cpp
#include <os_win.h> //------------------------------------------------------------------------------------------------- COsSpec::CMutex::CMutex() : hMutex(::CreateMutexW(nullptr, FALSE, g_wGuidMutex)) { Q_ASSERT(hMutex); } //------------------------------------------------------------------------------------------------- bool COsSpec::CMutex::FWait() { Q_ASSERT(hMutex); if (hMutex) { const DWORD dwResult = ::WaitForSingleObject(hMutex, 60*1000); if (dwResult == WAIT_OBJECT_0 || dwResult == WAIT_ABANDONED) return true; ::CloseHandle(hMutex); hMutex = nullptr; } return false; } //------------------------------------------------------------------------------------------------- void COsSpec::CMutex::FRelease() { if (hMutex) { ::ReleaseMutex(hMutex); ::CloseHandle(hMutex); hMutex = nullptr; } } //------------------------------------------------------------------------------------------------- //since Qt 5.2 Qt5Gui!QPixmap::fromWinHICON moved to Qt5WinExtras!QtWin::fromHICON //but it simply wrapper to old function, fix: extern "C" __declspec(dllimport) QPixmap _Z21qt_pixmapFromWinHICONP7HICON__(HICON hIcon); QPixmap COsSpec::FGetPixmap(const QString &strAppPath) { SHFILEINFOW shFileInfo; if (::SHGetFileInfoW(pointer_cast<const wchar_t*>(strAppPath.constData()), 0, &shFileInfo, sizeof(SHFILEINFOW), SHGFI_ICON | SHGFI_SMALLICON)) { const QPixmap pixmap = _Z21qt_pixmapFromWinHICONP7HICON__(shFileInfo.hIcon); ::DestroyIcon(shFileInfo.hIcon); return pixmap.isNull() ? QPixmap(":/img/unknown.png") : pixmap; } return QPixmap(":/img/unknown.png"); } //------------------------------------------------------------------------------------------------- bool COsSpec::FIsSaveStatEnabled() { bool bIsEnabled = false; const DWORD dwPid = ::GetCurrentProcessId(); if (dwPid != ASFW_ANY) //https://blogs.msdn.microsoft.com/oldnewthing/20040223-00/?p=40503/ { const HANDLE hSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwPid); if (hSnapshot != INVALID_HANDLE_VALUE) { MODULEENTRY32W moduleEntry32; moduleEntry32.dwSize = sizeof(MODULEENTRY32W); if (::Module32FirstW(hSnapshot, &moduleEntry32)) { do { #ifdef _WIN64 if (wcscmp(moduleEntry32.szModule, L"topapps64.dll") == 0) #else if (wcscmp(moduleEntry32.szModule, L"topapps32.dll") == 0) #endif { bIsEnabled = true; break; } } while (::Module32NextW(hSnapshot, &moduleEntry32)); } ::CloseHandle(hSnapshot); } } return bIsEnabled; } //------------------------------------------------------------------------------------------------- QVector<QPair<QString, qint64>> COsSpec::FGetStatFromRunningApps() { //GetModuleFileNameEx/GetProcessImageFileName/QueryFullProcessImageName/NtQueryInformationProcess(ProcessInformationClass) are working pretty bad //https://wj32.org/wp/2010/03/30/get-the-image-file-name-of-any-process-from-any-user-on-vista-and-above/ //NtQuerySystemInformation(SystemProcessInformation) replaces ToolHelp/EnumProcesses QVector<QPair<QString, qint64>> vectRunningApps; wchar_t *const wNativePaths = new wchar_t[dwDevicePathMaxLen*(L'Z'-L'A'+1)]; //--- Convert drive letters to a device paths --- wchar_t *wIt = wNativePaths; wchar_t wBuf[iAppPathSize]; wchar_t wLetter[] = L"A:"; DWORD dwDrives = ::GetLogicalDrives(); do { if ((dwDrives & 1) && ::QueryDosDeviceW(wLetter, wBuf, dwDevicePathMaxLen)) wcscpy(wIt, wBuf); else *wIt = L'\0'; wIt += dwDevicePathMaxLen; dwDrives >>= 1; } while (++*wLetter <= L'Z'); //--- Get info --- ULONG iSize; if (::NtQuerySystemInformation(SystemProcessInformation, nullptr, 0, &iSize) == STATUS_INFO_LENGTH_MISMATCH) { SYSTEM_PROCESS_INFORMATION *const pProcInfo = pointer_cast<SYSTEM_PROCESS_INFORMATION*>(new BYTE[iSize += 2048]); //+reserve buffer between two calls if (NT_SUCCESS(::NtQuerySystemInformation(SystemProcessInformation, pProcInfo, iSize, nullptr))) { const DWORD dwCurrentPid = ::GetCurrentProcessId(); const SYSTEM_PROCESS_INFORMATION *pIt = pProcInfo; //--- Enumerating --- do { const DWORD dwPid = reinterpret_cast<SIZE_T>(pIt->UniqueProcessId); Q_ASSERT(dwPid%4 == 0); if (dwPid != dwIdlePid && dwPid != dwSystemPid && dwPid != dwCurrentPid) { SYSTEM_PROCESS_IMAGE_NAME_INFORMATION processIdInfo; processIdInfo.ProcessId = pIt->UniqueProcessId; processIdInfo.ImageName.Buffer = wBuf; processIdInfo.ImageName.Length = 0; processIdInfo.ImageName.MaximumLength = iAppPathSize*sizeof(wchar_t); if (NT_SUCCESS(::NtQuerySystemInformation(static_cast<SYSTEM_INFORMATION_CLASS>(SystemProcessIdInformation), &processIdInfo, sizeof(SYSTEM_PROCESS_IMAGE_NAME_INFORMATION), nullptr))) { if (const HANDLE hProcess = ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, dwPid)) { FILETIME fileTime[2]; const bool bOk = ::GetProcessTimes(hProcess, fileTime, fileTime+1, fileTime+1, fileTime+1); ::CloseHandle(hProcess); if (bOk) { //--- Skip prefix --- wchar_t *wPath = wBuf; while (*wPath && *wPath != L'\\') ++wPath; if (*wPath == L'\\') { ++wPath; while (*wPath && *wPath != L'\\') ++wPath; if (*wPath == L'\\') { ++wPath; while (*wPath && *wPath != L'\\') ++wPath; if (*wPath == L'\\') { //--- Attempts to find a matching paths --- *wLetter = L'A'; wIt = wNativePaths; *wPath = L'\0'; do { if (*wIt && wcscmp(wBuf, wIt) == 0) { *wPath = L'\\'; *--wPath = L':'; *--wPath = *wLetter; vectRunningApps.append(qMakePair(QString::fromWCharArray(wPath), FFileTimeToUnixTime(fileTime))); break; } wIt += dwDevicePathMaxLen; } while (++*wLetter <= L'Z'); } } } } } } } } while (pIt->NextEntryOffset ? (pIt = pointer_cast<const SYSTEM_PROCESS_INFORMATION*>(pointer_cast<const BYTE*>(pIt) + pIt->NextEntryOffset), true) : false); } delete[] pProcInfo; } delete[] wNativePaths; return vectRunningApps; } //------------------------------------------------------------------------------------------------- QStringList COsSpec::FGetMethods() { return QStringList("AppInitDll"); } //------------------------------------------------------------------------------------------------- const char * COsSpec::FRunJob(const int iMethod) { const char *cError = nullptr; switch (iMethod) { case eAppInitDLL: { //https://support.microsoft.com/en-us/help/197571/working-with-the-appinit-dlls-registry-value //https://msdn.microsoft.com/en-us/library/windows/desktop/dd744762%28v=vs.85%29.aspx //every apps linked with user32.dll (there are very few executables that do not link with user32.dll) //load custom Dll, which detect a current system time in attaching/detaching cError = "Failed"; wchar_t wBuf[MAX_PATH+1]; const DWORD dwLen = ::GetModuleFileNameW(nullptr, wBuf, MAX_PATH+1); //+1 - check to trimmming if (dwLen >= 4 && dwLen < MAX_PATH) //correct path length { wchar_t *wDelim = wBuf+dwLen; do { if (*--wDelim == L'\\') break; } while (wDelim > wBuf); if (wDelim >= wBuf+2 && wDelim <= wBuf+MAX_PATH-15) //"\topapps96.dll`" { wcscpy(++wDelim, L"topapps32.dll"); cError = FAddAppInitDll(wBuf, false); if (cError == nullptr) { wDelim[7] = L'6'; wDelim[8] = L'4'; #ifdef _WIN64 cError = FAddAppInitDll(wBuf, true); #else BOOL bIsWow64; const HANDLE hProcess = ::GetCurrentProcess(); if (hProcess && ::IsWow64Process(hProcess, &bIsWow64)) { if (bIsWow64) cError = FAddAppInitDll(wBuf, true); } else cError = "IsWow64Process failed"; #endif if (!cError) { wcscpy(wDelim, L"stop!"); ::DeleteFileW(wBuf); } } } } break; } case eAppInitDLLnHelper: //AppInitDll with a background app //a custom Dll in DLL_PROCESS_ATTACH creates 0-period waitable timer, //which call SendMessage(WM_COPYDATA) to hidden window of background app //this app detect when a process created and notified when terminated via RegisterWaitForSingleObject //even if the process is crashed in comparison with the previous method case eDLLHook: //inject a custom Dll via WriteProcessMemory/CreateRemoteThread(LoadLibrary call) case eHelperOnly: //background app, which makes periodic snapshots of running apps, and monitors changes //stores the results periodically or when WM_QUERYENDSESSION/WM_ENDSESSION case ePsCreateProcessNotifyRoutine: //a driver based on PsSetCreateProcessNotifyRoutine //https://msdn.microsoft.com/en-us/library/windows/hardware/ff559951%28v=vs.85%29.aspx cError = "To-Do List..."; } if (cError) FStopJob(); return cError; } //------------------------------------------------------------------------------------------------- void COsSpec::FStopJob() { wchar_t wBuf[MAX_PATH+1]; DWORD dwLen = ::GetModuleFileNameW(nullptr, wBuf, MAX_PATH+1); if (dwLen >= 4 && dwLen < MAX_PATH) { wchar_t *wDelim = wBuf+dwLen; do { if (*--wDelim == L'\\') break; } while (wDelim > wBuf); if (wDelim >= wBuf+2 && wDelim <= wBuf+MAX_PATH-15) //"\topapps96.dll`" { wcscpy(++wDelim, L"stop!"); const HANDLE hFile = ::CreateFileW(wBuf, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile != INVALID_HANDLE_VALUE) ::CloseHandle(hFile); wcscpy(wDelim, L"topapps32.dll"); dwLen = wDelim-wBuf+13; DWORD dwDesiredAccess = KEY_QUERY_VALUE | KEY_SET_VALUE | KEY_WOW64_32KEY; int i = 2; do { HKEY hKey; if (::RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows", 0, dwDesiredAccess, &hKey) == ERROR_SUCCESS) { DWORD dwSize; if (::RegGetValueW(hKey, nullptr, L"AppInit_DLLs", RRF_RT_REG_SZ, nullptr, nullptr, &dwSize) == ERROR_SUCCESS) { wchar_t *const wNewString = new wchar_t[dwSize/sizeof(wchar_t)]; if (::RegGetValueW(hKey, nullptr, L"AppInit_DLLs", RRF_RT_REG_SZ, nullptr, wNewString, &dwSize) == ERROR_SUCCESS) if (wchar_t *wStart = wcsstr(wNewString, wBuf)) { if (wStart != wNewString) //delete delimeter { ++dwLen; --wStart; } wcscpy(wStart, wStart+dwLen); wStart = wNewString; if (*wStart == L',' || *wStart == L' ') ++wStart; ::RegSetValueExW(hKey, L"AppInit_DLLs", 0, REG_SZ, pointer_cast<const BYTE*>(wStart), (wcslen(wStart)+1)*sizeof(wchar_t)); } delete[] wNewString; } ::RegCloseKey(hKey); } } while (--i && (wDelim[7] = L'6', wDelim[8] = L'4', dwDesiredAccess = KEY_QUERY_VALUE | KEY_SET_VALUE | KEY_WOW64_64KEY, true)); CMutex cMutex; if (cMutex.FWait()) { wcscpy(wDelim, L"index.dat"); ::DeleteFileW(wDelim); wcsncpy(wDelim, L"data\\*\0", 8); SHFILEOPSTRUCT shFileOpStruct; shFileOpStruct.hwnd = nullptr; shFileOpStruct.wFunc = FO_DELETE; shFileOpStruct.pFrom = wDelim; shFileOpStruct.pTo = L"\0"; shFileOpStruct.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT; shFileOpStruct.fAnyOperationsAborted = FALSE; shFileOpStruct.hNameMappings = nullptr; shFileOpStruct.lpszProgressTitle = nullptr; ::SHFileOperationW(&shFileOpStruct); //cMutex.FRelease(); } } } } //------------------------------------------------------------------------------------------------- const char * COsSpec::FAddAppInitDll(const wchar_t *const wDllPath, const bool bIs64Key) { Q_ASSERT(wDllPath); const wchar_t *wIt = wDllPath; while (*wIt) { if (*wIt == L' ' || *wIt == L',') return "Place this app in a directory without spaces and commas"; //to avoid confusions ++wIt; } const char *cError = nullptr; if (::GetFileAttributesW(wDllPath) != INVALID_FILE_ATTRIBUTES) { HKEY hKey; if (::RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows", 0, bIs64Key ? (KEY_QUERY_VALUE | KEY_SET_VALUE | KEY_WOW64_64KEY) : (KEY_QUERY_VALUE | KEY_SET_VALUE | KEY_WOW64_32KEY), &hKey) == ERROR_SUCCESS) { DWORD dwValue, dwSize = sizeof(DWORD); if (::RegGetValueW(hKey, nullptr, L"LoadAppInit_DLLs", RRF_RT_REG_DWORD, nullptr, &dwValue, &dwSize) == ERROR_SUCCESS && dwValue == 1) { const LONG iResult = ::RegGetValueW(hKey, nullptr, L"RequireSignedAppInit_DLLs", RRF_RT_REG_DWORD, nullptr, &dwValue, &dwSize); if (iResult == ERROR_FILE_NOT_FOUND || (iResult == ERROR_SUCCESS && dwValue == 0)) { if (::RegGetValueW(hKey, nullptr, L"AppInit_DLLs", RRF_RT_REG_SZ, nullptr, nullptr, &dwSize) == ERROR_SUCCESS) { const DWORD dwSizeDll = (wIt-wDllPath+1)*sizeof(wchar_t); wchar_t *const wNewString = new wchar_t[(dwSize + dwSizeDll)/sizeof(wchar_t)]; if (::RegGetValueW(hKey, nullptr, L"AppInit_DLLs", RRF_RT_REG_SZ, nullptr, wNewString, &dwSize) == ERROR_SUCCESS) { if (!wcsstr(wNewString, wDllPath)) { wchar_t *wEnd = wcschr(wNewString, L'\0'); if (wEnd != wNewString) *wEnd++ = L','; wcscpy(wEnd, wDllPath); if (::RegSetValueExW(hKey, L"AppInit_DLLs", 0, REG_SZ, pointer_cast<const BYTE*>(wNewString), (wEnd-wNewString)*sizeof(wchar_t) + dwSizeDll) != ERROR_SUCCESS) cError = "Failed access to registry"; } } else cError = "AppInit_DLLs string failed"; delete[] wNewString; } } else cError = "Only signed DLL supports. Set\n\n" "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows\\\n\n" "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\Windows\\\n\n" "RequireSignedAppInit_DLLs to 0"; } else cError = "AppInitDlls doesn't work. Set\n\n" "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows\\\n\n" "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\Windows\\\n\n" "LoadAppInit_DLLs to 1"; ::RegCloseKey(hKey); } else cError = "Failed access to registry"; } else cError = "DLL not found"; return cError; }
[ "admin@example.com" ]
admin@example.com
a4f89c5bc5424528225977018ec484973c0b5592
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-iotsecuretunneling/source/model/TagResourceRequest.cpp
d70b7c622bf0817177d1a676fc83e61ed905c577
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
1,258
cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/iotsecuretunneling/model/TagResourceRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::IoTSecureTunneling::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; TagResourceRequest::TagResourceRequest() : m_resourceArnHasBeenSet(false), m_tagsHasBeenSet(false) { } Aws::String TagResourceRequest::SerializePayload() const { JsonValue payload; if(m_resourceArnHasBeenSet) { payload.WithString("resourceArn", m_resourceArn); } if(m_tagsHasBeenSet) { Aws::Utils::Array<JsonValue> tagsJsonList(m_tags.size()); for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex) { tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize()); } payload.WithArray("tags", std::move(tagsJsonList)); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection TagResourceRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "IoTSecuredTunneling.TagResource")); return headers; }
[ "sdavtaker@users.noreply.github.com" ]
sdavtaker@users.noreply.github.com
c3d3cac04addff70a05728ca5d855346293f93ba
02b6e42014dd8b30db8267041a7edb1accbcedf4
/LEDArranger.cpp
59909a52bff364dca6eb7f1c2ecf7e579cb8cc4a
[]
no_license
lisyaoran51/LEDFlow
f2efe004a8d45f9e109316f921727f78dd089528
338ad40e5e453dcd6e1ef99178208681a68edd94
refs/heads/master
2021-05-13T22:02:58.241616
2018-03-07T20:53:54
2018-03-07T20:53:54
116,478,483
0
0
null
null
null
null
UTF-8
C++
false
false
1,221
cpp
#include "LEDArranger.h" LEDArranger::LEDArranger(StatusConverter* sConverter) { startTime = float(millis()) / 1000.0; lastTime = startTime; converter = sConverter; } void LEDArranger::AddEvents(LinkedList<Event*>* newEvents) { for (int i = 0; i < newEvents->size(); i++) { events.add(newEvents->get(i)); } delete newEvents; } void LEDArranger::Update() { float nowTime = float(millis()) / 1000.0; float deltaTime = nowTime - lastTime; #ifdef _DEBUG_MODE String d2 = String("Now time: ") + millis() + "really get time: " + String(float(nowTime),3); DEBUG_PRINTLN(d2); #endif /* * pass every event update time, kill dead ones */ for (int i = 0; i < events.size(); i++) { Event* e = events.get(i); e->PassBy(deltaTime); if (!e->IsAlive()) { #ifdef _DEBUG_MODE NoteEvent* debugE = (NoteEvent*)e; String d = String("Kill dead event. Now time: ") + nowTime + ", Last time: " + lastTime + ", time left: " + debugE->GetTimeLeft() + ", dead time: " + NOTE_DEAD_TIME; DEBUG_PRINTLN(d); #endif events.remove(i); delete e; i--; } } lastTime = nowTime; } void LEDArranger::Arrange(LinkedList<Pair>* lightStatus) { converter->Convert(&events, lightStatus); }
[ "lisyaoran51@hotmail.com" ]
lisyaoran51@hotmail.com
09a2cde370143aa725d1f1d2a801e9b4fc265738
a0604bbb76abbb42cf83e99f673134c80397b92b
/fldserver/base/strings/string_piece.cc
e46471d931f0094a7bc0f533c960414f27febf22
[ "BSD-3-Clause" ]
permissive
Hussam-Turjman/FLDServer
816910da39b6780cfd540fa1e79c84a03c57a488
ccc6e98d105cfffbf44bfd0a49ee5dcaf47e9ddb
refs/heads/master
2022-07-29T20:59:28.954301
2022-07-03T12:02:42
2022-07-03T12:02:42
461,034,667
2
0
null
null
null
null
UTF-8
C++
false
false
9,340
cc
// Copyright (c) 2012 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 "fldserver/base/strings/string_piece.h" #include "fldserver/base/strings/utf_string_conversions.h" #include "fldserver/fldserver_config.h" #include <limits> #include <algorithm> #include <climits> #include <ostream> #include <string> namespace base { namespace { // For each character in characters_wanted, sets the index corresponding // to the ASCII code of that character to 1 in table. This is used by // the find_.*_of methods below to tell whether or not a character is in // the lookup table in constant time. // The argument `table' must be an array that is large enough to hold all // the possible values of an unsigned char. Thus it should be be declared // as follows: // bool table[UCHAR_MAX + 1] inline void BuildLookupTable(StringPiece characters_wanted, bool* table) { const size_t length = characters_wanted.length(); const char* const data = characters_wanted.data(); for (size_t i = 0; i < length; ++i) { table[static_cast<unsigned char>(data[i])] = true; } } } // namespace // MSVC doesn't like complex extern templates and DLLs. #if !defined(COMPILER_MSVC) template class BasicStringPiece<char>; template class BasicStringPiece<char16_t>; template class BasicStringPiece<wchar_t>; #endif std::ostream& operator<<(std::ostream& o, StringPiece piece) { o.write(piece.data(), static_cast<std::streamsize>(piece.size())); return o; } std::ostream& operator<<(std::ostream& o, StringPiece16 piece) { return o << UTF16ToUTF8(piece); } std::ostream& operator<<(std::ostream& o, WStringPiece piece) { return o << WideToUTF8(piece); } namespace internal { template <typename CharT> size_t findT(BasicStringPiece<CharT> self, BasicStringPiece<CharT> s, size_t pos) { if (pos > self.size()) return BasicStringPiece<CharT>::npos; typename BasicStringPiece<CharT>::const_iterator result = std::search(self.begin() + pos, self.end(), s.begin(), s.end()); const size_t xpos = static_cast<size_t>(result - self.begin()); return xpos + s.size() <= self.size() ? xpos : BasicStringPiece<CharT>::npos; } size_t find(StringPiece self, StringPiece s, size_t pos) { return findT(self, s, pos); } size_t find(StringPiece16 self, StringPiece16 s, size_t pos) { return findT(self, s, pos); } template <typename CharT> size_t rfindT(BasicStringPiece<CharT> self, BasicStringPiece<CharT> s, size_t pos) { if (self.size() < s.size()) return BasicStringPiece<CharT>::npos; if (s.empty()) return std::min(self.size(), pos); typename BasicStringPiece<CharT>::const_iterator last = self.begin() + std::min(self.size() - s.size(), pos) + s.size(); typename BasicStringPiece<CharT>::const_iterator result = std::find_end(self.begin(), last, s.begin(), s.end()); return result != last ? static_cast<size_t>(result - self.begin()) : BasicStringPiece<CharT>::npos; } size_t rfind(StringPiece self, StringPiece s, size_t pos) { return rfindT(self, s, pos); } size_t rfind(StringPiece16 self, StringPiece16 s, size_t pos) { return rfindT(self, s, pos); } // 8-bit version using lookup table. size_t find_first_of(StringPiece self, StringPiece s, size_t pos) { if (self.size() == 0 || s.size() == 0) return StringPiece::npos; // Avoid the cost of BuildLookupTable() for a single-character search. if (s.size() == 1) return self.find(s.data()[0], pos); bool lookup[UCHAR_MAX + 1] = {false}; BuildLookupTable(s, lookup); for (size_t i = pos; i < self.size(); ++i) { if (lookup[static_cast<unsigned char>(self.data()[i])]) { return i; } } return StringPiece::npos; } // Generic brute force version. template <typename CharT> size_t find_first_ofT(BasicStringPiece<CharT> self, BasicStringPiece<CharT> s, size_t pos) { // Use the faster std::find() if searching for a single character. typename BasicStringPiece<CharT>::const_iterator found = s.size() == 1 ? std::find(self.begin() + pos, self.end(), s[0]) : std::find_first_of(self.begin() + pos, self.end(), s.begin(), s.end()); if (found == self.end()) return BasicStringPiece<CharT>::npos; return found - self.begin(); } size_t find_first_of(StringPiece16 self, StringPiece16 s, size_t pos) { return find_first_ofT(self, s, pos); } // 8-bit version using lookup table. size_t find_first_not_of(StringPiece self, StringPiece s, size_t pos) { if (self.size() == 0) return StringPiece::npos; if (s.size() == 0) return 0; // Avoid the cost of BuildLookupTable() for a single-character search. if (s.size() == 1) return self.find_first_not_of(s.data()[0], pos); bool lookup[UCHAR_MAX + 1] = {false}; BuildLookupTable(s, lookup); for (size_t i = pos; i < self.size(); ++i) { if (!lookup[static_cast<unsigned char>(self.data()[i])]) { return i; } } return StringPiece::npos; } // Generic brute-force version. template <typename CharT> size_t find_first_not_ofT(BasicStringPiece<CharT> self, BasicStringPiece<CharT> s, size_t pos) { if (self.size() == 0) return BasicStringPiece<CharT>::npos; for (size_t self_i = pos; self_i < self.size(); ++self_i) { bool found = false; for (auto c : s) { if (self[self_i] == c) { found = true; break; } } if (!found) return self_i; } return BasicStringPiece<CharT>::npos; } size_t find_first_not_of(StringPiece16 self, StringPiece16 s, size_t pos) { return find_first_not_ofT(self, s, pos); } // 8-bit version using lookup table. size_t find_last_of(StringPiece self, StringPiece s, size_t pos) { if (self.size() == 0 || s.size() == 0) return StringPiece::npos; // Avoid the cost of BuildLookupTable() for a single-character search. if (s.size() == 1) return self.rfind(s.data()[0], pos); bool lookup[UCHAR_MAX + 1] = {false}; BuildLookupTable(s, lookup); for (size_t i = std::min(pos, self.size() - 1);; --i) { if (lookup[static_cast<unsigned char>(self.data()[i])]) return i; if (i == 0) break; } return StringPiece::npos; } // Generic brute-force version. template <typename CharT> size_t find_last_ofT(BasicStringPiece<CharT> self, BasicStringPiece<CharT> s, size_t pos) { if (self.size() == 0) return BasicStringPiece<CharT>::npos; for (size_t self_i = std::min(pos, self.size() - 1);; --self_i) { for (auto c : s) { if (self.data()[self_i] == c) return self_i; } if (self_i == 0) break; } return BasicStringPiece<CharT>::npos; } size_t find_last_of(StringPiece16 self, StringPiece16 s, size_t pos) { return find_last_ofT(self, s, pos); } // 8-bit version using lookup table. size_t find_last_not_of(StringPiece self, StringPiece s, size_t pos) { if (self.size() == 0) return StringPiece::npos; size_t i = std::min(pos, self.size() - 1); if (s.size() == 0) return i; // Avoid the cost of BuildLookupTable() for a single-character search. if (s.size() == 1) return self.find_last_not_of(s.data()[0], pos); bool lookup[UCHAR_MAX + 1] = {false}; BuildLookupTable(s, lookup); for (;; --i) { if (!lookup[static_cast<unsigned char>(self.data()[i])]) return i; if (i == 0) break; } return StringPiece::npos; } // Generic brute-force version. template <typename CharT> size_t find_last_not_ofT(BasicStringPiece<CharT> self, BasicStringPiece<CharT> s, size_t pos) { if (self.size() == 0) return StringPiece::npos; for (size_t self_i = std::min(pos, self.size() - 1);; --self_i) { bool found = false; for (auto c : s) { if (self.data()[self_i] == c) { found = true; break; } } if (!found) return self_i; if (self_i == 0) break; } return BasicStringPiece<CharT>::npos; } size_t find_last_not_of(StringPiece16 self, StringPiece16 s, size_t pos) { return find_last_not_ofT(self, s, pos); } size_t find(WStringPiece self, WStringPiece s, size_t pos) { return findT(self, s, pos); } size_t rfind(WStringPiece self, WStringPiece s, size_t pos) { return rfindT(self, s, pos); } size_t find_first_of(WStringPiece self, WStringPiece s, size_t pos) { return find_first_ofT(self, s, pos); } size_t find_first_not_of(WStringPiece self, WStringPiece s, size_t pos) { return find_first_not_ofT(self, s, pos); } size_t find_last_of(WStringPiece self, WStringPiece s, size_t pos) { return find_last_ofT(self, s, pos); } size_t find_last_not_of(WStringPiece self, WStringPiece s, size_t pos) { return find_last_not_ofT(self, s, pos); } } // namespace internal } // namespace base
[ "hussam.turjman@gmail.com" ]
hussam.turjman@gmail.com
6100097610e32407e29dd06a606eb59e2962a843
bb25059661ef7e2a085e7d254672d3fcbf6c60ec
/toDecimal.cpp
016f9df82babdb3afe4990b923110e433fdeeaea
[]
no_license
Gourav-Chouhan/C-programs
70176289603fb9c4b5ad6f05683b83a94661a689
f767f81c5b8b4fbd78052b635cd29672718ba754
refs/heads/master
2023-04-26T14:00:40.724024
2021-05-15T12:07:48
2021-05-15T12:07:48
367,621,718
0
0
null
null
null
null
UTF-8
C++
false
false
312
cpp
#include <iostream> #include <string.h> #include <math.h> using namespace std; int main() { string bin; cin>>bin; //cout<<bin.size(); int dec = 0; for (int i = 0; i < bin.size(); i++) { dec -= (pow(2, i))*(bin.at(bin.size() - i)); } cout<<dec; return 0; }
[ "gg0uravgch0uhan@gmail.com" ]
gg0uravgch0uhan@gmail.com
ecdedddbef2e8e5e45a50e79ee753ce67230afa8
86c1a486e011bff80d79bd2be6065d79f7558da9
/LevelSaveState.h
d44a171e97d77c3492d4133f182aee873a7e8a22
[]
no_license
meabefir/regex
ece634c1ea45d7ee34720e12d6780f32733deccb
492246e1540c856fb7b7df3a81c6fb66c4d76394
refs/heads/master
2023-04-04T04:31:03.440978
2021-04-22T06:58:18
2021-04-22T06:58:18
359,185,682
1
0
null
null
null
null
UTF-8
C++
false
false
658
h
#pragma once #include "State.h" #include "Button.h" class LevelSaveState : public State { private: sf::RectangleShape whiteBox; sf::Text infoTextRender; sf::Text inputTextRender; std::string text; std::unordered_map<std::string, Button*> buttons; public: LevelSaveState(sf::RenderWindow* window, std::vector<State*>* states); ~LevelSaveState(); void setText(std::string); void initFont(); void handleEvents(sf::Event); void updateInput(const float& dt); void update(const float& dt); void draw(sf::RenderTarget* target = nullptr, sf::View* UIView = nullptr); };
[ "hujapetru@gmail.com" ]
hujapetru@gmail.com
1d1908ba346e5925931ba8318172ede6cf18fd99
909595cdbb68692e44ba59b8d42cd6814eff7464
/算法笔记/快速幂基本.cpp
5bbe96209663848b2bcdb0d0f5740961e050775c
[]
no_license
luoguanghao/PAT
a57ac79e3029b921b3f3802b436a5ddeb72c9cff
866cee05b42911bbd0cdc78442381d34c3be539d
refs/heads/master
2020-05-30T16:13:09.339947
2019-06-02T12:00:23
2019-06-02T12:00:23
189,836,911
0
0
null
null
null
null
UTF-8
C++
false
false
271
cpp
#include <cmath> #include <cstdio> const double PI = acos(-1.0); const double eps = 1e-5; double r; int main(){ int a,b; scanf("%d %d",&a,&b); int ans=1, base=a; while(b!=0){ if(b&1!=0){ ans*=base; } base*=base; b>>=1; } printf("%d",ans); return 0; }
[ "896441113@qq.com" ]
896441113@qq.com
0ab1cc8e1e40e981e01aa090436fcf0b06a12c1b
f449d3be32d1e718bfe3627e4dc1d6d300a8c41f
/Classes/cell/ability/Ability.cpp
1d5ab2606b17672abe8ef6eddb0c7a986a1be3e5
[]
no_license
Crasader/tower-skycity-two
949dadd1e32622f67c7f194855ee3439fede43e4
f22202c1ebf5e16206f765b736d46491b10cfa7d
refs/heads/master
2020-12-13T01:31:27.267103
2015-11-09T11:08:00
2015-11-09T11:08:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
511
cpp
#ifndef __ABILITY_H__ #define __ABILITY_H__ #include "Ability.h" #include "WalkAble.h" Ability* Ability::create(std::string type) { Ability* ability = nullptr; if(type == "walk") { ability = new WalkAble(); } else if(type == "skill") { } else if(type == "fight") { } else if(type == "chat") { } else if(type == "swap") { } else { ability = new Ability(); } ability->autorelease(); return ability; } void Ability::setTarget(Cell* cell) { _target = cell; } #endif //__ABILITY_H__
[ "sdlwlxf@gmail.com" ]
sdlwlxf@gmail.com
0a08b771a4703ff7f270618775b7a35b584d97d3
42614c9938e56d9349f82e632fededd10a4382de
/0646-maximumLengthOfPairChain.cpp
1389a1e6ebbf5afe40b2edf66c14763aea5f4166
[]
no_license
rouman321/code-practice
fe1e092f0f99c689e0ffb3398222d6482cda3fe3
d43c73c8a74a95b5e5a568fe40b5cb0cda6c8974
refs/heads/master
2020-07-29T06:29:30.820220
2019-11-25T19:26:12
2019-11-25T19:26:12
209,698,973
0
0
null
null
null
null
UTF-8
C++
false
false
651
cpp
/* LeetCode 646. Maximum Length of Pair Chain medium time: 35.03% space: 100% */ class Solution { public: int findLongestChain(vector<vector<int>>& pairs) { sort(pairs.begin(),pairs.end()); vector<int> dp(pairs.size(),1); for(int i = 0;i < pairs.size();i++){ for(int j = 0;j < i;j++){ if(pairs[i][0]>pairs[j][1]){ dp[i] = max(dp[i],dp[j]+1); } } } int ret = 0; for(int i = 0;i < dp.size();i++){ ret = max(ret,dp[i]); // cout<<dp[i]<<" "; } // cout<<endl; return ret; } };
[ "rouman321@gmail.com" ]
rouman321@gmail.com
353d302545229c052430f42052c971571ac4cc3b
36b214de24e1f248d5491a3fff1bbf457a87f5ad
/0_99_save.h
83359a78990e821232a5ec40749dbf9086e3a3a2
[]
no_license
enburk/en-wiktionary
dc0a2b0effccc3d745ecc18952223a83fd32f1e4
cbed0ba8c27f120a46004978c01e4b254c1ffab3
refs/heads/master
2021-07-19T08:40:59.253245
2021-07-17T05:57:58
2021-07-17T05:57:58
183,902,557
0
0
null
null
null
null
UTF-8
C++
false
false
689
h
#pragma once #include "0.h" namespace pass0 { Pass <entry, entry> save = [](auto & input, auto & output) { bool started = false; std::ofstream fstream; for (auto && entry : input) { if (GENERATE_REPORTS and not started) { started = true; print("=== save 0... ==="); fstream = std::ofstream(path_out); } if (GENERATE_REPORTS) fstream << entry; output.push(std::move(entry)); } if (started) { fstream << esc; fstream.close(); print("=== save 0 ok ==="); } }; }
[ "enburk@gmail.com" ]
enburk@gmail.com
830aa860ac27b46ed8b85d4e5b26c49fa06646b7
22c59efd9f33b104321be0ea17a3324fb67ad6bf
/Proj2/generator.cpp
8aed402d8b979b9d74151dc0aa22548c6ff04cdb
[]
no_license
sushaoxiang911/AlgorithmsAndDataStructures
160e85b487bc065dfd4719228a803c2a869d35a1
bdcd9b3b282c19a3c37cd7b352135e8fb0819ec3
refs/heads/master
2021-01-19T22:14:01.300118
2014-12-15T06:59:44
2014-12-15T06:59:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
849
cpp
#include <iostream> #include <fstream> #include "stdlib.h" #include "time.h" #define CONTENTLENGTH 150 #define NAME 3 using namespace std; int a=0; void generate_name() { string name=""; static int a='A'; name=a++; if(a=='~') a++; cout<<"~~~~~~~~~~~~~~~~~~~~"; cout<<name; cout<<"~~~~~~~~~~~~~~~~~~~~"<<endl; } void generate_content() { string content=""; char temp; for(int i=0;i<CONTENTLENGTH;i++) { temp=(rand()%94)+32; if(rand()%40<10) { cout<<"."; } else if (rand()%40<10) { cout<<"\t"; } else if (rand()%80<10) { cout<<"\n"; a++; } else if (rand()%30<15) { cout<<" "; } else if (rand()%10<4) { cout<<"~"; } cout<<temp; } cout<<endl; } int main() { srand(time(NULL)); for (int i=0;i<NAME;i++) { generate_name(); generate_content(); if(a>40) { break; } } }
[ "ssx@umich.edu" ]
ssx@umich.edu
9c6b1e98f8d5bba64b8d3fd0d42d6aad0173a5e4
a9177742af0bbd45441d9f5e87b24016f1b28e84
/include/dynamic-graph/TaskVelocityDamping/TaskVelocityDamping.hh
07ecafb155f0f222dcb1505fd6ee050b935998b6
[]
no_license
pal-robotics-graveyard/task_velocity_damping
a22bb686288a6f6807321a2e699ea90fd023f54e
c2840daba0e29cfd471480b5de98e86b4d229eaf
refs/heads/master
2020-04-06T04:37:25.062789
2014-04-16T17:07:13
2014-04-16T17:07:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,003
hh
/* * Copyright 2011, Nicolas Mansard, LAAS-CNRS * * This file is part of sot-dyninv. * sot-dyninv 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. * sot-dyninv 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 sot-dyninv. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __sot_TaskVelocityDamping_H__ #define __sot_TaskVelocityDamping_H__ /* --------------------------------------------------------------------- */ /* --- INCLUDE --------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* SOT */ #include <sot-dyninv/signal-helper.h> #include <sot-dyninv/entity-helper.h> #include <sot/core/task.hh> #include <sot/core/flags.hh> #include <sot/core/matrix-homogeneous.hh> #include <sot/core/multi-bound.hh> #include <iostream> //#include <sot_transform/sot_frame_transform.h> #include <tf/transform_broadcaster.h> namespace dynamicgraph { namespace sot { /* --------------------------------------------------------------------- */ /* --- CLASS ----------------------------------------------------------- */ /* --------------------------------------------------------------------- */ class TaskVelocityDamping :public TaskAbstract ,public EntityHelper<TaskVelocityDamping> { public: /* --- CONSTRUCTOR ---- */ TaskVelocityDamping( const std::string& name ); public: /* --- ENTITY INHERITANCE --- */ DYNAMIC_GRAPH_ENTITY_DECL(); virtual void display( std::ostream& os ) const; public: /* --- SIGNALS --- */ DECLARE_SIGNAL_IN(dt,double); DECLARE_SIGNAL_IN(controlGain,double); DECLARE_SIGNAL_IN(di,double); DECLARE_SIGNAL_IN(ds,double); // DECLARE_SIGNAL_OUT(activeSize,int); public: /* --- COMPUTATION --- */ dg::sot::VectorMultiBound& computeTask( dg::sot::VectorMultiBound& res,int time ); ml::Matrix& computeJacobian( ml::Matrix& J,int time ); private: // boost::shared_ptr<SotFrameTransformer> sot_transformer_; // input signals for P1 std::vector<boost::shared_ptr< SignalPtr <dynamicgraph::Matrix, int> > > p1_vec; // input signals for p2 std::vector<boost::shared_ptr< SignalPtr <dynamicgraph::Matrix, int> > > p2_vec; // input signals for jacobians of p1 std::vector<boost::shared_ptr< SignalPtr <dynamicgraph::Matrix, int> > > jVel_vec; // output signals for n and distance std::vector<boost::shared_ptr< SignalTimeDependent <dynamicgraph::Vector, int> > > n_vec; std::vector<boost::shared_ptr< SignalTimeDependent <dynamicgraph::Vector, int> > > v_vec; std::vector<boost::shared_ptr< SignalTimeDependent <double, int> > > d_vec; void split(std::vector<std::string> &tokens, const std::string &text, char sep) const; void set_avoiding_objects(const std::string& avoiding_objects); // double& calculateDistanceSignal(double& d_sig, int i); // ml::Vector& calculateUnitVectorSignal(dynamicgraph::Vector res, int i); double calculateDistance(sot::MatrixHomogeneous p1, sot::MatrixHomogeneous p2); ml::Vector calculateDirectionalVector(sot::MatrixHomogeneous p1,sot::MatrixHomogeneous p2); ml::Vector calculateUnitVector(sot::MatrixHomogeneous p1,sot::MatrixHomogeneous p2); int avoidance_size_; std::vector<std::string> avoidance_objects_vec; tf::TransformBroadcaster br_; }; // class TaskVelocityDamping inline tf::Transform transformToTF(const dynamicgraph::Vector& vector) { tf::Transform transform; transform.setIdentity(); tf::Vector3 pos; pos.setValue(vector.elementAt(0),vector.elementAt(1),vector.elementAt(2)); transform.setOrigin(pos); return transform; } inline tf::Transform transformToTF(const dynamicgraph::Matrix& matrix){ tf::Transform transform; tf::Matrix3x3 rot; rot.setValue( matrix.elementAt(0,0), matrix.elementAt(0,1), matrix.elementAt(0,2), matrix.elementAt(1,0), matrix.elementAt(1,1), matrix.elementAt(1,2), matrix.elementAt(2,0), matrix.elementAt(2,1), matrix.elementAt(2,2) ); tf::Vector3 pos; pos.setValue(matrix.elementAt(0,3),matrix.elementAt(1,3),matrix.elementAt(2,3)); tf::Quaternion quat; rot.getRotation(quat); // check that!! transform.setRotation(quat); transform.setOrigin(pos); return transform; } } // namespace sot } // namespace dynamicgraph #endif // #ifndef __sot_TaskVelocityDamping_H__
[ "karsten.knese@googlemail.com" ]
karsten.knese@googlemail.com
af04cb3be80ca487c4a06da2538b70fc002cebe6
988264115ad52083e04fc7ead0bfeef04f7301cb
/satplan-cond-effects-2009/solvers/zchaff/zchaff-no-assignment/sat_solver.cpp
41c4c1d740d8a5ac532f95c4a7b0a47a7875cfac
[]
no_license
josej30/Planner-Sat-Constraints
5240c0a1c137d78f1a6705a35c0440e15c5e4c68
e944a13f446291e28d2139bc7a5e7f44404954f3
refs/heads/master
2021-01-22T10:25:52.737449
2010-07-17T21:24:52
2010-07-17T21:24:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,188
cpp
/* =========FOR INTERNAL USE ONLY. NO DISTRIBUTION PLEASE ========== */ /********************************************************************* Copyright 2000-2004, Princeton University. All rights reserved. By using this software the USER indicates that he or she has read, understood and will comply with the following: --- Princeton University hereby grants USER nonexclusive permission to use, copy and/or modify this software for internal, noncommercial, research purposes only. Any distribution, including commercial sale or license, of this software, copies of the software, its associated documentation and/or modifications of either is strictly prohibited without the prior consent of Princeton University. Title to copyright to this software and its associated documentation shall at all times remain with Princeton University. Appropriate copyright notice shall be placed on all software copies, and a complete copy of this notice shall be included in all copies of the associated documentation. No right is granted to use in advertising, publicity or otherwise any trademark, service mark, or the name of Princeton University. --- This software and any associated documentation is provided "as is" PRINCETON UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING THOSE OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, OR THAT USE OF THE SOFTWARE, MODIFICATIONS, OR ASSOCIATED DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER INTELLECTUAL PROPERTY RIGHTS OF A THIRD PARTY. Princeton University shall not be liable under any circumstances for any direct, indirect, special, incidental, or consequential damages with respect to any claim by USER or any third party on account of or arising from the use, or inability to use, this software or its associated documentation, even if Princeton University has been advised of the possibility of those damages. *********************************************************************/ #include <iostream> #include <fstream> #include <cstdlib> #include <cstdio> #include <set> #include <vector> #include <dirent.h> #include "SAT.h" using namespace std; const int MAX_LINE_LENGTH = 65536; const int MAX_WORD_LENGTH = 64; //This cnf parser function is based on the GRASP code by Joao Marques Silva void read_cnf(SAT_Manager mng, char * filename ) { // cout <<"read cnf "<<endl; char line_buffer[MAX_LINE_LENGTH]; char word_buffer[MAX_WORD_LENGTH]; set<int> clause_vars; set<int> clause_lits; int line_num = 0; if(opendir(filename)){ cerr << "Can't open input file, it's a directory" << endl; exit(1); } ifstream inp (filename, ios::in); if (!inp) { cerr << "Can't open input file" << endl; exit(1); } while (inp.getline(line_buffer, MAX_LINE_LENGTH)) { ++ line_num; if (line_buffer[0] == 'c') { continue; } else if (line_buffer[0] == 'p') { int var_num; int cl_num; int arg = sscanf (line_buffer, "p cnf %d %d", &var_num, &cl_num); if( arg < 2 ) { cerr << "Unable to read number of variables and clauses" << "at line " << line_num << endl; exit(3); } SAT_SetNumVariables(mng, var_num); //first element not used. } else { // Clause definition or continuation char *lp = line_buffer; do { char *wp = word_buffer; while (*lp && ((*lp == ' ') || (*lp == '\t'))) { lp++; } while (*lp && (*lp != ' ') && (*lp != '\t') && (*lp != '\n')) { *(wp++) = *(lp++); } *wp = '\0'; // terminate string if (strlen(word_buffer) != 0) { // check if number is there int var_idx = atoi (word_buffer); int sign = 0; if( var_idx != 0) { if( var_idx < 0) { var_idx = -var_idx; sign = 1; } clause_vars.insert(var_idx); clause_lits.insert( (var_idx << 1) + sign); } else { //add this clause if (clause_vars.size() != 0 && (clause_vars.size() == clause_lits.size())) { //yeah, can add this clause vector <int> temp; for (set<int>::iterator itr = clause_lits.begin(); itr != clause_lits.end(); ++itr) temp.push_back (*itr); SAT_AddClause(mng, & temp.begin()[0], temp.size() ); } else {} //it contain var of both polarity, so is automatically satisfied, just skip it clause_lits.clear(); clause_vars.clear(); } } } while (*lp); } } if (!inp.eof()) { cerr << "Input line " << line_num << " too long. Unable to continue..." << endl; exit(2); } // assert (clause_vars.size() == 0); //some benchmark has no 0 in the last clause if (clause_lits.size() && clause_vars.size()==clause_lits.size() ) { vector <int> temp; for (set<int>::iterator itr = clause_lits.begin(); itr != clause_lits.end(); ++itr) temp.push_back (*itr); SAT_AddClause(mng, & temp.begin()[0], temp.size() ); } clause_lits.clear(); clause_vars.clear(); // cout <<"done read cnf"<<endl; } void handle_result(SAT_Manager mng, int outcome, char * filename ) { char * result = "UNKNOWN"; FILE *SATRES; switch (outcome) { case SATISFIABLE: cout << "Instance Satisfiable" << endl; //following lines will print out a solution if a solution exist // for (int i=1, sz = SAT_NumVariables(mng); i<= sz; ++i) { // switch(SAT_GetVarAsgnment(mng, i)) { // case -1: // cout <<"("<< i<<")"; break; // case 0: // cout << "-" << i; break; // case 1: // cout << i ; break; // default: // cerr << "Unknown variable value state"<< endl; // exit(4); // } // cout << " "; // } result = "SAT"; if ( (SATRES = fopen( "SATRES", "w" )) == NULL ) { printf("\nSATRES file no se puede write\n\n"); exit( 1 ); } fprintf( SATRES, "1"); fprintf( SATRES, " %d %d %d %.2f", SAT_NumJoergvarset(mng), SAT_MaxDLevel(mng), SAT_NumDecisions(mng), SAT_GetCPUTime(mng)); fclose( SATRES ); break; case UNSATISFIABLE: result = "UNSAT"; cout << "Instance Unsatisfiable" << endl; if ( (SATRES = fopen( "SATRES", "w" )) == NULL ) { printf("\nSATRES file no se puede write\n\n"); exit( 1 ); } fprintf( SATRES, "0"); fprintf( SATRES, " %d %d %d %.2f", SAT_NumJoergvarset(mng), SAT_MaxDLevel(mng), SAT_NumDecisions(mng), SAT_GetCPUTime(mng)); fclose( SATRES ); break; case TIME_OUT: result = "ABORT : TIME OUT"; cout << "Time out, unable to determine the satisfiability of the instance"<<endl; break; case MEM_OUT: result = "ABORT : MEM OUT"; cout << "Memory out, unable to determine the satisfiability of the instance"<<endl; break; default: cerr << "Unknown outcome" << endl; } cout << "Random Seed Used\t\t\t\t" << SAT_Random_Seed(mng) << endl; // added by joerg hoffmann cout << "Num. of vars branched on\t\t\t" << SAT_NumJoergvarset(mng) << endl; cout << "Max Decision Level\t\t\t\t" << SAT_MaxDLevel(mng) << endl; cout << "Num. of Decisions\t\t\t\t" << SAT_NumDecisions(mng)<< endl; cout << "( Stack + Vsids + Shrinking Decisions )\t\t" <<SAT_NumDecisionsStackConf(mng); cout << " + " <<SAT_NumDecisionsVsids(mng)<<" + "<<SAT_NumDecisionsShrinking(mng)<<endl; cout << "Original Num Variables\t\t\t\t" << SAT_NumVariables(mng) << endl; cout << "Original Num Clauses\t\t\t\t" << SAT_InitNumClauses(mng) << endl; cout << "Original Num Literals\t\t\t\t" << SAT_InitNumLiterals(mng) << endl; cout << "Added Conflict Clauses\t\t\t\t" << SAT_NumAddedClauses(mng)- SAT_InitNumClauses(mng)<< endl; cout << "Num of Shrinkings\t\t\t\t" << SAT_NumShrinkings(mng)<< endl; cout << "Deleted Conflict Clauses\t\t\t" << SAT_NumDeletedClauses(mng)-SAT_NumDelOrigCls(mng) <<endl; cout << "Deleted Clauses\t\t\t\t\t" << SAT_NumDeletedClauses(mng) <<endl; cout << "Added Conflict Literals\t\t\t\t" << SAT_NumAddedLiterals(mng) - SAT_InitNumLiterals(mng) << endl; cout << "Deleted (Total) Literals\t\t\t" << SAT_NumDeletedLiterals(mng) <<endl; cout << "Number of Implication\t\t\t\t" << SAT_NumImplications(mng)<< endl; //other statistics comes here cout << "Total Run Time\t\t\t\t\t" << SAT_GetCPUTime(mng) << endl; // cout << "RESULT:\t" << filename << " " << result << " RunTime: " << SAT_GetCPUTime(mng)<< endl; cout << "RESULT:\t"<<result << endl; } void output_status(SAT_Manager mng) { cout << "Dec: " << SAT_NumDecisions(mng)<< "\t "; cout << "AddCl: " << SAT_NumAddedClauses(mng) <<"\t"; cout << "AddLit: " << SAT_NumAddedLiterals(mng)<<"\t"; cout << "DelCl: " << SAT_NumDeletedClauses(mng) <<"\t"; cout << "DelLit: " << SAT_NumDeletedLiterals(mng)<<"\t"; cout << "NumImp: " << SAT_NumImplications(mng) <<"\t"; cout << "AveBubbleMove: " << SAT_AverageBubbleMove(mng) <<"\t"; //other statistics comes here cout << "RunTime:" << SAT_GetElapsedCPUTime(mng) << endl; } void verify_solution(SAT_Manager mng) { int num_verified = 0; for ( int cl_idx = SAT_GetFirstClause (mng); cl_idx >= 0; cl_idx = SAT_GetNextClause(mng, cl_idx)) { int len = SAT_GetClauseNumLits(mng, cl_idx); int * lits = new int[len+1]; SAT_GetClauseLits( mng, cl_idx, lits); int i; for (i=0; i< len; ++i) { int v_idx = lits[i] >> 1; int sign = lits[i] & 0x1; int var_value = SAT_GetVarAsgnment( mng, v_idx); if( (var_value == 1 && sign == 0) || (var_value == 0 && sign == 1) ) break; } if (i >= len) { cerr << "Verify Satisfiable solution failed, please file a bug report, thanks. " << endl; exit(6); } delete [] lits; ++ num_verified; } cout <<"c "<< num_verified << " Clauses are true, Verify Solution successful."<<endl;; } int main(int argc, char ** argv) { SAT_Manager mng = SAT_InitManager(); if (argc < 2) { cerr << "Z-Chaff: Accelerated SAT Solver from Princeton. " << endl; cerr << "Copyright 2000-2004, Princeton University." << endl << endl;; cerr << "Usage: "<< argv[0] << " cnf_file [time_limit]" << endl; return 2; } cout << "Z-Chaff Version: " << SAT_Version(mng) << endl; cout << "Solving " << argv[1] << " ......" << endl; if (argc == 2) { read_cnf (mng, argv[1] ); } else { read_cnf (mng, argv[1] ); SAT_SetTimeLimit(mng, atoi(argv[2])); } /* if you want some statistics during the solving, uncomment following line */ // SAT_AddHookFun(mng,output_status, 5000); /* you can set all your parameters here, following values are the defaults*/ // SAT_SetMaxUnrelevance(mng, 20); // SAT_SetMinClsLenForDelete(mng, 100); // SAT_SetMaxConfClsLenAllowed(mng, 5000); /* randomness may help sometimes, by default, there is no randomness */ // SAT_SetRandomness (mng, 10); // SAT_SetRandSeed (mng, -1); int result = SAT_Solve(mng); if (result == SATISFIABLE) verify_solution(mng); handle_result (mng, result, argv[1]); return 0; }
[ "jose@volker.(none)" ]
jose@volker.(none)
bceef227862b6f6446f2c84ff975e60d46f2921b
db00f801f91c0e5f0937b37981fcdf9bdf5463da
/src/sync.cpp
64c4ec5a6e8531ce0382dbd91b947cda11d9aaf9
[ "MIT" ]
permissive
kitkatty/bitcoinrandom
bb3aef4fb008c85d2b2eba78912f0212ed294518
290e9e5c48f12b89147cf59220449ce92e2ab892
refs/heads/master
2020-03-20T12:22:19.282998
2018-06-24T18:33:52
2018-06-24T18:33:52
137,427,908
3
0
null
null
null
null
UTF-8
C++
false
false
5,591
cpp
// Copyright (c) 2011-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sync.h" #include "util.h" #include "utilstrencodings.h" #include <stdio.h> #include <boost/thread.hpp> #ifdef DEBUG_LOCKCONTENTION void PrintLockContention(const char* pszName, const char* pszFile, int nLine) { LogPrintf("LOCKCONTENTION: %s\n", pszName); LogPrintf("Locker: %s:%d\n", pszFile, nLine); } #endif /* DEBUG_LOCKCONTENTION */ #ifdef DEBUG_LOCKORDER // // Early deadlock detection. // Problem being solved: // Thread 1 locks A, then B, then C // Thread 2 locks D, then C, then A // --> may result in deadlock between the two threads, depending on when they run. // Solution implemented here: // Keep track of pairs of locks: (A before B), (A before C), etc. // Complain if any thread tries to lock in a different order. // struct CLockLocation { CLockLocation(const char* pszName, const char* pszFile, int nLine, bool fTryIn) { mutexName = pszName; sourceFile = pszFile; sourceLine = nLine; fTry = fTryIn; } std::string ToString() const { return mutexName + " " + sourceFile + ":" + itostr(sourceLine) + (fTry ? " (TRY)" : ""); } bool fTry; private: std::string mutexName; std::string sourceFile; int sourceLine; }; typedef std::vector<std::pair<void*, CLockLocation>> LockStack; typedef std::map<std::pair<void*, void*>, LockStack> LockOrders; typedef std::set<std::pair<void*, void*>> InvLockOrders; struct LockData { // Very ugly hack: as the global constructs and destructors run single // threaded, we use this boolean to know whether LockData still exists, // as DeleteLock can get called by global CCriticalSection destructors // after LockData disappears. bool available; LockData() : available(true) {} ~LockData() { available = false; } LockOrders lockorders; InvLockOrders invlockorders; boost::mutex dd_mutex; } static lockdata; boost::thread_specific_ptr<LockStack> lockstack; static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2) { LogPrintf("POTENTIAL DEADLOCK DETECTED\n"); LogPrintf("Previous lock order was:\n"); for (const std::pair<void*, CLockLocation>& i : s2) { if (i.first == mismatch.first) { LogPrintf(" (1)"); } if (i.first == mismatch.second) { LogPrintf(" (2)"); } LogPrintf(" %s\n", i.second.ToString()); } LogPrintf("Current lock order is:\n"); for (const std::pair<void*, CLockLocation>& i : s1) { if (i.first == mismatch.first) { LogPrintf(" (1)"); } if (i.first == mismatch.second) { LogPrintf(" (2)"); } LogPrintf(" %s\n", i.second.ToString()); } assert(false); } static void push_lock(void* c, const CLockLocation& locklocation, bool fTry) { if (lockstack.get() == nullptr) lockstack.reset(new LockStack); boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex); (*lockstack).push_back(std::make_pair(c, locklocation)); for (const std::pair<void*, CLockLocation>& i : (*lockstack)) { if (i.first == c) break; std::pair<void*, void*> p1 = std::make_pair(i.first, c); if (lockdata.lockorders.count(p1)) continue; lockdata.lockorders[p1] = (*lockstack); std::pair<void*, void*> p2 = std::make_pair(c, i.first); lockdata.invlockorders.insert(p2); if (lockdata.lockorders.count(p2)) potential_deadlock_detected(p1, lockdata.lockorders[p2], lockdata.lockorders[p1]); } } static void pop_lock() { (*lockstack).pop_back(); } void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry) { push_lock(cs, CLockLocation(pszName, pszFile, nLine, fTry), fTry); } void LeaveCritical() { pop_lock(); } std::string LocksHeld() { std::string result; for (const std::pair<void*, CLockLocation>& i : *lockstack) result += i.second.ToString() + std::string("\n"); return result; } void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) { for (const std::pair<void*, CLockLocation>& i : *lockstack) if (i.first == cs) return; fprintf(stderr, "Assertion failed: lock %s not held in %s:%i; locks held:\n%s", pszName, pszFile, nLine, LocksHeld().c_str()); abort(); } void DeleteLock(void* cs) { if (!lockdata.available) { // We're already shutting down. return; } boost::unique_lock<boost::mutex> lock(lockdata.dd_mutex); std::pair<void*, void*> item = std::make_pair(cs, (void*)0); LockOrders::iterator it = lockdata.lockorders.lower_bound(item); while (it != lockdata.lockorders.end() && it->first.first == cs) { std::pair<void*, void*> invitem = std::make_pair(it->first.second, it->first.first); lockdata.invlockorders.erase(invitem); lockdata.lockorders.erase(it++); } InvLockOrders::iterator invit = lockdata.invlockorders.lower_bound(item); while (invit != lockdata.invlockorders.end() && invit->first == cs) { std::pair<void*, void*> invinvitem = std::make_pair(invit->second, invit->first); lockdata.lockorders.erase(invinvitem); lockdata.invlockorders.erase(invit++); } } #endif /* DEBUG_LOCKORDER */
[ "34012208+kitkatty@users.noreply.github.com" ]
34012208+kitkatty@users.noreply.github.com
343b1adb8f3f97a07e8c6846bf98c3f601ec7806
f27ff2a8f371add47db997a181236dff8a9f9456
/powerset.hpp
f7072761383ee4803e3f5c7dc78e4f3a22f90183
[]
no_license
netanel208/Itertools
4df699ce0f1e28642ebba16df8aced1646a0d715
c72bd1932141f279d1c299aeb877bb1320bb3b9d
refs/heads/master
2020-05-20T11:53:43.455744
2019-05-23T12:37:11
2019-05-23T12:37:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,755
hpp
#pragma once #include "product.hpp" #include <set> #include <math.h> namespace itertools{ template<typename T> class powerset{ T container; uint size; public: powerset<T>(const T container): container(container) { int _size=0; for (auto element : container) _size++; size = _size; } class const_iterator { T power_set; uint bin_set; public: const_iterator(T power_set, int index): power_set(power_set), bin_set(index) {} auto operator*() const { std::set<typename std::remove_reference<typename std::remove_const<decltype(*(container.begin()))>::type>::type> tmp_set; int i=1; for (auto element : power_set){ if (i & bin_set) tmp_set.insert(element); i=i<<1; } return tmp_set; } const_iterator& operator++() { ++bin_set; return *this; } bool operator!=(const const_iterator& rhs) const { return (this->bin_set != rhs.bin_set); } template <typename U> friend std::ostream& operator <<(std::ostream& os, const typename powerset<U>::const_iterator& it); }; // END CLASS - const_iterator auto begin() const { return powerset<T>::const_iterator(container, 0); } auto end() const { return powerset<T>::const_iterator(container, int(pow(2,size))); } }; // END CLASS - powerset template <typename U> std::ostream& operator <<(std::ostream& os, const typename powerset<U>::const_iterator& it) { return os << *it; } template <typename U> std::ostream& operator <<(std::ostream& os, const typename std::set<U> tmp_set) { os << "{"; for (auto element : tmp_set){ os << element << ","; } if (tmp_set.size()) os.seekp(-1, os.cur); os << "}"; return os; } }
[ "orez132@gmail.com" ]
orez132@gmail.com
541aa30691cfa498cc720e07b4691d56c708b57e
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-lexv2-models/include/aws/lexv2-models/model/IntentSortAttribute.h
159e85a8248d11da5557f77e3226bbecec79a645
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
722
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/lexv2-models/LexModelsV2_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace LexModelsV2 { namespace Model { enum class IntentSortAttribute { NOT_SET, IntentName, LastUpdatedDateTime }; namespace IntentSortAttributeMapper { AWS_LEXMODELSV2_API IntentSortAttribute GetIntentSortAttributeForName(const Aws::String& name); AWS_LEXMODELSV2_API Aws::String GetNameForIntentSortAttribute(IntentSortAttribute value); } // namespace IntentSortAttributeMapper } // namespace Model } // namespace LexModelsV2 } // namespace Aws
[ "sdavtaker@users.noreply.github.com" ]
sdavtaker@users.noreply.github.com
13a391bdec878330bb120800995fe4297b6dc405
d1a4de3f9c6eb9585c2dd37de769f7ae6fd3a6dd
/source/canvas/framebuffer/FrameBufferGUI.cpp
b053d15a5a303b10d282851ab5f5238208572acb
[ "MIT" ]
permissive
RobertDamerius/CKeys
38f60114ec71709d67b529d197aa634145e02883
3a861e033abee595472770e85acba47b17f37bf8
refs/heads/master
2023-03-20T11:58:44.685210
2021-03-09T20:06:12
2021-03-09T20:06:12
271,225,926
3
0
null
null
null
null
UTF-8
C++
false
false
2,213
cpp
#include <FrameBufferGUI.hpp> FrameBufferGUI::FrameBufferGUI(){ this->cbo = 0; this->rbo = 0; this->fbo = 0; } bool FrameBufferGUI::Generate(GLint width, GLint height, GLenum textureUnitGUI){ Delete(); DEBUG_GLCHECK( glGenFramebuffers(1, &this->fbo); ); DEBUG_GLCHECK( glBindFramebuffer(GL_FRAMEBUFFER, this->fbo); ); // Colorbuffer DEBUG_GLCHECK( glGenTextures(1, &this->cbo); ); DEBUG_GLCHECK( glActiveTexture(textureUnitGUI); ); DEBUG_GLCHECK( glBindTexture(GL_TEXTURE_2D, this->cbo); ); DEBUG_GLCHECK( glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); ); DEBUG_GLCHECK( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); ); DEBUG_GLCHECK( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); ); DEBUG_GLCHECK( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); ); DEBUG_GLCHECK( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); ); DEBUG_GLCHECK( glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->cbo, 0); ); // Rendering buffer for depth DEBUG_GLCHECK( glGenRenderbuffers(1, &this->rbo); ); DEBUG_GLCHECK( glBindRenderbuffer(GL_RENDERBUFFER, this->rbo); ); DEBUG_GLCHECK( glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); ); DEBUG_GLCHECK( glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, this->rbo); ); // Check for completeness if(GL_FRAMEBUFFER_COMPLETE != glCheckFramebufferStatus(GL_FRAMEBUFFER)){ Delete(); return false; } DEBUG_GLCHECK( glBindFramebuffer(GL_FRAMEBUFFER, 0); ); return true; } void FrameBufferGUI::Delete(void){ // Delete colorbuffers if(this->cbo){ glDeleteTextures(1, &this->cbo); this->cbo = 0; } // Delete renderbuffer if(this->rbo){ glDeleteRenderbuffers(1, &this->rbo); this->rbo = 0; } // Delete framebuffer if(this->fbo){ glDeleteFramebuffers(1, &this->fbo); this->fbo = 0; } }
[ "damerius.mail@gmail.com" ]
damerius.mail@gmail.com
411c437f31772a521339ae96d97e192a991a4344
fce4cef1b6c4b40bd3a8048bc28b393d4c37f432
/Quellcode/src/blowfishcrypt.h
7166502d8b273fc664849cdd907451c08db508ad
[]
no_license
test-eban/it_s_2020
672fe22787b364688533879042daf4763869850a
b3efe0e32e1f28769599e2edc758177a41e0889b
refs/heads/master
2022-04-11T07:49:57.753949
2020-03-05T20:37:55
2020-03-05T20:37:55
233,927,283
0
0
null
null
null
null
UTF-8
C++
false
false
1,819
h
#ifndef BLOWFISH_H #define BLOWFISH_H #include "cryptclassbase.h" #include "utility.h" #include <openssl/blowfish.h> /** * @brief This class provides everything that is necessary to encrypt/decrypt the contents of a given QByteArray with the Blowfish cipher. * The Blowfish cipher is a symmetric-key block cipher. * @extends CryptClassBase * @see https://en.wikipedia.org/wiki/Blowfish_(cipher) * @see https://www.openssl.org/docs/man1.0.2/man3/blowfish.html * @author S. Laddach */ class SYMMETRICCIPHERS_EXPORT BlowfishCrypt: public CryptClassBase { public: /** * @brief default constructor. */ BlowfishCrypt() = default; /** * @brief This method is used to encrypt the contents of the given QByteArray with the Blowfish cipher. * @param clear QByteArray that contains the content that is going to be encrypted. * @return a QByteArray containing the encrypted content */ QByteArray* encrypt(QByteArray* clear) override; /** * @brief This method is used to decrypt the contents of the given QByteArray with the Blowfish cipher. * @param crypt QByteArray that contains the content that is going to be decrypted. * @return a QByteArray containing the encrypted content */ QByteArray* decrypt(QByteArray* crypt) override; /** * @brief setter for m_key1. Overwrites the baseclass setter because more logic is necessary. * @param new value for m_key1 */ void setKey1(QByteArray *key) override; /** * @brief setter for iv. Overwrites the baseclass setter because more logic is necessary. * @param new value for iv */ void setIv (QByteArray *iv) override; private: /** * @brief Blowfish (openssl) specific key-object. */ BF_KEY m_bfKey; }; #endif // BLOWFISH_H
[ "admin@testeban.de" ]
admin@testeban.de