blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 955
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 143
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 121
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
757766d5b9534a8341b7e39db49c029319f6bd2b | c78f931e0a7298b20f722b6351bb8b2566ec462b | /Centyry from year.cpp | 7083f588cb751c5ce7335f3457914027b569a925 | [] | no_license | tdutybqs/Practice | e37d125609c9b0d50ebc430e926a155814458675 | 8cdbac7080be9e6529d379fe98e919d91add215f | refs/heads/main | 2023-07-20T14:28:28.652383 | 2021-08-31T09:08:49 | 2021-08-31T09:08:49 | 381,703,801 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 442 | cpp | /*
Introduction
The first century spans from the year 1 up to and including the year 100, The second - from the year 101 up to and including the year 200, etc.
Task :
Given a year, return the century it is in.
Input , Output Examples :
1705 --> 18
1900 --> 19
1601 --> 17
2000 --> 20
Hope you enjoy it .. Awaiting for Best Practice Codes
Enjoy Learning !!!
*/
int centuryFromYear(int year) {
return year / 100 + int(year % 100 != 0);
}
| [
"[email protected]"
] | |
06cfb9ca96a61137a348fc2045f8693d23f03832 | d160bb839227b14bb25e6b1b70c8dffb8d270274 | /MCMS/Main/Processes/Resource/ResourceLib/ConfResources.cpp | 6a1729f5225cd051689ecd1184f8de8e5b900429 | [] | no_license | somesh-ballia/mcms | 62a58baffee123a2af427b21fa7979beb1e39dd3 | 41aaa87d5f3b38bc186749861140fef464ddadd4 | refs/heads/master | 2020-12-02T22:04:46.442309 | 2017-07-03T06:02:21 | 2017-07-03T06:02:21 | 96,075,113 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,433 | cpp | #include "ConfResources.h"
#include "StatusesGeneral.h"
#include "ProcessBase.h"
#include "TraceStream.h"
#include "ResourceManager.h"
#include "WrappersResource.h"
#include "HelperFuncs.h"
#include "VideoApiDefinitionsStrings.h"
#include <algorithm>
#include <functional>
////////////////////////////////////////////////////////////////////////////
// CUdpRsrcDesc
////////////////////////////////////////////////////////////////////////////
CUdpRsrcDesc::CUdpRsrcDesc(WORD rsrcPartyId, WORD servId, WORD subServId, WORD PQMid)
{
m_rsrcPartyId = rsrcPartyId;
m_servId = servId;
m_PQMid = PQMid;
m_subServId = subServId;
memset(&m_udp, 0, sizeof(UdpAddresses));
for (int i = 0; i < MAX_NUM_OF_ALLOCATED_PARTY_UDP_PORTS; i++)
{
m_rtp_channels[i] = 0;
m_rtcp_channels[i] = 0;
}
}
////////////////////////////////////////////////////////////////////////////
CUdpRsrcDesc::~CUdpRsrcDesc()
{
}
////////////////////////////////////////////////////////////////////////////
bool operator==(const CUdpRsrcDesc& lhs,const CUdpRsrcDesc& rhs)
{
return ((lhs.m_rsrcPartyId == rhs.m_rsrcPartyId) && (lhs.m_type == rhs.m_type ));
}
////////////////////////////////////////////////////////////////////////////
bool operator<(const CUdpRsrcDesc& lhs,const CUdpRsrcDesc& rhs)
{
if (lhs.m_rsrcPartyId != rhs.m_rsrcPartyId)
return (lhs.m_rsrcPartyId < rhs.m_rsrcPartyId);
return (lhs.m_type < rhs.m_type);
}
////////////////////////////////////////////////////////////////////////////
void CUdpRsrcDesc::SetIpAddresses(ipAddressV4If ipAddressV4, const ipv6AddressArray& ipAddressV6)
{
CIPV4Wrapper v4wrapper(m_udp.IpV4Addr);
v4wrapper.CopyData(ipAddressV4);
CIPV6AraryWrapper v6wrapper(m_udp.IpV6AddrArray);
v6wrapper.CopyData(ipAddressV6);
}
////////////////////////////////////////////////////////////////////////////
// CRsrcDesc
////////////////////////////////////////////////////////////////////////////
CRsrcDesc::CRsrcDesc(DWORD connectionId, eLogicalResourceTypes type, DWORD rsrcConfId, WORD rsrcPartyId,
WORD boxId , WORD bId, WORD subBid, WORD uid, WORD acceleratorId, WORD firstPortId, ECntrlType cntrl,
WORD channelId, BOOL bIsUpdated /*= FALSE*/ )
{
m_connectionId = connectionId;
m_type = type;
m_rsrcConfId = rsrcConfId;
m_rsrcPartyId = rsrcPartyId;
m_boxId = boxId;
m_boardId = bId;
m_subBoardId = subBid;
m_unitId = uid;
m_acceleratorId = acceleratorId;
m_firstPortId = firstPortId;
m_numPorts = 1;
m_cntrl = cntrl;
m_channelId = channelId;
m_bIsUpdated = bIsUpdated;
memset(&m_IpV4Addr, 0, sizeof(m_IpV4Addr));
}
////////////////////////////////////////////////////////////////////////////
CRsrcDesc::~CRsrcDesc()
{
}
////////////////////////////////////////////////////////////////////////////
bool operator==(const CRsrcDesc& lhs,const CRsrcDesc& rhs)
{
//net ports can be the same except for the board, portid, unit_id (=span id) and accelerator_id, so check this
if (lhs.m_type == eLogical_net && rhs.m_type == eLogical_net)
if (lhs.m_firstPortId != rhs.m_firstPortId || lhs.m_unitId != rhs.m_unitId || lhs.m_acceleratorId != rhs.m_acceleratorId || lhs.m_boardId != rhs.m_boardId)
return FALSE;
return ((lhs.m_rsrcPartyId == rhs.m_rsrcPartyId) &&
(lhs.m_type == rhs.m_type ) && (lhs.m_cntrl == rhs.m_cntrl));
}
////////////////////////////////////////////////////////////////////////////
bool operator<(const CRsrcDesc& lhs,const CRsrcDesc& rhs)
{
if (lhs.m_rsrcPartyId != rhs.m_rsrcPartyId)
return (lhs.m_rsrcPartyId < rhs.m_rsrcPartyId);
else if (lhs.m_type != rhs.m_type)
return (lhs.m_type < rhs.m_type);
else if (lhs.m_type != eLogical_net)
return (lhs.m_cntrl < rhs.m_cntrl);
else //if it's net type
{
if (lhs.m_firstPortId != rhs.m_firstPortId)
return (lhs.m_firstPortId < rhs.m_firstPortId);
else if (lhs.m_acceleratorId != rhs.m_acceleratorId)
return (lhs.m_acceleratorId < rhs.m_acceleratorId);
else if (lhs.m_unitId != rhs.m_unitId)
return (lhs.m_unitId < rhs.m_unitId);
else
return (lhs.m_boardId < rhs.m_boardId);
}
}
////////////////////////////////////////////////////////////////////////////
void CRsrcDesc::SetIpAddresses(ipAddressV4If ipAddressV4)
{
CIPV4Wrapper v4wrapper(m_IpV4Addr);
v4wrapper.CopyData(ipAddressV4);
}
////////////////////////////////////////////////////////////////////////////
eResourceTypes CRsrcDesc::GetPhysicalType() const
{
switch (m_type)
{
case eLogical_audio_encoder:
return ePhysical_art;
case eLogical_audio_decoder:
return ePhysical_art;
case eLogical_audio_controller:
return ePhysical_audio_controller;
case eLogical_video_encoder:
case eLogical_video_encoder_content:
case eLogical_COP_CIF_encoder:
case eLogical_COP_VSW_encoder:
case eLogical_COP_PCM_encoder:
case eLogical_COP_HD720_encoder:
case eLogical_COP_HD1080_encoder:
case eLogical_COP_4CIF_encoder:
return ePhysical_video_encoder;
case eLogical_video_decoder:
case eLogical_COP_Dynamic_decoder:
case eLogical_COP_VSW_decoder:
case eLogical_COP_LM_decoder:
return ePhysical_video_decoder;
case eLogical_rtp:
return ePhysical_art;
/*Not in use for now
case eLogical_ip_signaling:
return ePhysical_res_none;
*/
case eLogical_net:
return ePhysical_rtm;
case eLogical_ivr_controller:
return ePhysical_ivr_controller;
case eLogical_mux:
return ePhysical_art;
// OLGA - Soft MCU
case eLogical_relay_rtp:
case eLogical_relay_svc_to_avc_rtp:
case eLogical_relay_video_encoder:
return ePhysical_mrmp;
case eLogical_relay_audio_encoder:
case eLogical_relay_audio_decoder:
case eLogical_legacy_to_SAC_audio_encoder:
case eLogical_relay_avc_to_svc_rtp:
case eLogical_relay_avc_to_svc_rtp_with_audio_encoder:
return ePhysical_art;
case eLogical_relay_avc_to_svc_video_encoder_1:
case eLogical_relay_avc_to_svc_video_encoder_2:
return ePhysical_video_encoder;
default:
return ePhysical_res_none;
}
}
////////////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& os, CRsrcDesc& obj)
{
os
<< "\n ConnectionId :" << obj.m_connectionId
<< "\n ResourceType :" << obj.m_type
<< "\n ConfId :" << obj.m_rsrcConfId
<< "\n PartyId :" << obj.m_rsrcPartyId
<< "\n BoxId :" << obj.m_boxId
<< "\n BoardId :" << obj.m_boardId
<< "\n SubBoardId :" << obj.m_subBoardId
<< "\n UnitId :" << obj.m_unitId
<< "\n AcceleratorId :" << obj.m_acceleratorId
<< "\n FirstPortId :" << obj.m_firstPortId;
return os;
}
////////////////////////////////////////////////////////////////////////////
// CConfRsrc
////////////////////////////////////////////////////////////////////////////
CConfRsrc::CConfRsrc(DWORD monitorConfId, eSessionType sessionType, eLogicalResourceTypes encoderLogicalType, eConfMediaType confMediaType)
{
m_monitorConfId = monitorConfId;
m_sessionType = sessionType;
m_rsrcConfId = 0; //0 - not allocated.
m_num_Parties = 0;
m_pUdpRsrcDescList = new std::set<CUdpRsrcDesc>;
m_encoderTypeCOP = encoderLogicalType;
m_confMediaState = eMediaStateEmpty;
m_confMediaType = confMediaType;
m_mrcMcuId = 1;
}
////////////////////////////////////////////////////////////////////////////
CConfRsrc::CConfRsrc(const CConfRsrc& other) : CPObject(other), m_pUdpRsrcDescList(new std::set<CUdpRsrcDesc>(*(other.m_pUdpRsrcDescList)))
{
m_monitorConfId = other.m_monitorConfId;
m_sessionType = other.m_sessionType;
m_bondingPhones = other.m_bondingPhones;
m_parties = other.m_parties;
m_rsrcConfId = other.m_rsrcConfId; //0 - not allocated.
m_num_Parties = other.m_num_Parties;
m_encoderTypeCOP = other.m_encoderTypeCOP;
m_confMediaState = other.m_confMediaState;
m_confMediaType = other.m_confMediaType;
m_mrcMcuId = other.m_mrcMcuId;
m_pRsrcDescList = other.m_pRsrcDescList;
}
////////////////////////////////////////////////////////////////////////////
CConfRsrc::~CConfRsrc()
{
m_pUdpRsrcDescList->clear();
PDELETE( m_pUdpRsrcDescList);
m_pUdpRsrcDescList = 0 ;
}
////////////////////////////////////////////////////////////////////////////
WORD operator==(const CConfRsrc& lhs,const CConfRsrc& rhs)
{
return (lhs.m_monitorConfId == rhs.m_monitorConfId);
}
////////////////////////////////////////////////////////////////////////////
bool operator<(const CConfRsrc& lhs,const CConfRsrc& rhs)
{
return (lhs.m_monitorConfId < rhs.m_monitorConfId);
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::AddUdpDesc(CUdpRsrcDesc* pUdpRsrcDesc)
{
PASSERT_AND_RETURN_VALUE(!pUdpRsrcDesc, STATUS_FAIL);
std::set<CUdpRsrcDesc>::iterator _itr = m_pUdpRsrcDescList->find(*pUdpRsrcDesc);
PASSERT_AND_RETURN_VALUE(_itr != m_pUdpRsrcDescList->end(), STATUS_FAIL);
m_pUdpRsrcDescList->insert(*pUdpRsrcDesc);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
// The function only updates existing desc, not adding new one, if not found
STATUS CConfRsrc::UpdateUdpDesc(WORD rsrcpartyId, CUdpRsrcDesc* pUdpRsrcDesc)
{
PASSERT_AND_RETURN_VALUE(!pUdpRsrcDesc, STATUS_FAIL);
CUdpRsrcDesc desc(rsrcpartyId);
std::set<CUdpRsrcDesc>::iterator _itr = m_pUdpRsrcDescList->find(desc);
PASSERT_AND_RETURN_VALUE(_itr == m_pUdpRsrcDescList->end(), STATUS_FAIL);
m_pUdpRsrcDescList->erase(_itr);
m_pUdpRsrcDescList->insert(*pUdpRsrcDesc);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::RemoveUdpDesc(WORD rsrcpartyId)
{
std::set<CUdpRsrcDesc>::iterator i;
CUdpRsrcDesc desc(rsrcpartyId);
i = m_pUdpRsrcDescList->find(desc);
if (i == m_pUdpRsrcDescList->end())//not exists
{
PASSERT(1);
return STATUS_FAIL;
}
m_pUdpRsrcDescList->erase(i);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
const CUdpRsrcDesc* CConfRsrc::GetUdpDesc(WORD rsrcpartyId)const
{
std::set<CUdpRsrcDesc>::iterator i;
CUdpRsrcDesc desc(rsrcpartyId);
i = m_pUdpRsrcDescList->find(desc);
if (i == m_pUdpRsrcDescList->end())//not exists
{
PASSERT(1);
return NULL;
}
return (&(*i));
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::AddDesc(CRsrcDesc* pRsrcDesc)
{
if (!pRsrcDesc || pRsrcDesc->GetRsrcConfId() != m_rsrcConfId)
{
DBGPASSERT(1);
if (pRsrcDesc)
TRACEINTOLVLERR << "ERROR: m_rsrcConfId = " << m_rsrcConfId << ", GetRsrcConfId()=" << pRsrcDesc->GetRsrcConfId();
return STATUS_FAIL;
}
if (m_pRsrcDescList.find(*pRsrcDesc) != m_pRsrcDescList.end())
{//desc already exists
TRACEINTOLVLERR << "Failed, descriptor already exists" << *pRsrcDesc;
PASSERT_AND_RETURN_VALUE(1, STATUS_FAIL);
}
m_pRsrcDescList.insert(*pRsrcDesc);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::RemoveDesc(WORD rsrcpartyId, eLogicalResourceTypes type, ECntrlType cntrl, WORD portId, WORD unitId, WORD acceleratorId, WORD boardId)
{
CRsrcDesc desc(0, type, 0, rsrcpartyId, 0, boardId, 0, unitId, acceleratorId, portId, cntrl);
RSRC_DESC_MULTISET_ITR itr = m_pRsrcDescList.find(desc);
if (itr == m_pRsrcDescList.end()) // not exists
{
TRACEINTOLVLERR << "Failed, descriptor not exist" << desc;
PASSERT_AND_RETURN_VALUE(1, STATUS_FAIL);
}
m_pRsrcDescList.erase(itr);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
CRsrcDesc* CConfRsrc::GetDescFromConnectionId(DWORD connectionId)
{
RSRC_DESC_MULTISET_ITR itr;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if ((itr->GetConnId() == connectionId))
{
return ((CRsrcDesc*)(&(*itr)));
}
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////
const CRsrcDesc* CConfRsrc::GetDesc(WORD rsrcpartyId, eLogicalResourceTypes type, ECntrlType cntrl, WORD portId, WORD unitId, WORD acceleratorId, WORD boardId)
{
CRsrcDesc desc(0, type, 0, rsrcpartyId, 0, boardId, 0, unitId, acceleratorId, portId, cntrl);
RSRC_DESC_MULTISET_ITR i = m_pRsrcDescList.find(desc);
if (i == m_pRsrcDescList.end()) // not exists
{
// PASSERT(1);
return NULL;
}
return (&(*i));
}
////////////////////////////////////////////////////////////////////////////
const CRsrcDesc* CConfRsrc::GetDescByType(eLogicalResourceTypes type, ECntrlType cntrl)
{
RSRC_DESC_MULTISET_ITR itr;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if (itr->GetType() == type && itr->GetCntrlType() == cntrl)
{
return ((CRsrcDesc*)(&(*itr)));
}
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////
int CConfRsrc::GetDescArray( CRsrcDesc**& pRsrcDescArray)
{
int arrSize = m_pRsrcDescList.size();
if( 0 == arrSize )
return 0;
pRsrcDescArray = new CRsrcDesc*[arrSize];
RSRC_DESC_MULTISET_ITR itr;
int i = 0;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
pRsrcDescArray[i] = (CRsrcDesc*)&(*itr);
i++;
}
return i;
}
////////////////////////////////////////////////////////////////////////////
// Need to receive in pRsrcDescList memory of MAX_NUM_ALLOCATED_RSRCS_NET pointers (CRsrcDesc*) allocated for the output (and initialized to all NULLs)
// Returns number of RsrcDescs found.
WORD CConfRsrc::GetDescArrayPerResourceTypeByRsrcId(WORD rsrcpartyId,eLogicalResourceTypes type, CRsrcDesc** pRsrcDescArray, BYTE arrSize) const
{
RSRC_DESC_MULTISET_ITR itr;
int i = 0;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if ((itr->GetRsrcPartyId() == rsrcpartyId ) && ( (itr->GetType() == type) || (eLogical_res_none == type)))
{
if (i < arrSize) // For protection
{
pRsrcDescArray[i] = (CRsrcDesc*)&(*itr);
i++;
}
else
PASSERTMSG(1, "CConfRsrc::GetDescArrayPerResourceTypeByRsrcId - error in call to function");
}
}
return i;
}
////////////////////////////////////////////////////////////////////////////
const CPartyRsrc* CConfRsrc::GetPartyRsrcByRsrcPartyId(PartyRsrcID partyId) const
{
PARTIES::iterator _iiEnd = m_parties.end();
for (PARTIES::iterator _ii = m_parties.begin(); _ii != _iiEnd; ++_ii)
{
if (_ii->GetRsrcPartyId() == partyId)
return &(*_ii);
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////
WORD CConfRsrc::GetNumVideoPartiesPerBoard(WORD boardId)
{
WORD numVideoParties = 0;
PARTIES::iterator _iiEnd = m_parties.end();
for (PARTIES::iterator _ii = m_parties.begin(); _ii != _iiEnd; ++_ii)
{
PartyRsrcID partyId = _ii->GetRsrcPartyId();
CPartyRsrc* pParty = const_cast<CPartyRsrc*>(GetPartyRsrcByRsrcPartyId(partyId));
if (pParty)
{
eVideoPartyType videoPartyType = pParty->GetVideoPartyType();
if (eVideo_party_type_none != videoPartyType)
{
CRsrcDesc* pDecDesc = const_cast<CRsrcDesc*>(GetDesc(partyId, eLogical_video_decoder));
if (pDecDesc)
{
if (boardId == pDecDesc->GetBoardId())
numVideoParties++;
}
}
}
}
return numVideoParties;
}
////////////////////////////////////////////////////////////////////////////
// CPartyRsrc
////////////////////////////////////////////////////////////////////////////
CPartyRsrc::CPartyRsrc(PartyMonitorID monitorPartyId, eNetworkPartyType networkPartyType, eVideoPartyType videoPartyType, WORD ARTChannels, ePartyRole partyRole,eHdVswTypesInMixAvcSvc hdVswTypeInMixAvcSvcMode)
{
m_monitorPartyId = monitorPartyId;
m_networkPartyType = networkPartyType;
m_videoPartyType = videoPartyType;
m_resourcePartyType = e_Audio;
m_partyRole = partyRole;
m_rsrcPartyId = 0; //0 - not allocated.
m_CSconnId = 0;
#ifdef MS_LYNC_AVMCU_LINK
// MS Lync
m_partySigOrganizerConnId = 0;
m_partySigFocusConnId = 0;
m_partySigEventPackConnId = 0;
#endif
m_DialInReservedPorts = 0;
m_ARTChannels = ARTChannels;
m_roomPartyId = 0; //TIP Cisco
m_tipPartyType = eTipNone;
m_countPartyAsICEinMFW = FALSE;
m_ssrcAudio = 0;
m_tipNumOfScreens = 0;
m_HdVswTypeInMixAvcSvcMode = hdVswTypeInMixAvcSvcMode;
memset(m_ssrcContent, 0, sizeof(m_ssrcContent));
memset(m_ssrcVideo, 0, sizeof(m_ssrcVideo));
}
////////////////////////////////////////////////////////////////////////////
CPartyRsrc::CPartyRsrc(const CPartyRsrc& other) : CPObject(other),
m_monitorPartyId(other.m_monitorPartyId),
m_rsrcPartyId(other.m_rsrcPartyId),
m_roomPartyId(other.m_roomPartyId),
m_tipPartyType(other.m_tipPartyType),
m_tipNumOfScreens(other.m_tipNumOfScreens),
m_networkPartyType(other.m_networkPartyType),
m_videoPartyType(other.m_videoPartyType),
m_resourcePartyType(other.m_resourcePartyType),
m_partyRole(other.m_partyRole),
m_ARTChannels(other.m_ARTChannels),
m_CSconnId(other.m_CSconnId),
#ifdef MS_LYNC_AVMCU_LINK
// MS Lync
m_partySigOrganizerConnId(other.m_partySigOrganizerConnId),
m_partySigFocusConnId(other.m_partySigFocusConnId),
m_partySigEventPackConnId(other.m_partySigEventPackConnId),
#endif
m_DialInReservedPorts(other.m_DialInReservedPorts),
m_countPartyAsICEinMFW(other.m_countPartyAsICEinMFW),
m_HdVswTypeInMixAvcSvcMode(other.m_HdVswTypeInMixAvcSvcMode)
{
m_ssrcAudio = other.m_ssrcAudio;
for(WORD i=0;i<MAX_NUM_RECV_STREAMS_FOR_CONTENT;i++)
m_ssrcContent[i] = other.m_ssrcContent[i];
for(WORD i=0;i<MAX_NUM_RECV_STREAMS_FOR_VIDEO;i++)
m_ssrcVideo[i] = other.m_ssrcVideo[i];
}
////////////////////////////////////////////////////////////////////////////
CPartyRsrc::~CPartyRsrc()
{
}
////////////////////////////////////////////////////////////////////////////
void CPartyRsrc::SetARTChannels(WORD ARTChannels)
{
m_ARTChannels = ARTChannels;
// bridge-809: assert only not in soft MCU - in soft MCU ARTChannels set to 0, not to limit soft ART capacity
CSystemResources* pSyst = CHelperFuncs::GetSystemResources();
if (pSyst && !CHelperFuncs::IsSoftMCU(pSyst->GetProductType()))
{
DBGPASSERT(0 == ARTChannels);
}
}
////////////////////////////////////////////////////////////////////////////
WORD operator==(const CPartyRsrc& lhs,const CPartyRsrc& rhs)
{
return (lhs.m_monitorPartyId == rhs.m_monitorPartyId);
}
////////////////////////////////////////////////////////////////////////////
bool operator<(const CPartyRsrc& lhs,const CPartyRsrc& rhs)
{
return (lhs.m_monitorPartyId < rhs.m_monitorPartyId);
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::AddParty(CPartyRsrc& party)
{
PASSERTSTREAM_AND_RETURN_VALUE(m_parties.find(party) != m_parties.end(), "MonitorPartyId:" << party.GetMonitorPartyId() << " - Already exist", STATUS_FAIL);
TRACEINTO << "MonitorPartyId:" << party.GetMonitorPartyId() << ", PartyLogicalType:" << party.GetPartyResourceType();
m_parties.insert(party);
m_num_Parties++;
UpdateConfMediaStateByPartiesList();
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
BOOL CConfRsrc::CheckIfOneMorePartyCanBeAddedToConf2C(eVideoPartyType videoPartyType)
{
CSystemResources *pSystemResources = CHelperFuncs::GetSystemResources();
eSystemCardsMode systemCardsMode = pSystemResources ? pSystemResources->GetSystemCardsMode() : eSystemCardsMode_illegal;
if (eVSW_video_party_type == videoPartyType)
{
if((eVSW_28_session == m_sessionType && m_num_Parties > MAX_PARTIES_IN_CONF_2C_VSW28) ||
(eVSW_56_session == m_sessionType && m_num_Parties > MAX_PARTIES_IN_CONF_2C_VSW56))
{
return FALSE;
}
else if (eVSW_Auto_session == m_sessionType)
{
if ((eSystemCardsMode_breeze == systemCardsMode && m_num_Parties > 180))
return FALSE;
}
}
else if (eCOP_party_type == videoPartyType)
{
DWORD max_cop_parties = 160; //on breeze
CReservator* pReservator = CHelperFuncs::GetReservator();
if (pReservator)
max_cop_parties = pReservator->GetDongleRestriction();
TRACEINTO << " CConfRsrc::CheckIfOneMorePartyCanBeAddedToConf2C : max_cop_parties = " << max_cop_parties;
if ((eCOP_HD1080_session == m_sessionType || eCOP_HD720_50_session == m_sessionType) && m_num_Parties >= max_cop_parties)//192
return FALSE;
}
return TRUE;
}
////////////////////////////////////////////////////////////////////////////
WORD CConfRsrc::RemoveAllParties(BYTE force_kill_all_ports)
{
CResourceManager* pRsrcMngr = (CResourceManager*)(CProcessBase::GetProcess()->GetCurrentTask());
if (!pRsrcMngr)
{
PASSERT(1); return 0;
}
DEALLOC_PARTY_REQ_PARAMS_S* pdeallocateParams = new DEALLOC_PARTY_REQ_PARAMS_S;
memset(pdeallocateParams, 0, sizeof(DEALLOC_PARTY_REQ_PARAMS_S));
DEALLOC_PARTY_IND_PARAMS_S* pResult = new DEALLOC_PARTY_IND_PARAMS_S;
pdeallocateParams->numOfRsrcsWithProblems = 0;
pdeallocateParams->monitor_conf_id = m_monitorConfId;
pdeallocateParams->force_kill_all_ports = force_kill_all_ports;
// make a copy of parties container
PARTIES PartyRsrcList = m_parties;
PARTIES::iterator itr = PartyRsrcList.begin();
DWORD monitorPartyId = 0;
WORD numOfRemovedParties = 0;
for (itr = PartyRsrcList.begin(); itr != PartyRsrcList.end(); itr++)
{
monitorPartyId = ((CPartyRsrc*)(&(*itr)))->GetMonitorPartyId();
TRACEINTO << "monitorPartyId=" << monitorPartyId;
memset(pResult, 0, sizeof(DEALLOC_PARTY_IND_PARAMS_S));
pdeallocateParams->monitor_party_id = monitorPartyId;
pRsrcMngr->DeAlloc(pdeallocateParams, pResult);
if (pResult->status == STATUS_OK)
++numOfRemovedParties;
}
delete pdeallocateParams;
delete pResult;
return numOfRemovedParties;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::RemoveParty(PartyMonitorID monitorPartyId)
{
CPartyRsrc party(monitorPartyId);
PARTIES::iterator itr = m_parties.find(party);
PASSERTSTREAM_AND_RETURN_VALUE(itr == m_parties.end(), "MonitorPartyId:" << monitorPartyId << " - Party not exist", STATUS_FAIL);
m_parties.erase(itr);
m_num_Parties--;
UpdateConfMediaStateByPartiesList();
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
const CPartyRsrc* CConfRsrc::GetParty(PartyMonitorID monitorPartyId) const
{
CPartyRsrc party(monitorPartyId);
PARTIES::iterator itr = m_parties.find(party);
TRACECOND_AND_RETURN_VALUE(itr == m_parties.end(), "MonitorPartyId:" << monitorPartyId << " - Party not exist", NULL);
return &(*itr);
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::AddTempBondingPhoneNumber(PartyRsrcID partyId, Phone* pPhone)
{
PASSERT_AND_RETURN_VALUE(!pPhone, STATUS_FAIL);
Phone* phone = new Phone;
strcpy_safe(phone->phone_number, pPhone->phone_number);
m_bondingPhones.insert(BONDING_PHONES::value_type(partyId, phone));
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::RemoveTempBondingPhoneNumber(PartyRsrcID partyId)
{
BONDING_PHONES::iterator itr = m_bondingPhones.find(partyId);
if (itr == m_bondingPhones.end())
return STATUS_FAIL;
delete itr->second;
m_bondingPhones.erase(itr);
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
Phone* CConfRsrc::GetTempBondingPhoneNumberByRsrcPartyId(PartyRsrcID partyId) const
{
BONDING_PHONES::const_iterator itr = m_bondingPhones.find(partyId);
if (itr == m_bondingPhones.end())
return NULL;
return itr->second;
}
////////////////////////////////////////////////////////////////////////////
WORD CConfRsrc::IsBoardIdAllocatedToConf(WORD boardId)
{
//if board allocated o conf -
// there is have to be at least on RsrcDesc of this board.
//WORD bId = 2;
RSRC_DESC_MULTISET_ITR itr;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if (itr->GetBoardId() == boardId)
return TRUE;
}
return FALSE;
}
////////////////////////////////////////////////////////////////////////////
void CConfRsrc::AddListOfPartiesDescriptorsOnBoard(WORD boardId, WORD subBoardId, std::map<std::string,CONF_PARTY_ID_S*>* listOfConfIdPartyIdPair) const
{
RSRC_DESC_MULTISET_ITR itr;
CRsrcDesc rsrcdesc;
std::string strKey;
CONF_PARTY_ID_S* pConf_party_id_s = NULL;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
rsrcdesc = ((CRsrcDesc)(*itr));
if (rsrcdesc.GetBoardId() == boardId)
{
//if subboard is 1 (MFA), this means that the whole card will be taken out, including the RTM
//so it doesn't matter on which subboard it is
if (subBoardId == MFA_SUBBOARD_ID || rsrcdesc.GetSubBoardId() == subBoardId)
{
strKey = GetPartyKey(rsrcdesc.GetRsrcConfId() ,rsrcdesc.GetRsrcPartyId());
if (listOfConfIdPartyIdPair->find(strKey) == listOfConfIdPartyIdPair->end())
{
pConf_party_id_s = new CONF_PARTY_ID_S();
pConf_party_id_s->monitor_conf_id = GetMonitorConfId();
CPartyRsrc* pParty = (CPartyRsrc*)(GetPartyRsrcByRsrcPartyId(rsrcdesc.GetRsrcPartyId()));
if (pParty == NULL)
{
POBJDELETE(pConf_party_id_s);
PASSERT(1);
continue;
}
else
{
pConf_party_id_s->monitor_party_id = pParty->GetMonitorPartyId();
}
(*listOfConfIdPartyIdPair)[strKey] = pConf_party_id_s;
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////
std::string CConfRsrc::GetPartyKey(DWORD rsrcConfId, DWORD rsrcPartyId) const
{
std::ostringstream o;
o << rsrcConfId << "_" << rsrcPartyId;
return o.str();
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::GetFreeVideoRsrcVSW(CRsrcDesc*& pEncDesc, CRsrcDesc*& pDecDesc)
{
WORD rsrcId = 0, enc_found = 0, dec_found = 0;
RSRC_DESC_MULTISET_ITR itr;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
CRsrcDesc* pRsrcDesc = (CRsrcDesc*)&(*itr);
BOOL isDecType = CHelperFuncs::IsLogicalVideoDecoderType( pRsrcDesc->GetType());
BOOL isEncType = CHelperFuncs::IsLogicalVideoEncoderType( pRsrcDesc->GetType());
if (pRsrcDesc->GetIsUpdated() || (!isDecType && !isEncType) ||
(isDecType && dec_found) || (isEncType && enc_found))
continue;
rsrcId = pRsrcDesc->GetRsrcPartyId();
if (isDecType)
{
dec_found = rsrcId;
pDecDesc = pRsrcDesc;
}
else
{
enc_found = rsrcId;
pEncDesc = pRsrcDesc;
}
if (dec_found && enc_found && dec_found == enc_found)
break;
}
if (!pEncDesc || !pDecDesc)
return STATUS_FAIL;
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::GetBoardUnitIdByRoomIdTIP(DWORD room_id, WORD& boardIdTIP, WORD& unitIdTIP) //TIP Cisco
{
PARTIES::iterator _iiEnd = m_parties.end();
for (PARTIES::iterator _ii = m_parties.begin(); _ii != _iiEnd; ++_ii)
{
if (_ii->GetRoomPartyId() == room_id)
{
const CRsrcDesc* pAudEncDesc = GetDesc(_ii->GetRsrcPartyId(), eLogical_audio_encoder);
if (pAudEncDesc)
{
boardIdTIP = pAudEncDesc->GetBoardId();
unitIdTIP = pAudEncDesc->GetUnitId();
return STATUS_OK;
}
}
}
return STATUS_FAIL;
}
////////////////////////////////////////////////////////////////////////////
WORD CConfRsrc::GetBoardIdForRelayParty() //olga
{
PARTIES::iterator _it = std::find_if(m_parties.begin(), m_parties.end(), compareVideoPartyFunc());
if (_it != m_parties.end())
{
const CRsrcDesc* pRtpDesc = GetDesc(_it->GetRsrcPartyId(), eLogical_rtp);
if (pRtpDesc)
return pRtpDesc->GetBoardId();
}
TRACEINTO << "Relay party is not allocated on any board";
return 0;
}
////////////////////////////////////////////////////////////////////////////
bool CConfRsrc::CheckIfThereAreRelayParty() const
{
PARTIES::iterator _it = std::find_if(m_parties.begin(), m_parties.end(), compareVideoPartyFunc());
return (_it != m_parties.end());
}
////////////////////////////////////////////////////////////////////////////
bool CConfRsrc::CheckIfThereAreNotRelayParty() const
{
PARTIES::iterator _it = std::find_if(m_parties.begin(), m_parties.end(), not1(compareVideoPartyFunc()));
return (_it != m_parties.end());
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrc::GetBoardUnitIdByAvMcuLinkMain(PartyRsrcID mainPartyRsrcID, WORD& boardId, WORD& unitId)
{
const CRsrcDesc* pRtpDesc = GetDesc(mainPartyRsrcID, eLogical_rtp);
if (pRtpDesc)
{
boardId = pRtpDesc->GetBoardId();
unitId = pRtpDesc->GetUnitId();
return STATUS_OK;
}
return STATUS_FAIL;
}
////////////////////////////////////////////////////////////////////////////
void CConfRsrc::CountAvcSvcParties(WORD& numAvc, WORD& numSvc) const
{
numAvc = 0;
numSvc = 0;
PARTIES::iterator _iiEnd = m_parties.end();
for (PARTIES::iterator _ii = m_parties.begin(); _ii != _iiEnd; ++_ii)
{
if (CHelperFuncs::IsVideoRelayParty(_ii->GetVideoPartyType()))
numSvc++;
else
numAvc++;
}
}
////////////////////////////////////////////////////////////////////////////
// Need to receive in pRsrcDescList memory of MAX_NUM_ALLOCATED_RSRCS_NET pointers (CRsrcDesc*) allocated for the output (and initialized to all NULLs)
// Returns number of RsrcDescs found.
WORD CConfRsrc::GetPartyRcrsDescArrayByRsrcId(DWORD rsrcpartyId, CRsrcDesc** pRsrcDescArray, WORD arrSize)
{
RSRC_DESC_MULTISET_ITR itr;
int num_party_resources = 0;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if (itr->GetRsrcPartyId() == rsrcpartyId)
{
if (num_party_resources < arrSize) // For protection
{
pRsrcDescArray[num_party_resources] = (CRsrcDesc*)&(*itr);
num_party_resources++;
}
else{
PASSERTMSG(num_party_resources, "CConfRsrc::GetDescArrayPerResourceTypeByRsrcId - error in call to function");
}
}
}
return num_party_resources;
}
////////////////////////////////////////////////////////////////////////////
WORD CConfRsrc::GetPartyRTPDescArrayByRsrcId(DWORD rsrcpartyId, CRsrcDesc** pRsrcDescArray, WORD arrSize)
{
RSRC_DESC_MULTISET_ITR itr;
int num_party_resources = 0;
for (itr = m_pRsrcDescList.begin(); itr != m_pRsrcDescList.end(); itr++)
{
if (itr->GetRsrcPartyId() == rsrcpartyId && CHelperFuncs::IsLogicalRTPtype(itr->GetType()))
{
if (num_party_resources < arrSize) // For protection
{
pRsrcDescArray[num_party_resources] = (CRsrcDesc*)&(*itr);
num_party_resources++;
}
else{
PASSERTMSG(num_party_resources, "CConfRsrc::GetDescArrayPerResourceTypeByRsrcId - error in call to function");
}
}
}
return num_party_resources;
}
////////////////////////////////////////////////////////////////////////////
void CConfRsrc::UpdateConfMediaStateByPartiesList()
{
bool hasRelayParties = CheckIfThereAreRelayParty();
bool hasNotRelayParties = CheckIfThereAreNotRelayParty();
if (eMediaStateMixAvcSvc == m_confMediaState)
{
// since we don't support downgrade - we don't change ConfMediaState after it already in mixed
return;
}
if (!hasRelayParties && !hasNotRelayParties)
{
SetConfMediaState(eMediaStateEmpty);
}
else if (hasRelayParties && !hasNotRelayParties)
{
SetConfMediaState(eMediaStateSvcOnly);
}
else if (!hasRelayParties && hasNotRelayParties)
{
SetConfMediaState(eMediaStateAvcOnly);
}
}
////////////////////////////////////////////////////////////////////////////
// CConfRsrcDB
////////////////////////////////////////////////////////////////////////////
CConfRsrcDB::CConfRsrcDB()
{
m_numConfRsrcs = 0;
}
////////////////////////////////////////////////////////////////////////////
CConfRsrcDB::~CConfRsrcDB()
{
m_numConfRsrcs = 0;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrcDB::AddConfRsrc(CConfRsrc* pConfRsrc)
{
PASSERT_AND_RETURN_VALUE(!pConfRsrc, STATUS_FAIL);
PASSERT_AND_RETURN_VALUE(m_confList.find(*pConfRsrc) != m_confList.end(), STATUS_FAIL);
m_confList.insert(*pConfRsrc);
ConfRsrcID id = pConfRsrc->GetRsrcConfId();
if (STANDALONE_CONF_ID != id)
m_numConfRsrcs++;
TRACEINTO << "ConfId:" << id << ", NumOngoingConf:" << m_numConfRsrcs;
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrcDB::RemoveConfRsrc(ConfMonitorID confId)
{
CConfRsrc conf(confId);
RSRC_CONF_LIST::iterator _itr = m_confList.find(conf);
if (_itr == m_confList.end())
return STATUS_FAIL;
ConfRsrcID id = _itr->GetRsrcConfId();
if (STANDALONE_CONF_ID != id)
{
if (m_numConfRsrcs > 0)
m_numConfRsrcs--;
else
PASSERT(1);
}
m_confList.erase(_itr);
TRACEINTO << "ConfId:" << id << ", NumOngoingConf:" << m_numConfRsrcs;
return STATUS_OK;
}
////////////////////////////////////////////////////////////////////////////
CConfRsrc* CConfRsrcDB::GetConfRsrc(ConfMonitorID confId)
{
CConfRsrc conf(confId);
RSRC_CONF_LIST::iterator _itr = m_confList.find(conf);
if (_itr != m_confList.end())
return (CConfRsrc*)(&(*_itr));
return NULL;
}
////////////////////////////////////////////////////////////////////////////
CConfRsrc* CConfRsrcDB::GetConfRsrcByRsrcConfId(ConfRsrcID confId)
{
RSRC_CONF_LIST::iterator _end = m_confList.end();
for (RSRC_CONF_LIST::iterator _itr = m_confList.begin(); _itr != _end; ++_itr)
{
if (_itr->GetRsrcConfId() == confId)
return (CConfRsrc*)(&(*_itr));
}
return NULL;
}
////////////////////////////////////////////////////////////////////////////
STATUS CConfRsrcDB::GetMonitorIdsRsrcIds(ConfRsrcID confId, PartyRsrcID partyId, ConfMonitorID& monitorConfId, PartyMonitorID& monitorPartyId)
{
monitorConfId = 0xFFFFFFFF;
monitorPartyId = 0xFFFFFFFF;
RSRC_CONF_LIST::iterator _end = m_confList.end();
for (RSRC_CONF_LIST::iterator _itr = m_confList.begin(); _itr != _end; ++_itr)
{
if (_itr->GetRsrcConfId() == confId)
{
monitorConfId = _itr->GetMonitorConfId();
const CPartyRsrc* pParty = _itr->GetPartyRsrcByRsrcPartyId(partyId);
if (pParty)
{
monitorPartyId = pParty->GetMonitorPartyId();
return STATUS_OK;
}
}
}
return STATUS_FAIL;
}
////////////////////////////////////////////////////////////////////////////
bool CConfRsrcDB::IsExitingConf(ConfMonitorID confId)
{
const CConfRsrc* pConfRsrc = GetConfRsrc(confId);
return (pConfRsrc == NULL)? false : true;
}
////////////////////////////////////////////////////////////////////////////
bool CConfRsrcDB::IsEmptyConf(ConfMonitorID confId)
{
CConfRsrc* pConfRsrc = GetConfRsrc(confId);
PASSERT_AND_RETURN_VALUE(!pConfRsrc, true);
return pConfRsrc->GetNumParties() ? false : true;
}
////////////////////////////////////////////////////////////////////////////
ConfRsrcID CConfRsrcDB::MonitorToRsrcConfId(ConfMonitorID confId)
{
CConfRsrc* pConfRsrc = GetConfRsrc(confId);
return pConfRsrc ? pConfRsrc->GetRsrcConfId() : 0;
}
////////////////////////////////////////////////////////////////////////////
void CConfRsrcDB::GetAllPartiesOnBoard(WORD boardId, WORD subBoardId, std::map<std::string, CONF_PARTY_ID_S*>* listOfConfIdPartyIdPair)
{
RSRC_CONF_LIST::iterator _end = m_confList.end();
for (RSRC_CONF_LIST::iterator _itr = m_confList.begin(); _itr != _end; ++_itr)
_itr->AddListOfPartiesDescriptorsOnBoard(boardId, subBoardId, listOfConfIdPartyIdPair);
}
////////////////////////////////////////////////////////////////////////////
void CConfRsrcDB::FillISDNServiceName(ConfMonitorID confId, PartyMonitorID partyId, char serviceName[GENERAL_SERVICE_PROVIDER_NAME_LEN])
{
CSystemResources* pSystemResources = CHelperFuncs::GetSystemResources();
PASSERT_AND_RETURN(!pSystemResources);
const CConfRsrc* pConfRsrc = GetConfRsrc(confId);
TRACECOND_AND_RETURN(!pConfRsrc, "MonitorConfId:" << confId << " - Failed, conference not found");
const CPartyRsrc* pPartyRsrc = pConfRsrc->GetParty(partyId);
TRACECOND_AND_RETURN(!pPartyRsrc, "MonitorPartyId:" << partyId << " - Failed, participant not found");
CRsrcDesc** pRsrcDescArray = new CRsrcDesc*[MAX_NUM_ALLOCATED_RSRCS_NET];
for (int i = 0 ; i < MAX_NUM_ALLOCATED_RSRCS_NET ; i++)
pRsrcDescArray[i] = NULL;
// Get all resource descriptors of RTM per a given party
pConfRsrc->GetDescArrayPerResourceTypeByRsrcId(pPartyRsrc->GetRsrcPartyId(), eLogical_net, pRsrcDescArray);
if (pRsrcDescArray[0] == NULL)
{
TRACEINTO << "MonitorPartyId:" << partyId << " - Failed, RTMs not found for party";
delete []pRsrcDescArray;
return;
}
WORD boardId = pRsrcDescArray[0]->GetBoardId();
WORD unitId = pRsrcDescArray[0]->GetUnitId();
delete []pRsrcDescArray;
CBoard* pBoard = pSystemResources->GetBoard(boardId);
PASSERT_AND_RETURN(!pBoard);
const CSpanRTM* pSpan = pBoard->GetRTM(unitId);
PASSERT_AND_RETURN(!pSpan);
const char* serviceNameFromSpan = pSpan->GetSpanServiceName();
if (serviceNameFromSpan)
strcpy_safe(serviceName, sizeof(serviceName), serviceNameFromSpan);
}
////////////////////////////////////////////////////////////////////////////
PartyRsrcID CConfRsrcDB::MonitorToRsrcPartyId(ConfMonitorID confId, PartyMonitorID partyId)
{
const CConfRsrc* pConfRsrc = GetConfRsrc(confId);
if (pConfRsrc)
{
const CPartyRsrc* pPartyRsrc = pConfRsrc->GetParty(partyId);
if (pPartyRsrc)
return pPartyRsrc->GetRsrcPartyId();
}
return 0;
}
////////////////////////////////////////////////////////////////////////////
bool CConfRsrcDB::GetPartyType(ConfMonitorID confId, PartyMonitorID partyId,
eNetworkPartyType& networkPartyType,
eVideoPartyType& videoPartyType,
ePartyRole& partyRole,
WORD& artChannels,
eSessionType& sessionType)
{
const CConfRsrc* pConfRsrc = GetConfRsrc(confId);
TRACECOND_AND_RETURN_VALUE(!pConfRsrc, "MonitorConfId:" << confId << " - Failed, conference not found", false);
const CPartyRsrc* pPartyRsrc = pConfRsrc->GetParty(partyId);
TRACECOND_AND_RETURN_VALUE(!pPartyRsrc, "MonitorPartyId:" << partyId << " - Failed, participant not found", false);
networkPartyType = pPartyRsrc->GetNetworkPartyType();
videoPartyType = pPartyRsrc->GetVideoPartyType();
partyRole = pPartyRsrc->GetPartyRole();
artChannels = pPartyRsrc->GetARTChannels();
sessionType = pConfRsrc->GetSessionType();
return true;
}
| [
"[email protected]"
] | |
d43be44d339e4c748144208e5d4bd8fe9a5894e7 | 3368db882d23eba1fd8046d9e46583d7324d4dea | /Lesson 6/source/06.) Textures/win_OpenGLApp.cpp | 2a8751f01791f7cd05950c39fb5a5f26b9865e4b | [] | no_license | Juniperbrew/MS-OpenGLTutorial-Win32 | 8313923fc34948aafd7bc71de8d99552f734a454 | 6f6908999f1d887e41e311c019ab96724a60ac24 | refs/heads/master | 2021-01-10T16:39:55.731220 | 2016-01-02T09:49:59 | 2016-01-02T09:49:59 | 48,902,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,077 | cpp | #include "common_header.h"
#include "win_OpenGLApp.h"
COpenGLWinApp appMain;
char Keys::kp[256] = {0};
/*-----------------------------------------------
Name: key
Params: iKey - virtual key code
Result: Return true if key is pressed.
/*---------------------------------------------*/
int Keys::key(int iKey)
{
return (GetAsyncKeyState(iKey)>>15)&1;
}
/*-----------------------------------------------
Name: onekey
Params: iKey - virtual key code
Result: Return true if key was pressed, but only
once (the key must be released).
/*---------------------------------------------*/
int Keys::onekey(int iKey)
{
if(key(iKey) && !kp[iKey]){kp[iKey] = 1; return 1;}
if(!key(iKey))kp[iKey] = 0;
return 0;
}
/*-----------------------------------------------
Name: resetTimer
Params: none
Result: Resets application timer (for example
after re-activation of application).
/*---------------------------------------------*/
void COpenGLWinApp::resetTimer()
{
tLastFrame = clock();
fFrameInterval = 0.0f;
}
/*-----------------------------------------------
Name: updateTimer
Params: none
Result: Updates application timer.
/*---------------------------------------------*/
void COpenGLWinApp::updateTimer()
{
clock_t tCur = clock();
fFrameInterval = float(tCur-tLastFrame)/float(CLOCKS_PER_SEC);
tLastFrame = tCur;
}
/*-----------------------------------------------
Name: sof
Params: fVal
Result: Stands for speed optimized float.
/*---------------------------------------------*/
float COpenGLWinApp::sof(float fVal)
{
return fVal*fFrameInterval;
}
/*-----------------------------------------------
Name: initializeApp
Params: a_sAppName
Result: Initializes app with specified (unique)
application identifier.
/*---------------------------------------------*/
bool COpenGLWinApp::initializeApp(string a_sAppName)
{
sAppName = a_sAppName;
hMutex = CreateMutex(NULL, 1, sAppName.c_str());
if(GetLastError() == ERROR_ALREADY_EXISTS)
{
MessageBox(NULL, "This application already runs!", "Multiple Instances Found.", MB_ICONINFORMATION | MB_OK);
return 0;
}
return 1;
}
/*-----------------------------------------------
Name: registerAppClass
Params: a_hInstance - application instance handle
Result: Registers application window class.
/*---------------------------------------------*/
LRESULT CALLBACK globalMessageHandler(HWND hWnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
return appMain.msgHandlerMain(hWnd, uiMsg, wParam, lParam);
}
void COpenGLWinApp::registerAppClass(HINSTANCE a_hInstance)
{
WNDCLASSEX wcex;
memset(&wcex, 0, sizeof(WNDCLASSEX));
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_OWNDC;
wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wcex.hIcon = LoadIcon(hInstance, IDI_WINLOGO);
wcex.hIconSm = LoadIcon(hInstance, IDI_WINLOGO);
wcex.hCursor = LoadCursor(hInstance, IDC_ARROW);
wcex.hInstance = hInstance;
wcex.lpfnWndProc =
globalMessageHandler;
wcex.lpszClassName = sAppName.c_str();
wcex.lpszMenuName = NULL;
RegisterClassEx(&wcex);
}
/*-----------------------------------------------
Name: createWindow
Params: sTitle - title of created window
Result: Creates main application window.
/*---------------------------------------------*/
bool COpenGLWinApp::createWindow(string sTitle)
{
if(MessageBox(NULL, "Would you like to run in fullscreen?", "Fullscreen", MB_ICONQUESTION | MB_YESNO) == IDYES)
{
DEVMODE dmSettings = {0};
EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dmSettings); // Get current display settings
hWnd = CreateWindowEx(0, sAppName.c_str(), sTitle.c_str(), WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, // This is the commonly used style for fullscreen
0, 0, dmSettings.dmPelsWidth, dmSettings.dmPelsHeight, NULL,
NULL, hInstance, NULL);
}
else hWnd = CreateWindowEx(0, sAppName.c_str(), sTitle.c_str(), WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL,
NULL, hInstance, NULL);
if(!oglControl.initOpenGL(hInstance, &hWnd, 3, 3, initScene, renderScene, releaseScene, &oglControl))return false;
ShowWindow(hWnd, SW_SHOW);
// Just to send WM_SIZE message again
ShowWindow(hWnd, SW_SHOWMAXIMIZED);
UpdateWindow(hWnd);
return true;
}
/*-----------------------------------------------
Name: appBody
Params: none
Result: Main application body infinite loop.
/*---------------------------------------------*/
void COpenGLWinApp::appBody()
{
MSG msg;
while(1)
{
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if(msg.message == WM_QUIT)break; // If the message was WM_QUIT then exit application
else
{
TranslateMessage(&msg); // Otherwise send message to appropriate window
DispatchMessage(&msg);
}
}
else if(bAppActive)
{
updateTimer();
oglControl.render(&oglControl);
}
else Sleep(200); // Do not consume processor power if application isn't active
}
}
/*-----------------------------------------------
Name: shutdown
Params: none
Result: Shuts down application and releases used
memory.
/*---------------------------------------------*/
void COpenGLWinApp::shutdown()
{
oglControl.releaseOpenGLControl(&oglControl);
DestroyWindow(hWnd);
UnregisterClass(sAppName.c_str(), hInstance);
COpenGLControl::unregisterSimpleOpenGLClass(hInstance);
ReleaseMutex(hMutex);
}
/*-----------------------------------------------
Name: msgHandlerMain
Params: whatever
Result: Application messages handler.
/*---------------------------------------------*/
LRESULT CALLBACK COpenGLWinApp::msgHandlerMain(HWND hWnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
switch(uiMsg)
{
case WM_PAINT:
BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
break;
case WM_CLOSE:
PostQuitMessage(0);
break;
case WM_ACTIVATE:
{
switch(LOWORD(wParam))
{
case WA_ACTIVE:
case WA_CLICKACTIVE:
bAppActive = true;
resetTimer();
break;
case WA_INACTIVE:
bAppActive = false;
break;
}
break;
}
case WM_SIZE:
oglControl.resizeOpenGLViewportFull();
oglControl.setProjection3D(45.0f, float(LOWORD(lParam))/float(HIWORD(lParam)), 0.001f, 1000.0f);
break;
default:
return DefWindowProc(hWnd, uiMsg, wParam, lParam);
}
return 0;
}
/*-----------------------------------------------
Name: getInstance
Params: none
Result: Returns application instance.
/*---------------------------------------------*/
HINSTANCE COpenGLWinApp::getInstance()
{
return hInstance;
}
/*-----------------------------------------------
Name: msgHandlerMain
Params: whatever
Result: Application messages handler.
/*---------------------------------------------*/
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR sCmdLine, int iShow)
{
if(!appMain.initializeApp("06_opengl_3_3"))
return 0;
appMain.registerAppClass(hInstance);
if(!appMain.createWindow("06.) Textures - Tutorial by Michal Bubnar (www.mbsoftworks.sk)"))
return 0;
appMain.resetTimer();
appMain.appBody();
appMain.shutdown();
return 0;
}
| [
"[email protected]"
] | |
24db047e3e13fafc5ddd4547fc9e46520a696d7f | b301ab714ad4d4625d4a79005a1bda6456a283ec | /UVa/334.cpp | f025069dbdd616fd733ba2408d048555a145a5a6 | [] | no_license | askeySnip/OJ_records | 220fd83d406709328e8450df0f6da98ae57eb2d9 | 4b77e3bb5cf19b98572fa6583dff390e03ff1a7c | refs/heads/master | 2022-06-26T02:14:34.957580 | 2022-06-11T13:56:33 | 2022-06-11T13:56:33 | 117,955,514 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,302 | cpp | /*
ID: leezhen
TASK: practice
LANG: C++11
*/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <cmath>
#include <bitset>
using namespace std;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<pair<int, int> > vii;
// struct
#define inf 1e6
// data
int nc, ne, nm;
int dist[404][404];
char e[2][10];
vector<string> vstr;
map<string, int> mpsi;
int main() {
int kase = 0;
while(scanf("%d", &nc), nc) {
mpsi.clear();
vstr.clear();
for(int i=0; i<404; i++) {
for(int j=0; j<404; j++) {
if(i == j) dist[i][j] = 0;
else dist[i][j] = inf;
}
}
for(int i=0; i<nc; i++) {
scanf("%d", &ne);
scanf("%s", e[0]);
if(mpsi.find(e[0]) == mpsi.end()) {
vstr.push_back(e[0]);
mpsi[e[0]] = vstr.size()-1;
}
int last = 0;
for(int j=1; j<ne; j++) {
scanf("%s", e[1-last]);
if(mpsi.find(e[1-last]) == mpsi.end()) {
mpsi[e[1-last]] = vstr.size();
vstr.push_back(e[1-last]);
}
dist[mpsi[e[last]]][mpsi[e[1-last]]] = 1;
last = 1-last;
}
}
scanf("%d", &nm);
for(int i=0; i<nm; i++) {
scanf("%s %s", e[0], e[1]);
dist[mpsi[e[0]]][mpsi[e[1]]] = 1;
}
int n = vstr.size();
for(int k=0; k<n; k++) {
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
if(dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
vii ans;
for(int i=0; i<n; i++) {
for(int j=i+1; j<n; j++) {
if(dist[i][j] == inf && dist[j][i] == inf) ans.push_back(ii(i, j));
}
}
if(ans.empty())printf("Case %d, no concurrent events.\n", ++kase);
else {
printf("Case %d, %d concurrent events:\n", ++kase, (int)ans.size());
if((int)ans.size() == 1) {
printf("(%s,%s) \n", vstr[ans[0].first].c_str(), vstr[ans[0].second].c_str());
}
else {
printf("(%s,%s) (%s,%s) \n", vstr[ans[0].first].c_str(), vstr[ans[0].second].c_str(), vstr[ans[1].first].c_str(), vstr[ans[1].second].c_str());
}
}
}
return 0;
}
| [
"[email protected]"
] | |
8ab716daca33856e610a208732527f0dd9de4e8e | 70d18762f2443bb5df8df38967bcd38277573cdb | /arch/generic/kernel/gen_ke_arch64.cpp | 1f2b16ecf52f14ac9a8389e3bec0a1176360b3fd | [] | no_license | 15831944/evita-common-lisp | f829defc5386cd1988754c59f2056f0367c77ed7 | cb2cbd3cc541878d25dcedb4abd88cf8e2c881d9 | refs/heads/master | 2021-05-27T16:35:25.208083 | 2013-12-01T06:21:32 | 2013-12-01T06:21:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,776 | cpp | //////////////////////////////////////////////////////////////////////////////
//
// evcl - kernel - arch 64
// kernel/ke_arch64.cpp
//
// This file is part of Evita Common Lisp.
//
// Copyright (C) 1996-2006 by Project Vogue.
// Written by Yoshifumi "VOGUE" INOUE. ([email protected])
//
// @(#)$Id: //proj/evcl3/mainline/arch/generic/kernel/gen_ke_arch64.cpp#3 $
//
#if SIZEOF_VAL == 8
#include "../../../kernel/ke_arch.h"
namespace Kernel
{
const uint64
Kernel::Arch64::k_rgfBit[64] =
{
1ull << 0, 1ull << 1, 1ull << 2, 1ull << 3, 1ull << 4,
1ull << 5, 1ull << 6, 1ull << 7, 1ull << 8, 1ull << 9,
1ull << 10, 1ull << 11, 1ull << 12, 1ull << 13, 1ull << 14,
1ull << 15, 1ull << 16, 1ull << 17, 1ull << 18, 1ull << 19,
1ull << 20, 1ull << 21, 1ull << 22, 1ull << 23, 1ull << 24,
1ull << 25, 1ull << 26, 1ull << 27, 1ull << 28, 1ull << 29,
1ull << 30, 1ull << 31, 1ull << 32, 1ull << 33, 1ull << 34,
1ull << 35, 1ull << 36, 1ull << 37, 1ull << 38, 1ull << 39,
1ull << 40, 1ull << 41, 1ull << 42, 1ull << 43, 1ull << 44,
1ull << 45, 1ull << 46, 1ull << 47, 1ull << 48, 1ull << 49,
1ull << 50, 1ull << 51, 1ull << 52, 1ull << 53, 1ull << 54,
1ull << 55, 1ull << 56, 1ull << 57, 1ull << 58, 1ull << 59,
1ull << 60, 1ull << 61, 1ull << 62, 1ull << 63
}; // Kernel::Arch64::k_rgfBit
//////////////////////////////////////////////////////////////////////
//
// Mask For Bit Stream Leader and Trailer
//
// Bit Stream:
// LLLL LLLL xxxx xxxx ... xxxx xxxx TTTT TTTT
//
// x = bits for processing
// L = leader bits (not affect)
// T = trailer bits (not affect)
//
// Note: Bit stream is stored in each 32bit word from LSB to MSB.
//
//
// (loop for i below 64 do (format t "0x~16,'0Xull, // ~D~%" (1- (ash 1 i)) i))
const Arch64::BitEltT
Arch64::k_rgnLeaderMask[64] =
{
0x0000000000000000ull, // 0
0x0000000000000001ull, // 1
0x0000000000000003ull, // 2
0x0000000000000007ull, // 3
0x000000000000000Full, // 4
0x000000000000001Full, // 5
0x000000000000003Full, // 6
0x000000000000007Full, // 7
0x00000000000000FFull, // 8
0x00000000000001FFull, // 9
0x00000000000003FFull, // 10
0x00000000000007FFull, // 11
0x0000000000000FFFull, // 12
0x0000000000001FFFull, // 13
0x0000000000003FFFull, // 14
0x0000000000007FFFull, // 15
0x000000000000FFFFull, // 16
0x000000000001FFFFull, // 17
0x000000000003FFFFull, // 18
0x000000000007FFFFull, // 19
0x00000000000FFFFFull, // 20
0x00000000001FFFFFull, // 21
0x00000000003FFFFFull, // 22
0x00000000007FFFFFull, // 23
0x0000000000FFFFFFull, // 24
0x0000000001FFFFFFull, // 25
0x0000000003FFFFFFull, // 26
0x0000000007FFFFFFull, // 27
0x000000000FFFFFFFull, // 28
0x000000001FFFFFFFull, // 29
0x000000003FFFFFFFull, // 30
0x000000007FFFFFFFull, // 31
0x00000000FFFFFFFFull, // 32
0x00000001FFFFFFFFull, // 33
0x00000003FFFFFFFFull, // 34
0x00000007FFFFFFFFull, // 35
0x0000000FFFFFFFFFull, // 36
0x0000001FFFFFFFFFull, // 37
0x0000003FFFFFFFFFull, // 38
0x0000007FFFFFFFFFull, // 39
0x000000FFFFFFFFFFull, // 40
0x000001FFFFFFFFFFull, // 41
0x000003FFFFFFFFFFull, // 42
0x000007FFFFFFFFFFull, // 43
0x00000FFFFFFFFFFFull, // 44
0x00001FFFFFFFFFFFull, // 45
0x00003FFFFFFFFFFFull, // 46
0x00007FFFFFFFFFFFull, // 47
0x0000FFFFFFFFFFFFull, // 48
0x0001FFFFFFFFFFFFull, // 49
0x0003FFFFFFFFFFFFull, // 50
0x0007FFFFFFFFFFFFull, // 51
0x000FFFFFFFFFFFFFull, // 52
0x001FFFFFFFFFFFFFull, // 53
0x003FFFFFFFFFFFFFull, // 54
0x007FFFFFFFFFFFFFull, // 55
0x00FFFFFFFFFFFFFFull, // 56
0x01FFFFFFFFFFFFFFull, // 57
0x03FFFFFFFFFFFFFFull, // 58
0x07FFFFFFFFFFFFFFull, // 59
0x0FFFFFFFFFFFFFFFull, // 60
0x1FFFFFFFFFFFFFFFull, // 61
0x3FFFFFFFFFFFFFFFull, // 62
0x7FFFFFFFFFFFFFFFull, // 63
}; // k_rgnLeaderMask
// (loop with x = (1- (ash 1 64)) for i below 64 for m = (1- (ash 1 i))
// do (format t " 0x~16,'0Xull, // ~D~%" (- x m) i) )
const Arch64::BitEltT
Arch64::k_rgnTrailerMask[64] =
{
0xFFFFFFFFFFFFFFFFull, // 0
0xFFFFFFFFFFFFFFFEull, // 1
0xFFFFFFFFFFFFFFFCull, // 2
0xFFFFFFFFFFFFFFF8ull, // 3
0xFFFFFFFFFFFFFFF0ull, // 4
0xFFFFFFFFFFFFFFE0ull, // 5
0xFFFFFFFFFFFFFFC0ull, // 6
0xFFFFFFFFFFFFFF80ull, // 7
0xFFFFFFFFFFFFFF00ull, // 8
0xFFFFFFFFFFFFFE00ull, // 9
0xFFFFFFFFFFFFFC00ull, // 10
0xFFFFFFFFFFFFF800ull, // 11
0xFFFFFFFFFFFFF000ull, // 12
0xFFFFFFFFFFFFE000ull, // 13
0xFFFFFFFFFFFFC000ull, // 14
0xFFFFFFFFFFFF8000ull, // 15
0xFFFFFFFFFFFF0000ull, // 16
0xFFFFFFFFFFFE0000ull, // 17
0xFFFFFFFFFFFC0000ull, // 18
0xFFFFFFFFFFF80000ull, // 19
0xFFFFFFFFFFF00000ull, // 20
0xFFFFFFFFFFE00000ull, // 21
0xFFFFFFFFFFC00000ull, // 22
0xFFFFFFFFFF800000ull, // 23
0xFFFFFFFFFF000000ull, // 24
0xFFFFFFFFFE000000ull, // 25
0xFFFFFFFFFC000000ull, // 26
0xFFFFFFFFF8000000ull, // 27
0xFFFFFFFFF0000000ull, // 28
0xFFFFFFFFE0000000ull, // 29
0xFFFFFFFFC0000000ull, // 30
0xFFFFFFFF80000000ull, // 31
0xFFFFFFFF00000000ull, // 32
0xFFFFFFFE00000000ull, // 33
0xFFFFFFFC00000000ull, // 34
0xFFFFFFF800000000ull, // 35
0xFFFFFFF000000000ull, // 36
0xFFFFFFE000000000ull, // 37
0xFFFFFFC000000000ull, // 38
0xFFFFFF8000000000ull, // 39
0xFFFFFF0000000000ull, // 40
0xFFFFFE0000000000ull, // 41
0xFFFFFC0000000000ull, // 42
0xFFFFF80000000000ull, // 43
0xFFFFF00000000000ull, // 44
0xFFFFE00000000000ull, // 45
0xFFFFC00000000000ull, // 46
0xFFFF800000000000ull, // 47
0xFFFF000000000000ull, // 48
0xFFFE000000000000ull, // 49
0xFFFC000000000000ull, // 50
0xFFF8000000000000ull, // 51
0xFFF0000000000000ull, // 52
0xFFE0000000000000ull, // 53
0xFFC0000000000000ull, // 54
0xFF80000000000000ull, // 55
0xFF00000000000000ull, // 56
0xFE00000000000000ull, // 57
0xFC00000000000000ull, // 58
0xF800000000000000ull, // 59
0xF000000000000000ull, // 60
0xE000000000000000ull, // 61
0xC000000000000000ull, // 62
0x8000000000000000ull, // 63
}; // k_rgnTrailerMask
CASSERT(sizeof(Arch64::k_rgnLeaderMask) == sizeof(Arch64::k_rgnTrailerMask));
} // Kernel
#endif // SIZEOF_VAL == 8
| [
"[email protected]"
] | |
6af9d762a27675c814e1f06738962bbda04fa16b | 311525f7de84975434f55c00b545ccf7fe3dcce6 | /oi/japan/joisc/2017/day2/arranging_tickets.cpp | d2f48dc83125e17fcf6fcfd2ff8db33c7cff6918 | [] | no_license | fishy15/competitive_programming | 60f485bc4022e41efb0b7d2e12d094213d074f07 | d9bca2e6bea704f2bfe5a30e08aa0788be6a8022 | refs/heads/master | 2023-08-16T02:05:08.270992 | 2023-08-06T01:00:21 | 2023-08-06T01:00:21 | 171,861,737 | 29 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 7,612 | cpp | /*
* We can first split the circle at 0, initially marking each range from the lower number to the higher
* number. First, we note that we never want to flip both [a, b) and [c, d) where a < b <= c < d. This
* increases the count at each location not within the ranges by 2, and the values within the ranges don't
* change. Therefore, this only makes the situation worse.
*
* We can then binary search for the answer. Let the answer we are checking for be m. We can also define
* two other parameters: n will be the total number of ranges flipped, and t will be a point that all the
* ranges flipped will have in common (which must exist as we have shown earlier). For a given point, if
* there are currently a people that go over the point and there are n' tickets left to assign, then the
* amount of ranges we have to flip is max(ceil((a + n' - m) / 2), 0). We maintain a set of ranges to flip
* and then greedily flip the rightmost edges in the set, flipping as many as we need. Afterwards, we can
* do a final check to see if it works. Overall, this is O(n^2 m log(n) log(sum of c)).
*
* We can do two optimizations to this. First, we will try to limit the values of n that we will check.
* Let a_i denote the initial values, and b_i be the values after doing all necessary flips. We will prove
* that we can always pick a value of t such that b_t = or b_t = max(b_i) - 1. First of all, t can
* be any value in the intersection of all the ranges picked, so we can choose t to have the maximum value
* in the range. Now, suppose that there is some value outside of the intersection i such that b_i > b_t.
* We can then unflip both the flipped intervals with the leftmost right bound and the rightmost left bound
* If both ranges are distinct, then the b_i value of everything within the intersection will increase by
* +2 (increase by +1 if the ranges are not distinct). By repeating this process, we will either end up
* with b_t = m or b_t = m - 1, so our proof is done. Since n ranges will cover t, the b_t = a_t - n,
* so n = a_t - m or n = a_t - m + 1.
*
* Now, we want to limit the values of t that we have to check. We can first limit the candidates to t to
* be the values of i where a_i is the maximum of the array. If we let x_i denote the number of ranges
* flipped that include location i, then we know that x_j < x_t if j is not in the intersection. Taking the
* maximum possible value of b_j, we have b_j <= b_t + 1 and x_j + 1 <= x_t. Since a_i = x_i + b_i, we get
* that a_j <= a_t if j is not in the interesction, so a_t must be the maxmimum of a.
*
* Next, we will show that we only need to check the leftmost and rightmost indices where a_i is at its
* maximum. Denote these left and right indices by l and r. First, we will show that there is no need to
* flip a range [c, d) where l < c < d <= r. Suppose that there is some such range that we flip. If we
* unflip it, then everything outside the range decrements by 1, so it is still valid. Everything inside
* of the range increments by 1 as well. However, since x_l > x_t since l is not within the intersection
* of all flipped intervals, b_l > b_t originally, so incrementing b_t by 1 does not make the configuration
* invalid. Therefore, every interval that we flip must either include l or r. If there exists two intervals
* where one does not include l and the other does not include r, then we can unflip both of them. Let b'
* represent the new values at each location. For similar reasons as before, b'_l >= b'_i for l <= i <= r
* because a_l and a_r are the max values of a over the entire array, but x'_l and x'_r are still the
* lowest values between l and r (since they are the farthest from t). Everything outside of l and r will
* either not change in value or decrease by 2, so overall, the combination is still valid. We can keep
* repeating this process until all remaining ranges contain either l or r, so we could have chosen t = l
* or t = r. Therefore, we only need to check these two location.
*
* Overall, this cuts a factor of O(nm) from the solution, so the new time complexity is
* O(n log(n) log(sum of c)), which passes.
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <array>
#include <algorithm>
#include <utility>
#include <map>
#include <queue>
#include <set>
#include <cmath>
#include <cstdio>
#include <cstring>
#define ll long long
#define ld long double
#define eps 1e-8
#define MOD 1000000007
#define INF 0x3f3f3f3f
#define INFLL 0x3f3f3f3f3f3f3f3f
// change if necessary
#define MAXN 200010
using namespace std;
int n, m;
vector<array<int, 3>> range[MAXN];
ll init[MAXN];
int min_check, max_check;
struct cmp {
bool operator()(const array<int, 3> &a, const array<int, 3> &b) const {
if (a[1] == b[1]) {
if (a[0] == b[0]) {
return a[2] < b[2];
}
return a[0] > b[0];
}
return a[1] < b[1];
}
};
struct bit {
ll vals[MAXN];
void reset() {
for (int i = 0; i < n + 10; i++) {
vals[i] = 0;
}
for (int i = 0; i < n; i++) {
ll x = init[i];
if (i) x -= init[i - 1];
upd(i, x);
}
}
void upd(int x, ll v) {
x++;
while (x < n + 10) {
vals[x] += v;
x += x & -x;
}
}
void upd(int l, int r, ll v) {
upd(l, v);
upd(r, -v);
}
ll qry(int x) {
x++;
ll res = 0;
while (x) {
res += vals[x];
x -= x & -x;
}
return res;
}
} b;
ll check(ll m, ll n, ll t) {
b.reset();
priority_queue<array<int, 3>, vector<array<int, 3>>, cmp> pq;
for (int i = 0; i <= t; i++) {
ll need_rem = max((b.qry(i) + n - m + 1) / 2, 0LL);
n -= need_rem;
for (auto &arr : range[i]) {
if (arr[1] > t) {
pq.push(arr);
}
}
while (need_rem) {
if (pq.empty()) {
return false;
}
auto t = pq.top(); pq.pop();
ll to_rem = min<ll>(t[2], need_rem);
b.upd(0, t[0], to_rem);
b.upd(t[0], t[1], -to_rem);
b.upd(t[1], ::n, to_rem);
t[2] -= to_rem;
need_rem -= to_rem;
if (t[2]) pq.push(t);
}
}
for (int i = 0; i < ::n; i++) {
if (b.qry(i) > m) {
return false;
}
}
return true;
}
ll check(ll m) {
ll a = init[min_check];
return check(m, a - m, min_check) || check(m, a - m + 1, min_check)
|| check(m, a - m, max_check) || check(m, a - m + 1, max_check);
}
int main() {
cin.tie(0)->sync_with_stdio(0);
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b, c; cin >> a >> b >> c;
a--; b--;
if (a > b) swap(a, b);
init[a] += c;
init[b] -= c;
range[a].push_back({a, b, c});
}
for (int i = 1; i < n; i++) {
init[i] += init[i - 1];
}
for (int i = 0; i < n; i++) {
if (init[i] > init[min_check]) {
min_check = i;
max_check = i;
} else if (init[i] == init[min_check]) {
max_check = i;
}
}
ll l = 0;
ll r = init[min_check];
ll ans = init[min_check];
while (l <= r) {
ll m = (l + r) / 2;
if (check(m)) {
ans = m;
r = m - 1;
} else {
l = m + 1;
}
}
cout << ans << '\n';
return 0;
}
| [
"[email protected]"
] | |
9c3fa67cf4ece508073c0b6822db284debea7229 | 70fe255d0a301952a023be5e1c1fefd062d1e804 | /LintCode/37.cpp | f1154a8fa46ae6f897c35bd74ec803f12ec70812 | [
"MIT"
] | permissive | LauZyHou/Algorithm-To-Practice | 524d4318032467a975cf548d0c824098d63cca59 | 66c047fe68409c73a077eae561cf82b081cf8e45 | refs/heads/master | 2021-06-18T01:48:43.378355 | 2021-01-27T14:44:14 | 2021-01-27T14:44:14 | 147,997,740 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 255 | cpp | class Solution {
public:
/**
* @param number: A 3-digit number.
* @return: Reversed number.
*/
int reverseInteger(int number) {
int a = number%10;
int b = number/10%10;
int c = number/100;
return a*100+b*10+c;
}
}; | [
"[email protected]"
] | |
8a96e354acf08b5427cf3791a514286b61b32365 | ddbc8b916e028cf70467928d3be17506713baeff | /src/Setup/unzip.cpp | c2b062c3bb714c756f317e2995e1129180774b39 | [
"MIT"
] | permissive | Squirrel/Squirrel.Windows | e7687f81ae08ebf6f4b6005ed8394f78f6c9c1ad | 5e44cb4001a7d48f53ee524a2d90b3f5700a9920 | refs/heads/develop | 2023-09-03T23:06:14.600642 | 2023-08-01T17:34:34 | 2023-08-01T17:34:34 | 22,338,518 | 7,243 | 1,336 | MIT | 2023-08-01T17:34:36 | 2014-07-28T10:10:39 | C++ | UTF-8 | C++ | false | false | 145,049 | cpp | #include "stdafx.h"
#include "unzip.h"
// THIS FILE is almost entirely based upon code by Jean-loup Gailly
// and Mark Adler. It has been modified by Lucian Wischik.
// The modifications were: incorporate the bugfixes of 1.1.4, allow
// unzipping to/from handles/pipes/files/memory, encryption, unicode,
// a windowsish api, and putting everything into a single .cpp file.
// The original code may be found at http://www.gzip.org/zlib/
// The original copyright text follows.
//
//
//
// zlib.h -- interface of the 'zlib' general purpose compression library
// version 1.1.3, July 9th, 1998
//
// Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// Jean-loup Gailly Mark Adler
// [email protected] [email protected]
//
//
// The data format used by the zlib library is described by RFCs (Request for
// Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt
// (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
//
//
// The 'zlib' compression library provides in-memory compression and
// decompression functions, including integrity checks of the uncompressed
// data. This version of the library supports only one compression method
// (deflation) but other algorithms will be added later and will have the same
// stream interface.
//
// Compression can be done in a single step if the buffers are large
// enough (for example if an input file is mmap'ed), or can be done by
// repeated calls of the compression function. In the latter case, the
// application must provide more input and/or consume the output
// (providing more output space) before each call.
//
// The library also supports reading and writing files in gzip (.gz) format
// with an interface similar to that of stdio.
//
// The library does not install any signal handler. The decoder checks
// the consistency of the compressed data, so the library should never
// crash even in case of corrupted input.
//
// for more info about .ZIP format, see ftp://ftp.cdrom.com/pub/infozip/doc/appnote-970311-iz.zip
// PkWare has also a specification at ftp://ftp.pkware.com/probdesc.zip
#define ZIP_HANDLE 1
#define ZIP_FILENAME 2
#define ZIP_MEMORY 3
#define zmalloc(len) malloc(len)
#define zfree(p) free(p)
/*
void *zmalloc(unsigned int len)
{ char *buf = new char[len+32];
for (int i=0; i<16; i++)
{ buf[i]=i;
buf[len+31-i]=i;
}
*((unsigned int*)buf) = len;
char c[1000]; wsprintf(c,"malloc 0x%lx - %lu",buf+16,len);
OutputDebugString(c);
return buf+16;
}
void zfree(void *buf)
{ char c[1000]; wsprintf(c,"free 0x%lx",buf);
OutputDebugString(c);
char *p = ((char*)buf)-16;
unsigned int len = *((unsigned int*)p);
bool blown=false;
for (int i=0; i<16; i++)
{ char lo = p[i];
char hi = p[len+31-i];
if (hi!=i || (lo!=i && i>4)) blown=true;
}
if (blown)
{ OutputDebugString("BLOWN!!!");
}
delete[] p;
}
*/
typedef struct tm_unz_s
{ unsigned int tm_sec; // seconds after the minute - [0,59]
unsigned int tm_min; // minutes after the hour - [0,59]
unsigned int tm_hour; // hours since midnight - [0,23]
unsigned int tm_mday; // day of the month - [1,31]
unsigned int tm_mon; // months since January - [0,11]
unsigned int tm_year; // years - [1980..2044]
} tm_unz;
// unz_global_info structure contain global data about the ZIPfile
typedef struct unz_global_info_s
{ unsigned long number_entry; // total number of entries in the central dir on this disk
unsigned long size_comment; // size of the global comment of the zipfile
} unz_global_info;
// unz_file_info contain information about a file in the zipfile
typedef struct unz_file_info_s
{ unsigned long version; // version made by 2 bytes
unsigned long version_needed; // version needed to extract 2 bytes
unsigned long flag; // general purpose bit flag 2 bytes
unsigned long compression_method; // compression method 2 bytes
unsigned long dosDate; // last mod file date in Dos fmt 4 bytes
unsigned long crc; // crc-32 4 bytes
unsigned long compressed_size; // compressed size 4 bytes
unsigned long uncompressed_size; // uncompressed size 4 bytes
unsigned long size_filename; // filename length 2 bytes
unsigned long size_file_extra; // extra field length 2 bytes
unsigned long size_file_comment; // file comment length 2 bytes
unsigned long disk_num_start; // disk number start 2 bytes
unsigned long internal_fa; // internal file attributes 2 bytes
unsigned long external_fa; // external file attributes 4 bytes
tm_unz tmu_date;
} unz_file_info;
#define UNZ_OK (0)
#define UNZ_END_OF_LIST_OF_FILE (-100)
#define UNZ_ERRNO (Z_ERRNO)
#define UNZ_EOF (0)
#define UNZ_PARAMERROR (-102)
#define UNZ_BADZIPFILE (-103)
#define UNZ_INTERNALERROR (-104)
#define UNZ_CRCERROR (-105)
#define UNZ_PASSWORD (-106)
#define ZLIB_VERSION "1.1.3"
// Allowed flush values; see deflate() for details
#define Z_NO_FLUSH 0
#define Z_SYNC_FLUSH 2
#define Z_FULL_FLUSH 3
#define Z_FINISH 4
// compression levels
#define Z_NO_COMPRESSION 0
#define Z_BEST_SPEED 1
#define Z_BEST_COMPRESSION 9
#define Z_DEFAULT_COMPRESSION (-1)
// compression strategy; see deflateInit2() for details
#define Z_FILTERED 1
#define Z_HUFFMAN_ONLY 2
#define Z_DEFAULT_STRATEGY 0
// Possible values of the data_type field
#define Z_BINARY 0
#define Z_ASCII 1
#define Z_UNKNOWN 2
// The deflate compression method (the only one supported in this version)
#define Z_DEFLATED 8
// for initializing zalloc, zfree, opaque
#define Z_NULL 0
// case sensitivity when searching for filenames
#define CASE_SENSITIVE 1
#define CASE_INSENSITIVE 2
// Return codes for the compression/decompression functions. Negative
// values are errors, positive values are used for special but normal events.
#define Z_OK 0
#define Z_STREAM_END 1
#define Z_NEED_DICT 2
#define Z_ERRNO (-1)
#define Z_STREAM_ERROR (-2)
#define Z_DATA_ERROR (-3)
#define Z_MEM_ERROR (-4)
#define Z_BUF_ERROR (-5)
#define Z_VERSION_ERROR (-6)
// Basic data types
typedef unsigned char Byte; // 8 bits
typedef unsigned int uInt; // 16 bits or more
typedef unsigned long uLong; // 32 bits or more
typedef void *voidpf;
typedef void *voidp;
typedef long z_off_t;
typedef voidpf (*alloc_func) (voidpf opaque, uInt items, uInt size);
typedef void (*free_func) (voidpf opaque, voidpf address);
struct internal_state;
typedef struct z_stream_s {
Byte *next_in; // next input byte
uInt avail_in; // number of bytes available at next_in
uLong total_in; // total nb of input bytes read so far
Byte *next_out; // next output byte should be put there
uInt avail_out; // remaining free space at next_out
uLong total_out; // total nb of bytes output so far
char *msg; // last error message, NULL if no error
struct internal_state *state; // not visible by applications
alloc_func zalloc; // used to allocate the internal state
free_func zfree; // used to free the internal state
voidpf opaque; // private data object passed to zalloc and zfree
int data_type; // best guess about the data type: ascii or binary
uLong adler; // adler32 value of the uncompressed data
uLong reserved; // reserved for future use
} z_stream;
typedef z_stream *z_streamp;
// The application must update next_in and avail_in when avail_in has
// dropped to zero. It must update next_out and avail_out when avail_out
// has dropped to zero. The application must initialize zalloc, zfree and
// opaque before calling the init function. All other fields are set by the
// compression library and must not be updated by the application.
//
// The opaque value provided by the application will be passed as the first
// parameter for calls of zalloc and zfree. This can be useful for custom
// memory management. The compression library attaches no meaning to the
// opaque value.
//
// zalloc must return Z_NULL if there is not enough memory for the object.
// If zlib is used in a multi-threaded application, zalloc and zfree must be
// thread safe.
//
// The fields total_in and total_out can be used for statistics or
// progress reports. After compression, total_in holds the total size of
// the uncompressed data and may be saved for use in the decompressor
// (particularly if the decompressor wants to decompress everything in
// a single step).
//
// basic functions
const char *zlibVersion ();
// The application can compare zlibVersion and ZLIB_VERSION for consistency.
// If the first character differs, the library code actually used is
// not compatible with the zlib.h header file used by the application.
// This check is automatically made by inflateInit.
int inflate (z_streamp strm, int flush);
//
// inflate decompresses as much data as possible, and stops when the input
// buffer becomes empty or the output buffer becomes full. It may some
// introduce some output latency (reading input without producing any output)
// except when forced to flush.
//
// The detailed semantics are as follows. inflate performs one or both of the
// following actions:
//
// - Decompress more input starting at next_in and update next_in and avail_in
// accordingly. If not all input can be processed (because there is not
// enough room in the output buffer), next_in is updated and processing
// will resume at this point for the next call of inflate().
//
// - Provide more output starting at next_out and update next_out and avail_out
// accordingly. inflate() provides as much output as possible, until there
// is no more input data or no more space in the output buffer (see below
// about the flush parameter).
//
// Before the call of inflate(), the application should ensure that at least
// one of the actions is possible, by providing more input and/or consuming
// more output, and updating the next_* and avail_* values accordingly.
// The application can consume the uncompressed output when it wants, for
// example when the output buffer is full (avail_out == 0), or after each
// call of inflate(). If inflate returns Z_OK and with zero avail_out, it
// must be called again after making room in the output buffer because there
// might be more output pending.
//
// If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much
// output as possible to the output buffer. The flushing behavior of inflate is
// not specified for values of the flush parameter other than Z_SYNC_FLUSH
// and Z_FINISH, but the current implementation actually flushes as much output
// as possible anyway.
//
// inflate() should normally be called until it returns Z_STREAM_END or an
// error. However if all decompression is to be performed in a single step
// (a single call of inflate), the parameter flush should be set to
// Z_FINISH. In this case all pending input is processed and all pending
// output is flushed; avail_out must be large enough to hold all the
// uncompressed data. (The size of the uncompressed data may have been saved
// by the compressor for this purpose.) The next operation on this stream must
// be inflateEnd to deallocate the decompression state. The use of Z_FINISH
// is never required, but can be used to inform inflate that a faster routine
// may be used for the single inflate() call.
//
// If a preset dictionary is needed at this point (see inflateSetDictionary
// below), inflate sets strm-adler to the adler32 checksum of the
// dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise
// it sets strm->adler to the adler32 checksum of all output produced
// so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or
// an error code as described below. At the end of the stream, inflate()
// checks that its computed adler32 checksum is equal to that saved by the
// compressor and returns Z_STREAM_END only if the checksum is correct.
//
// inflate() returns Z_OK if some progress has been made (more input processed
// or more output produced), Z_STREAM_END if the end of the compressed data has
// been reached and all uncompressed output has been produced, Z_NEED_DICT if a
// preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
// corrupted (input stream not conforming to the zlib format or incorrect
// adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent
// (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not
// enough memory, Z_BUF_ERROR if no progress is possible or if there was not
// enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR
// case, the application may then call inflateSync to look for a good
// compression block.
//
int inflateEnd (z_streamp strm);
//
// All dynamically allocated data structures for this stream are freed.
// This function discards any unprocessed input and does not flush any
// pending output.
//
// inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
// was inconsistent. In the error case, msg may be set but then points to a
// static string (which must not be deallocated).
// Advanced functions
// The following functions are needed only in some special applications.
int inflateSetDictionary (z_streamp strm,
const Byte *dictionary,
uInt dictLength);
//
// Initializes the decompression dictionary from the given uncompressed byte
// sequence. This function must be called immediately after a call of inflate
// if this call returned Z_NEED_DICT. The dictionary chosen by the compressor
// can be determined from the Adler32 value returned by this call of
// inflate. The compressor and decompressor must use exactly the same
// dictionary.
//
// inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
// parameter is invalid (such as NULL dictionary) or the stream state is
// inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
// expected one (incorrect Adler32 value). inflateSetDictionary does not
// perform any decompression: this will be done by subsequent calls of
// inflate().
int inflateSync (z_streamp strm);
//
// Skips invalid compressed data until a full flush point can be found, or until all
// available input is skipped. No output is provided.
//
// inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
// if no more input was provided, Z_DATA_ERROR if no flush point has been found,
// or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
// case, the application may save the current current value of total_in which
// indicates where valid compressed data was found. In the error case, the
// application may repeatedly call inflateSync, providing more input each time,
// until success or end of the input data.
int inflateReset (z_streamp strm);
// This function is equivalent to inflateEnd followed by inflateInit,
// but does not free and reallocate all the internal decompression state.
// The stream will keep attributes that may have been set by inflateInit2.
//
// inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
// stream state was inconsistent (such as zalloc or state being NULL).
//
// checksum functions
// These functions are not related to compression but are exported
// anyway because they might be useful in applications using the
// compression library.
uLong adler32 (uLong adler, const Byte *buf, uInt len);
// Update a running Adler-32 checksum with the bytes buf[0..len-1] and
// return the updated checksum. If buf is NULL, this function returns
// the required initial value for the checksum.
// An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
// much faster. Usage example:
//
// uLong adler = adler32(0L, Z_NULL, 0);
//
// while (read_buffer(buffer, length) != EOF) {
// adler = adler32(adler, buffer, length);
// }
// if (adler != original_adler) error();
uLong ucrc32 (uLong crc, const Byte *buf, uInt len);
// Update a running crc with the bytes buf[0..len-1] and return the updated
// crc. If buf is NULL, this function returns the required initial value
// for the crc. Pre- and post-conditioning (one's complement) is performed
// within this function so it shouldn't be done by the application.
// Usage example:
//
// uLong crc = crc32(0L, Z_NULL, 0);
//
// while (read_buffer(buffer, length) != EOF) {
// crc = crc32(crc, buffer, length);
// }
// if (crc != original_crc) error();
const char *zError (int err);
int inflateSyncPoint (z_streamp z);
const uLong *get_crc_table (void);
typedef unsigned char uch;
typedef uch uchf;
typedef unsigned short ush;
typedef ush ushf;
typedef unsigned long ulg;
const char * const z_errmsg[10] = { // indexed by 2-zlib_error
"need dictionary", // Z_NEED_DICT 2
"stream end", // Z_STREAM_END 1
"", // Z_OK 0
"file error", // Z_ERRNO (-1)
"stream error", // Z_STREAM_ERROR (-2)
"data error", // Z_DATA_ERROR (-3)
"insufficient memory", // Z_MEM_ERROR (-4)
"buffer error", // Z_BUF_ERROR (-5)
"incompatible version",// Z_VERSION_ERROR (-6)
""};
#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
#define ERR_RETURN(strm,err) \
return (strm->msg = (char*)ERR_MSG(err), (err))
// To be used only when the state is known to be valid
// common constants
#define STORED_BLOCK 0
#define STATIC_TREES 1
#define DYN_TREES 2
// The three kinds of block type
#define MIN_MATCH 3
#define MAX_MATCH 258
// The minimum and maximum match lengths
#define PRESET_DICT 0x20 // preset dictionary flag in zlib header
// target dependencies
#define OS_CODE 0x0b // Window 95 & Windows NT
// functions
#define zmemzero(dest, len) memset(dest, 0, len)
// Diagnostic functions
#define LuAssert(cond,msg)
#define LuTrace(x)
#define LuTracev(x)
#define LuTracevv(x)
#define LuTracec(c,x)
#define LuTracecv(c,x)
typedef uLong (*check_func) (uLong check, const Byte *buf, uInt len);
voidpf zcalloc (voidpf opaque, unsigned items, unsigned size);
void zcfree (voidpf opaque, voidpf ptr);
#define ZALLOC(strm, items, size) \
(*((strm)->zalloc))((strm)->opaque, (items), (size))
#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
//void ZFREE(z_streamp strm,voidpf addr)
//{ *((strm)->zfree))((strm)->opaque, addr);
//}
#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
// Huffman code lookup table entry--this entry is four bytes for machines
// that have 16-bit pointers (e.g. PC's in the small or medium model).
typedef struct inflate_huft_s inflate_huft;
struct inflate_huft_s {
union {
struct {
Byte Exop; // number of extra bits or operation
Byte Bits; // number of bits in this code or subcode
} what;
uInt pad; // pad structure to a power of 2 (4 bytes for
} word; // 16-bit, 8 bytes for 32-bit int's)
uInt base; // literal, length base, distance base, or table offset
};
// Maximum size of dynamic tree. The maximum found in a long but non-
// exhaustive search was 1004 huft structures (850 for length/literals
// and 154 for distances, the latter actually the result of an
// exhaustive search). The actual maximum is not known, but the
// value below is more than safe.
#define MANY 1440
int inflate_trees_bits (
uInt *, // 19 code lengths
uInt *, // bits tree desired/actual depth
inflate_huft * *, // bits tree result
inflate_huft *, // space for trees
z_streamp); // for messages
int inflate_trees_dynamic (
uInt, // number of literal/length codes
uInt, // number of distance codes
uInt *, // that many (total) code lengths
uInt *, // literal desired/actual bit depth
uInt *, // distance desired/actual bit depth
inflate_huft * *, // literal/length tree result
inflate_huft * *, // distance tree result
inflate_huft *, // space for trees
z_streamp); // for messages
int inflate_trees_fixed (
uInt *, // literal desired/actual bit depth
uInt *, // distance desired/actual bit depth
const inflate_huft * *, // literal/length tree result
const inflate_huft * *, // distance tree result
z_streamp); // for memory allocation
struct inflate_blocks_state;
typedef struct inflate_blocks_state inflate_blocks_statef;
inflate_blocks_statef * inflate_blocks_new (
z_streamp z,
check_func c, // check function
uInt w); // window size
int inflate_blocks (
inflate_blocks_statef *,
z_streamp ,
int); // initial return code
void inflate_blocks_reset (
inflate_blocks_statef *,
z_streamp ,
uLong *); // check value on output
int inflate_blocks_free (
inflate_blocks_statef *,
z_streamp);
void inflate_set_dictionary (
inflate_blocks_statef *s,
const Byte *d, // dictionary
uInt n); // dictionary length
int inflate_blocks_sync_point (
inflate_blocks_statef *s);
struct inflate_codes_state;
typedef struct inflate_codes_state inflate_codes_statef;
inflate_codes_statef *inflate_codes_new (
uInt, uInt,
const inflate_huft *, const inflate_huft *,
z_streamp );
int inflate_codes (
inflate_blocks_statef *,
z_streamp ,
int);
void inflate_codes_free (
inflate_codes_statef *,
z_streamp );
typedef enum {
IBM_TYPE, // get type bits (3, including end bit)
IBM_LENS, // get lengths for stored
IBM_STORED, // processing stored block
IBM_TABLE, // get table lengths
IBM_BTREE, // get bit lengths tree for a dynamic block
IBM_DTREE, // get length, distance trees for a dynamic block
IBM_CODES, // processing fixed or dynamic block
IBM_DRY, // output remaining window bytes
IBM_DONE, // finished last block, done
IBM_BAD} // got a data error--stuck here
inflate_block_mode;
// inflate blocks semi-private state
struct inflate_blocks_state {
// mode
inflate_block_mode mode; // current inflate_block mode
// mode dependent information
union {
uInt left; // if STORED, bytes left to copy
struct {
uInt table; // table lengths (14 bits)
uInt index; // index into blens (or border)
uInt *blens; // bit lengths of codes
uInt bb; // bit length tree depth
inflate_huft *tb; // bit length decoding tree
} trees; // if DTREE, decoding info for trees
struct {
inflate_codes_statef
*codes;
} decode; // if CODES, current state
} sub; // submode
uInt last; // true if this block is the last block
// mode independent information
uInt bitk; // bits in bit buffer
uLong bitb; // bit buffer
inflate_huft *hufts; // single malloc for tree space
Byte *window; // sliding window
Byte *end; // one byte after sliding window
Byte *read; // window read pointer
Byte *write; // window write pointer
check_func checkfn; // check function
uLong check; // check on output
};
// defines for inflate input/output
// update pointers and return
#define UPDBITS {s->bitb=b;s->bitk=k;}
#define UPDIN {z->avail_in=n;z->total_in+=(uLong)(p-z->next_in);z->next_in=p;}
#define UPDOUT {s->write=q;}
#define UPDATE {UPDBITS UPDIN UPDOUT}
#define LEAVE {UPDATE return inflate_flush(s,z,r);}
// get bytes and bits
#define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;}
#define NEEDBYTE {if(n)r=Z_OK;else LEAVE}
#define NEXTBYTE (n--,*p++)
#define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<<k;k+=8;}}
#define DUMPBITS(j) {b>>=(j);k-=(j);}
// output bytes
#define WAVAIL (uInt)(q<s->read?s->read-q-1:s->end-q)
#define LOADOUT {q=s->write;m=(uInt)WAVAIL;m;}
#define WRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=(uInt)WAVAIL;}}
#define FLUSH {UPDOUT r=inflate_flush(s,z,r); LOADOUT}
#define NEEDOUT {if(m==0){WRAP if(m==0){FLUSH WRAP if(m==0) LEAVE}}r=Z_OK;}
#define OUTBYTE(a) {*q++=(Byte)(a);m--;}
// load local pointers
#define LOAD {LOADIN LOADOUT}
// masks for lower bits (size given to avoid silly warnings with Visual C++)
// And'ing with mask[n] masks the lower n bits
const uInt inflate_mask[17] = {
0x0000,
0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
};
// copy as much as possible from the sliding window to the output area
int inflate_flush (inflate_blocks_statef *, z_streamp, int);
int inflate_fast (uInt, uInt, const inflate_huft *, const inflate_huft *, inflate_blocks_statef *, z_streamp );
const uInt fixed_bl = 9;
const uInt fixed_bd = 5;
const inflate_huft fixed_tl[] = {
{{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
{{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},192},
{{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},160},
{{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},224},
{{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},144},
{{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},208},
{{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},176},
{{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},240},
{{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
{{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},200},
{{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},168},
{{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},232},
{{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},152},
{{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},216},
{{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},184},
{{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},248},
{{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
{{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},196},
{{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},164},
{{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},228},
{{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},148},
{{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},212},
{{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},180},
{{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},244},
{{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
{{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},204},
{{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},172},
{{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},236},
{{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},156},
{{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},220},
{{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},188},
{{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},252},
{{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
{{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},194},
{{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},162},
{{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},226},
{{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},146},
{{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},210},
{{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},178},
{{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},242},
{{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
{{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},202},
{{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},170},
{{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},234},
{{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},154},
{{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},218},
{{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},186},
{{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},250},
{{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
{{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},198},
{{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},166},
{{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},230},
{{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},150},
{{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},214},
{{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},182},
{{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},246},
{{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
{{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},206},
{{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},174},
{{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},238},
{{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},158},
{{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},222},
{{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},190},
{{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},254},
{{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
{{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},193},
{{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},161},
{{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},225},
{{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},145},
{{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},209},
{{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},177},
{{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},241},
{{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
{{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},201},
{{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},169},
{{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},233},
{{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},153},
{{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},217},
{{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},185},
{{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},249},
{{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
{{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},197},
{{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},165},
{{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},229},
{{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},149},
{{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},213},
{{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},181},
{{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},245},
{{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
{{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},205},
{{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},173},
{{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},237},
{{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},157},
{{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},221},
{{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},189},
{{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},253},
{{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
{{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},195},
{{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},163},
{{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},227},
{{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},147},
{{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},211},
{{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},179},
{{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},243},
{{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
{{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},203},
{{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},171},
{{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},235},
{{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},155},
{{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},219},
{{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},187},
{{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},251},
{{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
{{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},199},
{{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},167},
{{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},231},
{{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},151},
{{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},215},
{{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},183},
{{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},247},
{{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
{{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},207},
{{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},175},
{{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},239},
{{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},159},
{{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},223},
{{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},191},
{{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},255}
};
const inflate_huft fixed_td[] = {
{{{80,5}},1}, {{{87,5}},257}, {{{83,5}},17}, {{{91,5}},4097},
{{{81,5}},5}, {{{89,5}},1025}, {{{85,5}},65}, {{{93,5}},16385},
{{{80,5}},3}, {{{88,5}},513}, {{{84,5}},33}, {{{92,5}},8193},
{{{82,5}},9}, {{{90,5}},2049}, {{{86,5}},129}, {{{192,5}},24577},
{{{80,5}},2}, {{{87,5}},385}, {{{83,5}},25}, {{{91,5}},6145},
{{{81,5}},7}, {{{89,5}},1537}, {{{85,5}},97}, {{{93,5}},24577},
{{{80,5}},4}, {{{88,5}},769}, {{{84,5}},49}, {{{92,5}},12289},
{{{82,5}},13}, {{{90,5}},3073}, {{{86,5}},193}, {{{192,5}},24577}
};
// copy as much as possible from the sliding window to the output area
int inflate_flush(inflate_blocks_statef *s,z_streamp z,int r)
{
uInt n;
Byte *p;
Byte *q;
// local copies of source and destination pointers
p = z->next_out;
q = s->read;
// compute number of bytes to copy as far as end of window
n = (uInt)((q <= s->write ? s->write : s->end) - q);
if (n > z->avail_out) n = z->avail_out;
if (n && r == Z_BUF_ERROR) r = Z_OK;
// update counters
z->avail_out -= n;
z->total_out += n;
// update check information
if (s->checkfn != Z_NULL)
z->adler = s->check = (*s->checkfn)(s->check, q, n);
// copy as far as end of window
if (n!=0) // check for n!=0 to avoid waking up CodeGuard
{ memcpy(p, q, n);
p += n;
q += n;
}
// see if more to copy at beginning of window
if (q == s->end)
{
// wrap pointers
q = s->window;
if (s->write == s->end)
s->write = s->window;
// compute bytes to copy
n = (uInt)(s->write - q);
if (n > z->avail_out) n = z->avail_out;
if (n && r == Z_BUF_ERROR) r = Z_OK;
// update counters
z->avail_out -= n;
z->total_out += n;
// update check information
if (s->checkfn != Z_NULL)
z->adler = s->check = (*s->checkfn)(s->check, q, n);
// copy
if (n!=0) {memcpy(p,q,n); p+=n; q+=n;}
}
// update pointers
z->next_out = p;
s->read = q;
// done
return r;
}
// simplify the use of the inflate_huft type with some defines
#define exop word.what.Exop
#define bits word.what.Bits
typedef enum { // waiting for "i:"=input, "o:"=output, "x:"=nothing
START, // x: set up for LEN
LEN, // i: get length/literal/eob next
LENEXT, // i: getting length extra (have base)
DIST, // i: get distance next
DISTEXT, // i: getting distance extra
COPY, // o: copying bytes in window, waiting for space
LIT, // o: got literal, waiting for output space
WASH, // o: got eob, possibly still output waiting
END, // x: got eob and all data flushed
BADCODE} // x: got error
inflate_codes_mode;
// inflate codes private state
struct inflate_codes_state {
// mode
inflate_codes_mode mode; // current inflate_codes mode
// mode dependent information
uInt len;
union {
struct {
const inflate_huft *tree; // pointer into tree
uInt need; // bits needed
} code; // if LEN or DIST, where in tree
uInt lit; // if LIT, literal
struct {
uInt get; // bits to get for extra
uInt dist; // distance back to copy from
} copy; // if EXT or COPY, where and how much
} sub; // submode
// mode independent information
Byte lbits; // ltree bits decoded per branch
Byte dbits; // dtree bits decoder per branch
const inflate_huft *ltree; // literal/length/eob tree
const inflate_huft *dtree; // distance tree
};
inflate_codes_statef *inflate_codes_new(
uInt bl, uInt bd,
const inflate_huft *tl,
const inflate_huft *td, // need separate declaration for Borland C++
z_streamp z)
{
inflate_codes_statef *c;
if ((c = (inflate_codes_statef *)
ZALLOC(z,1,sizeof(struct inflate_codes_state))) != Z_NULL)
{
c->mode = START;
c->lbits = (Byte)bl;
c->dbits = (Byte)bd;
c->ltree = tl;
c->dtree = td;
LuTracev((stderr, "inflate: codes new\n"));
}
return c;
}
int inflate_codes(inflate_blocks_statef *s, z_streamp z, int r)
{
uInt j; // temporary storage
const inflate_huft *t; // temporary pointer
uInt e; // extra bits or operation
uLong b; // bit buffer
uInt k; // bits in bit buffer
Byte *p; // input data pointer
uInt n; // bytes available there
Byte *q; // output window write pointer
uInt m; // bytes to end of window or read pointer
Byte *f; // pointer to copy strings from
inflate_codes_statef *c = s->sub.decode.codes; // codes state
// copy input/output information to locals (UPDATE macro restores)
LOAD
// process input and output based on current state
for(;;) switch (c->mode)
{ // waiting for "i:"=input, "o:"=output, "x:"=nothing
case START: // x: set up for LEN
#ifndef SLOW
if (m >= 258 && n >= 10)
{
UPDATE
r = inflate_fast(c->lbits, c->dbits, c->ltree, c->dtree, s, z);
LOAD
if (r != Z_OK)
{
c->mode = r == Z_STREAM_END ? WASH : BADCODE;
break;
}
}
#endif // !SLOW
c->sub.code.need = c->lbits;
c->sub.code.tree = c->ltree;
c->mode = LEN;
case LEN: // i: get length/literal/eob next
j = c->sub.code.need;
NEEDBITS(j)
t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
DUMPBITS(t->bits)
e = (uInt)(t->exop);
if (e == 0) // literal
{
c->sub.lit = t->base;
LuTracevv((stderr, t->base >= 0x20 && t->base < 0x7f ?
"inflate: literal '%c'\n" :
"inflate: literal 0x%02x\n", t->base));
c->mode = LIT;
break;
}
if (e & 16) // length
{
c->sub.copy.get = e & 15;
c->len = t->base;
c->mode = LENEXT;
break;
}
if ((e & 64) == 0) // next table
{
c->sub.code.need = e;
c->sub.code.tree = t + t->base;
break;
}
if (e & 32) // end of block
{
LuTracevv((stderr, "inflate: end of block\n"));
c->mode = WASH;
break;
}
c->mode = BADCODE; // invalid code
z->msg = (char*)"invalid literal/length code";
r = Z_DATA_ERROR;
LEAVE
case LENEXT: // i: getting length extra (have base)
j = c->sub.copy.get;
NEEDBITS(j)
c->len += (uInt)b & inflate_mask[j];
DUMPBITS(j)
c->sub.code.need = c->dbits;
c->sub.code.tree = c->dtree;
LuTracevv((stderr, "inflate: length %u\n", c->len));
c->mode = DIST;
case DIST: // i: get distance next
j = c->sub.code.need;
NEEDBITS(j)
t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
DUMPBITS(t->bits)
e = (uInt)(t->exop);
if (e & 16) // distance
{
c->sub.copy.get = e & 15;
c->sub.copy.dist = t->base;
c->mode = DISTEXT;
break;
}
if ((e & 64) == 0) // next table
{
c->sub.code.need = e;
c->sub.code.tree = t + t->base;
break;
}
c->mode = BADCODE; // invalid code
z->msg = (char*)"invalid distance code";
r = Z_DATA_ERROR;
LEAVE
case DISTEXT: // i: getting distance extra
j = c->sub.copy.get;
NEEDBITS(j)
c->sub.copy.dist += (uInt)b & inflate_mask[j];
DUMPBITS(j)
LuTracevv((stderr, "inflate: distance %u\n", c->sub.copy.dist));
c->mode = COPY;
case COPY: // o: copying bytes in window, waiting for space
f = q - c->sub.copy.dist;
while (f < s->window) // modulo window size-"while" instead
f += s->end - s->window; // of "if" handles invalid distances
while (c->len)
{
NEEDOUT
OUTBYTE(*f++)
if (f == s->end)
f = s->window;
c->len--;
}
c->mode = START;
break;
case LIT: // o: got literal, waiting for output space
NEEDOUT
OUTBYTE(c->sub.lit)
c->mode = START;
break;
case WASH: // o: got eob, possibly more output
if (k > 7) // return unused byte, if any
{
//Assert(k < 16, "inflate_codes grabbed too many bytes")
k -= 8;
n++;
p--; // can always return one
}
FLUSH
if (s->read != s->write)
LEAVE
c->mode = END;
case END:
r = Z_STREAM_END;
LEAVE
case BADCODE: // x: got error
r = Z_DATA_ERROR;
LEAVE
default:
r = Z_STREAM_ERROR;
LEAVE
}
}
void inflate_codes_free(inflate_codes_statef *c,z_streamp z)
{ ZFREE(z, c);
LuTracev((stderr, "inflate: codes free\n"));
}
// infblock.c -- interpret and process block types to last block
// Copyright (C) 1995-1998 Mark Adler
// For conditions of distribution and use, see copyright notice in zlib.h
//struct inflate_codes_state {int dummy;}; // for buggy compilers
// Table for deflate from PKZIP's appnote.txt.
const uInt border[] = { // Order of the bit length code lengths
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
//
// Notes beyond the 1.93a appnote.txt:
//
// 1. Distance pointers never point before the beginning of the output stream.
// 2. Distance pointers can point back across blocks, up to 32k away.
// 3. There is an implied maximum of 7 bits for the bit length table and
// 15 bits for the actual data.
// 4. If only one code exists, then it is encoded using one bit. (Zero
// would be more efficient, but perhaps a little confusing.) If two
// codes exist, they are coded using one bit each (0 and 1).
// 5. There is no way of sending zero distance codes--a dummy must be
// sent if there are none. (History: a pre 2.0 version of PKZIP would
// store blocks with no distance codes, but this was discovered to be
// too harsh a criterion.) Valid only for 1.93a. 2.04c does allow
// zero distance codes, which is sent as one code of zero bits in
// length.
// 6. There are up to 286 literal/length codes. Code 256 represents the
// end-of-block. Note however that the static length tree defines
// 288 codes just to fill out the Huffman codes. Codes 286 and 287
// cannot be used though, since there is no length base or extra bits
// defined for them. Similarily, there are up to 30 distance codes.
// However, static trees define 32 codes (all 5 bits) to fill out the
// Huffman codes, but the last two had better not show up in the data.
// 7. Unzip can check dynamic Huffman blocks for complete code sets.
// The exception is that a single code would not be complete (see #4).
// 8. The five bits following the block type is really the number of
// literal codes sent minus 257.
// 9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
// (1+6+6). Therefore, to output three times the length, you output
// three codes (1+1+1), whereas to output four times the same length,
// you only need two codes (1+3). Hmm.
//10. In the tree reconstruction algorithm, Code = Code + Increment
// only if BitLength(i) is not zero. (Pretty obvious.)
//11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19)
//12. Note: length code 284 can represent 227-258, but length code 285
// really is 258. The last length deserves its own, short code
// since it gets used a lot in very redundant files. The length
// 258 is special since 258 - 3 (the min match length) is 255.
//13. The literal/length and distance code bit lengths are read as a
// single stream of lengths. It is possible (and advantageous) for
// a repeat code (16, 17, or 18) to go across the boundary between
// the two sets of lengths.
void inflate_blocks_reset(inflate_blocks_statef *s, z_streamp z, uLong *c)
{
if (c != Z_NULL)
*c = s->check;
if (s->mode == IBM_BTREE || s->mode == IBM_DTREE)
ZFREE(z, s->sub.trees.blens);
if (s->mode == IBM_CODES)
inflate_codes_free(s->sub.decode.codes, z);
s->mode = IBM_TYPE;
s->bitk = 0;
s->bitb = 0;
s->read = s->write = s->window;
if (s->checkfn != Z_NULL)
z->adler = s->check = (*s->checkfn)(0L, (const Byte *)Z_NULL, 0);
LuTracev((stderr, "inflate: blocks reset\n"));
}
inflate_blocks_statef *inflate_blocks_new(z_streamp z, check_func c, uInt w)
{
inflate_blocks_statef *s;
if ((s = (inflate_blocks_statef *)ZALLOC
(z,1,sizeof(struct inflate_blocks_state))) == Z_NULL)
return s;
if ((s->hufts =
(inflate_huft *)ZALLOC(z, sizeof(inflate_huft), MANY)) == Z_NULL)
{
ZFREE(z, s);
return Z_NULL;
}
if ((s->window = (Byte *)ZALLOC(z, 1, w)) == Z_NULL)
{
ZFREE(z, s->hufts);
ZFREE(z, s);
return Z_NULL;
}
s->end = s->window + w;
s->checkfn = c;
s->mode = IBM_TYPE;
LuTracev((stderr, "inflate: blocks allocated\n"));
inflate_blocks_reset(s, z, Z_NULL);
return s;
}
int inflate_blocks(inflate_blocks_statef *s, z_streamp z, int r)
{
uInt t; // temporary storage
uLong b; // bit buffer
uInt k; // bits in bit buffer
Byte *p; // input data pointer
uInt n; // bytes available there
Byte *q; // output window write pointer
uInt m; // bytes to end of window or read pointer
// copy input/output information to locals (UPDATE macro restores)
LOAD
// process input based on current state
for(;;) switch (s->mode)
{
case IBM_TYPE:
NEEDBITS(3)
t = (uInt)b & 7;
s->last = t & 1;
switch (t >> 1)
{
case 0: // stored
LuTracev((stderr, "inflate: stored block%s\n",
s->last ? " (last)" : ""));
DUMPBITS(3)
t = k & 7; // go to byte boundary
DUMPBITS(t)
s->mode = IBM_LENS; // get length of stored block
break;
case 1: // fixed
LuTracev((stderr, "inflate: fixed codes block%s\n",
s->last ? " (last)" : ""));
{
uInt bl, bd;
const inflate_huft *tl, *td;
inflate_trees_fixed(&bl, &bd, &tl, &td, z);
s->sub.decode.codes = inflate_codes_new(bl, bd, tl, td, z);
if (s->sub.decode.codes == Z_NULL)
{
r = Z_MEM_ERROR;
LEAVE
}
}
DUMPBITS(3)
s->mode = IBM_CODES;
break;
case 2: // dynamic
LuTracev((stderr, "inflate: dynamic codes block%s\n",
s->last ? " (last)" : ""));
DUMPBITS(3)
s->mode = IBM_TABLE;
break;
case 3: // illegal
DUMPBITS(3)
s->mode = IBM_BAD;
z->msg = (char*)"invalid block type";
r = Z_DATA_ERROR;
LEAVE
}
break;
case IBM_LENS:
NEEDBITS(32)
if ((((~b) >> 16) & 0xffff) != (b & 0xffff))
{
s->mode = IBM_BAD;
z->msg = (char*)"invalid stored block lengths";
r = Z_DATA_ERROR;
LEAVE
}
s->sub.left = (uInt)b & 0xffff;
b = k = 0; // dump bits
LuTracev((stderr, "inflate: stored length %u\n", s->sub.left));
s->mode = s->sub.left ? IBM_STORED : (s->last ? IBM_DRY : IBM_TYPE);
break;
case IBM_STORED:
if (n == 0)
LEAVE
NEEDOUT
t = s->sub.left;
if (t > n) t = n;
if (t > m) t = m;
memcpy(q, p, t);
p += t; n -= t;
q += t; m -= t;
if ((s->sub.left -= t) != 0)
break;
LuTracev((stderr, "inflate: stored end, %lu total out\n",
z->total_out + (q >= s->read ? q - s->read :
(s->end - s->read) + (q - s->window))));
s->mode = s->last ? IBM_DRY : IBM_TYPE;
break;
case IBM_TABLE:
NEEDBITS(14)
s->sub.trees.table = t = (uInt)b & 0x3fff;
// remove this section to workaround bug in pkzip
if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29)
{
s->mode = IBM_BAD;
z->msg = (char*)"too many length or distance symbols";
r = Z_DATA_ERROR;
LEAVE
}
// end remove
t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
if ((s->sub.trees.blens = (uInt*)ZALLOC(z, t, sizeof(uInt))) == Z_NULL)
{
r = Z_MEM_ERROR;
LEAVE
}
DUMPBITS(14)
s->sub.trees.index = 0;
LuTracev((stderr, "inflate: table sizes ok\n"));
s->mode = IBM_BTREE;
case IBM_BTREE:
while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10))
{
NEEDBITS(3)
s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7;
DUMPBITS(3)
}
while (s->sub.trees.index < 19)
s->sub.trees.blens[border[s->sub.trees.index++]] = 0;
s->sub.trees.bb = 7;
t = inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb,
&s->sub.trees.tb, s->hufts, z);
if (t != Z_OK)
{
r = t;
if (r == Z_DATA_ERROR)
{
ZFREE(z, s->sub.trees.blens);
s->mode = IBM_BAD;
}
LEAVE
}
s->sub.trees.index = 0;
LuTracev((stderr, "inflate: bits tree ok\n"));
s->mode = IBM_DTREE;
case IBM_DTREE:
while (t = s->sub.trees.table,
s->sub.trees.index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))
{
inflate_huft *h;
uInt i, j, c;
t = s->sub.trees.bb;
NEEDBITS(t)
h = s->sub.trees.tb + ((uInt)b & inflate_mask[t]);
t = h->bits;
c = h->base;
if (c < 16)
{
DUMPBITS(t)
s->sub.trees.blens[s->sub.trees.index++] = c;
}
else // c == 16..18
{
i = c == 18 ? 7 : c - 14;
j = c == 18 ? 11 : 3;
NEEDBITS(t + i)
DUMPBITS(t)
j += (uInt)b & inflate_mask[i];
DUMPBITS(i)
i = s->sub.trees.index;
t = s->sub.trees.table;
if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) ||
(c == 16 && i < 1))
{
ZFREE(z, s->sub.trees.blens);
s->mode = IBM_BAD;
z->msg = (char*)"invalid bit length repeat";
r = Z_DATA_ERROR;
LEAVE
}
c = c == 16 ? s->sub.trees.blens[i - 1] : 0;
do {
s->sub.trees.blens[i++] = c;
} while (--j);
s->sub.trees.index = i;
}
}
s->sub.trees.tb = Z_NULL;
{
uInt bl, bd;
inflate_huft *tl, *td;
inflate_codes_statef *c;
bl = 9; // must be <= 9 for lookahead assumptions
bd = 6; // must be <= 9 for lookahead assumptions
t = s->sub.trees.table;
t = inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f),
s->sub.trees.blens, &bl, &bd, &tl, &td,
s->hufts, z);
if (t != Z_OK)
{
if (t == (uInt)Z_DATA_ERROR)
{
ZFREE(z, s->sub.trees.blens);
s->mode = IBM_BAD;
}
r = t;
LEAVE
}
LuTracev((stderr, "inflate: trees ok\n"));
if ((c = inflate_codes_new(bl, bd, tl, td, z)) == Z_NULL)
{
r = Z_MEM_ERROR;
LEAVE
}
s->sub.decode.codes = c;
}
ZFREE(z, s->sub.trees.blens);
s->mode = IBM_CODES;
case IBM_CODES:
UPDATE
if ((r = inflate_codes(s, z, r)) != Z_STREAM_END)
return inflate_flush(s, z, r);
r = Z_OK;
inflate_codes_free(s->sub.decode.codes, z);
LOAD
LuTracev((stderr, "inflate: codes end, %lu total out\n",
z->total_out + (q >= s->read ? q - s->read :
(s->end - s->read) + (q - s->window))));
if (!s->last)
{
s->mode = IBM_TYPE;
break;
}
s->mode = IBM_DRY;
case IBM_DRY:
FLUSH
if (s->read != s->write)
LEAVE
s->mode = IBM_DONE;
case IBM_DONE:
r = Z_STREAM_END;
LEAVE
case IBM_BAD:
r = Z_DATA_ERROR;
LEAVE
default:
r = Z_STREAM_ERROR;
LEAVE
}
}
int inflate_blocks_free(inflate_blocks_statef *s, z_streamp z)
{
inflate_blocks_reset(s, z, Z_NULL);
ZFREE(z, s->window);
ZFREE(z, s->hufts);
ZFREE(z, s);
LuTracev((stderr, "inflate: blocks freed\n"));
return Z_OK;
}
// inftrees.c -- generate Huffman trees for efficient decoding
// Copyright (C) 1995-1998 Mark Adler
// For conditions of distribution and use, see copyright notice in zlib.h
//
extern const char inflate_copyright[] =
" inflate 1.1.3 Copyright 1995-1998 Mark Adler ";
// If you use the zlib library in a product, an acknowledgment is welcome
// in the documentation of your product. If for some reason you cannot
// include such an acknowledgment, I would appreciate that you keep this
// copyright string in the executable of your product.
int huft_build (
uInt *, // code lengths in bits
uInt, // number of codes
uInt, // number of "simple" codes
const uInt *, // list of base values for non-simple codes
const uInt *, // list of extra bits for non-simple codes
inflate_huft **,// result: starting table
uInt *, // maximum lookup bits (returns actual)
inflate_huft *, // space for trees
uInt *, // hufts used in space
uInt * ); // space for values
// Tables for deflate from PKZIP's appnote.txt.
const uInt cplens[31] = { // Copy lengths for literal codes 257..285
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
// see note #13 above about 258
const uInt cplext[31] = { // Extra bits for literal codes 257..285
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; // 112==invalid
const uInt cpdist[30] = { // Copy offsets for distance codes 0..29
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577};
const uInt cpdext[30] = { // Extra bits for distance codes
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
12, 12, 13, 13};
//
// Huffman code decoding is performed using a multi-level table lookup.
// The fastest way to decode is to simply build a lookup table whose
// size is determined by the longest code. However, the time it takes
// to build this table can also be a factor if the data being decoded
// is not very long. The most common codes are necessarily the
// shortest codes, so those codes dominate the decoding time, and hence
// the speed. The idea is you can have a shorter table that decodes the
// shorter, more probable codes, and then point to subsidiary tables for
// the longer codes. The time it costs to decode the longer codes is
// then traded against the time it takes to make longer tables.
//
// This results of this trade are in the variables lbits and dbits
// below. lbits is the number of bits the first level table for literal/
// length codes can decode in one step, and dbits is the same thing for
// the distance codes. Subsequent tables are also less than or equal to
// those sizes. These values may be adjusted either when all of the
// codes are shorter than that, in which case the longest code length in
// bits is used, or when the shortest code is *longer* than the requested
// table size, in which case the length of the shortest code in bits is
// used.
//
// There are two different values for the two tables, since they code a
// different number of possibilities each. The literal/length table
// codes 286 possible values, or in a flat code, a little over eight
// bits. The distance table codes 30 possible values, or a little less
// than five bits, flat. The optimum values for speed end up being
// about one bit more than those, so lbits is 8+1 and dbits is 5+1.
// The optimum values may differ though from machine to machine, and
// possibly even between compilers. Your mileage may vary.
//
// If BMAX needs to be larger than 16, then h and x[] should be uLong.
#define BMAX 15 // maximum bit length of any code
int huft_build(
uInt *b, // code lengths in bits (all assumed <= BMAX)
uInt n, // number of codes (assumed <= 288)
uInt s, // number of simple-valued codes (0..s-1)
const uInt *d, // list of base values for non-simple codes
const uInt *e, // list of extra bits for non-simple codes
inflate_huft * *t, // result: starting table
uInt *m, // maximum lookup bits, returns actual
inflate_huft *hp, // space for trees
uInt *hn, // hufts used in space
uInt *v) // working area: values in order of bit length
// Given a list of code lengths and a maximum table size, make a set of
// tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR
// if the given code set is incomplete (the tables are still built in this
// case), or Z_DATA_ERROR if the input is invalid.
{
uInt a; // counter for codes of length k
uInt c[BMAX+1]; // bit length count table
uInt f; // i repeats in table every f entries
int g; // maximum code length
int h; // table level
register uInt i; // counter, current code
register uInt j; // counter
register int k; // number of bits in current code
int l; // bits per table (returned in m)
uInt mask; // (1 << w) - 1, to avoid cc -O bug on HP
register uInt *p; // pointer into c[], b[], or v[]
inflate_huft *q; // points to current table
struct inflate_huft_s r; // table entry for structure assignment
inflate_huft *u[BMAX]; // table stack
register int w; // bits before this table == (l * h)
uInt x[BMAX+1]; // bit offsets, then code stack
uInt *xp; // pointer into x
int y; // number of dummy codes added
uInt z; // number of entries in current table
// Generate counts for each bit length
p = c;
#define C0 *p++ = 0;
#define C2 C0 C0 C0 C0
#define C4 C2 C2 C2 C2
C4; p; // clear c[]--assume BMAX+1 is 16
p = b; i = n;
do {
c[*p++]++; // assume all entries <= BMAX
} while (--i);
if (c[0] == n) // null input--all zero length codes
{
*t = (inflate_huft *)Z_NULL;
*m = 0;
return Z_OK;
}
// Find minimum and maximum length, bound *m by those
l = *m;
for (j = 1; j <= BMAX; j++)
if (c[j])
break;
k = j; // minimum code length
if ((uInt)l < j)
l = j;
for (i = BMAX; i; i--)
if (c[i])
break;
g = i; // maximum code length
if ((uInt)l > i)
l = i;
*m = l;
// Adjust last length count to fill out codes, if needed
for (y = 1 << j; j < i; j++, y <<= 1)
if ((y -= c[j]) < 0)
return Z_DATA_ERROR;
if ((y -= c[i]) < 0)
return Z_DATA_ERROR;
c[i] += y;
// Generate starting offsets into the value table for each length
x[1] = j = 0;
p = c + 1; xp = x + 2;
while (--i) { // note that i == g from above
*xp++ = (j += *p++);
}
// Make a table of values in order of bit lengths
p = b; i = 0;
do {
if ((j = *p++) != 0)
v[x[j]++] = i;
} while (++i < n);
n = x[g]; // set n to length of v
// Generate the Huffman codes and for each, make the table entries
x[0] = i = 0; // first Huffman code is zero
p = v; // grab values in bit order
h = -1; // no tables yet--level -1
w = -l; // bits decoded == (l * h)
u[0] = (inflate_huft *)Z_NULL; // just to keep compilers happy
q = (inflate_huft *)Z_NULL; // ditto
z = 0; // ditto
// go through the bit lengths (k already is bits in shortest code)
for (; k <= g; k++)
{
a = c[k];
while (a--)
{
// here i is the Huffman code of length k bits for value *p
// make tables up to required level
while (k > w + l)
{
h++;
w += l; // previous table always l bits
// compute minimum size table less than or equal to l bits
z = g - w;
z = z > (uInt)l ? l : z; // table size upper limit
if ((f = 1 << (j = k - w)) > a + 1) // try a k-w bit table
{ // too few codes for k-w bit table
f -= a + 1; // deduct codes from patterns left
xp = c + k;
if (j < z)
while (++j < z) // try smaller tables up to z bits
{
if ((f <<= 1) <= *++xp)
break; // enough codes to use up j bits
f -= *xp; // else deduct codes from patterns
}
}
z = 1 << j; // table entries for j-bit table
// allocate new table
if (*hn + z > MANY) // (note: doesn't matter for fixed)
return Z_DATA_ERROR; // overflow of MANY
u[h] = q = hp + *hn;
*hn += z;
// connect to last table, if there is one
if (h)
{
x[h] = i; // save pattern for backing up
r.bits = (Byte)l; // bits to dump before this table
r.exop = (Byte)j; // bits in this table
j = i >> (w - l);
r.base = (uInt)(q - u[h-1] - j); // offset to this table
u[h-1][j] = r; // connect to last table
}
else
*t = q; // first table is returned result
}
// set up table entry in r
r.bits = (Byte)(k - w);
if (p >= v + n)
r.exop = 128 + 64; // out of values--invalid code
else if (*p < s)
{
r.exop = (Byte)(*p < 256 ? 0 : 32 + 64); // 256 is end-of-block
r.base = *p++; // simple code is just the value
}
else
{
r.exop = (Byte)(e[*p - s] + 16 + 64);// non-simple--look up in lists
r.base = d[*p++ - s];
}
// fill code-like entries with r
f = 1 << (k - w);
for (j = i >> w; j < z; j += f)
q[j] = r;
// backwards increment the k-bit code i
for (j = 1 << (k - 1); i & j; j >>= 1)
i ^= j;
i ^= j;
// backup over finished tables
mask = (1 << w) - 1; // needed on HP, cc -O bug
while ((i & mask) != x[h])
{
h--; // don't need to update q
w -= l;
mask = (1 << w) - 1;
}
}
}
// Return Z_BUF_ERROR if we were given an incomplete table
return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
}
int inflate_trees_bits(
uInt *c, // 19 code lengths
uInt *bb, // bits tree desired/actual depth
inflate_huft * *tb, // bits tree result
inflate_huft *hp, // space for trees
z_streamp z) // for messages
{
int r;
uInt hn = 0; // hufts used in space
uInt *v; // work area for huft_build
if ((v = (uInt*)ZALLOC(z, 19, sizeof(uInt))) == Z_NULL)
return Z_MEM_ERROR;
r = huft_build(c, 19, 19, (uInt*)Z_NULL, (uInt*)Z_NULL,
tb, bb, hp, &hn, v);
if (r == Z_DATA_ERROR)
z->msg = (char*)"oversubscribed dynamic bit lengths tree";
else if (r == Z_BUF_ERROR || *bb == 0)
{
z->msg = (char*)"incomplete dynamic bit lengths tree";
r = Z_DATA_ERROR;
}
ZFREE(z, v);
return r;
}
int inflate_trees_dynamic(
uInt nl, // number of literal/length codes
uInt nd, // number of distance codes
uInt *c, // that many (total) code lengths
uInt *bl, // literal desired/actual bit depth
uInt *bd, // distance desired/actual bit depth
inflate_huft * *tl, // literal/length tree result
inflate_huft * *td, // distance tree result
inflate_huft *hp, // space for trees
z_streamp z) // for messages
{
int r;
uInt hn = 0; // hufts used in space
uInt *v; // work area for huft_build
// allocate work area
if ((v = (uInt*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL)
return Z_MEM_ERROR;
// build literal/length tree
r = huft_build(c, nl, 257, cplens, cplext, tl, bl, hp, &hn, v);
if (r != Z_OK || *bl == 0)
{
if (r == Z_DATA_ERROR)
z->msg = (char*)"oversubscribed literal/length tree";
else if (r != Z_MEM_ERROR)
{
z->msg = (char*)"incomplete literal/length tree";
r = Z_DATA_ERROR;
}
ZFREE(z, v);
return r;
}
// build distance tree
r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, hp, &hn, v);
if (r != Z_OK || (*bd == 0 && nl > 257))
{
if (r == Z_DATA_ERROR)
z->msg = (char*)"oversubscribed distance tree";
else if (r == Z_BUF_ERROR) {
z->msg = (char*)"incomplete distance tree";
r = Z_DATA_ERROR;
}
else if (r != Z_MEM_ERROR)
{
z->msg = (char*)"empty distance tree with lengths";
r = Z_DATA_ERROR;
}
ZFREE(z, v);
return r;
}
// done
ZFREE(z, v);
return Z_OK;
}
int inflate_trees_fixed(
uInt *bl, // literal desired/actual bit depth
uInt *bd, // distance desired/actual bit depth
const inflate_huft * * tl, // literal/length tree result
const inflate_huft * *td, // distance tree result
z_streamp ) // for memory allocation
{
*bl = fixed_bl;
*bd = fixed_bd;
*tl = fixed_tl;
*td = fixed_td;
return Z_OK;
}
// inffast.c -- process literals and length/distance pairs fast
// Copyright (C) 1995-1998 Mark Adler
// For conditions of distribution and use, see copyright notice in zlib.h
//
//struct inflate_codes_state {int dummy;}; // for buggy compilers
// macros for bit input with no checking and for returning unused bytes
#define GRABBITS(j) {while(k<(j)){b|=((uLong)NEXTBYTE)<<k;k+=8;}}
#define UNGRAB {c=z->avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;}
// Called with number of bytes left to write in window at least 258
// (the maximum string length) and number of input bytes available
// at least ten. The ten bytes are six bytes for the longest length/
// distance pair plus four bytes for overloading the bit buffer.
int inflate_fast(
uInt bl, uInt bd,
const inflate_huft *tl,
const inflate_huft *td, // need separate declaration for Borland C++
inflate_blocks_statef *s,
z_streamp z)
{
const inflate_huft *t; // temporary pointer
uInt e; // extra bits or operation
uLong b; // bit buffer
uInt k; // bits in bit buffer
Byte *p; // input data pointer
uInt n; // bytes available there
Byte *q; // output window write pointer
uInt m; // bytes to end of window or read pointer
uInt ml; // mask for literal/length tree
uInt md; // mask for distance tree
uInt c; // bytes to copy
uInt d; // distance back to copy from
Byte *r; // copy source pointer
// load input, output, bit values
LOAD
// initialize masks
ml = inflate_mask[bl];
md = inflate_mask[bd];
// do until not enough input or output space for fast loop
do { // assume called with m >= 258 && n >= 10
// get literal/length code
GRABBITS(20) // max bits for literal/length code
if ((e = (t = tl + ((uInt)b & ml))->exop) == 0)
{
DUMPBITS(t->bits)
LuTracevv((stderr, t->base >= 0x20 && t->base < 0x7f ?
"inflate: * literal '%c'\n" :
"inflate: * literal 0x%02x\n", t->base));
*q++ = (Byte)t->base;
m--;
continue;
}
for (;;) {
DUMPBITS(t->bits)
if (e & 16)
{
// get extra bits for length
e &= 15;
c = t->base + ((uInt)b & inflate_mask[e]);
DUMPBITS(e)
LuTracevv((stderr, "inflate: * length %u\n", c));
// decode distance base of block to copy
GRABBITS(15); // max bits for distance code
e = (t = td + ((uInt)b & md))->exop;
for (;;) {
DUMPBITS(t->bits)
if (e & 16)
{
// get extra bits to add to distance base
e &= 15;
GRABBITS(e) // get extra bits (up to 13)
d = t->base + ((uInt)b & inflate_mask[e]);
DUMPBITS(e)
LuTracevv((stderr, "inflate: * distance %u\n", d));
// do the copy
m -= c;
r = q - d;
if (r < s->window) // wrap if needed
{
do {
r += s->end - s->window; // force pointer in window
} while (r < s->window); // covers invalid distances
e = (uInt) (s->end - r);
if (c > e)
{
c -= e; // wrapped copy
do {
*q++ = *r++;
} while (--e);
r = s->window;
do {
*q++ = *r++;
} while (--c);
}
else // normal copy
{
*q++ = *r++; c--;
*q++ = *r++; c--;
do {
*q++ = *r++;
} while (--c);
}
}
else /* normal copy */
{
*q++ = *r++; c--;
*q++ = *r++; c--;
do {
*q++ = *r++;
} while (--c);
}
break;
}
else if ((e & 64) == 0)
{
t += t->base;
e = (t += ((uInt)b & inflate_mask[e]))->exop;
}
else
{
z->msg = (char*)"invalid distance code";
UNGRAB
UPDATE
return Z_DATA_ERROR;
}
};
break;
}
if ((e & 64) == 0)
{
t += t->base;
if ((e = (t += ((uInt)b & inflate_mask[e]))->exop) == 0)
{
DUMPBITS(t->bits)
LuTracevv((stderr, t->base >= 0x20 && t->base < 0x7f ?
"inflate: * literal '%c'\n" :
"inflate: * literal 0x%02x\n", t->base));
*q++ = (Byte)t->base;
m--;
break;
}
}
else if (e & 32)
{
LuTracevv((stderr, "inflate: * end of block\n"));
UNGRAB
UPDATE
return Z_STREAM_END;
}
else
{
z->msg = (char*)"invalid literal/length code";
UNGRAB
UPDATE
return Z_DATA_ERROR;
}
};
} while (m >= 258 && n >= 10);
// not enough input or output--restore pointers and return
UNGRAB
UPDATE
return Z_OK;
}
// crc32.c -- compute the CRC-32 of a data stream
// Copyright (C) 1995-1998 Mark Adler
// For conditions of distribution and use, see copyright notice in zlib.h
// @(#) $Id$
// Table of CRC-32's of all single-byte values (made by make_crc_table)
const uLong crc_table[256] = {
0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
0x2d02ef8dL
};
const uLong * get_crc_table()
{ return (const uLong *)crc_table;
}
#define CRC_DO1(buf) crc = crc_table[((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8);
#define CRC_DO2(buf) CRC_DO1(buf); CRC_DO1(buf);
#define CRC_DO4(buf) CRC_DO2(buf); CRC_DO2(buf);
#define CRC_DO8(buf) CRC_DO4(buf); CRC_DO4(buf);
uLong ucrc32(uLong crc, const Byte *buf, uInt len)
{ if (buf == Z_NULL) return 0L;
crc = crc ^ 0xffffffffL;
while (len >= 8) {CRC_DO8(buf); len -= 8;}
if (len) do {CRC_DO1(buf);} while (--len);
return crc ^ 0xffffffffL;
}
// =============================================================
// some decryption routines
#define CRC32(c, b) (crc_table[((int)(c)^(b))&0xff]^((c)>>8))
void Uupdate_keys(unsigned long *keys, char c)
{ keys[0] = CRC32(keys[0],c);
keys[1] += keys[0] & 0xFF;
keys[1] = keys[1]*134775813L +1;
keys[2] = CRC32(keys[2], keys[1] >> 24);
}
char Udecrypt_byte(unsigned long *keys)
{ unsigned temp = ((unsigned)keys[2] & 0xffff) | 2;
return (char)(((temp * (temp ^ 1)) >> 8) & 0xff);
}
char zdecode(unsigned long *keys, char c)
{ c^=Udecrypt_byte(keys);
Uupdate_keys(keys,c);
return c;
}
// adler32.c -- compute the Adler-32 checksum of a data stream
// Copyright (C) 1995-1998 Mark Adler
// For conditions of distribution and use, see copyright notice in zlib.h
// @(#) $Id$
#define BASE 65521L // largest prime smaller than 65536
#define NMAX 5552
// NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
#define AD_DO1(buf,i) {s1 += buf[i]; s2 += s1;}
#define AD_DO2(buf,i) AD_DO1(buf,i); AD_DO1(buf,i+1);
#define AD_DO4(buf,i) AD_DO2(buf,i); AD_DO2(buf,i+2);
#define AD_DO8(buf,i) AD_DO4(buf,i); AD_DO4(buf,i+4);
#define AD_DO16(buf) AD_DO8(buf,0); AD_DO8(buf,8);
// =========================================================================
uLong adler32(uLong adler, const Byte *buf, uInt len)
{
unsigned long s1 = adler & 0xffff;
unsigned long s2 = (adler >> 16) & 0xffff;
int k;
if (buf == Z_NULL) return 1L;
while (len > 0) {
k = len < NMAX ? len : NMAX;
len -= k;
while (k >= 16) {
AD_DO16(buf);
buf += 16;
k -= 16;
}
if (k != 0) do {
s1 += *buf++;
s2 += s1;
} while (--k);
s1 %= BASE;
s2 %= BASE;
}
return (s2 << 16) | s1;
}
// zutil.c -- target dependent utility functions for the compression library
// Copyright (C) 1995-1998 Jean-loup Gailly.
// For conditions of distribution and use, see copyright notice in zlib.h
// @(#) $Id$
const char * zlibVersion()
{
return ZLIB_VERSION;
}
// exported to allow conversion of error code to string for compress() and
// uncompress()
const char * zError(int err)
{ return ERR_MSG(err);
}
voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
{
if (opaque) items += size - size; // make compiler happy
return (voidpf)calloc(items, size);
}
void zcfree (voidpf opaque, voidpf ptr)
{
zfree(ptr);
if (opaque) return; // make compiler happy
}
// inflate.c -- zlib interface to inflate modules
// Copyright (C) 1995-1998 Mark Adler
// For conditions of distribution and use, see copyright notice in zlib.h
//struct inflate_blocks_state {int dummy;}; // for buggy compilers
typedef enum {
IM_METHOD, // waiting for method byte
IM_FLAG, // waiting for flag byte
IM_DICT4, // four dictionary check bytes to go
IM_DICT3, // three dictionary check bytes to go
IM_DICT2, // two dictionary check bytes to go
IM_DICT1, // one dictionary check byte to go
IM_DICT0, // waiting for inflateSetDictionary
IM_BLOCKS, // decompressing blocks
IM_CHECK4, // four check bytes to go
IM_CHECK3, // three check bytes to go
IM_CHECK2, // two check bytes to go
IM_CHECK1, // one check byte to go
IM_DONE, // finished check, done
IM_BAD} // got an error--stay here
inflate_mode;
// inflate private state
struct internal_state {
// mode
inflate_mode mode; // current inflate mode
// mode dependent information
union {
uInt method; // if IM_FLAGS, method byte
struct {
uLong was; // computed check value
uLong need; // stream check value
} check; // if CHECK, check values to compare
uInt marker; // if IM_BAD, inflateSync's marker bytes count
} sub; // submode
// mode independent information
int nowrap; // flag for no wrapper
uInt wbits; // log2(window size) (8..15, defaults to 15)
inflate_blocks_statef
*blocks; // current inflate_blocks state
};
int inflateReset(z_streamp z)
{
if (z == Z_NULL || z->state == Z_NULL)
return Z_STREAM_ERROR;
z->total_in = z->total_out = 0;
z->msg = Z_NULL;
z->state->mode = z->state->nowrap ? IM_BLOCKS : IM_METHOD;
inflate_blocks_reset(z->state->blocks, z, Z_NULL);
LuTracev((stderr, "inflate: reset\n"));
return Z_OK;
}
int inflateEnd(z_streamp z)
{
if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL)
return Z_STREAM_ERROR;
if (z->state->blocks != Z_NULL)
inflate_blocks_free(z->state->blocks, z);
ZFREE(z, z->state);
z->state = Z_NULL;
LuTracev((stderr, "inflate: end\n"));
return Z_OK;
}
int inflateInit2(z_streamp z)
{ const char *version = ZLIB_VERSION; int stream_size = sizeof(z_stream);
if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || stream_size != sizeof(z_stream)) return Z_VERSION_ERROR;
int w = -15; // MAX_WBITS: 32K LZ77 window.
// Warning: reducing MAX_WBITS makes minigzip unable to extract .gz files created by gzip.
// The memory requirements for deflate are (in bytes):
// (1 << (windowBits+2)) + (1 << (memLevel+9))
// that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
// plus a few kilobytes for small objects. For example, if you want to reduce
// the default memory requirements from 256K to 128K, compile with
// make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
// Of course this will generally degrade compression (there's no free lunch).
//
// The memory requirements for inflate are (in bytes) 1 << windowBits
// that is, 32K for windowBits=15 (default value) plus a few kilobytes
// for small objects.
// initialize state
if (z == Z_NULL) return Z_STREAM_ERROR;
z->msg = Z_NULL;
if (z->zalloc == Z_NULL)
{
z->zalloc = zcalloc;
z->opaque = (voidpf)0;
}
if (z->zfree == Z_NULL) z->zfree = zcfree;
if ((z->state = (struct internal_state *)
ZALLOC(z,1,sizeof(struct internal_state))) == Z_NULL)
return Z_MEM_ERROR;
z->state->blocks = Z_NULL;
// handle undocumented nowrap option (no zlib header or check)
z->state->nowrap = 0;
if (w < 0)
{
w = - w;
z->state->nowrap = 1;
}
// set window size
if (w < 8 || w > 15)
{
inflateEnd(z);
return Z_STREAM_ERROR;
}
z->state->wbits = (uInt)w;
// create inflate_blocks state
if ((z->state->blocks =
inflate_blocks_new(z, z->state->nowrap ? Z_NULL : adler32, (uInt)1 << w))
== Z_NULL)
{
inflateEnd(z);
return Z_MEM_ERROR;
}
LuTracev((stderr, "inflate: allocated\n"));
// reset state
inflateReset(z);
return Z_OK;
}
#define IM_NEEDBYTE {if(z->avail_in==0)return r;r=f;}
#define IM_NEXTBYTE (z->avail_in--,z->total_in++,*z->next_in++)
int inflate(z_streamp z, int f)
{
int r;
uInt b;
if (z == Z_NULL || z->state == Z_NULL || z->next_in == Z_NULL)
return Z_STREAM_ERROR;
f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
r = Z_BUF_ERROR;
for (;;) switch (z->state->mode)
{
case IM_METHOD:
IM_NEEDBYTE
if (((z->state->sub.method = IM_NEXTBYTE) & 0xf) != Z_DEFLATED)
{
z->state->mode = IM_BAD;
z->msg = (char*)"unknown compression method";
z->state->sub.marker = 5; // can't try inflateSync
break;
}
if ((z->state->sub.method >> 4) + 8 > z->state->wbits)
{
z->state->mode = IM_BAD;
z->msg = (char*)"invalid window size";
z->state->sub.marker = 5; // can't try inflateSync
break;
}
z->state->mode = IM_FLAG;
case IM_FLAG:
IM_NEEDBYTE
b = IM_NEXTBYTE;
if (((z->state->sub.method << 8) + b) % 31)
{
z->state->mode = IM_BAD;
z->msg = (char*)"incorrect header check";
z->state->sub.marker = 5; // can't try inflateSync
break;
}
LuTracev((stderr, "inflate: zlib header ok\n"));
if (!(b & PRESET_DICT))
{
z->state->mode = IM_BLOCKS;
break;
}
z->state->mode = IM_DICT4;
case IM_DICT4:
IM_NEEDBYTE
z->state->sub.check.need = (uLong)IM_NEXTBYTE << 24;
z->state->mode = IM_DICT3;
case IM_DICT3:
IM_NEEDBYTE
z->state->sub.check.need += (uLong)IM_NEXTBYTE << 16;
z->state->mode = IM_DICT2;
case IM_DICT2:
IM_NEEDBYTE
z->state->sub.check.need += (uLong)IM_NEXTBYTE << 8;
z->state->mode = IM_DICT1;
case IM_DICT1:
IM_NEEDBYTE; r;
z->state->sub.check.need += (uLong)IM_NEXTBYTE;
z->adler = z->state->sub.check.need;
z->state->mode = IM_DICT0;
return Z_NEED_DICT;
case IM_DICT0:
z->state->mode = IM_BAD;
z->msg = (char*)"need dictionary";
z->state->sub.marker = 0; // can try inflateSync
return Z_STREAM_ERROR;
case IM_BLOCKS:
r = inflate_blocks(z->state->blocks, z, r);
if (r == Z_DATA_ERROR)
{
z->state->mode = IM_BAD;
z->state->sub.marker = 0; // can try inflateSync
break;
}
if (r == Z_OK)
r = f;
if (r != Z_STREAM_END)
return r;
r = f;
inflate_blocks_reset(z->state->blocks, z, &z->state->sub.check.was);
if (z->state->nowrap)
{
z->state->mode = IM_DONE;
break;
}
z->state->mode = IM_CHECK4;
case IM_CHECK4:
IM_NEEDBYTE
z->state->sub.check.need = (uLong)IM_NEXTBYTE << 24;
z->state->mode = IM_CHECK3;
case IM_CHECK3:
IM_NEEDBYTE
z->state->sub.check.need += (uLong)IM_NEXTBYTE << 16;
z->state->mode = IM_CHECK2;
case IM_CHECK2:
IM_NEEDBYTE
z->state->sub.check.need += (uLong)IM_NEXTBYTE << 8;
z->state->mode = IM_CHECK1;
case IM_CHECK1:
IM_NEEDBYTE
z->state->sub.check.need += (uLong)IM_NEXTBYTE;
if (z->state->sub.check.was != z->state->sub.check.need)
{
z->state->mode = IM_BAD;
z->msg = (char*)"incorrect data check";
z->state->sub.marker = 5; // can't try inflateSync
break;
}
LuTracev((stderr, "inflate: zlib check ok\n"));
z->state->mode = IM_DONE;
case IM_DONE:
return Z_STREAM_END;
case IM_BAD:
return Z_DATA_ERROR;
default:
return Z_STREAM_ERROR;
}
}
// unzip.c -- IO on .zip files using zlib
// Version 0.15 beta, Mar 19th, 1998,
// Read unzip.h for more info
#define UNZ_BUFSIZE (16384)
#define UNZ_MAXFILENAMEINZIP (256)
#define SIZECENTRALDIRITEM (0x2e)
#define SIZEZIPLOCALHEADER (0x1e)
const char unz_copyright[] = " unzip 0.15 Copyright 1998 Gilles Vollant ";
// unz_file_info_interntal contain internal info about a file in zipfile
typedef struct unz_file_info_internal_s
{
uLong offset_curfile;// relative offset of local header 4 bytes
} unz_file_info_internal;
typedef struct
{ bool is_handle; // either a handle or memory
bool canseek;
// for handles:
HANDLE h; bool herr; unsigned long initial_offset; bool mustclosehandle;
// for memory:
void *buf; unsigned int len,pos; // if it's a memory block
} LUFILE;
LUFILE *lufopen(void *z,unsigned int len,DWORD flags,ZRESULT *err)
{ if (flags!=ZIP_HANDLE && flags!=ZIP_FILENAME && flags!=ZIP_MEMORY) {*err=ZR_ARGS; return NULL;}
//
HANDLE h=0; bool canseek=false; *err=ZR_OK;
bool mustclosehandle=false;
if (flags==ZIP_HANDLE||flags==ZIP_FILENAME)
{ if (flags==ZIP_HANDLE)
{ HANDLE hf = z;
h=hf; mustclosehandle=false;
#ifdef DuplicateHandle
BOOL res = DuplicateHandle(GetCurrentProcess(),hf,GetCurrentProcess(),&h,0,FALSE,DUPLICATE_SAME_ACCESS);
if (!res) mustclosehandle=true;
#endif
}
else
{ h=CreateFile((const TCHAR*)z,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if (h==INVALID_HANDLE_VALUE) {*err=ZR_NOFILE; return NULL;}
mustclosehandle=true;
}
// test if we can seek on it. We can't use GetFileType(h)==FILE_TYPE_DISK since it's not on CE.
DWORD res = SetFilePointer(h,0,0,FILE_CURRENT);
canseek = (res!=0xFFFFFFFF);
}
LUFILE *lf = new LUFILE;
if (flags==ZIP_HANDLE||flags==ZIP_FILENAME)
{ lf->is_handle=true; lf->mustclosehandle=mustclosehandle;
lf->canseek=canseek;
lf->h=h; lf->herr=false;
lf->initial_offset=0;
if (canseek) lf->initial_offset = SetFilePointer(h,0,NULL,FILE_CURRENT);
}
else
{ lf->is_handle=false;
lf->canseek=true;
lf->mustclosehandle=false;
lf->buf=z; lf->len=len; lf->pos=0; lf->initial_offset=0;
}
*err=ZR_OK;
return lf;
}
int lufclose(LUFILE *stream)
{ if (stream==NULL) return EOF;
if (stream->mustclosehandle) CloseHandle(stream->h);
delete stream;
return 0;
}
int luferror(LUFILE *stream)
{ if (stream->is_handle && stream->herr) return 1;
else return 0;
}
long int luftell(LUFILE *stream)
{ if (stream->is_handle && stream->canseek) return SetFilePointer(stream->h,0,NULL,FILE_CURRENT)-stream->initial_offset;
else if (stream->is_handle) return 0;
else return stream->pos;
}
int lufseek(LUFILE *stream, long offset, int whence)
{ if (stream->is_handle && stream->canseek)
{ if (whence==SEEK_SET) SetFilePointer(stream->h,stream->initial_offset+offset,0,FILE_BEGIN);
else if (whence==SEEK_CUR) SetFilePointer(stream->h,offset,NULL,FILE_CURRENT);
else if (whence==SEEK_END) SetFilePointer(stream->h,offset,NULL,FILE_END);
else return 19; // EINVAL
return 0;
}
else if (stream->is_handle) return 29; // ESPIPE
else
{ if (whence==SEEK_SET) stream->pos=offset;
else if (whence==SEEK_CUR) stream->pos+=offset;
else if (whence==SEEK_END) stream->pos=stream->len+offset;
return 0;
}
}
size_t lufread(void *ptr,size_t size,size_t n,LUFILE *stream)
{ unsigned int toread = (unsigned int)(size*n);
if (stream->is_handle)
{ DWORD red; BOOL res = ReadFile(stream->h,ptr,toread,&red,NULL);
if (!res) stream->herr=true;
return red/size;
}
if (stream->pos+toread > stream->len) toread = stream->len-stream->pos;
memcpy(ptr, (char*)stream->buf + stream->pos, toread); DWORD red = toread;
stream->pos += red;
return red/size;
}
// file_in_zip_read_info_s contain internal information about a file in zipfile,
// when reading and decompress it
typedef struct
{
char *read_buffer; // internal buffer for compressed data
z_stream stream; // zLib stream structure for inflate
uLong pos_in_zipfile; // position in byte on the zipfile, for fseek
uLong stream_initialised; // flag set if stream structure is initialised
uLong offset_local_extrafield;// offset of the local extra field
uInt size_local_extrafield;// size of the local extra field
uLong pos_local_extrafield; // position in the local extra field in read
uLong crc32; // crc32 of all data uncompressed
uLong crc32_wait; // crc32 we must obtain after decompress all
uLong rest_read_compressed; // number of byte to be decompressed
uLong rest_read_uncompressed;//number of byte to be obtained after decomp
LUFILE* file; // io structore of the zipfile
uLong compression_method; // compression method (0==store)
uLong byte_before_the_zipfile;// byte before the zipfile, (>0 for sfx)
bool encrypted; // is it encrypted?
unsigned long keys[3]; // decryption keys, initialized by unzOpenCurrentFile
int encheadleft; // the first call(s) to unzReadCurrentFile will read this many encryption-header bytes first
char crcenctest; // if encrypted, we'll check the encryption buffer against this
} file_in_zip_read_info_s;
// unz_s contain internal information about the zipfile
typedef struct
{
LUFILE* file; // io structore of the zipfile
unz_global_info gi; // public global information
uLong byte_before_the_zipfile;// byte before the zipfile, (>0 for sfx)
uLong num_file; // number of the current file in the zipfile
uLong pos_in_central_dir; // pos of the current file in the central dir
uLong current_file_ok; // flag about the usability of the current file
uLong central_pos; // position of the beginning of the central dir
uLong size_central_dir; // size of the central directory
uLong offset_central_dir; // offset of start of central directory with respect to the starting disk number
unz_file_info cur_file_info; // public info about the current file in zip
unz_file_info_internal cur_file_info_internal; // private info about it
file_in_zip_read_info_s* pfile_in_zip_read; // structure about the current file if we are decompressing it
} unz_s, *unzFile;
int unzStringFileNameCompare (const char* fileName1,const char* fileName2,int iCaseSensitivity);
// Compare two filename (fileName1,fileName2).
z_off_t unztell (unzFile file);
// Give the current position in uncompressed data
int unzeof (unzFile file);
// return 1 if the end of file was reached, 0 elsewhere
int unzGetLocalExtrafield (unzFile file, voidp buf, unsigned len);
// Read extra field from the current file (opened by unzOpenCurrentFile)
// This is the local-header version of the extra field (sometimes, there is
// more info in the local-header version than in the central-header)
//
// if buf==NULL, it return the size of the local extra field
//
// if buf!=NULL, len is the size of the buffer, the extra header is copied in
// buf.
// the return value is the number of bytes copied in buf, or (if <0)
// the error code
// ===========================================================================
// Read a byte from a gz_stream; update next_in and avail_in. Return EOF
// for end of file.
// IN assertion: the stream s has been sucessfully opened for reading.
int unzlocal_getByte(LUFILE *fin,int *pi)
{ unsigned char c;
int err = (int)lufread(&c, 1, 1, fin);
if (err==1)
{ *pi = (int)c;
return UNZ_OK;
}
else
{ if (luferror(fin)) return UNZ_ERRNO;
else return UNZ_EOF;
}
}
// ===========================================================================
// Reads a long in LSB order from the given gz_stream. Sets
int unzlocal_getShort (LUFILE *fin,uLong *pX)
{
uLong x ;
int i;
int err;
err = unzlocal_getByte(fin,&i);
x = (uLong)i;
if (err==UNZ_OK)
err = unzlocal_getByte(fin,&i);
x += ((uLong)i)<<8;
if (err==UNZ_OK)
*pX = x;
else
*pX = 0;
return err;
}
int unzlocal_getLong (LUFILE *fin,uLong *pX)
{
uLong x ;
int i;
int err;
err = unzlocal_getByte(fin,&i);
x = (uLong)i;
if (err==UNZ_OK)
err = unzlocal_getByte(fin,&i);
x += ((uLong)i)<<8;
if (err==UNZ_OK)
err = unzlocal_getByte(fin,&i);
x += ((uLong)i)<<16;
if (err==UNZ_OK)
err = unzlocal_getByte(fin,&i);
x += ((uLong)i)<<24;
if (err==UNZ_OK)
*pX = x;
else
*pX = 0;
return err;
}
// My own strcmpi / strcasecmp
int strcmpcasenosensitive_internal (const char* fileName1,const char *fileName2)
{
for (;;)
{
char c1=*(fileName1++);
char c2=*(fileName2++);
if ((c1>='a') && (c1<='z'))
c1 -= (char)0x20;
if ((c2>='a') && (c2<='z'))
c2 -= (char)0x20;
if (c1=='\0')
return ((c2=='\0') ? 0 : -1);
if (c2=='\0')
return 1;
if (c1<c2)
return -1;
if (c1>c2)
return 1;
}
}
//
// Compare two filename (fileName1,fileName2).
// If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
// If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi or strcasecmp)
//
int unzStringFileNameCompare (const char*fileName1,const char*fileName2,int iCaseSensitivity)
{ if (iCaseSensitivity==1) return strcmp(fileName1,fileName2);
else return strcmpcasenosensitive_internal(fileName1,fileName2);
}
#define BUFREADCOMMENT (0x400)
// Locate the Central directory of a zipfile (at the end, just before
// the global comment). Lu bugfix 2005.07.26 - returns 0xFFFFFFFF if not found,
// rather than 0, since 0 is a valid central-dir-location for an empty zipfile.
uLong unzlocal_SearchCentralDir(LUFILE *fin)
{ if (lufseek(fin,0,SEEK_END) != 0) return 0xFFFFFFFF;
uLong uSizeFile = luftell(fin);
uLong uMaxBack=0xffff; // maximum size of global comment
if (uMaxBack>uSizeFile) uMaxBack = uSizeFile;
unsigned char *buf = (unsigned char*)zmalloc(BUFREADCOMMENT+4);
if (buf==NULL) return 0xFFFFFFFF;
uLong uPosFound=0xFFFFFFFF;
uLong uBackRead = 4;
while (uBackRead<uMaxBack)
{ uLong uReadSize,uReadPos ;
int i;
if (uBackRead+BUFREADCOMMENT>uMaxBack) uBackRead = uMaxBack;
else uBackRead+=BUFREADCOMMENT;
uReadPos = uSizeFile-uBackRead ;
uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? (BUFREADCOMMENT+4) : (uSizeFile-uReadPos);
if (lufseek(fin,uReadPos,SEEK_SET)!=0) break;
if (lufread(buf,(uInt)uReadSize,1,fin)!=1) break;
for (i=(int)uReadSize-3; (i--)>=0;)
{ if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06))
{ uPosFound = uReadPos+i; break;
}
}
if (uPosFound!=0) break;
}
if (buf) zfree(buf);
return uPosFound;
}
int unzGoToFirstFile (unzFile file);
int unzCloseCurrentFile (unzFile file);
// Open a Zip file.
// If the zipfile cannot be opened (file don't exist or in not valid), return NULL.
// Otherwise, the return value is a unzFile Handle, usable with other unzip functions
unzFile unzOpenInternal(LUFILE *fin)
{ if (fin==NULL) return NULL;
if (unz_copyright[0]!=' ') {lufclose(fin); return NULL;}
int err=UNZ_OK;
unz_s us;
uLong central_pos,uL;
central_pos = unzlocal_SearchCentralDir(fin);
if (central_pos==0xFFFFFFFF) err=UNZ_ERRNO;
if (lufseek(fin,central_pos,SEEK_SET)!=0) err=UNZ_ERRNO;
// the signature, already checked
if (unzlocal_getLong(fin,&uL)!=UNZ_OK) err=UNZ_ERRNO;
// number of this disk
uLong number_disk; // number of the current dist, used for spanning ZIP, unsupported, always 0
if (unzlocal_getShort(fin,&number_disk)!=UNZ_OK) err=UNZ_ERRNO;
// number of the disk with the start of the central directory
uLong number_disk_with_CD; // number the the disk with central dir, used for spaning ZIP, unsupported, always 0
if (unzlocal_getShort(fin,&number_disk_with_CD)!=UNZ_OK) err=UNZ_ERRNO;
// total number of entries in the central dir on this disk
if (unzlocal_getShort(fin,&us.gi.number_entry)!=UNZ_OK) err=UNZ_ERRNO;
// total number of entries in the central dir
uLong number_entry_CD; // total number of entries in the central dir (same than number_entry on nospan)
if (unzlocal_getShort(fin,&number_entry_CD)!=UNZ_OK) err=UNZ_ERRNO;
if ((number_entry_CD!=us.gi.number_entry) || (number_disk_with_CD!=0) || (number_disk!=0)) err=UNZ_BADZIPFILE;
// size of the central directory
if (unzlocal_getLong(fin,&us.size_central_dir)!=UNZ_OK) err=UNZ_ERRNO;
// offset of start of central directory with respect to the starting disk number
if (unzlocal_getLong(fin,&us.offset_central_dir)!=UNZ_OK) err=UNZ_ERRNO;
// zipfile comment length
if (unzlocal_getShort(fin,&us.gi.size_comment)!=UNZ_OK) err=UNZ_ERRNO;
if ((central_pos+fin->initial_offset<us.offset_central_dir+us.size_central_dir) && (err==UNZ_OK)) err=UNZ_BADZIPFILE;
if (err!=UNZ_OK) {lufclose(fin);return NULL;}
us.file=fin;
us.byte_before_the_zipfile = central_pos+fin->initial_offset - (us.offset_central_dir+us.size_central_dir);
us.central_pos = central_pos;
us.pfile_in_zip_read = NULL;
fin->initial_offset = 0; // since the zipfile itself is expected to handle this
unz_s *s = (unz_s*)zmalloc(sizeof(unz_s));
*s=us;
unzGoToFirstFile((unzFile)s);
return (unzFile)s;
}
// Close a ZipFile opened with unzipOpen.
// If there is files inside the .Zip opened with unzipOpenCurrentFile (see later),
// these files MUST be closed with unzipCloseCurrentFile before call unzipClose.
// return UNZ_OK if there is no problem.
int unzClose (unzFile file)
{
unz_s* s;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (s->pfile_in_zip_read!=NULL)
unzCloseCurrentFile(file);
lufclose(s->file);
if (s) zfree(s); // unused s=0;
return UNZ_OK;
}
// Write info about the ZipFile in the *pglobal_info structure.
// No preparation of the structure is needed
// return UNZ_OK if there is no problem.
int unzGetGlobalInfo (unzFile file,unz_global_info *pglobal_info)
{
unz_s* s;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
*pglobal_info=s->gi;
return UNZ_OK;
}
// Translate date/time from Dos format to tm_unz (readable more easilty)
void unzlocal_DosDateToTmuDate (uLong ulDosDate, tm_unz* ptm)
{
uLong uDate;
uDate = (uLong)(ulDosDate>>16);
ptm->tm_mday = (uInt)(uDate&0x1f) ;
ptm->tm_mon = (uInt)((((uDate)&0x1E0)/0x20)-1) ;
ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ;
ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800);
ptm->tm_min = (uInt) ((ulDosDate&0x7E0)/0x20) ;
ptm->tm_sec = (uInt) (2*(ulDosDate&0x1f)) ;
}
// Get Info about the current file in the zipfile, with internal only info
int unzlocal_GetCurrentFileInfoInternal (unzFile file,
unz_file_info *pfile_info,
unz_file_info_internal
*pfile_info_internal,
char *szFileName,
uLong fileNameBufferSize,
void *extraField,
uLong extraFieldBufferSize,
char *szComment,
uLong commentBufferSize);
int unzlocal_GetCurrentFileInfoInternal (unzFile file, unz_file_info *pfile_info,
unz_file_info_internal *pfile_info_internal, char *szFileName,
uLong fileNameBufferSize, void *extraField, uLong extraFieldBufferSize,
char *szComment, uLong commentBufferSize)
{
unz_s* s;
unz_file_info file_info;
unz_file_info_internal file_info_internal;
int err=UNZ_OK;
uLong uMagic;
long lSeek=0;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (lufseek(s->file,s->pos_in_central_dir+s->byte_before_the_zipfile,SEEK_SET)!=0)
err=UNZ_ERRNO;
// we check the magic
if (err==UNZ_OK)
if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK)
err=UNZ_ERRNO;
else if (uMagic!=0x02014b50)
err=UNZ_BADZIPFILE;
if (unzlocal_getShort(s->file,&file_info.version) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&file_info.version_needed) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&file_info.flag) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&file_info.compression_method) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getLong(s->file,&file_info.dosDate) != UNZ_OK)
err=UNZ_ERRNO;
unzlocal_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date);
if (unzlocal_getLong(s->file,&file_info.crc) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getLong(s->file,&file_info.compressed_size) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getLong(s->file,&file_info.uncompressed_size) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&file_info.size_filename) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&file_info.size_file_extra) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&file_info.size_file_comment) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&file_info.disk_num_start) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&file_info.internal_fa) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getLong(s->file,&file_info.external_fa) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getLong(s->file,&file_info_internal.offset_curfile) != UNZ_OK)
err=UNZ_ERRNO;
lSeek+=file_info.size_filename;
if ((err==UNZ_OK) && (szFileName!=NULL))
{
uLong uSizeRead ;
if (file_info.size_filename<fileNameBufferSize)
{
*(szFileName+file_info.size_filename)='\0';
uSizeRead = file_info.size_filename;
}
else
uSizeRead = fileNameBufferSize;
if ((file_info.size_filename>0) && (fileNameBufferSize>0))
if (lufread(szFileName,(uInt)uSizeRead,1,s->file)!=1)
err=UNZ_ERRNO;
lSeek -= uSizeRead;
}
if ((err==UNZ_OK) && (extraField!=NULL))
{
uLong uSizeRead ;
if (file_info.size_file_extra<extraFieldBufferSize)
uSizeRead = file_info.size_file_extra;
else
uSizeRead = extraFieldBufferSize;
if (lSeek!=0)
if (lufseek(s->file,lSeek,SEEK_CUR)==0)
lSeek=0;
else
err=UNZ_ERRNO;
if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0))
if (lufread(extraField,(uInt)uSizeRead,1,s->file)!=1)
err=UNZ_ERRNO;
lSeek += file_info.size_file_extra - uSizeRead;
}
else
lSeek+=file_info.size_file_extra;
if ((err==UNZ_OK) && (szComment!=NULL))
{
uLong uSizeRead ;
if (file_info.size_file_comment<commentBufferSize)
{
*(szComment+file_info.size_file_comment)='\0';
uSizeRead = file_info.size_file_comment;
}
else
uSizeRead = commentBufferSize;
if (lSeek!=0)
if (lufseek(s->file,lSeek,SEEK_CUR)==0)
{} // unused lSeek=0;
else
err=UNZ_ERRNO;
if ((file_info.size_file_comment>0) && (commentBufferSize>0))
if (lufread(szComment,(uInt)uSizeRead,1,s->file)!=1)
err=UNZ_ERRNO;
//unused lSeek+=file_info.size_file_comment - uSizeRead;
}
else {} //unused lSeek+=file_info.size_file_comment;
if ((err==UNZ_OK) && (pfile_info!=NULL))
*pfile_info=file_info;
if ((err==UNZ_OK) && (pfile_info_internal!=NULL))
*pfile_info_internal=file_info_internal;
return err;
}
// Write info about the ZipFile in the *pglobal_info structure.
// No preparation of the structure is needed
// return UNZ_OK if there is no problem.
int unzGetCurrentFileInfo (unzFile file, unz_file_info *pfile_info,
char *szFileName, uLong fileNameBufferSize, void *extraField, uLong extraFieldBufferSize,
char *szComment, uLong commentBufferSize)
{ return unzlocal_GetCurrentFileInfoInternal(file,pfile_info,NULL,szFileName,fileNameBufferSize,
extraField,extraFieldBufferSize, szComment,commentBufferSize);
}
// Set the current file of the zipfile to the first file.
// return UNZ_OK if there is no problem
int unzGoToFirstFile (unzFile file)
{
int err;
unz_s* s;
if (file==NULL) return UNZ_PARAMERROR;
s=(unz_s*)file;
s->pos_in_central_dir=s->offset_central_dir;
s->num_file=0;
err=unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
&s->cur_file_info_internal,
NULL,0,NULL,0,NULL,0);
s->current_file_ok = (err == UNZ_OK);
return err;
}
// Set the current file of the zipfile to the next file.
// return UNZ_OK if there is no problem
// return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
int unzGoToNextFile (unzFile file)
{
unz_s* s;
int err;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (!s->current_file_ok)
return UNZ_END_OF_LIST_OF_FILE;
if (s->num_file+1==s->gi.number_entry)
return UNZ_END_OF_LIST_OF_FILE;
s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename +
s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ;
s->num_file++;
err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
&s->cur_file_info_internal,
NULL,0,NULL,0,NULL,0);
s->current_file_ok = (err == UNZ_OK);
return err;
}
// Try locate the file szFileName in the zipfile.
// For the iCaseSensitivity signification, see unzStringFileNameCompare
// return value :
// UNZ_OK if the file is found. It becomes the current file.
// UNZ_END_OF_LIST_OF_FILE if the file is not found
int unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity)
{
unz_s* s;
int err;
uLong num_fileSaved;
uLong pos_in_central_dirSaved;
if (file==NULL)
return UNZ_PARAMERROR;
if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (!s->current_file_ok)
return UNZ_END_OF_LIST_OF_FILE;
num_fileSaved = s->num_file;
pos_in_central_dirSaved = s->pos_in_central_dir;
err = unzGoToFirstFile(file);
while (err == UNZ_OK)
{
char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1];
unzGetCurrentFileInfo(file,NULL,
szCurrentFileName,sizeof(szCurrentFileName)-1,
NULL,0,NULL,0);
if (unzStringFileNameCompare(szCurrentFileName,szFileName,iCaseSensitivity)==0)
return UNZ_OK;
err = unzGoToNextFile(file);
}
s->num_file = num_fileSaved ;
s->pos_in_central_dir = pos_in_central_dirSaved ;
return err;
}
// Read the local header of the current zipfile
// Check the coherency of the local header and info in the end of central
// directory about this file
// store in *piSizeVar the size of extra info in local header
// (filename and size of extra field data)
int unzlocal_CheckCurrentFileCoherencyHeader (unz_s *s,uInt *piSizeVar,
uLong *poffset_local_extrafield, uInt *psize_local_extrafield)
{
uLong uMagic,uData,uFlags;
uLong size_filename;
uLong size_extra_field;
int err=UNZ_OK;
*piSizeVar = 0;
*poffset_local_extrafield = 0;
*psize_local_extrafield = 0;
if (lufseek(s->file,s->cur_file_info_internal.offset_curfile + s->byte_before_the_zipfile,SEEK_SET)!=0)
return UNZ_ERRNO;
if (err==UNZ_OK)
if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK)
err=UNZ_ERRNO;
else if (uMagic!=0x04034b50)
err=UNZ_BADZIPFILE;
if (unzlocal_getShort(s->file,&uData) != UNZ_OK)
err=UNZ_ERRNO;
// else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion))
// err=UNZ_BADZIPFILE;
if (unzlocal_getShort(s->file,&uFlags) != UNZ_OK)
err=UNZ_ERRNO;
if (unzlocal_getShort(s->file,&uData) != UNZ_OK)
err=UNZ_ERRNO;
else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method))
err=UNZ_BADZIPFILE;
if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) &&
(s->cur_file_info.compression_method!=Z_DEFLATED))
err=UNZ_BADZIPFILE;
if (unzlocal_getLong(s->file,&uData) != UNZ_OK) // date/time
err=UNZ_ERRNO;
if (unzlocal_getLong(s->file,&uData) != UNZ_OK) // crc
err=UNZ_ERRNO;
else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) &&
((uFlags & 8)==0))
err=UNZ_BADZIPFILE;
if (unzlocal_getLong(s->file,&uData) != UNZ_OK) // size compr
err=UNZ_ERRNO;
else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) &&
((uFlags & 8)==0))
err=UNZ_BADZIPFILE;
if (unzlocal_getLong(s->file,&uData) != UNZ_OK) // size uncompr
err=UNZ_ERRNO;
else if ((err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) &&
((uFlags & 8)==0))
err=UNZ_BADZIPFILE;
if (unzlocal_getShort(s->file,&size_filename) != UNZ_OK)
err=UNZ_ERRNO;
else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename))
err=UNZ_BADZIPFILE;
*piSizeVar += (uInt)size_filename;
if (unzlocal_getShort(s->file,&size_extra_field) != UNZ_OK)
err=UNZ_ERRNO;
*poffset_local_extrafield= s->cur_file_info_internal.offset_curfile +
SIZEZIPLOCALHEADER + size_filename;
*psize_local_extrafield = (uInt)size_extra_field;
*piSizeVar += (uInt)size_extra_field;
return err;
}
// Open for reading data the current file in the zipfile.
// If there is no error and the file is opened, the return value is UNZ_OK.
int unzOpenCurrentFile (unzFile file, const char *password)
{
int err;
int Store;
uInt iSizeVar;
unz_s* s;
file_in_zip_read_info_s* pfile_in_zip_read_info;
uLong offset_local_extrafield; // offset of the local extra field
uInt size_local_extrafield; // size of the local extra field
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
if (!s->current_file_ok)
return UNZ_PARAMERROR;
if (s->pfile_in_zip_read != NULL)
unzCloseCurrentFile(file);
if (unzlocal_CheckCurrentFileCoherencyHeader(s,&iSizeVar,
&offset_local_extrafield,&size_local_extrafield)!=UNZ_OK)
return UNZ_BADZIPFILE;
pfile_in_zip_read_info = (file_in_zip_read_info_s*)zmalloc(sizeof(file_in_zip_read_info_s));
if (pfile_in_zip_read_info==NULL)
return UNZ_INTERNALERROR;
pfile_in_zip_read_info->read_buffer=(char*)zmalloc(UNZ_BUFSIZE);
pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield;
pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield;
pfile_in_zip_read_info->pos_local_extrafield=0;
if (pfile_in_zip_read_info->read_buffer==NULL)
{
if (pfile_in_zip_read_info!=0) zfree(pfile_in_zip_read_info); //unused pfile_in_zip_read_info=0;
return UNZ_INTERNALERROR;
}
pfile_in_zip_read_info->stream_initialised=0;
if ((s->cur_file_info.compression_method!=0) && (s->cur_file_info.compression_method!=Z_DEFLATED))
{ // unused err=UNZ_BADZIPFILE;
}
Store = s->cur_file_info.compression_method==0;
pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc;
pfile_in_zip_read_info->crc32=0;
pfile_in_zip_read_info->compression_method = s->cur_file_info.compression_method;
pfile_in_zip_read_info->file=s->file;
pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile;
pfile_in_zip_read_info->stream.total_out = 0;
if (!Store)
{
pfile_in_zip_read_info->stream.zalloc = (alloc_func)0;
pfile_in_zip_read_info->stream.zfree = (free_func)0;
pfile_in_zip_read_info->stream.opaque = (voidpf)0;
err=inflateInit2(&pfile_in_zip_read_info->stream);
if (err == Z_OK)
pfile_in_zip_read_info->stream_initialised=1;
// windowBits is passed < 0 to tell that there is no zlib header.
// Note that in this case inflate *requires* an extra "dummy" byte
// after the compressed stream in order to complete decompression and
// return Z_STREAM_END.
// In unzip, i don't wait absolutely Z_STREAM_END because I known the
// size of both compressed and uncompressed data
}
pfile_in_zip_read_info->rest_read_compressed = s->cur_file_info.compressed_size ;
pfile_in_zip_read_info->rest_read_uncompressed = s->cur_file_info.uncompressed_size ;
pfile_in_zip_read_info->encrypted = (s->cur_file_info.flag&1)!=0;
bool extlochead = (s->cur_file_info.flag&8)!=0;
if (extlochead) pfile_in_zip_read_info->crcenctest = (char)((s->cur_file_info.dosDate>>8)&0xff);
else pfile_in_zip_read_info->crcenctest = (char)(s->cur_file_info.crc >> 24);
pfile_in_zip_read_info->encheadleft = (pfile_in_zip_read_info->encrypted?12:0);
pfile_in_zip_read_info->keys[0] = 305419896L;
pfile_in_zip_read_info->keys[1] = 591751049L;
pfile_in_zip_read_info->keys[2] = 878082192L;
for (const char *cp=password; cp!=0 && *cp!=0; cp++) Uupdate_keys(pfile_in_zip_read_info->keys,*cp);
pfile_in_zip_read_info->pos_in_zipfile =
s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER +
iSizeVar;
pfile_in_zip_read_info->stream.avail_in = (uInt)0;
s->pfile_in_zip_read = pfile_in_zip_read_info;
return UNZ_OK;
}
// Read bytes from the current file.
// buf contain buffer where data must be copied
// len the size of buf.
// return the number of byte copied if somes bytes are copied (and also sets *reached_eof)
// return 0 if the end of file was reached. (and also sets *reached_eof).
// return <0 with error code if there is an error. (in which case *reached_eof is meaningless)
// (UNZ_ERRNO for IO error, or zLib error for uncompress error)
int unzReadCurrentFile (unzFile file, voidp buf, unsigned len, bool *reached_eof)
{ int err=UNZ_OK;
uInt iRead = 0;
if (reached_eof!=0) *reached_eof=false;
unz_s *s = (unz_s*)file;
if (s==NULL) return UNZ_PARAMERROR;
file_in_zip_read_info_s* pfile_in_zip_read_info = s->pfile_in_zip_read;
if (pfile_in_zip_read_info==NULL) return UNZ_PARAMERROR;
if ((pfile_in_zip_read_info->read_buffer == NULL)) return UNZ_END_OF_LIST_OF_FILE;
if (len==0) return 0;
pfile_in_zip_read_info->stream.next_out = (Byte*)buf;
pfile_in_zip_read_info->stream.avail_out = (uInt)len;
if (len>pfile_in_zip_read_info->rest_read_uncompressed)
{ pfile_in_zip_read_info->stream.avail_out = (uInt)pfile_in_zip_read_info->rest_read_uncompressed;
}
while (pfile_in_zip_read_info->stream.avail_out>0)
{ if ((pfile_in_zip_read_info->stream.avail_in==0) && (pfile_in_zip_read_info->rest_read_compressed>0))
{ uInt uReadThis = UNZ_BUFSIZE;
if (pfile_in_zip_read_info->rest_read_compressed<uReadThis) uReadThis = (uInt)pfile_in_zip_read_info->rest_read_compressed;
if (uReadThis == 0) {if (reached_eof!=0) *reached_eof=true; return UNZ_EOF;}
if (lufseek(pfile_in_zip_read_info->file, pfile_in_zip_read_info->pos_in_zipfile + pfile_in_zip_read_info->byte_before_the_zipfile,SEEK_SET)!=0) return UNZ_ERRNO;
if (lufread(pfile_in_zip_read_info->read_buffer,uReadThis,1,pfile_in_zip_read_info->file)!=1) return UNZ_ERRNO;
pfile_in_zip_read_info->pos_in_zipfile += uReadThis;
pfile_in_zip_read_info->rest_read_compressed-=uReadThis;
pfile_in_zip_read_info->stream.next_in = (Byte*)pfile_in_zip_read_info->read_buffer;
pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis;
//
if (pfile_in_zip_read_info->encrypted)
{ char *buf = (char*)pfile_in_zip_read_info->stream.next_in;
for (unsigned int i=0; i<uReadThis; i++) buf[i]=zdecode(pfile_in_zip_read_info->keys,buf[i]);
}
}
unsigned int uDoEncHead = pfile_in_zip_read_info->encheadleft;
if (uDoEncHead>pfile_in_zip_read_info->stream.avail_in) uDoEncHead=pfile_in_zip_read_info->stream.avail_in;
if (uDoEncHead>0)
{ char bufcrc=pfile_in_zip_read_info->stream.next_in[uDoEncHead-1];
pfile_in_zip_read_info->rest_read_uncompressed-=uDoEncHead;
pfile_in_zip_read_info->stream.avail_in -= uDoEncHead;
pfile_in_zip_read_info->stream.next_in += uDoEncHead;
pfile_in_zip_read_info->encheadleft -= uDoEncHead;
if (pfile_in_zip_read_info->encheadleft==0)
{ if (bufcrc!=pfile_in_zip_read_info->crcenctest) return UNZ_PASSWORD;
}
}
if (pfile_in_zip_read_info->compression_method==0)
{ uInt uDoCopy,i ;
if (pfile_in_zip_read_info->stream.avail_out < pfile_in_zip_read_info->stream.avail_in)
{ uDoCopy = pfile_in_zip_read_info->stream.avail_out ;
}
else
{ uDoCopy = pfile_in_zip_read_info->stream.avail_in ;
}
for (i=0;i<uDoCopy;i++) *(pfile_in_zip_read_info->stream.next_out+i) = *(pfile_in_zip_read_info->stream.next_in+i);
pfile_in_zip_read_info->crc32 = ucrc32(pfile_in_zip_read_info->crc32,pfile_in_zip_read_info->stream.next_out,uDoCopy);
pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy;
pfile_in_zip_read_info->stream.avail_in -= uDoCopy;
pfile_in_zip_read_info->stream.avail_out -= uDoCopy;
pfile_in_zip_read_info->stream.next_out += uDoCopy;
pfile_in_zip_read_info->stream.next_in += uDoCopy;
pfile_in_zip_read_info->stream.total_out += uDoCopy;
iRead += uDoCopy;
if (pfile_in_zip_read_info->rest_read_uncompressed==0) {if (reached_eof!=0) *reached_eof=true;}
}
else
{ uLong uTotalOutBefore,uTotalOutAfter;
const Byte *bufBefore;
uLong uOutThis;
int flush=Z_SYNC_FLUSH;
uTotalOutBefore = pfile_in_zip_read_info->stream.total_out;
bufBefore = pfile_in_zip_read_info->stream.next_out;
//
err=inflate(&pfile_in_zip_read_info->stream,flush);
//
uTotalOutAfter = pfile_in_zip_read_info->stream.total_out;
uOutThis = uTotalOutAfter-uTotalOutBefore;
pfile_in_zip_read_info->crc32 = ucrc32(pfile_in_zip_read_info->crc32,bufBefore,(uInt)(uOutThis));
pfile_in_zip_read_info->rest_read_uncompressed -= uOutThis;
iRead += (uInt)(uTotalOutAfter - uTotalOutBefore);
if (err==Z_STREAM_END || pfile_in_zip_read_info->rest_read_uncompressed==0)
{ if (reached_eof!=0) *reached_eof=true;
return iRead;
}
if (err!=Z_OK) break;
}
}
if (err==Z_OK) return iRead;
return err;
}
// Give the current position in uncompressed data
z_off_t unztell (unzFile file)
{
unz_s* s;
file_in_zip_read_info_s* pfile_in_zip_read_info;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
pfile_in_zip_read_info=s->pfile_in_zip_read;
if (pfile_in_zip_read_info==NULL)
return UNZ_PARAMERROR;
return (z_off_t)pfile_in_zip_read_info->stream.total_out;
}
// return 1 if the end of file was reached, 0 elsewhere
int unzeof (unzFile file)
{
unz_s* s;
file_in_zip_read_info_s* pfile_in_zip_read_info;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
pfile_in_zip_read_info=s->pfile_in_zip_read;
if (pfile_in_zip_read_info==NULL)
return UNZ_PARAMERROR;
if (pfile_in_zip_read_info->rest_read_uncompressed == 0)
return 1;
else
return 0;
}
// Read extra field from the current file (opened by unzOpenCurrentFile)
// This is the local-header version of the extra field (sometimes, there is
// more info in the local-header version than in the central-header)
// if buf==NULL, it return the size of the local extra field that can be read
// if buf!=NULL, len is the size of the buffer, the extra header is copied in buf.
// the return value is the number of bytes copied in buf, or (if <0) the error code
int unzGetLocalExtrafield (unzFile file,voidp buf,unsigned len)
{
unz_s* s;
file_in_zip_read_info_s* pfile_in_zip_read_info;
uInt read_now;
uLong size_to_read;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
pfile_in_zip_read_info=s->pfile_in_zip_read;
if (pfile_in_zip_read_info==NULL)
return UNZ_PARAMERROR;
size_to_read = (pfile_in_zip_read_info->size_local_extrafield -
pfile_in_zip_read_info->pos_local_extrafield);
if (buf==NULL)
return (int)size_to_read;
if (len>size_to_read)
read_now = (uInt)size_to_read;
else
read_now = (uInt)len ;
if (read_now==0)
return 0;
if (lufseek(pfile_in_zip_read_info->file, pfile_in_zip_read_info->offset_local_extrafield + pfile_in_zip_read_info->pos_local_extrafield,SEEK_SET)!=0)
return UNZ_ERRNO;
if (lufread(buf,(uInt)size_to_read,1,pfile_in_zip_read_info->file)!=1)
return UNZ_ERRNO;
return (int)read_now;
}
// Close the file in zip opened with unzipOpenCurrentFile
// Return UNZ_CRCERROR if all the file was read but the CRC is not good
int unzCloseCurrentFile (unzFile file)
{
int err=UNZ_OK;
unz_s* s;
file_in_zip_read_info_s* pfile_in_zip_read_info;
if (file==NULL)
return UNZ_PARAMERROR;
s=(unz_s*)file;
pfile_in_zip_read_info=s->pfile_in_zip_read;
if (pfile_in_zip_read_info==NULL)
return UNZ_PARAMERROR;
if (pfile_in_zip_read_info->rest_read_uncompressed == 0)
{
if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait)
err=UNZ_CRCERROR;
}
if (pfile_in_zip_read_info->read_buffer!=0)
{ void *buf = pfile_in_zip_read_info->read_buffer;
zfree(buf);
pfile_in_zip_read_info->read_buffer=0;
}
pfile_in_zip_read_info->read_buffer = NULL;
if (pfile_in_zip_read_info->stream_initialised)
inflateEnd(&pfile_in_zip_read_info->stream);
pfile_in_zip_read_info->stream_initialised = 0;
if (pfile_in_zip_read_info!=0) zfree(pfile_in_zip_read_info); // unused pfile_in_zip_read_info=0;
s->pfile_in_zip_read=NULL;
return err;
}
// Get the global comment string of the ZipFile, in the szComment buffer.
// uSizeBuf is the size of the szComment buffer.
// return the number of byte copied or an error code <0
int unzGetGlobalComment (unzFile file, char *szComment, uLong uSizeBuf)
{ //int err=UNZ_OK;
unz_s* s;
uLong uReadThis ;
if (file==NULL) return UNZ_PARAMERROR;
s=(unz_s*)file;
uReadThis = uSizeBuf;
if (uReadThis>s->gi.size_comment) uReadThis = s->gi.size_comment;
if (lufseek(s->file,s->central_pos+22,SEEK_SET)!=0) return UNZ_ERRNO;
if (uReadThis>0)
{ *szComment='\0';
if (lufread(szComment,(uInt)uReadThis,1,s->file)!=1) return UNZ_ERRNO;
}
if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment)) *(szComment+s->gi.size_comment)='\0';
return (int)uReadThis;
}
int unzOpenCurrentFile (unzFile file, const char *password);
int unzReadCurrentFile (unzFile file, void *buf, unsigned len);
int unzCloseCurrentFile (unzFile file);
typedef unsigned __int32 lutime_t; // define it ourselves since we don't include time.h
FILETIME timet2filetime(const lutime_t t)
{ LONGLONG i = Int32x32To64(t,10000000) + 116444736000000000;
FILETIME ft;
ft.dwLowDateTime = (DWORD) i;
ft.dwHighDateTime = (DWORD)(i >>32);
return ft;
}
FILETIME dosdatetime2filetime(WORD dosdate,WORD dostime)
{ // date: bits 0-4 are day of month 1-31. Bits 5-8 are month 1..12. Bits 9-15 are year-1980
// time: bits 0-4 are seconds/2, bits 5-10 are minute 0..59. Bits 11-15 are hour 0..23
SYSTEMTIME st;
st.wYear = (WORD)(((dosdate>>9)&0x7f) + 1980);
st.wMonth = (WORD)((dosdate>>5)&0xf);
st.wDay = (WORD)(dosdate&0x1f);
st.wHour = (WORD)((dostime>>11)&0x1f);
st.wMinute = (WORD)((dostime>>5)&0x3f);
st.wSecond = (WORD)((dostime&0x1f)*2);
st.wMilliseconds = 0;
FILETIME ft; SystemTimeToFileTime(&st,&ft);
return ft;
}
class TUnzip
{ public:
TUnzip(const char *pwd) : uf(0), unzbuf(0), currentfile(-1), czei(-1), password(0) {if (pwd!=0) {password=new char[strlen(pwd)+1]; strcpy_s(password,MAX_PATH,pwd);}}
~TUnzip() {if (password!=0) delete[] password; password=0; if (unzbuf!=0) delete[] unzbuf; unzbuf=0;}
unzFile uf; int currentfile; ZIPENTRY cze; int czei;
char *password;
char *unzbuf; // lazily created and destroyed, used by Unzip
TCHAR rootdir[MAX_PATH]; // includes a trailing slash
ZRESULT Open(void *z,unsigned int len,DWORD flags);
ZRESULT Get(int index,ZIPENTRY *ze);
ZRESULT Find(const TCHAR *name,bool ic,int *index,ZIPENTRY *ze);
ZRESULT Unzip(int index,void *dst,unsigned int len,DWORD flags);
ZRESULT SetUnzipBaseDir(const TCHAR *dir);
ZRESULT Close();
};
ZRESULT TUnzip::Open(void *z,unsigned int len,DWORD flags)
{ if (uf!=0 || currentfile!=-1) return ZR_NOTINITED;
//
#ifdef GetCurrentDirectory
GetCurrentDirectory(MAX_PATH,rootdir);
#else
_tcscpy(rootdir,_T("\\"));
#endif
TCHAR lastchar = rootdir[_tcslen(rootdir)-1];
if (lastchar!='\\' && lastchar!='/') _tcscat_s(rootdir,_T("\\"));
//
if (flags==ZIP_HANDLE)
{ // test if we can seek on it. We can't use GetFileType(h)==FILE_TYPE_DISK since it's not on CE.
DWORD res = SetFilePointer(z,0,0,FILE_CURRENT);
bool canseek = (res!=0xFFFFFFFF);
if (!canseek) return ZR_SEEK;
}
ZRESULT e; LUFILE *f = lufopen(z,len,flags,&e);
if (f==NULL) return e;
uf = unzOpenInternal(f);
if (uf==0) return ZR_NOFILE;
return ZR_OK;
}
ZRESULT TUnzip::SetUnzipBaseDir(const TCHAR *dir)
{
_tcscpy_s(rootdir, MAX_PATH, dir);
TCHAR lastchar = rootdir[_tcslen(rootdir)-1];
if (lastchar!='\\' && lastchar!='/') _tcscat_s(rootdir,_T("\\"));
return ZR_OK;
}
ZRESULT TUnzip::Get(int index,ZIPENTRY *ze)
{ if (index<-1 || index>=(int)uf->gi.number_entry) return ZR_ARGS;
if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1;
if (index==czei && index!=-1) {memcpy(ze,&cze,sizeof(ZIPENTRY)); return ZR_OK;}
if (index==-1)
{ ze->index = uf->gi.number_entry;
ze->name[0]=0;
ze->attr=0;
ze->atime.dwLowDateTime=0; ze->atime.dwHighDateTime=0;
ze->ctime.dwLowDateTime=0; ze->ctime.dwHighDateTime=0;
ze->mtime.dwLowDateTime=0; ze->mtime.dwHighDateTime=0;
ze->comp_size=0;
ze->unc_size=0;
return ZR_OK;
}
if (index<(int)uf->num_file) unzGoToFirstFile(uf);
while ((int)uf->num_file<index) unzGoToNextFile(uf);
unz_file_info ufi; char fn[MAX_PATH];
unzGetCurrentFileInfo(uf,&ufi,fn,MAX_PATH,NULL,0,NULL,0);
// now get the extra header. We do this ourselves, instead of
// calling unzOpenCurrentFile &c., to avoid allocating more than necessary.
unsigned int extralen,iSizeVar; unsigned long offset;
int res = unzlocal_CheckCurrentFileCoherencyHeader(uf,&iSizeVar,&offset,&extralen);
if (res!=UNZ_OK) return ZR_CORRUPT;
if (lufseek(uf->file,offset,SEEK_SET)!=0) return ZR_READ;
unsigned char *extra = new unsigned char[extralen];
if (lufread(extra,1,(uInt)extralen,uf->file)!=extralen) {delete[] extra; return ZR_READ;}
//
ze->index=uf->num_file;
TCHAR tfn[MAX_PATH];
#ifdef UNICODE
MultiByteToWideChar(CP_UTF8,0,fn,-1,tfn,MAX_PATH);
#else
strcpy(tfn,fn);
#endif
// As a safety feature: if the zip filename had sneaky stuff
// like "c:\windows\file.txt" or "\windows\file.txt" or "fred\..\..\..\windows\file.txt"
// then we get rid of them all. That way, when the programmer does UnzipItem(hz,i,ze.name),
// it won't be a problem. (If the programmer really did want to get the full evil information,
// then they can edit out this security feature from here).
// In particular, we chop off any prefixes that are "c:\" or "\" or "/" or "[stuff]\.." or "[stuff]/.."
const TCHAR *sfn=tfn;
for (;;)
{ if (sfn[0]!=0 && sfn[1]==':') {sfn+=2; continue;}
if (sfn[0]=='\\') {sfn++; continue;}
if (sfn[0]=='/') {sfn++; continue;}
const TCHAR *c;
c=_tcsstr(sfn,_T("\\..\\")); if (c!=0) {sfn=c+4; continue;}
c=_tcsstr(sfn,_T("\\../")); if (c!=0) {sfn=c+4; continue;}
c=_tcsstr(sfn,_T("/../")); if (c!=0) {sfn=c+4; continue;}
c=_tcsstr(sfn,_T("/..\\")); if (c!=0) {sfn=c+4; continue;}
break;
}
_tcscpy_s(ze->name, MAX_PATH, sfn);
// zip has an 'attribute' 32bit value. Its lower half is windows stuff
// its upper half is standard unix stat.st_mode. We'll start trying
// to read it in unix mode
unsigned long a = ufi.external_fa;
bool isdir = (a&0x40000000)!=0;
bool readonly= (a&0x00800000)==0;
//bool readable= (a&0x01000000)!=0; // unused
//bool executable=(a&0x00400000)!=0; // unused
bool hidden=false, system=false, archive=true;
// but in normal hostmodes these are overridden by the lower half...
int host = ufi.version>>8;
if (host==0 || host==7 || host==11 || host==14)
{ readonly= (a&0x00000001)!=0;
hidden= (a&0x00000002)!=0;
system= (a&0x00000004)!=0;
isdir= (a&0x00000010)!=0;
archive= (a&0x00000020)!=0;
}
ze->attr=0;
if (isdir) ze->attr |= FILE_ATTRIBUTE_DIRECTORY;
if (archive) ze->attr|=FILE_ATTRIBUTE_ARCHIVE;
if (hidden) ze->attr|=FILE_ATTRIBUTE_HIDDEN;
if (readonly) ze->attr|=FILE_ATTRIBUTE_READONLY;
if (system) ze->attr|=FILE_ATTRIBUTE_SYSTEM;
ze->comp_size = ufi.compressed_size;
ze->unc_size = ufi.uncompressed_size;
//
WORD dostime = (WORD)(ufi.dosDate&0xFFFF);
WORD dosdate = (WORD)((ufi.dosDate>>16)&0xFFFF);
FILETIME ftd = dosdatetime2filetime(dosdate,dostime);
FILETIME ft; LocalFileTimeToFileTime(&ftd,&ft);
ze->atime=ft; ze->ctime=ft; ze->mtime=ft;
// the zip will always have at least that dostime. But if it also has
// an extra header, then we'll instead get the info from that.
unsigned int epos=0;
while (epos+4<extralen)
{ char etype[3]; etype[0]=extra[epos+0]; etype[1]=extra[epos+1]; etype[2]=0;
int size = extra[epos+2];
if (strcmp(etype,"UT")!=0) {epos += 4+size; continue;}
int flags = extra[epos+4];
bool hasmtime = (flags&1)!=0;
bool hasatime = (flags&2)!=0;
bool hasctime = (flags&4)!=0;
epos+=5;
if (hasmtime)
{ lutime_t mtime = ((extra[epos+0])<<0) | ((extra[epos+1])<<8) |((extra[epos+2])<<16) | ((extra[epos+3])<<24);
epos+=4;
ze->mtime = timet2filetime(mtime);
}
if (hasatime)
{ lutime_t atime = ((extra[epos+0])<<0) | ((extra[epos+1])<<8) |((extra[epos+2])<<16) | ((extra[epos+3])<<24);
epos+=4;
ze->atime = timet2filetime(atime);
}
if (hasctime)
{ lutime_t ctime = ((extra[epos+0])<<0) | ((extra[epos+1])<<8) |((extra[epos+2])<<16) | ((extra[epos+3])<<24);
epos+=4;
ze->ctime = timet2filetime(ctime);
}
break;
}
//
if (extra!=0) delete[] extra;
memcpy(&cze,ze,sizeof(ZIPENTRY)); czei=index;
return ZR_OK;
}
ZRESULT TUnzip::Find(const TCHAR *tname,bool ic,int *index,ZIPENTRY *ze)
{ char name[MAX_PATH];
#ifdef UNICODE
WideCharToMultiByte(CP_UTF8,0,tname,-1,name,MAX_PATH,0,0);
#else
strcpy(name,tname);
#endif
int res = unzLocateFile(uf,name,ic?CASE_INSENSITIVE:CASE_SENSITIVE);
if (res!=UNZ_OK)
{ if (index!=0) *index=-1;
if (ze!=NULL) {ZeroMemory(ze,sizeof(ZIPENTRY)); ze->index=-1;}
return ZR_NOTFOUND;
}
if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1;
int i = (int)uf->num_file;
if (index!=NULL) *index=i;
if (ze!=NULL)
{ ZRESULT zres = Get(i,ze);
if (zres!=ZR_OK) return zres;
}
return ZR_OK;
}
void EnsureDirectory(const TCHAR *rootdir, const TCHAR *dir)
{ if (rootdir!=0 && GetFileAttributes(rootdir)==0xFFFFFFFF) CreateDirectory(rootdir,0);
if (*dir==0) return;
const TCHAR *lastslash=dir, *c=lastslash;
while (*c!=0) {if (*c=='/' || *c=='\\') lastslash=c; c++;}
const TCHAR *name=lastslash;
if (lastslash!=dir)
{ TCHAR tmp[MAX_PATH]; memcpy(tmp,dir,sizeof(TCHAR)*(lastslash-dir));
tmp[lastslash-dir]=0;
EnsureDirectory(rootdir,tmp);
name++;
}
TCHAR cd[MAX_PATH]; *cd=0; if (rootdir!=0) _tcscpy_s(cd, MAX_PATH, rootdir); _tcscat_s(cd,dir);
if (GetFileAttributes(cd)==0xFFFFFFFF) CreateDirectory(cd,NULL);
}
ZRESULT TUnzip::Unzip(int index,void *dst,unsigned int len,DWORD flags)
{ if (flags!=ZIP_MEMORY && flags!=ZIP_FILENAME && flags!=ZIP_HANDLE) return ZR_ARGS;
if (flags==ZIP_MEMORY)
{ if (index!=currentfile)
{ if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1;
if (index>=(int)uf->gi.number_entry) return ZR_ARGS;
if (index<(int)uf->num_file) unzGoToFirstFile(uf);
while ((int)uf->num_file<index) unzGoToNextFile(uf);
unzOpenCurrentFile(uf,password); currentfile=index;
}
bool reached_eof;
int res = unzReadCurrentFile(uf,dst,len,&reached_eof);
if (res<=0) {unzCloseCurrentFile(uf); currentfile=-1;}
if (reached_eof) return ZR_OK;
if (res>0) return ZR_MORE;
if (res==UNZ_PASSWORD) return ZR_PASSWORD;
return ZR_FLATE;
}
// otherwise we're writing to a handle or a file
if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1;
if (index>=(int)uf->gi.number_entry) return ZR_ARGS;
if (index<(int)uf->num_file) unzGoToFirstFile(uf);
while ((int)uf->num_file<index) unzGoToNextFile(uf);
ZIPENTRY ze; Get(index,&ze);
// zipentry=directory is handled specially
if ((ze.attr&FILE_ATTRIBUTE_DIRECTORY)!=0)
{ if (flags==ZIP_HANDLE) return ZR_OK; // don't do anything
const TCHAR *dir = (const TCHAR*)dst;
bool isabsolute = (dir[0]=='/' || dir[0]=='\\' || (dir[0]!=0 && dir[1]==':'));
if (isabsolute) EnsureDirectory(0,dir); else EnsureDirectory(rootdir,dir);
return ZR_OK;
}
// otherwise, we write the zipentry to a file/handle
HANDLE h;
if (flags==ZIP_HANDLE) h=dst;
else
{ const TCHAR *ufn = (const TCHAR*)dst;
// We'll qualify all relative names to our root dir, and leave absolute names as they are
// ufn="zipfile.txt" dir="" name="zipfile.txt" fn="c:\\currentdir\\zipfile.txt"
// ufn="dir1/dir2/subfile.txt" dir="dir1/dir2/" name="subfile.txt" fn="c:\\currentdir\\dir1/dir2/subfiles.txt"
// ufn="\z\file.txt" dir="\z\" name="file.txt" fn="\z\file.txt"
// This might be a security risk, in the case where we just use the zipentry's name as "ufn", where
// a malicious zip could unzip itself into c:\windows. Our solution is that GetZipItem (which
// is how the user retrieve's the file's name within the zip) never returns absolute paths.
const TCHAR *name=ufn; const TCHAR *c=name; while (*c!=0) {if (*c=='/' || *c=='\\') name=c+1; c++;}
TCHAR dir[MAX_PATH]; _tcscpy_s(dir, MAX_PATH, ufn); if (name==ufn) *dir=0; else dir[name-ufn]=0;
TCHAR fn[MAX_PATH];
bool isabsolute = (dir[0]=='/' || dir[0]=='\\' || (dir[0]!=0 && dir[1]==':'));
if (isabsolute) {wsprintf(fn,_T("%s%s"),dir,name); EnsureDirectory(0,dir);}
else {wsprintf(fn,_T("%s%s%s"),rootdir,dir,name); EnsureDirectory(rootdir,dir);}
//
h = CreateFile(fn,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,ze.attr,NULL);
}
if (h==INVALID_HANDLE_VALUE) return ZR_NOFILE;
unzOpenCurrentFile(uf,password);
if (unzbuf==0) unzbuf=new char[16384]; DWORD haderr=0;
//
for (; haderr==0;)
{ bool reached_eof;
int res = unzReadCurrentFile(uf,unzbuf,16384,&reached_eof);
if (res==UNZ_PASSWORD) {haderr=ZR_PASSWORD; break;}
if (res<0) {haderr=ZR_FLATE; break;}
if (res>0) {DWORD writ; BOOL bres=WriteFile(h,unzbuf,res,&writ,NULL); if (!bres) {haderr=ZR_WRITE; break;}}
if (reached_eof) break;
if (res==0) {haderr=ZR_FLATE; break;}
}
if (!haderr) SetFileTime(h,&ze.ctime,&ze.atime,&ze.mtime); // may fail if it was a pipe
if (flags!=ZIP_HANDLE) CloseHandle(h);
unzCloseCurrentFile(uf);
if (haderr!=0) return haderr;
return ZR_OK;
}
ZRESULT TUnzip::Close()
{ if (currentfile!=-1) unzCloseCurrentFile(uf); currentfile=-1;
if (uf!=0) unzClose(uf); uf=0;
return ZR_OK;
}
ZRESULT lasterrorU=ZR_OK;
unsigned int FormatZipMessageU(ZRESULT code, TCHAR *buf,unsigned int len)
{ if (code==ZR_RECENT) code=lasterrorU;
const TCHAR *msg=_T("unknown zip result code");
switch (code)
{ case ZR_OK: msg=_T("Success"); break;
case ZR_NODUPH: msg=_T("Culdn't duplicate handle"); break;
case ZR_NOFILE: msg=_T("Couldn't create/open file"); break;
case ZR_NOALLOC: msg=_T("Failed to allocate memory"); break;
case ZR_WRITE: msg=_T("Error writing to file"); break;
case ZR_NOTFOUND: msg=_T("File not found in the zipfile"); break;
case ZR_MORE: msg=_T("Still more data to unzip"); break;
case ZR_CORRUPT: msg=_T("Zipfile is corrupt or not a zipfile"); break;
case ZR_READ: msg=_T("Error reading file"); break;
case ZR_PASSWORD: msg=_T("Correct password required"); break;
case ZR_ARGS: msg=_T("Caller: faulty arguments"); break;
case ZR_PARTIALUNZ: msg=_T("Caller: the file had already been partially unzipped"); break;
case ZR_NOTMMAP: msg=_T("Caller: can only get memory of a memory zipfile"); break;
case ZR_MEMSIZE: msg=_T("Caller: not enough space allocated for memory zipfile"); break;
case ZR_FAILED: msg=_T("Caller: there was a previous error"); break;
case ZR_ENDED: msg=_T("Caller: additions to the zip have already been ended"); break;
case ZR_ZMODE: msg=_T("Caller: mixing creation and opening of zip"); break;
case ZR_NOTINITED: msg=_T("Zip-bug: internal initialisation not completed"); break;
case ZR_SEEK: msg=_T("Zip-bug: trying to seek the unseekable"); break;
case ZR_MISSIZE: msg=_T("Zip-bug: the anticipated size turned out wrong"); break;
case ZR_NOCHANGE: msg=_T("Zip-bug: tried to change mind, but not allowed"); break;
case ZR_FLATE: msg=_T("Zip-bug: an internal error during flation"); break;
}
unsigned int mlen=(unsigned int)_tcslen(msg);
if (buf==0 || len==0) return mlen;
unsigned int n=mlen; if (n+1>len) n=len-1;
_tcsncpy_s(buf,MAX_PATH,msg,n); buf[n]=0;
return mlen;
}
typedef struct
{ DWORD flag;
TUnzip *unz;
} TUnzipHandleData;
HZIP OpenZipInternal(void *z,unsigned int len,DWORD flags, const char *password)
{ TUnzip *unz = new TUnzip(password);
lasterrorU = unz->Open(z,len,flags);
if (lasterrorU!=ZR_OK) {delete unz; return 0;}
TUnzipHandleData *han = new TUnzipHandleData;
han->flag=1; han->unz=unz; return (HZIP)han;
}
HZIP OpenZipHandle(HANDLE h, const char *password) {return OpenZipInternal((void*)h,0,ZIP_HANDLE,password);}
HZIP OpenZip(const TCHAR *fn, const char *password) {return OpenZipInternal((void*)fn,0,ZIP_FILENAME,password);}
HZIP OpenZip(void *z,unsigned int len, const char *password) {return OpenZipInternal(z,len,ZIP_MEMORY,password);}
ZRESULT GetZipItem(HZIP hz, int index, ZIPENTRY *ze)
{ ze->index=0; *ze->name=0; ze->unc_size=0;
if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;}
TUnzipHandleData *han = (TUnzipHandleData*)hz;
if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;}
TUnzip *unz = han->unz;
lasterrorU = unz->Get(index,ze);
return lasterrorU;
}
ZRESULT FindZipItem(HZIP hz, const TCHAR *name, bool ic, int *index, ZIPENTRY *ze)
{ if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;}
TUnzipHandleData *han = (TUnzipHandleData*)hz;
if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;}
TUnzip *unz = han->unz;
lasterrorU = unz->Find(name,ic,index,ze);
return lasterrorU;
}
ZRESULT UnzipItemInternal(HZIP hz, int index, void *dst, unsigned int len, DWORD flags)
{ if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;}
TUnzipHandleData *han = (TUnzipHandleData*)hz;
if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;}
TUnzip *unz = han->unz;
lasterrorU = unz->Unzip(index,dst,len,flags);
return lasterrorU;
}
ZRESULT UnzipItemHandle(HZIP hz, int index, HANDLE h) {return UnzipItemInternal(hz,index,(void*)h,0,ZIP_HANDLE);}
ZRESULT UnzipItem(HZIP hz, int index, const TCHAR *fn) {return UnzipItemInternal(hz,index,(void*)fn,0,ZIP_FILENAME);}
ZRESULT UnzipItem(HZIP hz, int index, void *z,unsigned int len) {return UnzipItemInternal(hz,index,z,len,ZIP_MEMORY);}
ZRESULT SetUnzipBaseDir(HZIP hz, const TCHAR *dir)
{ if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;}
TUnzipHandleData *han = (TUnzipHandleData*)hz;
if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;}
TUnzip *unz = han->unz;
lasterrorU = unz->SetUnzipBaseDir(dir);
return lasterrorU;
}
ZRESULT CloseZipU(HZIP hz)
{ if (hz==0) {lasterrorU=ZR_ARGS;return ZR_ARGS;}
TUnzipHandleData *han = (TUnzipHandleData*)hz;
if (han->flag!=1) {lasterrorU=ZR_ZMODE;return ZR_ZMODE;}
TUnzip *unz = han->unz;
lasterrorU = unz->Close();
delete unz;
delete han;
return lasterrorU;
}
bool IsZipHandleU(HZIP hz)
{ if (hz==0) return false;
TUnzipHandleData *han = (TUnzipHandleData*)hz;
return (han->flag==1);
} | [
"[email protected]"
] | |
24b0cfcee928793ccea8ee66d47b29775ad07acb | 37585de86ef412211a9b2519817d3ff5247373c8 | /Ideas/Tables.cpp | 12fc8654ef051bc6cf9129489e60bc617c02528b | [
"LicenseRef-scancode-warranty-disclaimer",
"Fair"
] | permissive | ghassanpl/reflector | 7b99162a0e792ff6a0eebecf98c277791df6bae4 | 217a9fe630f7a9c6ea196d26d69364138be5a5bc | refs/heads/master | 2023-08-17T13:42:14.394557 | 2023-08-13T10:57:16 | 2023-08-13T18:49:58 | 196,881,074 | 12 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 5,336 | cpp | #if 0
RClass(Record, Multithreaded);
struct Movie
{
RBody(); =>
BaseTable* mParentTable = nullptr;
friend struct MovieTable;
mutable bool mDeletePending = false;
enum class Column { ID, Name, Score, ReleaseYear, IMDBId, SomeSource };
std::bitset<enum_count<Column>() + /* entire row needs flushing */1> mChanges;
/// TODO: Do we require inherting from reflectable? We could use its Dirty flag
RField(Key, Autoincrement);
int ID = 0;
RField(Index = { Collation = CaseInsensitive });
string Name;
RField(Index = { Sort = Descending });
double Score = 5.0;
RField(Index);
int ReleaseYear = 2000;
RField(Index, Unique);
uint64_t IMDBId = 0;
=> void SetIMBDId(uint64_t val) {
mParentTable->InTransaction([this, &val] {
mParentTable->ConstrainedSet(this, (int)Column::IMDBId, this->IMDBId, val);
mParentTable->Reindex(this, (int)Column::IMDBId);
mParentTable->Reindex(this, (int)Column::SomeSource);
});
}
RMethod(Index);
int SomeSource() const; /// Cannot have arguments, must be const
/// Only private fields ? How to limit changing indexed fields?
};
=>
struct BaseTable
{
std::mutex mWriteTransactionMutex;
std::atomic_size_t mTransactionDepth{0};
}
template <typename ROW_TYPE, typename CRTP>
struct TTable : BaseTable
{
using RowType = ROW_TYPE;
using PrimaryKeyType = RowType::PrimaryKeyType;
static constexpr inline RowCount = RowType::mRowCount;
std::array<bool, RowCount> mIndicesInNeedOfRebuilding;
void Reindex(ROW_TYPE* because_of, int column)
{
mIndicesInNeedOfRebuilding[column] = true;
}
void BeginTransaction()
{
if constexpr (RowType::Attribute_Multithreaded)
{
if (mTransactionDepth == 0)
mWriteTransactionMutex.lock();
}
mTransactionDepth++;
};
void EndTransaction()
{
mTransactionDepth--;
if (mTransactionDepth == 0)
{
for (int i=0; i<RowCount; ++i)
if (mIndicesInNeedOfRebuilding)
static_cast<CRTP*>(this)->PerformReindex(i);
if constexpr (RowType::Attribute_Multithreaded)
mWriteTransactionMutex.unlock();
}
}
std::map<PK, T, std::less<>> TableStorage;
};
struct OrderBy : SelectParam
{
OrderBy(member function pointer, asc/desc = asc);
OrderBy(member variable pointer, asc/desc = asc);
OrderBy(column id, asc/desc = asc);
OrderBy(column name, asc/desc = asc);
};
struct MovieTable : TTable<Movie, MovieTable>
{
auto InTransaction(auto&& func) -> decltype(func(this))
{
BeginWriteTransaction();
try
{
return func(this);
EndWriteTransaction();
}
catch (e)
{
if (!RollbackTransaction()) /// mTransactionDepth > 1
throw;
}
return {};
}
/// Not thread-safe
RowType const* Get(PrimaryKeyType const& key)
{
auto row = Find(key);
if (row && !row->mDeletePending)
return row;
return nullptr;
}
auto With(PrimaryKeyType const& key, auto&& func)
{
return InTransaction([&]{
auto row = Get(key);
return row ? func(*row) : {};
});
}
std::optional<RowType> Delete(PrimaryKeyType const& key)
{
}
/// Params are stuff like LIMIT, ORDER BY, etc.
std::vector<RowType> DeleteWhere(auto&& func, auto... params)
{
return InTransaction([&] {
MovieTableSelection selection = Select(func, params...);
return RemoveRows(selection);
});
}
void ForEach(auto&& func);
MovieTableSelection Select(auto&& func, auto... params);
/// group by, distinct, window, joins, having
std::optional<PrimaryKeyType> Insert(RowType row);
std::vector<PrimaryKeyType> Insert(std::span<RowType> rows);
std::optional<PrimaryKeyType> InsertOr(ABORT/FAIL/IGNORE/REPLACE/ROLLBACK, RowType row);
std::optional<PrimaryKeyType> InsertOrUpdate(RowType new_row, auto&& update_func)
{
if (conflict)
{
update_func(new_row, old_row);
old_row->SetDirty();
}
}
void Update(auto&& update_func, auto&& where, auto... params)
{
return InTransaction([&] {
MovieTableSelection selection = Select(where, params...);
for (auto& obj : selection)
{
update_func(obj);
obj->SetDirty();
}
});
}
private:
struct TransactionElement
{
int ElementType = /// UPDATE_FIELD, DELETE_ROW;
row_ptr Row = {};
int ColumnId = {};
std::any OldFieldValue;
};
enum {
ROW_Name,
ROW_Score,
ROW_ReleaseYear,
ROW_IMDBId,
ROW_SomeSource,
ROW_COUNT,
};
void PerformReindex(int row)
{
switch (row)
{
case ROW_Name: PerformReindex_Name();
...
}
}
friend struct Movie;
using RowPtr = either `PrimaryKeyType` or `RowType*`
std::multimap<string, RowPtr, Reflector::Collator<CaseInsensitive>::Less> IndexFor_Name;
std::multimap<double, RowPtr, std::greater<>> IndexFor_Score;
std::multimap<int, RowPtr, std::less<>> IndexFor_ReleaseYear;
std::map<uint64_t, RowPtr, std::less<>> IndexFor_IMDBId;
std::multimap<int, RowPtr, std::less<>> IndexFor_SomeSource;
};
template <typename TABLE>
struct TTableSelection
{
std::vector<TABLE::PrimaryKeyType> SelectedRows;
void SortByColumns(auto... columns);
void Crop(int start, int count);
};
struct MovieTableSelection : TTableSelection<MovieTable>
{
};
#endif | [
"[email protected]"
] | |
6f9e2a1251e0d80527ebef9b1764f62a60cc7984 | c26e9d3f92d95f7ce9d0fd5ef2c18dd95ec209a5 | /hackerrank/graph/murderer.cpp | 1fb9dd65652537e7209bab94ed2d7f66c6acb818 | [] | no_license | crystal95/Competetive-Programming-at-different-platforms | c9ad1684f6258539309d07960ed6abfa7d1a16d0 | 92d283171b0ae0307e9ded473c6eea16f62cb60e | refs/heads/master | 2021-01-09T21:44:28.175506 | 2016-03-27T21:26:26 | 2016-03-27T21:26:26 | 54,848,617 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,083 | cpp | using namespace std;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <iostream>
#include <queue>
#include <algorithm>
#include <unordered_set>
typedef long long int ll;
typedef pair<int,int> ii;
void bfs(vector<vector<int> > &adj,int s,vector<int> &dis,int n)
{
int i ;
unordered_set<int> unvisited;
for(i=1;i<=n;i++)
unvisited.insert(i);
queue<int> q;
q.push(s);
unvisited.erase(s);
while(!q.empty())
{
int tmp=q.front();
q.pop();
for(auto it=unvisited.begin();it!=unvisited.end();++it)
{
if(find(adj[tmp].begin(),adj[tmp].end(),*it)==adj[tmp].end())
{
q.push(*it);
dis[*it]=dis[tmp]+1;
unvisited.erase(*it);
}
}
}
}
int main()
{
int T;
cin>>T;
while(T--)
{
int i,n,m,u,v,s,w,start;
cin>>n>>m;
vector<vector<int > > adj(n+1);
vector<int> dis(n+1,0);
for(i=0;i<m;i++)
{
cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
cin>>start;
bfs(adj,start,dis,n);
for(i=1;i<=n;i++)
{
if(start!=i)
cout<<dis[i]<<" ";
}
cout<<endl;
}
return 0;
}
| [
"[email protected]"
] | |
71b57f5243d516e395976e4bdf4e9b22391da34d | 46de5c99419f112b4507fd386f398769626ad328 | /thinkbig2.cpp | 16cfc1eba8eed89495a53e3254d4d0856bad3cb9 | [] | no_license | sanu11/Codes | 20a7903d95d600078db8b0bf0e12a3731615c3c1 | dd58a5577b51ade54f95c96003fc2c99609c15eb | refs/heads/master | 2021-01-21T04:50:36.855876 | 2019-07-09T05:12:56 | 2019-07-09T05:12:56 | 48,174,017 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 768 | cpp |
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m;
cin>>n;
int arr[n];
int x,y;
map<int,int>a;
map<int,int>::iterator p;
for(int i=0;i<n;i++)
{
cin>>arr[i];
cin>>x;
for(int j=0;j<x;j++)
{
cin>>y;
p=a.find(y);
if(p==a.end())
a.insert(make_pair(y,1));
}
}
p=a.begin();
for(int i=0;i<n;i++)
{
p=a.begin();
while(p!=a.end())
{
// cout<<arr[i]<<" "<<p->first<<endl;
if(arr[i]==p->first)
p->second--;
p++;
}
}
p=a.begin();
int sum=0;
while(p!=a.end())
{
//cout<<p->first<<" "<<p->second<<endl;
sum+=p->second;
p++;
}
cout<<sum<<endl;
return 0;
}
| [
"[email protected]"
] | |
22b4b85995b27b9bf5a3b2c844bcb56c4ab65e55 | 090243cf699213f32f870baf2902eb4211f825d6 | /cf/621/D.cpp | 27cba968aae8be25270c8a561e72debc59131184 | [] | no_license | zhu-he/ACM-Source | 0d4d0ac0668b569846b12297e7ed4abbb1c16571 | 02e3322e50336063d0d2dad37b2761ecb3d4e380 | refs/heads/master | 2021-06-07T18:27:19.702607 | 2016-07-10T09:20:48 | 2016-07-10T09:20:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 625 | cpp | #include <cstdio>
#include <cmath>
const char s[12][10] = {"x^y^z", "x^z^y", "(x^y)^z", "(x^z)^y", "y^x^z", "y^z^x", "(y^x)^z", "(y^z)^x", "z^x^y", "z^y^x", "(z^x)^y", "(z^y)^x"};
double d[12];
int main()
{
double x, y, z;
scanf("%lf %lf %lf", &x, &y, &z);
d[0] = pow(y, z) * log(x);
d[1] = pow(z, y) * log(x);
d[2] = d[3] = y * z * log(x);
d[4] = pow(x, z) * log(y);
d[5] = pow(z, x) * log(y);
d[6] = d[7] = x * z * log(y);
d[8] = pow(x, y) * log(z);
d[9] = pow(y, x) * log(z);
d[10] = d[11] = x * y * log(z);
int mx = 0;
for (int i = 1; i < 12; ++i)
if (d[i] > d[mx])
mx = i;
puts(s[mx]);
return 0;
}
| [
"[email protected]"
] | |
b54f8af3b8d91ec3312f1936cc121941612c52f9 | 33c05858242f026297d97a902656ee8f066683a8 | /satellite_sniffer_BoTFSM/src/Canvas.cpp | ad8ababfa55c65250d872cc2f5187e0f6e6b207d | [] | no_license | CodecoolBP20171/cpp-satellite-sniffer-botfsm | d8bcb902da2c4f3e2d7b827da0558343022687c3 | b29818ae7dc1d2f7f3967c278a3d01c447786df8 | refs/heads/master | 2021-06-01T16:43:46.978984 | 2018-09-30T13:10:56 | 2018-09-30T13:10:56 | 113,032,533 | 4 | 2 | null | 2018-09-30T13:10:57 | 2017-12-04T11:09:09 | C | UTF-8 | C++ | false | false | 883 | cpp | #include "stdafx.h"
#include "Canvas.h"
#include "Resources.h"
#include <SDL.h>
Canvas::Canvas(const int width, const int height)
{
this->height = height;
this->width = width;
texture = SDL_CreateTexture(Resources::getInstance()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height);
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
}
void Canvas::resize(const int width, const int height)
{
if (texture) SDL_DestroyTexture(texture);
this->height = height;
this->width = width;
texture = SDL_CreateTexture(Resources::getInstance()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height);
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
}
void Canvas::setAsRenderTarget()
{
SDL_SetRenderTarget(Resources::getInstance()->getRenderer(), texture);
}
Canvas::~Canvas()
{
}
| [
"[email protected]"
] | |
a35449fec2af60cbb23f7da0b8bae35a4ce64aef | 1dc05c3cb3a57aea5f64052f329eaf458f73c832 | /topic/LeetCode/0807maxIncreaseKeepingSkyline.cpp | 603cf6950b266ec0a72ef42137f69d3f137e23ee | [] | no_license | ITShadow/practiceCode | 0b1fcbb6b150a1ee91283e8ac7a8d928b4751eda | 4b407ad98e3abc0be5eadc97ff32165f9f367104 | refs/heads/master | 2023-04-08T05:53:21.734166 | 2021-04-26T03:45:46 | 2021-04-26T03:45:46 | 295,429,631 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,203 | cpp | /* 在二维数组grid中,grid[i][j]代表位于某处的建筑物的高度。 我们被允许增加任何数量(不同建筑物的数量可能不同)的建筑物的高度。 高度 0 也被认为是建筑物。
最后,从新数组的所有四个方向(即顶部,底部,左侧和右侧)观看的“天际线”必须与原始数组的天际线相同。 城市的天际线是从远处观看时,由所有建筑物形成的矩形的外部轮廓。 请看下面的例子。
建筑物高度可以增加的最大总和是多少?
例子:
输入: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
输出: 35
解释:
The grid is:
[ [3, 0, 8, 4],
[2, 4, 5, 7],
[9, 2, 6, 3],
[0, 3, 1, 0] ]
从数组竖直方向(即顶部,底部)看“天际线”是:[9, 4, 8, 7]
从水平水平方向(即左侧,右侧)看“天际线”是:[8, 7, 9, 3]
在不影响天际线的情况下对建筑物进行增高后,新数组如下:
gridNew = [ [8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3] ]
说明:
1 < grid.length = grid[0].length <= 50。
grid[i][j] 的高度范围是: [0, 100]。
一座建筑物占据一个grid[i][j]:换言之,它们是 1 x 1 x grid[i][j] 的长方体。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-increase-to-keep-city-skyline
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {
if (grid.empty()) return 0;
int R = grid.size();
int C = grid[0].size();
vector<int> row_max(R, 0);
vector<int> col_max(C, 0);
for (int i = 0; i < R; ++i) {
for (int j = 0; j < C; ++j) {
row_max[i] = max(row_max[i], grid[i][j]);
col_max[j] = max(col_max[j], grid[i][j]);
}
}
int res = 0;
for (int i = 0; i < R; ++i) {
for (int j = 0; j < C; ++j) {
res += min(row_max[i], col_max[j]) - grid[i][j];
}
}
return res;
}
}; */
/* 就是找行列最大 */ | [
"[email protected]"
] | |
28ccee844626dc8f532b974e14b830d2f77d8276 | fce00ed7da745340691c8c6cf47905ba4fe5a08e | /UchClient/FrmMain.cpp | 632d7a2b262d04091ced8c1a66af203405b47a34 | [
"Unlicense"
] | permissive | EAirPeter/Uch | bc9bae801721a9241afbfe8add293cf5dcf7a322 | 193ee52fb98d2d224cd22483b2523caf02805cfe | refs/heads/master | 2021-07-24T15:06:17.555444 | 2017-11-05T14:25:50 | 2017-11-05T14:25:50 | 109,581,211 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,153 | cpp | #include "Common.hpp"
#include "FrmFileRecv.hpp"
#include "FrmFileSend.hpp"
#include "FrmMain.hpp"
#include "Ucl.hpp"
#include <nana/gui/filebox.hpp>
using namespace nana;
FrmMain::FrmMain() :
form(nullptr, {768, 480}, appear::decorate<
appear::taskbar, appear::minimize, appear::maximize, appear::sizable
>())
{
caption(Title(L"Client"));
events().destroy(std::bind(&FrmMain::X_OnDestroy, this, std::placeholders::_1));
events().user(std::bind(&FrmMain::X_OnUser, this, std::placeholders::_1));
events().unload([this] (const arg_unload &e) {
msgbox mbx {nullptr, TitleU8(L"Exit"), msgbox::yes_no};
mbx.icon(msgbox::icon_question);
mbx << L"Are you sure to exit Uch?";
if (mbx() != mbx.pick_yes)
e.cancel = true;
});
x_btnSend.caption(L"Send");
x_btnSend.events().click(std::bind(&FrmMain::X_OnSend, this));
x_btnSend.events().key_press([this] (const arg_keyboard &e) {
if (e.key == keyboard::enter)
X_OnSend();
});
x_btnFile.caption(L"Send File");
x_btnFile.events().click(std::bind(&FrmMain::X_OnFile, this));
x_btnFile.events().key_press([this] (const arg_keyboard &e) {
if (e.key == keyboard::enter)
X_OnFile();
});
x_btnExit.caption(L"Exit");
x_btnExit.events().click(std::bind(&FrmMain::close, this));
x_btnExit.events().key_press([this] (const arg_keyboard &e) {
if (e.key == keyboard::enter)
close();
});
x_txtMessage.multi_lines(false).tip_string(u8"Message:");
x_txtMessage.events().focus([this] (const arg_focus &e) {
x_txtMessage.select(e.getting);
});
x_txtMessage.events().key_press([this] (const arg_keyboard &e) {
if (e.key == keyboard::enter)
X_OnSend();
});
x_lbxUsers.enable_single(true, false);
x_lbxUsers.append_header(L"Who", 110);
x_lbxUsers.append({L"Online", L"Offline"});
x_lbxMessages.sortable(false);
x_lbxMessages.append_header(L"When", 80);
x_lbxMessages.append_header(L"How", 180);
x_lbxMessages.append_header(L"What", 310);
x_pl.div(
"margin=[14,16]"
" <weight=120 List> <weight=8>"
" <vert"
" <Msgs> <weight=7>"
" <weight=25 Imsg> <weight=7>"
" <weight=25 <> <weight=259 gap=8 Btns>>"
" >"
);
x_pl["List"] << x_lbxUsers;
x_pl["Msgs"] << x_lbxMessages;
x_pl["Imsg"] << x_txtMessage;
x_pl["Btns"] << x_btnExit << x_btnFile << x_btnSend;
x_pl.collocate();
Ucl::Bus().Register(*this);
}
void FrmMain::OnEvent(event::EvMessage &e) noexcept {
constexpr static auto kszFmt = L"(%s) %s => %s";
x_lbxMessages.at(0).append({
FormattedTime(),
FormatString(L"(%s) %s => %s", e.sCat.c_str(), e.sFrom.c_str(), e.sTo.c_str()),
e.sWhat
});
x_lbxMessages.scroll(true);
}
void FrmMain::OnEvent(event::EvListUon &e) noexcept {
x_lbxUsers.at(1).model<std::recursive_mutex>(
e.vecUon,
[] (auto &c) {
return AsWideString(c.front().text);
},
[] (auto &s) {
return std::vector<listbox::cell> {AsUtf8String(s)};
}
);
}
void FrmMain::OnEvent(event::EvListUff &e) noexcept {
x_lbxUsers.at(2).model<std::recursive_mutex>(
e.vecUff,
[] (auto &c) {
return AsWideString(c.front().text);
},
[] (auto &s) {
return std::vector<listbox::cell> {AsUtf8String(s)};
}
);
}
void FrmMain::OnEvent(event::EvFileReq &e) noexcept {
user(std::make_unique<event::EvFileReq>(e).release());
}
void FrmMain::X_OnSend() {
auto vec = x_lbxUsers.selected();
if (vec.empty()) {
msgbox mbx {nullptr, TitleU8(L"Send message"), msgbox::ok};
mbx.icon(msgbox::icon_error);
mbx << L"Please select a recipient";
mbx();
return;
}
auto &idx = vec.front();
auto sUser = AsWideString(x_lbxUsers.at(idx.cat).at(idx.item).text(0));
switch (idx.cat) {
case 1:
// Online
X_AddMessage({kszCatChat, kszSelf, sUser, x_txtMessage.caption_wstring()});
(*Ucl::Pmg())[sUser].PostPacket(protocol::EvpMessage {
x_txtMessage.caption_wstring()
});
break;
case 2:
// Offline
X_AddMessage({kszCatFmsg, kszSelf, sUser, x_txtMessage.caption_wstring()});
Ucl::Con()->PostPacket(protocol::EvcMessageTo {
sUser, x_txtMessage.caption_wstring()
});
break;
default:
throw ExnIllegalState {};
}
x_txtMessage.caption(String {});
}
void FrmMain::X_OnFile() {
auto vec = x_lbxUsers.selected();
if (vec.empty()) {
msgbox mbx {TitleU8(L"Send file")};
mbx.icon(msgbox::icon_error);
mbx << L"Please select a recipient";
mbx();
return;
}
auto &idx = vec.front();
if (idx.cat != 1) {
msgbox mbx {TitleU8(L"Send file")};
mbx.icon(msgbox::icon_error);
mbx << L"Please select an online user";
mbx();
return;
}
auto sUser = AsWideString(x_lbxUsers.at(idx.cat).at(idx.item).text(0));
filebox fbx {nullptr, true};
if (!fbx())
return;
auto sPath = AsWideString(fbx.file());
UccPipl *pPipl;
try {
pPipl = &(*Ucl::Pmg())[sUser];
}
catch (std::out_of_range) {
msgbox mbx {TitleU8(L"Send file")};
mbx << L"The user if offline";
mbx();
return;
}
form_loader<FrmFileSend>() (*this, pPipl, sPath).show();
}
void FrmMain::X_OnDestroy(const nana::arg_destroy &e) {
Ucl::Con()->PostPacket(protocol::EvcExit {Ucl::Usr()});
Ucl::Con()->Shutdown();
Ucl::Pmg()->Shutdown();
Ucl::Bus().Unregister(*this);
}
void FrmMain::X_OnUser(const nana::arg_user &e) {
std::unique_ptr<event::EvFileReq> up {
reinterpret_cast<event::EvFileReq *>(e.param)
};
try {
form_loader<FrmFileRecv>() (*this, up->pPipl, up->eReq).show();
}
catch (ExnIllegalState) {}
}
void FrmMain::X_AddMessage(event::EvMessage &&e) noexcept {
OnEvent(e);
}
| [
"[email protected]"
] | |
ec71eee9144a294508e930330ca1e438fb3fc919 | 32b88f828b33279cfe33420c2ed969131a7df987 | /Code/Core/Mem/MemTracker.cpp | 777a97039b84548fb8dbfdacb216b93ff26a076f | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | punitchandra/fastbuild | 53b51f001350104629e71434bb5e521a1bb63cae | 8a445d77343bc4881b33a5ebcf31a2ec8777ae2d | refs/heads/master | 2021-01-15T13:23:26.995800 | 2017-08-21T15:05:32 | 2017-08-21T15:05:32 | 38,138,811 | 0 | 0 | null | 2015-06-26T23:30:24 | 2015-06-26T23:30:23 | null | UTF-8 | C++ | false | false | 7,281 | cpp | // MemTracker.cpp
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "Core/PrecompiledHeader.h"
#include "MemTracker.h"
//------------------------------------------------------------------------------
#if defined( MEMTRACKER_ENABLED )
// Includes
//------------------------------------------------------------------------------
#include "Core/Mem/MemPoolBlock.h"
#include "Core/Process/Atomic.h"
#include "Core/Process/Thread.h"
#include "Core/Tracing/Tracing.h"
// system
#include <memory.h> // for memset
// Static Data
//------------------------------------------------------------------------------
/*static*/ uint32_t MemTracker::s_Id( 0 );
/*static*/ bool MemTracker::s_Enabled( true );
/*static*/ bool MemTracker::s_Initialized( false );
/*static*/ uint32_t MemTracker::s_AllocationCount( 0 );
/*static*/ uint64_t MemTracker::s_Mutex[];
/*static*/ MemTracker::Allocation ** MemTracker::s_AllocationHashTable = nullptr;
/*static*/ MemPoolBlock * MemTracker::s_Allocations( nullptr );
// Thread-Local Data
//------------------------------------------------------------------------------
THREAD_LOCAL uint32_t g_MemTrackerDisabledOnThisThread( 0 );
// Defines
#define ALLOCATION_MINIMUM_ALIGN ( 0x4 ) // assume at least 4 byte alignment
#define ALLOCATION_HASH_SHIFT ( 0x2 ) // shift off lower bits
#define ALLOCATION_HASH_SIZE ( 0x100000 ) // one megabyte
#define ALLOCATION_HASH_MASK ( 0x0FFFFF ) // mask off upper bits
// Alloc
//------------------------------------------------------------------------------
/*static*/ void MemTracker::Alloc( void * ptr, size_t size, const char * file, int line )
{
if ( !s_Enabled )
{
return;
}
// handle allocations during initialization
if ( g_MemTrackerDisabledOnThisThread )
{
return;
}
++g_MemTrackerDisabledOnThisThread;
if ( !s_Initialized )
{
Init();
}
const size_t hashIndex = ( ( (size_t)ptr >> ALLOCATION_HASH_SHIFT ) & ALLOCATION_HASH_MASK );
{
MutexHolder mh( GetMutex() );
Allocation * a = (Allocation *)s_Allocations->Alloc( sizeof( Allocation ) );
++s_AllocationCount;
a->m_Id = ++s_Id;
a->m_Ptr = ptr;
a->m_Size = size;
a->m_Next = s_AllocationHashTable[ hashIndex ];
a->m_File = file;
a->m_Line = line;
static size_t breakOnSize = (size_t)-1;
static uint32_t breakOnId = 0;
if ( ( size == breakOnSize ) || ( a->m_Id == breakOnId ) )
{
BREAK_IN_DEBUGGER;
}
s_AllocationHashTable[ hashIndex ] = a;
}
--g_MemTrackerDisabledOnThisThread;
}
// Free
//------------------------------------------------------------------------------
/*static*/ void MemTracker::Free( void * ptr )
{
if ( !s_Enabled )
{
return;
}
if ( !s_Initialized )
{
return;
}
if ( g_MemTrackerDisabledOnThisThread )
{
return;
}
const size_t hashIndex = ( ( (size_t)ptr >> ALLOCATION_HASH_SHIFT ) & ALLOCATION_HASH_MASK );
MutexHolder mh( GetMutex() );
Allocation * a = s_AllocationHashTable[ hashIndex ];
Allocation * prev = nullptr;
while ( a )
{
if ( a->m_Ptr == ptr )
{
if ( prev == nullptr )
{
s_AllocationHashTable[ hashIndex ] = a->m_Next;
}
else
{
prev->m_Next = a->m_Next;
}
++g_MemTrackerDisabledOnThisThread;
s_Allocations->Free( a );
--s_AllocationCount;
--g_MemTrackerDisabledOnThisThread;
break;
}
prev = a;
a = a->m_Next;
}
}
// DumpAllocations
//------------------------------------------------------------------------------
/*static*/ void MemTracker::DumpAllocations()
{
if ( s_Enabled == false )
{
OUTPUT( "DumpAllocations failed - MemTracker not enabled\n" );
return;
}
if ( s_Initialized == false )
{
OUTPUT( "DumpAllocations : No allocations\n" );
return;
}
MutexHolder mh( GetMutex() );
if ( s_AllocationCount == 0 )
{
OUTPUT( "DumpAllocations : No allocations\n" );
return;
}
uint64_t total = 0;
uint64_t numAllocs = 0;
// for each leak, we'll print a view of the memory
unsigned char displayChar[256];
memset( displayChar, '.', sizeof( displayChar ) );
const unsigned char * okChars = (const unsigned char *)"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`1234567890-=!@#$^&*()_+[]{};:'\",<>/?|\\";
const unsigned char * ok = okChars;
for ( ;; ) { unsigned char c = *ok; if ( c == 0 ) break; displayChar[ c ] = c; ++ok; }
char memView[ 32 ] = { 0 };
OUTPUT( "--- DumpAllocations ------------------------------------------------\n" );
for ( size_t i=0; i<ALLOCATION_HASH_SIZE; ++i )
{
Allocation * a = s_AllocationHashTable[ i ];
while ( a )
{
uint32_t id = a->m_Id;
uint64_t addr = (size_t)a->m_Ptr;
uint64_t size = a->m_Size;
// format a view of the memory contents
const char * src = (const char *)addr;
char * dst = memView;
const size_t num = Math::Min< size_t >( (size_t)size, 31 );
for ( uint32_t j=0; j<num; ++j )
{
unsigned char c = *src;
*dst = displayChar[ c ];
++src;
++dst;
}
*dst = 0;
OUTPUT( "%s(%u): Id %u : %u bytes @ 0x%016llx (Mem: %s)\n", a->m_File, a->m_Line, id, size, addr, memView );
++numAllocs;
total += size;
a = a->m_Next;
}
}
OUTPUT( "--------------------------------------------------------------------\n" );
OUTPUT( "Total: %llu bytes in %llu allocs\n", total, numAllocs );
OUTPUT( "--------------------------------------------------------------------\n" );
}
// Reset
//------------------------------------------------------------------------------
/*static*/ void MemTracker::Reset()
{
MutexHolder mh( GetMutex() );
++g_MemTrackerDisabledOnThisThread;
// free all allocation tracking
for ( size_t i=0; i<ALLOCATION_HASH_SIZE; ++i )
{
Allocation * a = s_AllocationHashTable[ i ];
while ( a )
{
s_Allocations->Free( a );
--s_AllocationCount;
a = a->m_Next;
}
s_AllocationHashTable[ i ] = nullptr;
}
ASSERT( s_AllocationCount == 0 );
s_Id = 0;
--g_MemTrackerDisabledOnThisThread;
}
// Init
//------------------------------------------------------------------------------
/*static*/ void MemTracker::Init()
{
CTASSERT( sizeof( MemTracker::s_Mutex ) == sizeof( Mutex ) );
ASSERT( g_MemTrackerDisabledOnThisThread );
// first caller does init
static uint32_t threadSafeGuard( 0 );
if ( AtomicIncU32( &threadSafeGuard ) != 1 )
{
// subsequent callers wait for init
while ( !s_Initialized ) {}
return;
}
// construct primary mutex in-place
INPLACE_NEW ( &GetMutex() ) Mutex;
// init hash table
s_AllocationHashTable = new Allocation*[ ALLOCATION_HASH_SIZE ];
memset( s_AllocationHashTable, 0, ALLOCATION_HASH_SIZE * sizeof( Allocation * ) );
// init pool for allocation structures
s_Allocations = new MemPoolBlock( sizeof( Allocation ), __alignof( Allocation ) );
MemoryBarrier();
s_Initialized = true;
}
//------------------------------------------------------------------------------
#endif // MEMTRACKER_ENABLED
//------------------------------------------------------------------------------
| [
"[email protected]"
] | |
4bf7445e62392551dbda48960e850b648fa4164c | 0863a85756b0385a36605f6da18550d74df417ea | /insertDeletBinarySearchTree/main.cpp | 06dc38bff06ee3a609f252482761aa820f13f3d0 | [] | no_license | tianjingyu1/cProject | f759fb538538d689b14e38995c00afd5b70d1283 | b5c01517b8f9f654f175161de1c0967cbe43f557 | refs/heads/master | 2021-02-27T15:39:22.998819 | 2020-05-29T00:13:41 | 2020-05-29T00:13:41 | 245,616,533 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,967 | cpp | #include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
BinTree Insert( BinTree BST, ElementType X )
{
if( !BST ){ /* 若原树为空,生成并返回一个结点的二叉搜索树 */
BST = (BinTree)malloc(sizeof(struct TNode));
BST->Data = X;
BST->Left = BST->Right = NULL;
}
else { /* 开始找要插入元素的位置 */
if( X < BST->Data )
BST->Left = Insert( BST->Left, X ); /*递归插入左子树*/
else if( X > BST->Data )
BST->Right = Insert( BST->Right, X ); /*递归插入右子树*/
/* else X已经存在,什么都不做 */
}
return BST;
}
BinTree Delete( BinTree BST, ElementType X )
{
Position Tmp;
if( !BST )
printf("要删除的元素未找到");
else {
if( X < BST->Data )
BST->Left = Delete( BST->Left, X ); /* 从左子树递归删除 */
else if( X > BST->Data )
BST->Right = Delete( BST->Right, X ); /* 从右子树递归删除 */
else { /* BST就是要删除的结点 */
/* 如果被删除结点有左右两个子结点 */
if( BST->Left && BST->Right ) {
/* 从右子树中找最小的元素填充删除结点 */
Tmp = FindMin( BST->Right );
BST->Data = Tmp->Data;
/* 从右子树中删除最小元素 */
BST->Right = Delete( BST->Right, BST->Data );
}
else { /* 被删除结点有一个或无子结点 */
Tmp = BST;
if( !BST->Left ) /* 只有右孩子或无子结点 */
BST = BST->Right;
else /* 只有左孩子 */
BST = BST->Left;
free( Tmp );
}
}
}
return BST;
}
int main(int argc, char** argv) {
return 0;
}
| [
"[email protected]"
] | |
fb140c6343d8cb845bec30e15d68b2741357c692 | 5668d876245e982c842409466b39e6660e5fc740 | /servo_brazo_potenciometros_guardaposicion.ino | 3ef4e592616b58aabc9c2a86ef50a4ec55730403 | [] | no_license | RiquiMora/Brazo-Robotico-4DOF | 5dea34ff7115e9e5e126d5e292b84d92cfcb2d4b | a472bd7ea25e75f91f6079aa184c3a1e47ec18b2 | refs/heads/master | 2020-03-19T02:04:27.984336 | 2018-05-31T15:05:30 | 2018-05-31T15:05:30 | 135,596,748 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,326 | ino | #include <Servo.h>
Servo hombro, brazo, base, garra;
int potpi = 0;
int pot = 1;
int potp = 2;
int po = 3;
int val; // variable to read the value from the analog pin
int val1;
int val2;
int val3;
const int max_root = 180;
char valores;
String codigo = "";
boolean mode = true;
void setup() {
Serial.begin(9600);
base.attach(11);
brazo.attach(10);
hombro.attach(9);
garra.attach(8);
}
void loop() {
val = analogRead(potpi); // reads the value of the potentiometer (value between 0 and 1023)
val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
hombro.write(val); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
val1 = analogRead(pot); // reads the value of the potentiometer (value between 0 and 1023)
val1 = map(val1, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
brazo.write(val1); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
val2 = analogRead(potp); // reads the value of the potentiometer (value between 0 and 1023)
val2 = map(val2, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
base.write(val2); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
val3 = analogRead(po); // reads the value of the potentiometer (value between 0 and 1023)
val3 = map(val3, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
garra.write(val3); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there
String metodo="",init = ""; boolean tipo = false;
int posicion = 0;
base.write(60);
brazo.write(60);
hombro.write(60);
garra.write(60);
if(Serial.available() > 0)
{
codigo = "";
while(Serial.available() > 0)
{
valores = Decimal_to_ASCII(Serial.read());
Serial.print(valores);
codigo = codigo + valores;
}
delay(2000);
}
Serial.println(codigo);
delay(2000);
for( int i=0; i < codigo.length(); i++)
{
if(tipo == false)
{
if(codigo.charAt(i) == '(')
{
tipo = true;
continue;
}
metodo = metodo + codigo.charAt(i);
} else
{
init = init + codigo.charAt(i);
if(codigo.charAt(i) == ')')
{
continue;
}else if(codigo.charAt(i) == ';'){
delay(2000);
posicion = init.toInt();
if(metodo == "brazo")
{
posicion < 180 ? brazo.write(posicion) : brazo.write(180);
Serial.println("brazo");
delay(2000);
}else if(metodo == "base")
{
posicion < max_root ? base.write(posicion) : base.write(180);
Serial.println("base");
delay(2000);
}else if(metodo == "hombro")
{
posicion < max_root ? hombro.write(posicion) : hombro.write(180);
Serial.println("hombro");
delay(2000);
}else if(metodo == "garra")
{
posicion < max_root ? garra.write(posicion) : garra.write(180);
Serial.println("garra");
delay(2000);
}
metodo = "";
tipo = false;
init = "";
}
}
}
}
char Decimal_to_ASCII(int entrada){
char salida=' ';
switch(entrada){
case 32:
salida=' ';
break;
case 33:
salida='!';
break;
case 34:
salida='"';
break;
case 35:
salida='#';
break;
case 36:
salida='$';
break;
case 37:
salida='%';
break;
case 38:
salida='&';
break;
case 39:
salida=' ';
break;
case 40:
salida='(';
break;
case 41:
salida=')';
break;
case 42:
salida='*';
break;
case 43:
salida='+';
break;
case 44:
salida=',';
break;
case 45:
salida='-';
break;
case 46:
salida='.';
break;
case 47:
salida='/';
break;
case 48:
salida='0';
break;
case 49:
salida='1';
break;
case 50:
salida='2';
break;
case 51:
salida='3';
break;
case 52:
salida='4';
break;
case 53:
salida='5';
break;
case 54:
salida='6';
break;
case 55:
salida='7';
break;
case 56:
salida='8';
break;
case 57:
salida='9';
break;
case 58:
salida=':';
break;
case 59:
salida=';';
break;
case 60:
salida='<';
break;
case 61:
salida='=';
break;
case 62:
salida='>';
break;
case 63:
salida='?';
break;
case 64:
salida='@';
break;
case 65:
salida='A';
break;
case 66:
salida='B';
break;
case 67:
salida='C';
break;
case 68:
salida='D';
break;
case 69:
salida='E';
break;
case 70:
salida='F';
break;
case 71:
salida='G';
break;
case 72:
salida='H';
break;
case 73:
salida='I';
break;
case 74:
salida='J';
break;
case 75:
salida='K';
break;
case 76:
salida='L';
break;
case 77:
salida='M';
break;
case 78:
salida='N';
break;
case 79:
salida='O';
break;
case 80:
salida='P';
break;
case 81:
salida='Q';
break;
case 82:
salida='R';
break;
case 83:
salida='S';
break;
case 84:
salida='T';
break;
case 85:
salida='U';
break;
case 86:
salida='V';
break;
case 87:
salida='W';
break;
case 88:
salida='X';
break;
case 89:
salida='Y';
break;
case 90:
salida='Z';
break;
case 91:
salida='[';
break;
case 92:
salida=' ';
break;
case 93:
salida=']';
break;
case 94:
salida='^';
break;
case 95:
salida='_';
break;
case 96:
salida='`';
break;
case 97:
salida='a';
break;
case 98:
salida='b';
break;
case 99:
salida='c';
break;
case 100:
salida='d';
break;
case 101:
salida='e';
break;
case 102:
salida='f';
break;
case 103:
salida='g';
break;
case 104:
salida='h';
break;
case 105:
salida='i';
break;
case 106:
salida='j';
break;
case 107:
salida='k';
break;
case 108:
salida='l';
break;
case 109:
salida='m';
break;
case 110:
salida='n';
break;
case 111:
salida='o';
break;
case 112:
salida='p';
break;
case 113:
salida='q';
break;
case 114:
salida='r';
break;
case 115:
salida='s';
break;
case 116:
salida='t';
break;
case 117:
salida='u';
break;
case 118:
salida='v';
break;
case 119:
salida='w';
break;
case 120:
salida='x';
break;
case 121:
salida='y';
break;
case 122:
salida='z';
break;
case 123:
salida='{';
break;
case 124:
salida='|';
break;
case 125:
salida='}';
break;
case 126:
salida='~';
break;
}
return salida;
}
| [
"[email protected]"
] | |
6ac48384b37ee2583609e4478de1a2f61b0ef09a | a7ec77cc491d24998e00a68a203c54b9e121ef79 | /SDK/include/SoT_Interaction_enums.hpp | b48b3df2a125a4b79427c6855e7e76f7316ab0bd | [] | no_license | EO-Zanzo/zSoT-DLL | a213547ca63a884a009991b9a5c49f7c08ecffcb | 3b241befbb47062cda3cebc3ac0cf12e740ddfd7 | refs/heads/master | 2020-12-26T21:21:14.909021 | 2020-02-01T17:39:43 | 2020-02-01T17:39:43 | 237,647,839 | 4 | 1 | null | 2020-02-01T17:05:08 | 2020-02-01T17:05:08 | null | UTF-8 | C++ | false | false | 866 | hpp | #pragma once
// Sea of Thieves (2.0) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Enums
//---------------------------------------------------------------------------
// Enum Interaction.EInteractionBlockReason
enum class EInteractionBlockReason : uint8_t
{
EInteractionBlockReason__None = 0,
EInteractionBlockReason__Radial = 1,
EInteractionBlockReason__Other = 2,
EInteractionBlockReason__EInteractionBlockReason_MAX = 3
};
// Enum Interaction.EInteractionObject
enum class EInteractionObject : uint8_t
{
EInteractionObject__None = 0,
EInteractionObject__Shop = 1,
EInteractionObject__Chest = 2,
EInteractionObject__Barrel = 3,
EInteractionObject__EInteractionObject_MAX = 4
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
a8d17ef93bf42f1113f7e8f7b8af41d62d7166d6 | 2b1a79a1fd6ebe6ebeb3b58d6b8144bf8ccd8c0d | /Games/Rong/Export/cpp/windows/obj/src/StringTools.cpp | 7cd4329bc5960408e432ca980ec5fefd8315e61a | [] | no_license | spoozbe/Portfolio | 18ba48bad5981e21901d2ef2b5595584b2451c19 | 4818a58eb50cbec949854456af6bbd49d6f37716 | refs/heads/master | 2021-01-02T08:45:38.660402 | 2014-11-02T04:49:25 | 2014-11-02T04:49:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,029 | cpp | #include <hxcpp.h>
#ifndef INCLUDED_StringTools
#include <StringTools.h>
#endif
Void StringTools_obj::__construct()
{
return null();
}
StringTools_obj::~StringTools_obj() { }
Dynamic StringTools_obj::__CreateEmpty() { return new StringTools_obj; }
hx::ObjectPtr< StringTools_obj > StringTools_obj::__new()
{ hx::ObjectPtr< StringTools_obj > result = new StringTools_obj();
result->__construct();
return result;}
Dynamic StringTools_obj::__Create(hx::DynamicArray inArgs)
{ hx::ObjectPtr< StringTools_obj > result = new StringTools_obj();
result->__construct();
return result;}
::String StringTools_obj::urlEncode( ::String s){
HX_STACK_PUSH("StringTools::urlEncode","C:\\Motion-Twin\\haxe/std/StringTools.hx",41);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(41)
return s.__URLEncode();
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,urlEncode,return )
::String StringTools_obj::urlDecode( ::String s){
HX_STACK_PUSH("StringTools::urlDecode","C:\\Motion-Twin\\haxe/std/StringTools.hx",68);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(68)
return s.__URLDecode();
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,urlDecode,return )
::String StringTools_obj::htmlEscape( ::String s){
HX_STACK_PUSH("StringTools::htmlEscape","C:\\Motion-Twin\\haxe/std/StringTools.hx",95);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(95)
return s.split(HX_CSTRING("&"))->join(HX_CSTRING("&")).split(HX_CSTRING("<"))->join(HX_CSTRING("<")).split(HX_CSTRING(">"))->join(HX_CSTRING(">"));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,htmlEscape,return )
::String StringTools_obj::htmlUnescape( ::String s){
HX_STACK_PUSH("StringTools::htmlUnescape","C:\\Motion-Twin\\haxe/std/StringTools.hx",102);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(102)
return s.split(HX_CSTRING(">"))->join(HX_CSTRING(">")).split(HX_CSTRING("<"))->join(HX_CSTRING("<")).split(HX_CSTRING("&"))->join(HX_CSTRING("&"));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,htmlUnescape,return )
bool StringTools_obj::startsWith( ::String s,::String start){
HX_STACK_PUSH("StringTools::startsWith","C:\\Motion-Twin\\haxe/std/StringTools.hx",113);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(start,"start");
HX_STACK_LINE(113)
return (bool((s.length >= start.length)) && bool((s.substr((int)0,start.length) == start)));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,startsWith,return )
bool StringTools_obj::endsWith( ::String s,::String end){
HX_STACK_PUSH("StringTools::endsWith","C:\\Motion-Twin\\haxe/std/StringTools.hx",126);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(end,"end");
HX_STACK_LINE(132)
int elen = end.length; HX_STACK_VAR(elen,"elen");
HX_STACK_LINE(133)
int slen = s.length; HX_STACK_VAR(slen,"slen");
HX_STACK_LINE(134)
return (bool((slen >= elen)) && bool((s.substr((slen - elen),elen) == end)));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,endsWith,return )
bool StringTools_obj::isSpace( ::String s,int pos){
HX_STACK_PUSH("StringTools::isSpace","C:\\Motion-Twin\\haxe/std/StringTools.hx",141);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(pos,"pos");
HX_STACK_LINE(142)
Dynamic c = s.charCodeAt(pos); HX_STACK_VAR(c,"c");
HX_STACK_LINE(143)
return (bool((bool((c >= (int)9)) && bool((c <= (int)13)))) || bool((c == (int)32)));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,isSpace,return )
::String StringTools_obj::ltrim( ::String s){
HX_STACK_PUSH("StringTools::ltrim","C:\\Motion-Twin\\haxe/std/StringTools.hx",149);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(155)
int l = s.length; HX_STACK_VAR(l,"l");
HX_STACK_LINE(156)
int r = (int)0; HX_STACK_VAR(r,"r");
HX_STACK_LINE(157)
while(((bool((r < l)) && bool(::StringTools_obj::isSpace(s,r))))){
HX_STACK_LINE(157)
(r)++;
}
HX_STACK_LINE(160)
if (((r > (int)0))){
HX_STACK_LINE(161)
return s.substr(r,(l - r));
}
else{
HX_STACK_LINE(163)
return s;
}
HX_STACK_LINE(160)
return null();
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,ltrim,return )
::String StringTools_obj::rtrim( ::String s){
HX_STACK_PUSH("StringTools::rtrim","C:\\Motion-Twin\\haxe/std/StringTools.hx",170);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(176)
int l = s.length; HX_STACK_VAR(l,"l");
HX_STACK_LINE(177)
int r = (int)0; HX_STACK_VAR(r,"r");
HX_STACK_LINE(178)
while(((bool((r < l)) && bool(::StringTools_obj::isSpace(s,((l - r) - (int)1)))))){
HX_STACK_LINE(178)
(r)++;
}
HX_STACK_LINE(181)
if (((r > (int)0))){
HX_STACK_LINE(181)
return s.substr((int)0,(l - r));
}
else{
HX_STACK_LINE(183)
return s;
}
HX_STACK_LINE(181)
return null();
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,rtrim,return )
::String StringTools_obj::trim( ::String s){
HX_STACK_PUSH("StringTools::trim","C:\\Motion-Twin\\haxe/std/StringTools.hx",192);
HX_STACK_ARG(s,"s");
HX_STACK_LINE(192)
return ::StringTools_obj::ltrim(::StringTools_obj::rtrim(s));
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,trim,return )
::String StringTools_obj::rpad( ::String s,::String c,int l){
HX_STACK_PUSH("StringTools::rpad","C:\\Motion-Twin\\haxe/std/StringTools.hx",207);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(c,"c");
HX_STACK_ARG(l,"l");
HX_STACK_LINE(211)
int sl = s.length; HX_STACK_VAR(sl,"sl");
HX_STACK_LINE(212)
int cl = c.length; HX_STACK_VAR(cl,"cl");
HX_STACK_LINE(213)
while(((sl < l))){
HX_STACK_LINE(213)
if ((((l - sl) < cl))){
HX_STACK_LINE(215)
hx::AddEq(s,c.substr((int)0,(l - sl)));
HX_STACK_LINE(216)
sl = l;
}
else{
HX_STACK_LINE(218)
hx::AddEq(s,c);
HX_STACK_LINE(219)
hx::AddEq(sl,cl);
}
}
HX_STACK_LINE(222)
return s;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(StringTools_obj,rpad,return )
::String StringTools_obj::lpad( ::String s,::String c,int l){
HX_STACK_PUSH("StringTools::lpad","C:\\Motion-Twin\\haxe/std/StringTools.hx",229);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(c,"c");
HX_STACK_ARG(l,"l");
HX_STACK_LINE(233)
::String ns = HX_CSTRING(""); HX_STACK_VAR(ns,"ns");
HX_STACK_LINE(234)
int sl = s.length; HX_STACK_VAR(sl,"sl");
HX_STACK_LINE(235)
if (((sl >= l))){
HX_STACK_LINE(235)
return s;
}
HX_STACK_LINE(237)
int cl = c.length; HX_STACK_VAR(cl,"cl");
HX_STACK_LINE(238)
while(((sl < l))){
HX_STACK_LINE(238)
if ((((l - sl) < cl))){
HX_STACK_LINE(240)
hx::AddEq(ns,c.substr((int)0,(l - sl)));
HX_STACK_LINE(241)
sl = l;
}
else{
HX_STACK_LINE(243)
hx::AddEq(ns,c);
HX_STACK_LINE(244)
hx::AddEq(sl,cl);
}
}
HX_STACK_LINE(247)
return (ns + s);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(StringTools_obj,lpad,return )
::String StringTools_obj::replace( ::String s,::String sub,::String by){
HX_STACK_PUSH("StringTools::replace","C:\\Motion-Twin\\haxe/std/StringTools.hx",254);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(sub,"sub");
HX_STACK_ARG(by,"by");
HX_STACK_LINE(254)
return s.split(sub)->join(by);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC3(StringTools_obj,replace,return )
::String StringTools_obj::hex( int n,Dynamic digits){
HX_STACK_PUSH("StringTools::hex","C:\\Motion-Twin\\haxe/std/StringTools.hx",269);
HX_STACK_ARG(n,"n");
HX_STACK_ARG(digits,"digits");
HX_STACK_LINE(275)
::String s = HX_CSTRING(""); HX_STACK_VAR(s,"s");
HX_STACK_LINE(276)
::String hexChars = HX_CSTRING("0123456789ABCDEF"); HX_STACK_VAR(hexChars,"hexChars");
HX_STACK_LINE(277)
do{
HX_STACK_LINE(278)
s = (hexChars.charAt((int(n) & int((int)15))) + s);
HX_STACK_LINE(279)
hx::UShrEq(n,(int)4);
}
while(((n > (int)0)));
HX_STACK_LINE(282)
if (((digits != null()))){
HX_STACK_LINE(283)
while(((s.length < digits))){
HX_STACK_LINE(284)
s = (HX_CSTRING("0") + s);
}
}
HX_STACK_LINE(285)
return s;
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,hex,return )
int StringTools_obj::fastCodeAt( ::String s,int index){
HX_STACK_PUSH("StringTools::fastCodeAt","C:\\Motion-Twin\\haxe/std/StringTools.hx",292);
HX_STACK_ARG(s,"s");
HX_STACK_ARG(index,"index");
HX_STACK_LINE(292)
return s.cca(index);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC2(StringTools_obj,fastCodeAt,return )
bool StringTools_obj::isEOF( int c){
HX_STACK_PUSH("StringTools::isEOF","C:\\Motion-Twin\\haxe/std/StringTools.hx",322);
HX_STACK_ARG(c,"c");
HX_STACK_LINE(322)
return (c == (int)0);
}
STATIC_HX_DEFINE_DYNAMIC_FUNC1(StringTools_obj,isEOF,return )
StringTools_obj::StringTools_obj()
{
}
void StringTools_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(StringTools);
HX_MARK_END_CLASS();
}
void StringTools_obj::__Visit(HX_VISIT_PARAMS)
{
}
Dynamic StringTools_obj::__Field(const ::String &inName,bool inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"hex") ) { return hex_dyn(); }
break;
case 4:
if (HX_FIELD_EQ(inName,"trim") ) { return trim_dyn(); }
if (HX_FIELD_EQ(inName,"rpad") ) { return rpad_dyn(); }
if (HX_FIELD_EQ(inName,"lpad") ) { return lpad_dyn(); }
break;
case 5:
if (HX_FIELD_EQ(inName,"ltrim") ) { return ltrim_dyn(); }
if (HX_FIELD_EQ(inName,"rtrim") ) { return rtrim_dyn(); }
if (HX_FIELD_EQ(inName,"isEOF") ) { return isEOF_dyn(); }
break;
case 7:
if (HX_FIELD_EQ(inName,"isSpace") ) { return isSpace_dyn(); }
if (HX_FIELD_EQ(inName,"replace") ) { return replace_dyn(); }
break;
case 8:
if (HX_FIELD_EQ(inName,"endsWith") ) { return endsWith_dyn(); }
break;
case 9:
if (HX_FIELD_EQ(inName,"urlEncode") ) { return urlEncode_dyn(); }
if (HX_FIELD_EQ(inName,"urlDecode") ) { return urlDecode_dyn(); }
break;
case 10:
if (HX_FIELD_EQ(inName,"htmlEscape") ) { return htmlEscape_dyn(); }
if (HX_FIELD_EQ(inName,"startsWith") ) { return startsWith_dyn(); }
if (HX_FIELD_EQ(inName,"fastCodeAt") ) { return fastCodeAt_dyn(); }
break;
case 12:
if (HX_FIELD_EQ(inName,"htmlUnescape") ) { return htmlUnescape_dyn(); }
}
return super::__Field(inName,inCallProp);
}
Dynamic StringTools_obj::__SetField(const ::String &inName,const Dynamic &inValue,bool inCallProp)
{
return super::__SetField(inName,inValue,inCallProp);
}
void StringTools_obj::__GetFields(Array< ::String> &outFields)
{
super::__GetFields(outFields);
};
static ::String sStaticFields[] = {
HX_CSTRING("urlEncode"),
HX_CSTRING("urlDecode"),
HX_CSTRING("htmlEscape"),
HX_CSTRING("htmlUnescape"),
HX_CSTRING("startsWith"),
HX_CSTRING("endsWith"),
HX_CSTRING("isSpace"),
HX_CSTRING("ltrim"),
HX_CSTRING("rtrim"),
HX_CSTRING("trim"),
HX_CSTRING("rpad"),
HX_CSTRING("lpad"),
HX_CSTRING("replace"),
HX_CSTRING("hex"),
HX_CSTRING("fastCodeAt"),
HX_CSTRING("isEOF"),
String(null()) };
static ::String sMemberFields[] = {
String(null()) };
static void sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(StringTools_obj::__mClass,"__mClass");
};
static void sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(StringTools_obj::__mClass,"__mClass");
};
Class StringTools_obj::__mClass;
void StringTools_obj::__register()
{
Static(__mClass) = hx::RegisterClass(HX_CSTRING("StringTools"), hx::TCanCast< StringTools_obj> ,sStaticFields,sMemberFields,
&__CreateEmpty, &__Create,
&super::__SGetClass(), 0, sMarkStatics, sVisitStatics);
}
void StringTools_obj::__boot()
{
}
| [
"[email protected]"
] | |
f46de1bd281fa3736931ddc5c85eb5849f2b7ee0 | 723b67f6a8b202dc5bb009427f60ffd9f185dba8 | /devel/include/ros_arduino_msgs/ServoWriteResponse.h | ef1a29d38d970bae98cdea4932c90d41f162ce62 | [] | no_license | Dhawgupta/catkin_ws | 15edced50d3d69bf78851315658646cd671eb911 | edab645f1a94c83925836b36d38ecf2ad8f42abc | refs/heads/master | 2021-01-19T10:56:09.954495 | 2017-04-11T09:52:20 | 2017-04-11T09:52:20 | 87,917,514 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,028 | h | // Generated by gencpp from file ros_arduino_msgs/ServoWriteResponse.msg
// DO NOT EDIT!
#ifndef ROS_ARDUINO_MSGS_MESSAGE_SERVOWRITERESPONSE_H
#define ROS_ARDUINO_MSGS_MESSAGE_SERVOWRITERESPONSE_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace ros_arduino_msgs
{
template <class ContainerAllocator>
struct ServoWriteResponse_
{
typedef ServoWriteResponse_<ContainerAllocator> Type;
ServoWriteResponse_()
{
}
ServoWriteResponse_(const ContainerAllocator& _alloc)
{
(void)_alloc;
}
typedef boost::shared_ptr< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> const> ConstPtr;
}; // struct ServoWriteResponse_
typedef ::ros_arduino_msgs::ServoWriteResponse_<std::allocator<void> > ServoWriteResponse;
typedef boost::shared_ptr< ::ros_arduino_msgs::ServoWriteResponse > ServoWriteResponsePtr;
typedef boost::shared_ptr< ::ros_arduino_msgs::ServoWriteResponse const> ServoWriteResponseConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace ros_arduino_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'ros_arduino_msgs': ['/home/dawg/catkin_ws/src/ros_arduino_bridge/ros_arduino_msgs/msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
{
static const char* value()
{
return "d41d8cd98f00b204e9800998ecf8427e";
}
static const char* value(const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xd41d8cd98f00b204ULL;
static const uint64_t static_value2 = 0xe9800998ecf8427eULL;
};
template<class ContainerAllocator>
struct DataType< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
{
static const char* value()
{
return "ros_arduino_msgs/ServoWriteResponse";
}
static const char* value(const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
{
static const char* value()
{
return "\n\
";
}
static const char* value(const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream&, T)
{}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct ServoWriteResponse_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream&, const std::string&, const ::ros_arduino_msgs::ServoWriteResponse_<ContainerAllocator>&)
{}
};
} // namespace message_operations
} // namespace ros
#endif // ROS_ARDUINO_MSGS_MESSAGE_SERVOWRITERESPONSE_H
| [
"[email protected]"
] | |
4b1a2ff69ea1c73dca9f8d22448ade38d373b8e1 | 84df2566bbce86ad087ec0465eaed091737b8e69 | /66. Trojki liczb/66.3/main.cpp | 925fdf6fbfb5a04c38f48df0aa157c12d0745e0b | [] | no_license | matura-inf/cpp | 5d6ea1bd12395042551f9e55fc3a88375a0aa911 | f1a9cb6930b536acb5fb1632773abd411daa0c3d | refs/heads/main | 2023-03-01T04:03:05.107390 | 2021-02-10T21:40:32 | 2021-02-10T21:40:32 | 309,538,910 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,325 | cpp | #include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
ifstream in("../trojki.txt");
ofstream out("../wyniki_trojki.txt", ofstream::app);
long long pierwsza, druga, trzecia, nr_linii = 0;
long long pierwsza_p = 1, druga_p = 2, trzecia_p = 3;
long long pierwsza_n = 1, druga_n = 2, trzecia_n = 3;
out << endl
<< "Zad3" << endl
<< endl;
while (in >> pierwsza >> druga >> trzecia)
{
if (nr_linii % 2 == 0)
{
pierwsza_p = pierwsza;
druga_p = druga;
trzecia_p = trzecia;
}
if (nr_linii % 2 == 1)
{
pierwsza_n = pierwsza;
druga_n = druga;
trzecia_n = trzecia;
}
if (((pow(pierwsza_p, 2) + pow(druga_p, 2) == pow(trzecia_p, 2)) || (pow(pierwsza_p, 2) + pow(trzecia_p, 2) == pow(druga_p, 2)) || (pow(trzecia_p, 2) + pow(druga_p, 2) == pow(pierwsza_p, 2))) && ((pow(pierwsza_n, 2) + pow(druga_n, 2) == pow(trzecia_n, 2)) || (pow(pierwsza_n, 2) + pow(trzecia_n, 2) == pow(druga_n, 2)) || (pow(trzecia_n, 2) + pow(druga_n, 2) == pow(pierwsza_n, 2))))
{
out << pierwsza_n << " " << druga_n << " " << trzecia_n << endl;
out << pierwsza_p << " " << druga_p << " " << trzecia_p << endl
<< endl;
}
nr_linii++;
}
in.close();
out.close();
system("pause");
return 0;
} | [
"[email protected]"
] | |
6dab7827ababfb8c432c08e1e9a9dc6eff7e91be | 866948421e7f22480da2bdf699c54220734e3a4b | /C/permutation.cpp | 1de35f518bc8136f4d30d264ac7ce768cd0b7ed8 | [] | no_license | QinShelly/workspace | f0f5aba1280a1a112cf7df316b7857454338fb2d | 4734ec9e561c64bcbdb11e321163048c1c140f58 | refs/heads/master | 2020-07-06T21:49:25.249134 | 2020-02-08T07:34:34 | 2020-02-08T07:34:34 | 67,876,658 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 530 | cpp | #include <iostream>
int a[10],book[10],n;
void dfs(int step){
int i;
if (step == n + 1) {
for (i=1; i<=n; i++) {
printf(" %d",a[i]);
}
printf("\n");
}
for (i = 1; i <= n; i++) {
if (book[i] == 0 ) {
a[step] = i;
book[i] = 1;
dfs(step + 1);
book[i] = 0;
}
}
return;
}
int main(int argc, const char * argv[]) {
scanf("%d",&n);
dfs(1);
getchar();
return 0;
}
| [
"[email protected]"
] | |
510031590fb18ee868c9ac88fb8da30c2ec3e09a | b056684eb040d7f14f3d1bd5a5ae26d33bd18481 | /src/file_trans/include/file_trans.grpc.pb.h | 87036594527e453e37245aeeeaa4e6ddcda5ffe1 | [] | no_license | amyxu1/webpack-mdns | 5f1fbba65452d7475e5cc7a2548805ddf1c74859 | 516a44825d200ca495afe18f59411ae2cecec28e | refs/heads/master | 2023-06-02T21:17:44.070368 | 2021-06-15T16:52:22 | 2021-06-15T16:52:22 | 294,596,101 | 1 | 1 | null | 2020-11-06T07:05:55 | 2020-09-11T04:43:30 | Makefile | UTF-8 | C++ | false | true | 14,845 | h | // Generated by the gRPC C++ plugin.
// If you make any local change, they will be lost.
// source: file_trans.proto
#ifndef GRPC_file_5ftrans_2eproto__INCLUDED
#define GRPC_file_5ftrans_2eproto__INCLUDED
#include "file_trans.pb.h"
#include <functional>
#include <grpc/impl/codegen/port_platform.h>
#include <grpcpp/impl/codegen/async_generic_service.h>
#include <grpcpp/impl/codegen/async_stream.h>
#include <grpcpp/impl/codegen/async_unary_call.h>
#include <grpcpp/impl/codegen/client_callback.h>
#include <grpcpp/impl/codegen/client_context.h>
#include <grpcpp/impl/codegen/completion_queue.h>
#include <grpcpp/impl/codegen/message_allocator.h>
#include <grpcpp/impl/codegen/method_handler.h>
#include <grpcpp/impl/codegen/proto_utils.h>
#include <grpcpp/impl/codegen/rpc_method.h>
#include <grpcpp/impl/codegen/server_callback.h>
#include <grpcpp/impl/codegen/server_callback_handlers.h>
#include <grpcpp/impl/codegen/server_context.h>
#include <grpcpp/impl/codegen/service_type.h>
#include <grpcpp/impl/codegen/status.h>
#include <grpcpp/impl/codegen/stub_options.h>
#include <grpcpp/impl/codegen/sync_stream.h>
namespace file_trans {
class WebpackServer final {
public:
static constexpr char const* service_full_name() {
return "file_trans.WebpackServer";
}
class StubInterface {
public:
virtual ~StubInterface() {}
std::unique_ptr< ::grpc::ClientReaderInterface< ::file_trans::FileChunk>> SendFile(::grpc::ClientContext* context, const ::file_trans::Request& request) {
return std::unique_ptr< ::grpc::ClientReaderInterface< ::file_trans::FileChunk>>(SendFileRaw(context, request));
}
std::unique_ptr< ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>> AsyncSendFile(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq, void* tag) {
return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>>(AsyncSendFileRaw(context, request, cq, tag));
}
std::unique_ptr< ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>> PrepareAsyncSendFile(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>>(PrepareAsyncSendFileRaw(context, request, cq));
}
class experimental_async_interface {
public:
virtual ~experimental_async_interface() {}
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
virtual void SendFile(::grpc::ClientContext* context, ::file_trans::Request* request, ::grpc::ClientReadReactor< ::file_trans::FileChunk>* reactor) = 0;
#else
virtual void SendFile(::grpc::ClientContext* context, ::file_trans::Request* request, ::grpc::experimental::ClientReadReactor< ::file_trans::FileChunk>* reactor) = 0;
#endif
};
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
typedef class experimental_async_interface async_interface;
#endif
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
async_interface* async() { return experimental_async(); }
#endif
virtual class experimental_async_interface* experimental_async() { return nullptr; }
private:
virtual ::grpc::ClientReaderInterface< ::file_trans::FileChunk>* SendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request) = 0;
virtual ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>* AsyncSendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq, void* tag) = 0;
virtual ::grpc::ClientAsyncReaderInterface< ::file_trans::FileChunk>* PrepareAsyncSendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq) = 0;
};
class Stub final : public StubInterface {
public:
Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel);
std::unique_ptr< ::grpc::ClientReader< ::file_trans::FileChunk>> SendFile(::grpc::ClientContext* context, const ::file_trans::Request& request) {
return std::unique_ptr< ::grpc::ClientReader< ::file_trans::FileChunk>>(SendFileRaw(context, request));
}
std::unique_ptr< ::grpc::ClientAsyncReader< ::file_trans::FileChunk>> AsyncSendFile(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq, void* tag) {
return std::unique_ptr< ::grpc::ClientAsyncReader< ::file_trans::FileChunk>>(AsyncSendFileRaw(context, request, cq, tag));
}
std::unique_ptr< ::grpc::ClientAsyncReader< ::file_trans::FileChunk>> PrepareAsyncSendFile(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncReader< ::file_trans::FileChunk>>(PrepareAsyncSendFileRaw(context, request, cq));
}
class experimental_async final :
public StubInterface::experimental_async_interface {
public:
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
void SendFile(::grpc::ClientContext* context, ::file_trans::Request* request, ::grpc::ClientReadReactor< ::file_trans::FileChunk>* reactor) override;
#else
void SendFile(::grpc::ClientContext* context, ::file_trans::Request* request, ::grpc::experimental::ClientReadReactor< ::file_trans::FileChunk>* reactor) override;
#endif
private:
friend class Stub;
explicit experimental_async(Stub* stub): stub_(stub) { }
Stub* stub() { return stub_; }
Stub* stub_;
};
class experimental_async_interface* experimental_async() override { return &async_stub_; }
private:
std::shared_ptr< ::grpc::ChannelInterface> channel_;
class experimental_async async_stub_{this};
::grpc::ClientReader< ::file_trans::FileChunk>* SendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request) override;
::grpc::ClientAsyncReader< ::file_trans::FileChunk>* AsyncSendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq, void* tag) override;
::grpc::ClientAsyncReader< ::file_trans::FileChunk>* PrepareAsyncSendFileRaw(::grpc::ClientContext* context, const ::file_trans::Request& request, ::grpc::CompletionQueue* cq) override;
const ::grpc::internal::RpcMethod rpcmethod_SendFile_;
};
static std::unique_ptr<Stub> NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions());
class Service : public ::grpc::Service {
public:
Service();
virtual ~Service();
virtual ::grpc::Status SendFile(::grpc::ServerContext* context, const ::file_trans::Request* request, ::grpc::ServerWriter< ::file_trans::FileChunk>* writer);
};
template <class BaseClass>
class WithAsyncMethod_SendFile : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service* /*service*/) {}
public:
WithAsyncMethod_SendFile() {
::grpc::Service::MarkMethodAsync(0);
}
~WithAsyncMethod_SendFile() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestSendFile(::grpc::ServerContext* context, ::file_trans::Request* request, ::grpc::ServerAsyncWriter< ::file_trans::FileChunk>* writer, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncServerStreaming(0, context, request, writer, new_call_cq, notification_cq, tag);
}
};
typedef WithAsyncMethod_SendFile<Service > AsyncService;
template <class BaseClass>
class ExperimentalWithCallbackMethod_SendFile : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service* /*service*/) {}
public:
ExperimentalWithCallbackMethod_SendFile() {
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
::grpc::Service::
#else
::grpc::Service::experimental().
#endif
MarkMethodCallback(0,
new ::grpc_impl::internal::CallbackServerStreamingHandler< ::file_trans::Request, ::file_trans::FileChunk>(
[this](
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
::grpc::CallbackServerContext*
#else
::grpc::experimental::CallbackServerContext*
#endif
context, const ::file_trans::Request* request) { return this->SendFile(context, request); }));
}
~ExperimentalWithCallbackMethod_SendFile() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
virtual ::grpc::ServerWriteReactor< ::file_trans::FileChunk>* SendFile(
::grpc::CallbackServerContext* /*context*/, const ::file_trans::Request* /*request*/)
#else
virtual ::grpc::experimental::ServerWriteReactor< ::file_trans::FileChunk>* SendFile(
::grpc::experimental::CallbackServerContext* /*context*/, const ::file_trans::Request* /*request*/)
#endif
{ return nullptr; }
};
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
typedef ExperimentalWithCallbackMethod_SendFile<Service > CallbackService;
#endif
typedef ExperimentalWithCallbackMethod_SendFile<Service > ExperimentalCallbackService;
template <class BaseClass>
class WithGenericMethod_SendFile : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service* /*service*/) {}
public:
WithGenericMethod_SendFile() {
::grpc::Service::MarkMethodGeneric(0);
}
~WithGenericMethod_SendFile() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
};
template <class BaseClass>
class WithRawMethod_SendFile : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service* /*service*/) {}
public:
WithRawMethod_SendFile() {
::grpc::Service::MarkMethodRaw(0);
}
~WithRawMethod_SendFile() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestSendFile(::grpc::ServerContext* context, ::grpc::ByteBuffer* request, ::grpc::ServerAsyncWriter< ::grpc::ByteBuffer>* writer, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncServerStreaming(0, context, request, writer, new_call_cq, notification_cq, tag);
}
};
template <class BaseClass>
class ExperimentalWithRawCallbackMethod_SendFile : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service* /*service*/) {}
public:
ExperimentalWithRawCallbackMethod_SendFile() {
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
::grpc::Service::
#else
::grpc::Service::experimental().
#endif
MarkMethodRawCallback(0,
new ::grpc_impl::internal::CallbackServerStreamingHandler< ::grpc::ByteBuffer, ::grpc::ByteBuffer>(
[this](
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
::grpc::CallbackServerContext*
#else
::grpc::experimental::CallbackServerContext*
#endif
context, const::grpc::ByteBuffer* request) { return this->SendFile(context, request); }));
}
~ExperimentalWithRawCallbackMethod_SendFile() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
virtual ::grpc::ServerWriteReactor< ::grpc::ByteBuffer>* SendFile(
::grpc::CallbackServerContext* /*context*/, const ::grpc::ByteBuffer* /*request*/)
#else
virtual ::grpc::experimental::ServerWriteReactor< ::grpc::ByteBuffer>* SendFile(
::grpc::experimental::CallbackServerContext* /*context*/, const ::grpc::ByteBuffer* /*request*/)
#endif
{ return nullptr; }
};
typedef Service StreamedUnaryService;
template <class BaseClass>
class WithSplitStreamingMethod_SendFile : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service* /*service*/) {}
public:
WithSplitStreamingMethod_SendFile() {
::grpc::Service::MarkMethodStreamed(0,
new ::grpc::internal::SplitServerStreamingHandler<
::file_trans::Request, ::file_trans::FileChunk>(
[this](::grpc_impl::ServerContext* context,
::grpc_impl::ServerSplitStreamer<
::file_trans::Request, ::file_trans::FileChunk>* streamer) {
return this->StreamedSendFile(context,
streamer);
}));
}
~WithSplitStreamingMethod_SendFile() override {
BaseClassMustBeDerivedFromService(this);
}
// disable regular version of this method
::grpc::Status SendFile(::grpc::ServerContext* /*context*/, const ::file_trans::Request* /*request*/, ::grpc::ServerWriter< ::file_trans::FileChunk>* /*writer*/) override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
// replace default version of method with split streamed
virtual ::grpc::Status StreamedSendFile(::grpc::ServerContext* context, ::grpc::ServerSplitStreamer< ::file_trans::Request,::file_trans::FileChunk>* server_split_streamer) = 0;
};
typedef WithSplitStreamingMethod_SendFile<Service > SplitStreamedService;
typedef WithSplitStreamingMethod_SendFile<Service > StreamedService;
};
} // namespace file_trans
#endif // GRPC_file_5ftrans_2eproto__INCLUDED
| [
"[email protected]"
] | |
2b17e47589ce2b7bb6579f599aad8e4a664896b5 | b8487f927d9fb3fa5529ad3686535714c687dd50 | /include/hermes/VM/JIT/DenseUInt64.h | 7cb45f61cba99d132ac4e42fc17f6b4a3b55cbc0 | [
"MIT"
] | permissive | hoangtuanhedspi/hermes | 4a1399f05924f0592c36a9d4b3fd1f804f383c14 | 02dbf3c796da4d09ec096ae1d5808dcb1b6062bf | refs/heads/master | 2020-07-12T21:21:53.781167 | 2019-08-27T22:58:17 | 2019-08-27T22:59:55 | 204,908,743 | 1 | 0 | MIT | 2019-08-28T17:44:49 | 2019-08-28T10:44:49 | null | UTF-8 | C++ | false | false | 2,568 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*/
#ifndef HERMES_VM_JIT_DENSEUINT64_H
#define HERMES_VM_JIT_DENSEUINT64_H
#include "hermes/VM/HermesValue.h"
#include "llvm/ADT/DenseMapInfo.h"
namespace hermes {
namespace vm {
/// A wrapper for using uint64_t with llvm::DenseMap/Set.
class DenseUInt64 {
public:
/// Enum to differentiate between LLVM's empty/tombstone and normal values.
enum class MapKeyType {
empty,
tombstone,
valid,
};
DenseUInt64(uint64_t cval) : keyType_(MapKeyType::valid), rawValue_(cval) {}
DenseUInt64(void *addr)
: keyType_(MapKeyType::valid), rawValue_((uint64_t)addr) {}
DenseUInt64(HermesValue hv)
: keyType_(MapKeyType::valid), rawValue_(hv.getRaw()) {}
DenseUInt64(double v) : DenseUInt64(HermesValue::encodeDoubleValue(v)) {}
DenseUInt64(MapKeyType keyType) : keyType_(keyType), rawValue_(0) {
assert(keyType_ != MapKeyType::valid && "valid entries must have a value");
}
bool operator==(const DenseUInt64 &other) const {
return keyType_ == other.keyType_ && rawValue_ == other.rawValue_;
}
HermesValue valueAsHV() const {
assert(
keyType_ == MapKeyType::valid &&
"attempting to get the value of tombstone/empty entry");
return HermesValue(rawValue_);
}
void *valueAsAddr() const {
assert(
keyType_ == MapKeyType::valid &&
"attempting to get the value of tombstone/empty entry");
return (void *)rawValue_;
}
uint64_t rawValue() const {
return rawValue_;
}
private:
/// The type of value we have: empty/tombstone/normal.
MapKeyType keyType_;
/// A raw uint64_t: it could be a HermesValue or an address
uint64_t rawValue_;
};
} // namespace vm
} // namespace hermes
namespace llvm {
/// Traits to enable using UInt64Constant with llvm::DenseSet/Map.
template <>
struct DenseMapInfo<hermes::vm::DenseUInt64> {
using UInt64Constant = hermes::vm::DenseUInt64;
using MapKeyType = UInt64Constant::MapKeyType;
static inline UInt64Constant getEmptyKey() {
return MapKeyType::empty;
}
static inline UInt64Constant getTombstoneKey() {
return MapKeyType::tombstone;
}
static inline unsigned getHashValue(UInt64Constant x) {
return DenseMapInfo<uint64_t>::getHashValue(x.rawValue());
}
static inline bool isEqual(UInt64Constant a, UInt64Constant b) {
return a == b;
}
};
} // namespace llvm
#endif // HERMES_VM_JIT_DENSEUINT64_H
| [
"[email protected]"
] | |
ca132ef2e0abab744552b5d3569fea6189f708df | 9407b552787d3e872d8cdcfae5f86cd056042dfa | /dfs2.cpp | 802f9dd49b7db9f78140d4c167793fdfe7ce8a5a | [] | no_license | themechanicalcoder/Data-Structure-And-Algorithms | 7077c30cecdd42c8291c07b39089252d6cd672e3 | 3dc49f9926de10b2645e0b1c022ddbce932e208c | refs/heads/master | 2021-06-19T21:12:35.973712 | 2020-12-18T10:58:03 | 2020-12-18T10:58:03 | 134,423,943 | 0 | 1 | null | 2020-03-22T11:18:56 | 2018-05-22T14:02:38 | C++ | UTF-8 | C++ | false | false | 574 | cpp | #include<bits/stdc++.h>
using namespace std;
vector<list<int> >g;
vector<int>v;
vector<int>d;
void dfs(int u){
if(!v[u]){
v[u]=1;
cout<<u<<" ";
for(auto it=g[u].begin();it!=g[u].end();it++){
if(!v[*it]){
d[*it]=d[u]+1;
dfs(*it);
}
}
}}
int main(){
int n,m,a,b;
cin>>n>>m;
d.assign(n+1,0);
v.assign(n+1,0);
g.assign(n+1,list<int>());
for(int i=0;i<m;i++){
cin>>a>>b;
g[a].push_back(b);
g[b].push_back(a);
}
for(int i=1;i<=n;i++){
if(!v[i]){
dfs(i);
}
}
for(int i=1;i<=n;i++){
cout<<d[i];
}
return 0;
}
| [
"[email protected]"
] | |
95f7befcf665c6bd7d6cf9cdcc561666e56f2e88 | cf88c1e3d9587f2bdc8cf40397bca3f0b5f11e7c | /Arrays/Array_Rearrangement/MaxLengthBitonicSubsequence.cpp | fb2e5de210006b85afeb4f3b2d78fe1f36e1b413 | [] | no_license | shaival141/Practice_Old | f6193b4ae2365548d70c047180de429f9a9fdc1d | f02d55faf1c0a861093bf0e094747c64bdd81b34 | refs/heads/master | 2022-01-05T12:54:54.863035 | 2018-05-18T18:05:06 | 2018-05-18T18:05:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,321 | cpp | /* Dynamic Programming implementation of longest bitonic subsequence problem */
#include<stdio.h>
#include<stdlib.h>
/* lbs() returns the length of the Longest Bitonic Subsequence in
arr[] of size n. The function mainly creates two temporary arrays
lis[] and lds[] and returns the maximum lis[i] + lds[i] - 1.
lis[i] ==> Longest Increasing subsequence ending with arr[i]
lds[i] ==> Longest decreasing subsequence starting with arr[i]
*/
int lbs( int arr[], int n )
{
int i,j;
int lis[n];
int lds[n];
for(i=0;i<n;i++)
lis[i]=1;
for(i=0;i<n;i++)
lds[i]=1;
for(i=1;i<n;i++)
{
for(j=0;j<i;j++)
{
if(arr[j]<arr[i] && lis[i]<lis[j]+1)
lis[i]=lis[j]+1;
}
}
for(i=n-1;i>=0;i--)
{
for(j=n-1;j>i;j--)
{
if(arr[j]<arr[i] && lds[i]<lds[j]+1)
lds[i]=lds[j]+1;
}
}
int max=0;
for(i=0;i<n;i++)
{
if(lis[i]+lds[i]-1>max)
{
max =lis[i] + lds[i] - 1;
}
}
return max;
}
/* Driver program to test above function */
int main()
{
int arr[] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5,
13, 3, 11, 7, 15};
int n = sizeof(arr)/sizeof(arr[0]);
printf("Length of LBS is %d\n", lbs( arr, n ) );
return 0;
} | [
"[email protected]"
] | |
18296b24c1a4c774d930261e017e37a0cf8d04fa | d0601b28a3060105e82c2a839d435c4329fe82a9 | /OpenGL_Material/build-OpenGL_Material-Desktop_Qt_5_8_0_MSVC2015_64bit-Debug/debug/moc_mainwindow.cpp | 51b68186ab06892d4bfefdfe122cf57267d5fcdf | [] | no_license | guoerba/opengl | 9458b1b3827e24884bcd0a1b91d122ab6a252f8e | 103da63ada1703a3f450cfde19f41b04e922187e | refs/heads/master | 2020-07-10T15:40:49.828059 | 2019-08-25T13:52:58 | 2019-08-25T13:52:58 | 204,300,456 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,706 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'mainwindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.8.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../OpenGL_Material/mainwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mainwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.8.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MainWindow_t {
QByteArrayData data[1];
char stringdata0[11];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = {
{
QT_MOC_LITERAL(0, 0, 10) // "MainWindow"
},
"MainWindow"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MainWindow[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObject MainWindow::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data,
qt_meta_data_MainWindow, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0))
return static_cast<void*>(const_cast< MainWindow*>(this));
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | |
31c05ddd07b9d79686913c8c08a00eaf1395abbb | 6fdd703d48a01bb73bf658c8d3aac0d98f965967 | /src_cpp/elfgames/go/train/data_loader.h | 472fb3d536934f874a4ab6fd4147fce6d3ed1d0d | [
"BSD-3-Clause"
] | permissive | roughsoft/ELF | 27f762aad66f4946411f2fdae71a45fabd028730 | 751eb1cf85aac15e3c3c792a47afa1ac64ea810c | refs/heads/master | 2020-03-25T19:54:55.579846 | 2018-08-08T21:34:11 | 2018-08-08T21:34:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,596 | h | /**
* Copyright (c) 2018-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include "../common/record.h"
#include "elf/distributed/shared_reader.h"
#include "elf/distributed/shared_rw_buffer2.h"
struct Stats {
std::atomic<int> client_size;
std::atomic<int> buffer_size;
std::atomic<int> failed_count;
std::atomic<int> msg_count;
std::atomic<uint64_t> total_msg_size;
Stats()
: client_size(0),
buffer_size(0),
failed_count(0),
msg_count(0),
total_msg_size(0) {}
std::string info() const {
std::stringstream ss;
ss << "#msg: " << buffer_size << " #client: " << client_size << ", ";
ss << "Msg count: " << msg_count
<< ", avg msg size: " << (float)(total_msg_size) / msg_count
<< ", failed count: " << failed_count;
return ss.str();
}
void feed(const elf::shared::InsertInfo& insert_info) {
if (!insert_info.success) {
failed_count++;
} else {
buffer_size += insert_info.delta;
msg_count++;
total_msg_size += insert_info.msg_size;
}
}
};
class DataInterface {
public:
virtual void OnStart() {}
virtual elf::shared::InsertInfo OnReceive(
const std::string& identity,
const std::string& msg) = 0;
virtual bool OnReply(const std::string& identity, std::string* msg) = 0;
};
class DataOnlineLoader {
public:
DataOnlineLoader(const elf::shared::Options& net_options)
: logger_(elf::logging::getLogger("DataOnlineLoader-", "")) {
auto curr_timestamp = time(NULL);
const std::string database_name =
"data-" + std::to_string(curr_timestamp) + ".db";
reader_.reset(new elf::shared::Reader(database_name, net_options));
std::cout << reader_->info() << std::endl;
}
void start(DataInterface* interface) {
auto proc_func = [&, interface](
elf::shared::Reader* reader,
const std::string& identity,
const std::string& msg) -> bool {
(void)reader;
try {
auto info = interface->OnReceive(identity, msg);
stats_.feed(info);
/*
if (options_.verbose) {
std::cout << "Content from " << identity
<< ", msg_size: " << msg.size() << ", " << stats_.info()
<< std::endl;
}
*/
if (stats_.msg_count % 1000 == 0) {
std::cout << elf_utils::now() << ", last_identity: " << identity
<< ", " << stats_.info() << std::endl;
}
return info.success;
} catch (...) {
logger_->error("Data malformed! String is {}", msg);
return false;
}
};
auto replier_func = [&, interface](
elf::shared::Reader* reader,
const std::string& identity,
std::string* msg) -> bool {
(void)reader;
interface->OnReply(identity, msg);
if (logger_->should_log(spdlog::level::level_enum::debug)) {
logger_->debug(
"Replier: about to send: recipient {}; msg {}; reader {}",
identity,
*msg,
reader_->info());
}
return true;
};
reader_->startReceiving(
proc_func, replier_func, [interface]() { interface->OnStart(); });
}
~DataOnlineLoader() {}
private:
std::unique_ptr<elf::shared::Reader> reader_;
Stats stats_;
std::shared_ptr<spdlog::logger> logger_;
};
| [
"[email protected]"
] | |
583d34be535e307cea59286df8c350b922d68244 | 4dabe3dca7a679a5ba7c79cd4e0384657657dec2 | /views/console/proposedCombinationView.cpp | 71f0f78cfcc080d0bf61444707db3121b212baf5 | [] | no_license | carlosv5/MasterMind | 47285e4a3b191294bc07650873fb13e46459e42d | b45c61a264c936191e8db23f27234b91943e7638 | refs/heads/master | 2020-04-20T12:26:51.642639 | 2019-05-11T19:05:23 | 2019-05-11T19:05:23 | 150,888,071 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,741 | cpp | #include <assert.h>
#include <iostream>
#include "proposedCombinationView.hpp"
#include "../../controllers/colocateController.hpp"
#include "../../models/proposedCombination.hpp"
using namespace std;
ProposedCombinationView::ProposedCombinationView(){};
ProposedCombination ProposedCombinationView::readProposedCombination(ProposedCombination proposedCombination, int SIZE_COMBINATION){
showColorOptions();
std::cout << "--Insert your colors (XXXX)--" << std::endl;
std::string combinationString;
getline(std::cin, combinationString);
char * combination = proposedCombination.getCombination();
for (int i = 0; i < SIZE_COMBINATION; i++)
{
char *colorArray = new char[Color::numberOfColors];
Color::values(colorArray);
bool isAColor = false;
for (int j = 0; j < Color::numberOfColors; j++)
{
if (combinationString[i] == colorArray[j])
{
isAColor = true;
}
}
assert(isAColor);
char colorToInsert = combinationString[i];
combination[i] = colorToInsert;
}
return proposedCombination;
}
void ProposedCombinationView::showColorOptions()
{
std::cout << "You can use these colors:" << std::endl;
char *colorArray = new char[Color::numberOfColors];
Color::values(colorArray);
for (int i = 0; i < Color::numberOfColors; i++)
{
std::cout << colorArray[i] << " ";
}
std::cout << std::endl;
delete (colorArray);
}
void ProposedCombinationView::printResults(ProposedCombination * proposedCombinations, int turn)
{
std::cout << "Results:" << std::endl;
for (int i = 0; i < turn + 1; i++){
for (int j = 0; j < proposedCombinations[0].getSize(); j++)
{
std::cout << "|" << proposedCombinations[i].getCombination()[j] << "|"
<< " ";
}
std::cout << "Results:|" << proposedCombinations[i].getResults()[INDEX_BLACK_RESULT] << " Blacks|" << proposedCombinations[i].getResults()[INDEX_WHITE_RESULT] << "Whites|"
<< " " << std::endl;
}
}
void ProposedCombinationView::printPreviewCombinations(ProposedCombination * proposedCombinations, int turn)
{
std::cout << "The board is:" << std::endl;
for (int i = 0; i < turn; i++){
for (int j = 0; j < proposedCombinations[0].getSize(); j++)
{
std::cout << "|" << proposedCombinations[i].getCombination()[j] << "|"
<< " ";
}
std::cout << "Results:|" << proposedCombinations[i].getResults()[INDEX_BLACK_RESULT] << " Blacks|" << proposedCombinations[i].getResults()[INDEX_WHITE_RESULT] << "Whites|"
<< " " << std::endl;
}
} | [
"[email protected]"
] | |
f2fd573fb8ac9dde4919620147f9c6d1cc0536a0 | d47ad8721876e05cc92a48ea772981dd2541d27c | /FPMLib/lib/bfc/autores.h | 78620a35bff0d40b0b1f790be9dc42de2b418042 | [] | no_license | cjld/ANNO-video | 5ac5f604d43e00a3ee8b2a40050413ffd8334c3e | e8ad4f1d617f8b2393db5241a40f98c156127e52 | refs/heads/master | 2021-01-25T06:45:24.164963 | 2017-06-12T15:54:19 | 2017-06-12T15:54:19 | 93,606,386 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,150 | h |
#ifndef _FF_BFC_AUTORES_H
#define _FF_BFC_AUTORES_H
#include <utility>
#include <iterator>
#include"ffdef.h"
_FF_BEG
//To help implement reference-counter in @AutoRes.
template<typename ValT>
class ReferenceCounter
{
typedef std::pair<int,ValT> _CounterT;
private:
_CounterT *_pdata;
void _inc() const
{
++_pdata->first;
}
void _dec() const
{
--_pdata->first;
}
public:
ReferenceCounter()
:_pdata(new _CounterT(1,ValT()))
{
}
ReferenceCounter(const ValT& val)
:_pdata(new _CounterT(1,val))
{
}
ReferenceCounter(const ReferenceCounter& right)
:_pdata(right._pdata)
{
this->_inc();
}
ReferenceCounter& operator=(const ReferenceCounter& right)
{
if(_pdata!=right._pdata)
{
if(this->IsLast())
delete _pdata;
else
this->_dec();
_pdata=right._pdata;
right._inc();
}
return *this;
}
//whether current reference is the last one.
bool IsLast() const
{
return _pdata->first==1;
}
//get the value stored with the counter.
const ValT& Value() const
{
return _pdata->second;
}
ValT& Value()
{
return _pdata->second;
}
//swap two counters.
void Swap(ReferenceCounter& right)
{
std::swap(this->_pdata,right._pdata);
}
~ReferenceCounter()
{
if(this->IsLast())
delete _pdata;
else
this->_dec();
}
};
//auto-resource, which is the base to implement AutoPtr,AutoArrayPtr and AutoComPtr.
template<typename PtrT,typename RetPtrT,typename ReleaseOpT>
class AutoRes
{
enum{_F_DETACHED=0x01};
struct _ValT
{
PtrT ptr;
ReleaseOpT rel_op;
int flag;
public:
_ValT()
:ptr(PtrT()),flag(0)
{
}
_ValT(const PtrT & _ptr,const ReleaseOpT & _rel_op, int _flag=0)
:ptr(_ptr),rel_op(_rel_op),flag(_flag)
{
}
void release()
{
if((flag&_F_DETACHED)==0)
rel_op(ptr);
}
};
typedef ReferenceCounter<_ValT> _CounterT;
protected:
_CounterT _counter;
void _release()
{ //release the referenced object with the stored operator.
_counter.Value().release();
}
public:
AutoRes()
{
}
explicit AutoRes(PtrT ptr,const ReleaseOpT& op=ReleaseOpT())
:_counter(_ValT(ptr,op))
{
}
AutoRes& operator=(const AutoRes& right)
{
if(this!=&right)
{
if(_counter.IsLast())
this->_release();
_counter=right._counter;
}
return *this;
}
RetPtrT operator->() const
{
return &*_counter.Value().ptr;
}
typename std::iterator_traits<RetPtrT>::reference operator*() const
{
return *_counter.Value().ptr;
}
void Swap(AutoRes& right)
{
_counter.Swap(right._counter);
}
//detach the referenced object from @*this.
RetPtrT Detach()
{
_counter.Value().flag|=_F_DETACHED;
return &*_counter.Value().ptr;
}
operator PtrT()
{
return _counter.Value().ptr;
}
~AutoRes() throw()
{
if(_counter.IsLast())
this->_release();
}
};
//operator to delete a single object.
class DeleteObj
{
public:
template<typename _PtrT>
void operator()(_PtrT ptr)
{
delete ptr;
}
};
template<typename _ObjT>
class AutoPtr
:public AutoRes<_ObjT*,_ObjT*,DeleteObj>
{
public:
explicit AutoPtr(_ObjT* ptr=NULL)
:AutoRes<_ObjT*,_ObjT*,DeleteObj>(ptr)
{
}
};
//operator to delete array of objects.
class DeleteArray
{
public:
template<typename _PtrT>
void operator()(_PtrT ptr)
{
delete[]ptr;
}
};
template<typename _ObjT>
class AutoArrayPtr
:public AutoRes<_ObjT*,_ObjT*,DeleteArray>
{
public:
explicit AutoArrayPtr(_ObjT* ptr=NULL)
:AutoRes<_ObjT*,_ObjT*,DeleteArray>(ptr)
{
}
//_ObjT& operator[](int i) const
//{
// return this->_counter.Value().ptr[i];
//}
};
class OpCloseFile
{
public:
void operator()(const FILE *fp)
{
if(fp)
fclose((FILE*)fp);
}
};
class AutoFilePtr
:public AutoRes<FILE*,FILE*,OpCloseFile>
{
public:
explicit AutoFilePtr(FILE *fp=NULL)
:AutoRes<FILE*,FILE*,OpCloseFile>(fp)
{
}
};
//operator to release COM object.
class ReleaseObj
{
public:
template<typename _PtrT>
void operator()(_PtrT ptr)
{
if(ptr)
ptr->Release();
}
};
template<typename _ObjT>
class AutoComPtr
:public AutoRes<_ObjT*,_ObjT*,ReleaseObj>
{
public:
explicit AutoComPtr(_ObjT* ptr=NULL)
:AutoRes<_ObjT*,_ObjT*,ReleaseObj>(ptr)
{
}
};
class DestroyObj
{
public:
template<typename _PtrT>
void operator()(_PtrT ptr)
{
if(ptr)
ptr->Destroy();
}
};
template<typename _ObjT>
class AutoDestroyPtr
:public AutoRes<_ObjT*,_ObjT*,DestroyObj>
{
public:
explicit AutoDestroyPtr(_ObjT* ptr=NULL)
:AutoRes<_ObjT*,_ObjT*,DestroyObj>(ptr)
{
}
};
template<typename _ServerPtrT>
class ReleaseClientOp
{
private:
_ServerPtrT m_pServer;
public:
ReleaseClientOp(_ServerPtrT pServer=_ServerPtrT())
:m_pServer(pServer)
{
}
template<typename _ClientPtrT>
void operator()(_ClientPtrT ptr)
{
if(m_pServer)
m_pServer->ReleaseClient(ptr);
}
};
template<typename _ServerPtrT,typename _ClientPtrT>
class AutoClientPtr
:public AutoRes<_ClientPtrT,_ClientPtrT,ReleaseClientOp<_ServerPtrT> >
{
typedef AutoRes<_ClientPtrT,_ClientPtrT,ReleaseClientOp<_ServerPtrT> > _MyBaseT;
public:
explicit AutoClientPtr(_ServerPtrT pServer=_ServerPtrT(),_ClientPtrT pClient=_ClientPtrT())
:_MyBaseT(pClient,ReleaseClientOp<_ServerPtrT>(pServer))
{
}
};
_FF_END
#endif
| [
"[email protected]"
] | |
aaa8f706eca185ad9f7dd72dda3930415ee4cc22 | e4f29494a0ecb0a19b231a17e51127a7ddbfe387 | /TcpDebug.ino | 4c4d7c9df0d7cf9d84c51667ee552e72d3a97973 | [] | no_license | EvertDekker/Nixieclock3V1 | de9fb41a14decd21a2a86ba4914bc6c5b1839414 | 67a97d38f1895dbb285c541efe6988dcb04496fc | refs/heads/master | 2020-05-29T15:43:43.041005 | 2019-05-29T13:26:52 | 2019-05-29T13:26:52 | 189,228,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | ino | void init_telnet_debug(){
#ifdef TELNET
if (MDNS.begin(hostn)) {
Serial.println("* MDNS responder started. Hostname -> ");
Serial.println(hostn);
}
MDNS.addService("telnet", "tcp", 23); // Initialize the telnet server of RemoteDebug
Debug.begin(hostn); // Initiaze the telnet server
Debug.setResetCmdEnabled(true); // Enable the reset command
//Debug.showTime(true); // To show time
#endif
}
| [
"[email protected]"
] | |
85ea4dd8d55151bc08e835ee9c71d1a426ef6ce3 | 13c402c37ff65709039cb190f9079667429fd31d | /dll/StatisticsClass.cpp | 2b0c76776a165c45531775a642a1473fe7a1e2c5 | [] | no_license | DarkGL/TrackerUI | 7146689298e1b44386b4575d06c96c4c5b461463 | 3de5fb05c662ba1bb06673d815062de2448ff22b | refs/heads/master | 2023-03-17T04:39:45.409222 | 2023-03-15T06:48:49 | 2023-03-15T06:48:49 | 41,966,780 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,308 | cpp | #include "StatisticsClass.h"
const char * StatisticsClass::urlNewClient = "http://csiks.pl/pliki/stats/newClient.php";
const char * StatisticsClass::urlPingClient = "http://csiks.pl/pliki/stats/pingClient.php";
char StatisticsClass::token[] = "";
bool StatisticsClass::clientConnected = false;
void StatisticsClass::newClient(){
if( this -> getClientConnected() ){
return ;
}
HINTERNET connectHandle = InternetOpen( "HL" ,0,NULL, NULL, 0);
if( !connectHandle ){
return;
}
char connectUrl[ 512 ];
snprintf( connectUrl , sizeof( connectUrl ) , "%s?version=%s" , StatisticsClass::urlNewClient , currentVersion );
HINTERNET openAddress = InternetOpenUrl( connectHandle , connectUrl , NULL , 0, INTERNET_FLAG_PRAGMA_NOCACHE , 0);
if ( !openAddress ){
InternetCloseHandle( connectHandle );
return;
}
char bufferRead[ 64 ];
DWORD NumberOfBytesRead = 0;
InternetReadFile( openAddress , bufferRead , sizeof bufferRead , &NumberOfBytesRead );
if( NumberOfBytesRead <= 0 ){
InternetCloseHandle( openAddress );
InternetCloseHandle( connectHandle );
return;
}
InternetCloseHandle( openAddress );
InternetCloseHandle( connectHandle );
this -> setToken( bufferRead );
this -> setClientConnected( true );
}
void StatisticsClass::pingClient(){
if( !this -> getClientConnected() ){
return ;
}
char bufferUrl[ 2048 ];
snprintf( bufferUrl , sizeof( bufferUrl ) / sizeof( char ) , "%s?token=%s&version=%s" , StatisticsClass::urlPingClient , this -> getToken() , currentVersion );
HINTERNET connectHandle = InternetOpen( "HL" ,0,NULL, NULL, 0);
if( !connectHandle ){
return;
}
HINTERNET openAddress = InternetOpenUrl( connectHandle , bufferUrl , NULL , 0, INTERNET_FLAG_PRAGMA_NOCACHE , 0);
if ( !openAddress ){
InternetCloseHandle( connectHandle );
return;
}
InternetCloseHandle( openAddress );
InternetCloseHandle( connectHandle );
}
bool StatisticsClass::getClientConnected(){
return StatisticsClass::clientConnected;
}
void StatisticsClass::setClientConnected( bool value ){
StatisticsClass::clientConnected = value;
}
const char * StatisticsClass::getToken(){
return StatisticsClass::token;
}
void StatisticsClass::setToken( char * tokenSet ){
strcpy( StatisticsClass::token , tokenSet );
}
| [
"[email protected]"
] | |
c35c2d62a156829d22448cc6b0d87e80e60d5a76 | c27a1b7e258b9fa30653a9aa6dd36dcd1df15810 | /arduino_code_outer.ino | a27b32227a2881ae73337661e4ccde0c8c8668c9 | [] | no_license | Emmanuel-Edidiong/Automatic-Wireless-Weather-Station-with-Arduino | 1b0b97d20a742c1dfb98d8b97966ee2560e86c00 | 8268b1b4dbe8bbb79386ecaf867eea141e34610b | refs/heads/master | 2020-09-13T13:51:21.347427 | 2019-11-19T23:08:11 | 2019-11-19T23:08:11 | 222,806,119 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,116 | ino | /*
Outdoor unit - Transmitter
*/
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <dht.h>
#include <LowPower.h>
#define dataPin 8 // DHT22 data pina
dht DHT; // Creates a DHT object
RF24 radio(10, 9); // CE, CSN
const byte address[6] = "00001";
char thChar[32] = "";
String thString = "";
void setup() {
Serial.begin(115200);
radio.begin();
radio.openWritingPipe(address);
radio.setPALevel(RF24_PA_MIN);
radio.stopListening();
}
void loop() {
int readData = DHT.read22(dataPin); // Reads the data from the sensor
int t = DHT.temperature; // Gets the values of the temperature
int h = DHT.humidity; // Gets the values of the humidity
thString = String(t) + String(h);
thString.toCharArray(thChar, 12);
Serial.println(thChar);
// Sent the data wirelessly to the indoor unit
for (int i = 0; i <= 3; i++) { // Send the data 3 times
radio.write(&thChar, sizeof(thChar));
delay(50);
}
// Sleep for 2 minutes, 15*8 = 120s
for (int sleepCounter = 15; sleepCounter > 0; sleepCounter--)
{
LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
}
}
| [
"[email protected]"
] | |
579829351084c1173b9154fd34d518856cd45da2 | 829869a01da6da0f17dcc173bb5ddd640fd8ba2c | /src/server/test/pegasus_write_service_impl_test.cpp | f3ee0a89b6f99cdf004fb08a169bca7d8300c1f6 | [
"Apache-2.0"
] | permissive | SunnyShow/incubator-pegasus | fff92fa95354c7e44de6c82eb6bb4e6181b8f86d | c02e055e803dab479a31d3cac31739b75542f804 | refs/heads/master | 2022-12-21T00:30:26.747514 | 2020-09-28T16:03:42 | 2020-09-28T16:03:42 | 299,217,109 | 0 | 0 | Apache-2.0 | 2020-09-28T06:57:47 | 2020-09-28T06:57:47 | null | UTF-8 | C++ | false | false | 8,058 | cpp | // Copyright (c) 2017, Xiaomi, Inc. All rights reserved.
// This source code is licensed under the Apache License Version 2.0, which
// can be found in the LICENSE file in the root directory of this source tree.
#include "pegasus_server_test_base.h"
#include "server/pegasus_server_write.h"
#include "server/pegasus_write_service_impl.h"
#include "message_utils.h"
#include <dsn/utility/defer.h>
namespace pegasus {
namespace server {
class pegasus_write_service_impl_test : public pegasus_server_test_base
{
protected:
std::unique_ptr<pegasus_server_write> _server_write;
pegasus_write_service::impl *_write_impl{nullptr};
public:
void SetUp() override
{
start();
_server_write = dsn::make_unique<pegasus_server_write>(_server.get(), true);
_write_impl = _server_write->_write_svc->_impl.get();
}
uint64_t read_timestamp_from(dsn::string_view raw_key)
{
std::string raw_value;
rocksdb::Status s = _write_impl->_db->Get(
_write_impl->_rd_opts, utils::to_rocksdb_slice(raw_key), &raw_value);
uint64_t local_timetag =
pegasus_extract_timetag(_write_impl->_pegasus_data_version, raw_value);
return extract_timestamp_from_timetag(local_timetag);
}
// start with duplicating.
void set_app_duplicating()
{
_server->stop(false);
dsn::replication::destroy_replica(_replica);
dsn::app_info app_info;
app_info.app_type = "pegasus";
app_info.duplicating = true;
_replica =
dsn::replication::create_test_replica(_replica_stub, _gpid, app_info, "./", false);
_server = dsn::make_unique<pegasus_server_impl>(_replica);
SetUp();
}
int db_get(dsn::string_view raw_key, db_get_context *get_ctx)
{
return _write_impl->db_get(raw_key, get_ctx);
}
void single_set(dsn::blob raw_key, dsn::blob user_value)
{
dsn::apps::update_request put;
put.key = raw_key;
put.value = user_value;
db_write_context write_ctx;
dsn::apps::update_response put_resp;
_write_impl->batch_put(write_ctx, put, put_resp);
ASSERT_EQ(_write_impl->batch_commit(0), 0);
}
};
TEST_F(pegasus_write_service_impl_test, put_verify_timetag)
{
set_app_duplicating();
dsn::blob raw_key;
pegasus::pegasus_generate_key(
raw_key, dsn::string_view("hash_key"), dsn::string_view("sort_key"));
std::string value = "value";
int64_t decree = 10;
/// insert timestamp 10
uint64_t timestamp = 10;
auto ctx = db_write_context::create(decree, timestamp);
ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value, 0));
ASSERT_EQ(0, _write_impl->db_write(ctx.decree));
_write_impl->clear_up_batch_states(decree, 0);
ASSERT_EQ(read_timestamp_from(raw_key), timestamp);
/// insert timestamp 15, which overwrites the previous record
timestamp = 15;
ctx = db_write_context::create(decree, timestamp);
ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value, 0));
ASSERT_EQ(0, _write_impl->db_write(ctx.decree));
_write_impl->clear_up_batch_states(decree, 0);
ASSERT_EQ(read_timestamp_from(raw_key), timestamp);
/// insert timestamp 15 from remote, which will overwrite the previous record,
/// since its cluster id is larger (current cluster_id=1)
timestamp = 15;
ctx.remote_timetag = pegasus::generate_timetag(timestamp, 2, false);
ctx.verify_timetag = true;
ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value + "_new", 0));
ASSERT_EQ(0, _write_impl->db_write(ctx.decree));
_write_impl->clear_up_batch_states(decree, 0);
ASSERT_EQ(read_timestamp_from(raw_key), timestamp);
std::string raw_value;
dsn::blob user_value;
rocksdb::Status s =
_write_impl->_db->Get(_write_impl->_rd_opts, utils::to_rocksdb_slice(raw_key), &raw_value);
pegasus_extract_user_data(_write_impl->_pegasus_data_version, std::move(raw_value), user_value);
ASSERT_EQ(user_value.to_string(), "value_new");
// write retry
ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value + "_new", 0));
ASSERT_EQ(0, _write_impl->db_write(ctx.decree));
_write_impl->clear_up_batch_states(decree, 0);
/// insert timestamp 16 from local, which will overwrite the remote record,
/// since its timestamp is larger
timestamp = 16;
ctx = db_write_context::create(decree, timestamp);
ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value, 0));
ASSERT_EQ(0, _write_impl->db_write(ctx.decree));
_write_impl->clear_up_batch_states(decree, 0);
ASSERT_EQ(read_timestamp_from(raw_key), timestamp);
// write retry
ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value, 0));
ASSERT_EQ(0, _write_impl->db_write(ctx.decree));
_write_impl->clear_up_batch_states(decree, 0);
}
// verify timetag on data version v0
TEST_F(pegasus_write_service_impl_test, verify_timetag_compatible_with_version_0)
{
dsn::fail::setup();
dsn::fail::cfg("db_get", "100%1*return()");
// if db_write_batch_put_ctx invokes db_get, this test must fail.
const_cast<uint32_t &>(_write_impl->_pegasus_data_version) = 0; // old version
dsn::blob raw_key;
pegasus::pegasus_generate_key(
raw_key, dsn::string_view("hash_key"), dsn::string_view("sort_key"));
std::string value = "value";
int64_t decree = 10;
uint64_t timestamp = 10;
auto ctx = db_write_context::create_duplicate(decree, timestamp, true);
ASSERT_EQ(0, _write_impl->db_write_batch_put_ctx(ctx, raw_key, value, 0));
ASSERT_EQ(0, _write_impl->db_write(ctx.decree));
_write_impl->clear_up_batch_states(decree, 0);
dsn::fail::teardown();
}
class incr_test : public pegasus_write_service_impl_test
{
public:
void SetUp() override
{
pegasus_write_service_impl_test::SetUp();
pegasus::pegasus_generate_key(
req.key, dsn::string_view("hash_key"), dsn::string_view("sort_key"));
}
dsn::apps::incr_request req;
dsn::apps::incr_response resp;
};
TEST_F(incr_test, incr_on_absent_record)
{
// ensure key is absent
db_get_context get_ctx;
db_get(req.key, &get_ctx);
ASSERT_FALSE(get_ctx.found);
req.increment = 100;
_write_impl->incr(0, req, resp);
ASSERT_EQ(resp.new_value, 100);
db_get(req.key, &get_ctx);
ASSERT_TRUE(get_ctx.found);
}
TEST_F(incr_test, negative_incr_and_zero_incr)
{
req.increment = -100;
ASSERT_EQ(0, _write_impl->incr(0, req, resp));
ASSERT_EQ(resp.new_value, -100);
req.increment = -1;
ASSERT_EQ(0, _write_impl->incr(0, req, resp));
ASSERT_EQ(resp.new_value, -101);
req.increment = 0;
ASSERT_EQ(0, _write_impl->incr(0, req, resp));
ASSERT_EQ(resp.new_value, -101);
}
TEST_F(incr_test, invalid_incr)
{
single_set(req.key, dsn::blob::create_from_bytes("abc"));
req.increment = 10;
_write_impl->incr(1, req, resp);
ASSERT_EQ(resp.error, rocksdb::Status::kInvalidArgument);
ASSERT_EQ(resp.new_value, 0);
single_set(req.key, dsn::blob::create_from_bytes("100"));
req.increment = std::numeric_limits<int64_t>::max();
_write_impl->incr(1, req, resp);
ASSERT_EQ(resp.error, rocksdb::Status::kInvalidArgument);
ASSERT_EQ(resp.new_value, 100);
}
TEST_F(incr_test, fail_on_get)
{
dsn::fail::setup();
dsn::fail::cfg("db_get", "100%1*return()");
// when db_get failed, incr should return an error.
req.increment = 10;
_write_impl->incr(1, req, resp);
ASSERT_EQ(resp.error, FAIL_DB_GET);
dsn::fail::teardown();
}
TEST_F(incr_test, fail_on_put)
{
dsn::fail::setup();
dsn::fail::cfg("db_write_batch_put", "100%1*return()");
// when rocksdb put failed, incr should return an error.
req.increment = 10;
_write_impl->incr(1, req, resp);
ASSERT_EQ(resp.error, FAIL_DB_WRITE_BATCH_PUT);
dsn::fail::teardown();
}
} // namespace server
} // namespace pegasus
| [
"[email protected]"
] | |
d59c5f726c85c0426fe1f464a529f7fc97a16b65 | a6f1cd042e91b17f72bcc7872a47cc022f2cf21e | /DFS/140. Word Break II.cpp | f0c3e25853d36e6953d7c4095b60ae93953c6b90 | [] | no_license | sammiiT/leetcode | bc1b8fa107c15bbdd803e6f5e4f86a179904a988 | 8e882f4a6fb05ba645bd1ff8355d3b8f14654fb0 | refs/heads/master | 2023-09-06T04:43:54.582944 | 2023-09-04T15:19:00 | 2023-09-04T15:19:00 | 219,103,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,104 | cpp | //===類似題===
139. Word Break
472. Concatenated Words
//=== 思路====
(*) DFS算法
- 陣列中的每一個節點都可以當作root節點, 每一個節點都是上一層的child節點
- 此題的陣列是vector<string> wordDict
- 因為陣列元素可以reused,所以每進入下一層, loop迴圈都從i=0開始
0. segment 是要連續,不能中間斷掉, 左半部和右半部連接
1.宣告 string& out, 紀錄每一個滿足條件的string
2.宣告 vector<string>& res, 紀錄滿足最後條件的string
3.每一次substring都要從string[0]開始,
- 取從0開始的substr, 判斷此substr是否等於wordDict[i]
--不等於就continue
4.每一次都要記錄(append)新的string; out.append(wordDict[i]+" ")
跳回上一層要把append刪除; out = out.substr(0,size);//size維之前out的長度
5.最回傳res
(*)
cout<<str.substr(pos, str.size()-pos)<<endl;
//str.size()是1-index, pos是0-index 相減??????
(*)思路重構
1.以wordDict為依據, 遍歷wordDict並與string做比較
2.wordDict[i]不同的排列方式, 可以滿足string的segmentation => 所以用DFS
for(int i=0; i<wordDict.size(); ++i){...}
3.每一次判斷string segement, 都把此segment從string中刪除, 並將剩下的string放到下一層DFS中做運算
//=====
void helper(string s ,vector<string>& wordDict, string& out, vector<string>& res){
if(s.size()==0){
out.pop_back();//將space 字元移除
res.push_back(out);
return;
}
for(int i=0; i<wordDict.size(); ++i){
int len = wordDict[i].size();
if(s.substr(0,len)!=wordDict[i]) continue;//不同排列順序
string tmp = s.substr(len,s.size()-len);//剩下的String
int size = out.size();
out.append(wordDict[i]+" ");
helper(tmp,wordDict,out,res);
out = out.substr(0,size);//沒有辦法pop_back() string,所以用之前紀錄的substriing size
}
}
vector<string> wordBreak(string s, vector<string>& wordDict) {
vector<string> res;
string out;
helper(s,wordDict,out,res);
return res;
}
| [
"[email protected]"
] | |
759a015ca9170f3456ab0ac5f3a1626efca68ad7 | 483428f23277dc3fd2fad6588de334fc9b8355d2 | /hpp/iOSDevice32/Release/uTPLb_MemoryStreamPool.hpp | bee8378fa9718a035cca20b9ad1bd10f11e6c5d4 | [] | no_license | gzwplato/LockBox3-1 | 7084932d329beaaa8169b94729c4b05c420ebe44 | 89e300b47f8c1393aefbec01ffb89ddf96306c55 | refs/heads/master | 2021-05-10T18:41:18.748523 | 2015-07-04T09:48:06 | 2015-07-04T09:48:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,375 | hpp | // CodeGear C++Builder
// Copyright (c) 1995, 2015 by Embarcadero Technologies, Inc.
// All rights reserved
// (DO NOT EDIT: machine generated header) 'uTPLb_MemoryStreamPool.pas' rev: 29.00 (iOS)
#ifndef Utplb_memorystreampoolHPP
#define Utplb_memorystreampoolHPP
#pragma delphiheader begin
#pragma option push
#pragma option -w- // All warnings off
#pragma option -Vx // Zero-length empty class member
#pragma pack(push,8)
#include <System.hpp>
#include <SysInit.hpp>
#include <System.Classes.hpp>
//-- user supplied -----------------------------------------------------------
namespace Utplb_memorystreampool
{
//-- forward type declarations -----------------------------------------------
__interface IMemoryStreamPool;
typedef System::DelphiInterface<IMemoryStreamPool> _di_IMemoryStreamPool;
class DELPHICLASS TPooledMemoryStream;
//-- type declarations -------------------------------------------------------
__interface INTERFACE_UUID("{ADB2D4BA-40F6-4249-923E-201D4719609B}") IMemoryStreamPool : public System::IInterface
{
virtual int __fastcall BayCount(void) = 0 ;
virtual void __fastcall GetUsage(int Size, int &Current, int &Peak) = 0 ;
virtual int __fastcall GetSize(int Idx) = 0 ;
virtual System::Classes::TMemoryStream* __fastcall NewMemoryStream(int InitSize) = 0 ;
};
#pragma pack(push,4)
class PASCALIMPLEMENTATION TPooledMemoryStream : public System::Classes::TMemoryStream
{
typedef System::Classes::TMemoryStream inherited;
protected:
_di_IMemoryStreamPool FPool;
int FCoVector;
virtual void * __fastcall Realloc(int &NewCapacity);
public:
__fastcall TPooledMemoryStream(const _di_IMemoryStreamPool Pool1);
public:
/* TMemoryStream.Destroy */ inline __fastcall virtual ~TPooledMemoryStream(void) { }
};
#pragma pack(pop)
//-- var, const, procedure ---------------------------------------------------
extern DELPHI_PACKAGE _di_IMemoryStreamPool __fastcall NewPool(void);
} /* namespace Utplb_memorystreampool */
#if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_UTPLB_MEMORYSTREAMPOOL)
using namespace Utplb_memorystreampool;
#endif
#pragma pack(pop)
#pragma option pop
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // Utplb_memorystreampoolHPP
| [
"[email protected]"
] | |
0097d92533baaeb7b0f9a69817088336a809c56e | e9c9efaa1f19a28a5154c19312b2871cc4449f92 | /src/fsw/FCCode/ADCSBoxController.hpp | d57a42f104cc371266e2b4a71bca2c39e6067346 | [
"MIT"
] | permissive | Vsj986/FlightSoftware | 52bc663d00786e6866a4cbaf2c04282cacf4ad97 | c8ae3504a1685d05556a0c9253b147f9d24c03b6 | refs/heads/master | 2022-04-24T23:48:34.531495 | 2020-04-28T08:07:32 | 2020-04-28T08:07:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,690 | hpp | #ifndef ADCS_BOX_CONTROLLER_HPP_
#define ADCS_BOX_CONTROLLER_HPP_
#include "Drivers/ADCS.hpp"
#include "TimedControlTask.hpp"
/**
* @brief Takes input command statefields and commands the ADCS Box.
*
* Note this CT doesn't do any computing, just actuation
* This CT is inteded to only do hardware calls
*/
class ADCSBoxController : public TimedControlTask<void>
{
public:
/**
* @brief Construct a new ADCSBoxController control task
*
* @param registry input StateField registry
* @param offset control task offset
* @param _adcs the input adcs system
*/
ADCSBoxController(StateFieldRegistry ®istry, unsigned int offset, Devices::ADCS &_adcs);
/** ADCS Driver. **/
Devices::ADCS& adcs_system;
/**
* @brief Given the command statefields, use the ADCS driver to execute
*/
void execute() override;
protected:
/**
* @brief Command to get from mission_manager
*
*/
const WritableStateField<unsigned char>* adcs_state_fp;
/**
* @brief RWA command fields
*
*/
const WritableStateField<unsigned char>* rwa_mode_fp;
const WritableStateField<f_vector_t>* rwa_speed_cmd_fp;
const WritableStateField<f_vector_t>* rwa_torque_cmd_fp;
const WritableStateField<float>* rwa_speed_filter_fp;
const WritableStateField<float>* rwa_ramp_filter_fp;
/**
* @brief MTR command fields
*
*/
const WritableStateField<unsigned char>* mtr_mode_fp;
const WritableStateField<f_vector_t>* mtr_cmd_fp;
const WritableStateField<float>* mtr_limit_fp;
/**
* @brief SSA command fields
*
*/
const ReadableStateField<unsigned char>* ssa_mode_fp;
const WritableStateField<float>* ssa_voltage_filter_fp;
/**
* @brief IMU command fields
*
*/
const WritableStateField<unsigned char>* mag1_mode_fp;
const WritableStateField<unsigned char>* mag2_mode_fp;
const WritableStateField<float>* imu_mag_filter_fp;
const WritableStateField<float>* imu_gyr_filter_fp;
const WritableStateField<float>* imu_gyr_temp_filter_fp;
const WritableStateField<float>* imu_gyr_temp_kp_fp;
const WritableStateField<float>* imu_gyr_temp_ki_fp;
const WritableStateField<float>* imu_gyr_temp_kd_fp;
const WritableStateField<float>* imu_gyr_temp_desired_fp;
/**
* @brief HAVT command tables, a vector of pointers to bool state fields
*
*/
std::vector<WritableStateField<bool>*> havt_cmd_reset_vector_fp;
std::vector<WritableStateField<bool>*> havt_cmd_disable_vector_fp;
};
#endif
| [
"[email protected]"
] | |
fc66a1678930bf9093bd076f90dd380635b60366 | ceeddddcf3e99e909c4af5ff2b9fad4a8ecaeb2a | /branches/releases/1.3.NET/source/Irrlicht/CGUIColorSelectDialog.h | fed63371d4d75b6f6d20e164aab8c2e8f2527655 | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive"
] | permissive | jivibounty/irrlicht | d9d6993bd0aee00dce2397a887b7f547ade74fbb | c5c80cde40b6d14fe5661440638d36a16b41d7ab | refs/heads/master | 2021-01-18T02:56:08.844268 | 2015-07-21T08:02:25 | 2015-07-21T08:02:25 | 39,405,895 | 0 | 0 | null | 2015-07-20T20:07:06 | 2015-07-20T20:07:06 | null | UTF-8 | C++ | false | false | 1,684 | h | // Copyright (C) 2002-2007 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_GUI_COLOR_SELECT_DIALOG_H_INCLUDED__
#define __C_GUI_COLOR_SELECT_DIALOG_H_INCLUDED__
#include "IGUIColorSelectDialog.h"
#include "IGUIButton.h"
#include "IGUIEditBox.h"
#include "IGUIScrollBar.h"
#include "IGUIImage.h"
#include "irrArray.h"
namespace irr
{
namespace gui
{
class CGUIColorSelectDialog : public IGUIColorSelectDialog
{
public:
//! constructor
CGUIColorSelectDialog(const wchar_t* title, IGUIEnvironment* environment, IGUIElement* parent, s32 id);
//! destructor
virtual ~CGUIColorSelectDialog();
//! called if an event happened.
virtual bool OnEvent(SEvent event);
//! draws the element and its children
virtual void draw();
private:
//! sends the event that the file has been selected.
void sendSelectedEvent();
//! sends the event that the file choose process has been canceld
void sendCancelEvent();
core::position2d<s32> DragStart;
bool Dragging;
IGUIButton* CloseButton;
IGUIButton* OKButton;
IGUIButton* CancelButton;
struct SBatteryItem
{
f32 Incoming;
f32 Outgoing;
IGUIEditBox * Edit;
IGUIScrollBar *Scrollbar;
};
core::array< SBatteryItem > Battery;
struct SColorCircle
{
IGUIImage * Control;
video::ITexture * Texture;
};
SColorCircle ColorRing;
void buildColorRing( const core::dimension2d<s32> & dim, s32 supersample, const u32 borderColor );
};
} // end namespace gui
} // end namespace irr
#endif
| [
"hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475"
] | hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475 |
4369c661485646300e4388170f7303ad261fce8b | 70dc2b3a7418bb0b5b8092b037bb3eeeea1ed4a0 | /gui-kde/unitselector.h | 638588de4f3f8c94b3295bf57eabc8f9ffb756fe | [] | no_license | jusirkka/freeciv-kde | 829bc62643876b1491bbf8e3b3f8274383aedf3a | 417c80d46b53f0a7fe75f3ffd5200041f1a58d57 | refs/heads/master | 2020-04-20T01:55:45.980679 | 2019-04-28T03:28:24 | 2019-04-28T03:28:24 | 168,558,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 999 | h | #ifndef UNITSELECTOR_H
#define UNITSELECTOR_H
#include <QWidget>
#include <QTimer>
struct tile;
struct unit;
namespace KV {
class UnitSelector: public QWidget
{
Q_OBJECT
public:
explicit UnitSelector(tile* t, QWidget *parent = nullptr);
protected:
void paintEvent(QPaintEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void keyPressEvent(QKeyEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void wheelEvent(QWheelEvent *event) override;
void closeEvent(QCloseEvent *event) override;
void enterEvent(QEvent *event) override;
void leaveEvent(QEvent *event) override;
private slots:
void updateUnits();
private:
void updateUnitList();
void createPixmap();
private:
QPixmap m_pix;
QPixmap m_pixHigh;
QSize m_itemSize;
QList<unit*> m_unitList;
QFont m_font;
QFont m_infoFont;
int m_indexHigh;
int m_unitOffset;
tile *m_tile;
QTimer m_delay;
bool m_first;
};
}
#endif // UNITSELECTOR_H
| [
"[email protected]"
] | |
4a9133ddb6d9eb9f7a3eb47d157200415e748cd3 | 4b6db2bfec027acdd71e1d030829983bade67980 | /src/Draw/Text.h | ff67611214c68cec2ac1055830858cf152892386 | [] | no_license | AkiraSekine/CreaDXTKLib | 78b0980777814d6d2a4336cfdb779d1ab0007f7b | 9259ecd31a003c620dddc770e383173f5d3bcda7 | refs/heads/develop | 2020-03-30T23:07:33.919981 | 2019-02-15T06:02:02 | 2019-02-15T06:02:02 | 151,691,370 | 0 | 0 | null | 2019-02-15T06:02:03 | 2018-10-05T08:23:28 | HTML | SHIFT_JIS | C++ | false | false | 2,502 | h | #pragma once
#include "../Default/pch.h"
#include "../Utility/Singleton.h"
#include "../Math/Vector2.h"
#include <string>
#include <map>
namespace CreaDXTKLib
{
namespace Draw
{
/// <summary>
/// テキスト描画クラス
/// </summary>
class Text final : public Utility::Singleton<Text>
{
SINGLETON(Text)
public:
/// <summary>
/// フォントファイルの読み込み
/// </summary>
/// <param name="_key">ハンドル名</param>
/// <param name="_fileName">ファイル名</param>
void Load(const std::wstring& _key, const std::wstring& _fileName);
/// <summary>
/// テキストの描画
/// </summary>
/// <param name="_key">ハンドル名</param>
/// <param name="_position">描画座標</param>
/// <param name="_text">描画文字列(フォーマット)</param>
void Draw(const std::wstring& _key, const Math::Vector2& _position, const std::wstring _text, ...);
/// <summary>
/// テキストの描画
/// </summary>
/// <param name="_key">ハンドル名</param>
/// <param name="_position">描画座標</param>
/// <param name="_color">色</param>
/// <param name="_text">描画文字列(フォーマット)</param>
void Draw(const std::wstring& _key, const Math::Vector2& _position, const DirectX::XMVECTORF32& _color , const std::wstring _text, ...);
/// <summary>
/// テキストの描画
/// </summary>
/// <param name="_key">ハンドル名</param>
/// <param name="_position">描画座標</param>
/// <param name="_color">色</param>
/// <param name="_text">描画文字列(フォーマット)</param>
void Draw(const std::wstring& _key, const Math::Vector2& _position, const DirectX::FXMVECTOR& _color , const std::wstring _text, ...);
/// <summary>
/// 初期化処理
/// </summary>
void Initialize(Microsoft::WRL::ComPtr<ID3D11Device1> _device, Microsoft::WRL::ComPtr<ID3D11DeviceContext1> _context);
/// <summary>
/// 終了処理
/// </summary>
void OnEnd();
private:
Microsoft::WRL::ComPtr<ID3D11Device1> m_device;
std::unique_ptr<DirectX::SpriteBatch> m_spriteBatch;
std::map<std::wstring, DirectX::SpriteFont*> m_fonts = std::map<std::wstring, DirectX::SpriteFont*>();
};
} // Draw
} // CreaDXTKLib | [
"[email protected]"
] | |
3046cc516b94d3d61b5944e8e72cb324eb8e83b2 | 2f10f807d3307b83293a521da600c02623cdda82 | /deps/boost/win/debug/include/boost/hana/fwd/concept/sequence.hpp | 422e52578079c9edc98e149f855e4d4868c1d9cf | [] | no_license | xpierrohk/dpt-rp1-cpp | 2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e | 643d053983fce3e6b099e2d3c9ab8387d0ea5a75 | refs/heads/master | 2021-05-23T08:19:48.823198 | 2019-07-26T17:35:28 | 2019-07-26T17:35:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | hpp | version https://git-lfs.github.com/spec/v1
oid sha256:2995f98908d109d3d0c6f3843c95855164d1b5d8229cdc1d99bcf3b7094d3655
size 7412
| [
"[email protected]"
] | |
088e07cf5b8e57147205361a7bb8da08825fbeeb | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /third_party/blink/renderer/core/html/link_element_loading_test.cc | c82c7593f5fe8ef11d8e34e702f07dfa1a2f5fb7 | [
"LGPL-2.0-only",
"BSD-2-Clause",
"LGPL-2.1-only",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 1,395 | cc | // Copyright 2016 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 "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/html/html_link_element.h"
#include "third_party/blink/renderer/core/testing/sim/sim_request.h"
#include "third_party/blink/renderer/core/testing/sim/sim_test.h"
namespace blink {
class LinkElementLoadingTest : public SimTest {};
TEST_F(LinkElementLoadingTest,
ShouldCancelLoadingStyleSheetIfLinkElementIsDisconnected) {
SimRequest main_resource("https://example.com/test.html", "text/html");
SimRequest css_resource("https://example.com/test.css", "text/css");
LoadURL("https://example.com/test.html");
main_resource.Start();
main_resource.Write(
"<!DOCTYPE html><link id=link rel=stylesheet href=test.css>");
// Sheet is streaming in, but not ready yet.
css_resource.Start();
// Remove a link element from a document
HTMLLinkElement* link =
ToHTMLLinkElement(GetDocument().getElementById("link"));
EXPECT_NE(nullptr, link);
link->remove();
// Finish the load.
css_resource.Complete();
main_resource.Finish();
// Link element's sheet loading should be canceled.
EXPECT_EQ(nullptr, link->sheet());
}
} // namespace blink
| [
"[email protected]"
] | |
1cd2b7ce9a506eb8b775389be6d61a36481bfe5c | 3c1dbc0532ec129a34dfc5eb6b663d7eaf31a1f8 | /limak_house.cpp | ac80f9d7ee246671c9cd11ac2355035eae409fcd | [] | no_license | fredybotas/Spoj | c79702b163627f3f83461fb2ccb923c544ae7a16 | 5a99e0d15b8fcbbb093dc1c694cdd56c2f83f0c4 | refs/heads/master | 2021-01-19T20:34:56.636668 | 2017-02-27T00:03:39 | 2017-02-27T00:03:39 | 81,080,973 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,865 | cpp | #include <stdio.h>
#include <string.h>
int main(){
//najdi spodok
char buffer[20];
int curr, i, low = 0, high = 1000;
while(low < high){
curr = (low + high) / 2;
printf("? %d %d\n", curr, 0);
fflush(stdout);
scanf("%s", buffer);
if(!strcmp(buffer, "YES"))
low = curr + 1;
else
high = curr;
}
for(i = curr - 3; i < curr + 4; i++){
if(i == 1000){
curr = 1000;
break;
}
printf("? %d %d\n", i, 0);
fflush(stdout);
scanf("%s", buffer);
if(!strcmp(buffer, "YES"))
continue;
else{
curr = i - 1;
break;
}
}
int x_square = curr*2;
//trojuholnik
low = x_square/2;
high = 1000;
while(low < high){
curr = (low + high) / 2;
printf("? %d %d\n", curr, x_square);
fflush(stdout);
scanf("%s", buffer);
if(!strcmp(buffer, "YES"))
low = curr + 1;
else
high = curr;
}
for(i = curr - 3; i < curr + 4; i++){
if(i == 1000){
curr = 1000;
break;
}
printf("? %d %d\n", i, x_square);
fflush(stdout);
scanf("%s", buffer);
if(!strcmp(buffer, "YES"))
continue;
else{
curr = i - 1;
break;
}
}
int x_triangle = curr*2;
low = x_square;
high = 1000;
while(low < high){
curr = (low + high) / 2;
printf("? %d %d\n", 0, curr);
fflush(stdout);
scanf("%s", buffer);
if(!strcmp(buffer, "YES"))
low = curr + 1;
else
high = curr;
}
for(i = curr - 3; i < curr + 4; i++){
if(i == 1000){
curr = 1000;
break;
}
printf("? %d %d\n", 0, i);
fflush(stdout);
scanf("%s", buffer);
if(!strcmp(buffer, "YES"))
continue;
else{
curr = i - 1;
break;
}
}
int height = curr;
printf("! %d\n", x_square*x_square + x_triangle*(height - x_square)/2);
fflush(stdout);
return 0;
}
| [
"[email protected]"
] | |
38f7c8a3cad67c635c35e49aa86561033dd5059e | b2b9e4d616a6d1909f845e15b6eaa878faa9605a | /Genemardon/20150726浙大月赛/H.cpp | a21dd35a335cc1f9d08f48963c32541c661122f1 | [] | no_license | JinbaoWeb/ACM | db2a852816d2f4e395086b2b7f2fdebbb4b56837 | 021b0c8d9c96c1bc6e10374ea98d0706d7b509e1 | refs/heads/master | 2021-01-18T22:32:50.894840 | 2016-06-14T07:07:51 | 2016-06-14T07:07:51 | 55,882,694 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 737 | cpp | #include <stdio.h>
#include <string.h>
#include <algorithm>
#include <vector>
using namespace std;
vector<int>tab[50010];
int n,m,q;
int ans[50010];
int main(int argc, char const *argv[])
{
while (scanf("%d%d%d",&n,&m,&q) != EOF)
{
memset(ans,0,sizeof(ans));
for (int i=1;i<=n;i++) tab[i].clear();
for (int i=0;i<m;i++)
{
int u,v;
scanf("%d%d",&u,&v);
if (v<u)
tab[u].push_back(v);
}
int m1=n,m2=n;
for (int i=n;i>1;i--)
{
for (int j=0;j<tab[i].size();j++) if (tab[i][j]<m1)
{
m2=m1;
m1=tab[i][j];
}
else if (tab[i][j]<m2)
{
m2=tab[i][j];
}
ans[i]=max(i-m2,0);
}
int ask;
for (int i=0;i<q;i++)
{
scanf("%d",&ask);
printf("%d\n", ans[ask]);
}
}
return 0;
} | [
"[email protected]"
] | |
508d55d75ab154fe547faf8438d150f7652f0e14 | 52a3c93c38bef127eaee4420f36a89d929a321c5 | /SDK/SoT_BP_FishingFish_Wrecker_05_Colour_05_Moon_classes.hpp | 8be34a73802fcedf704075651af56099a98ab051 | [] | no_license | RDTCREW/SoT-SDK_2_0_7_reserv | 8e921275508d09e5f81b10f9a43e47597223cb35 | db6a5fc4cdb9348ddfda88121ebe809047aa404a | refs/heads/master | 2020-07-24T17:18:40.537329 | 2019-09-11T18:53:58 | 2019-09-11T18:53:58 | 207,991,316 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 883 | hpp | #pragma once
// Sea of Thieves (2.0) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_BP_FishingFish_Wrecker_05_Colour_05_Moon_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_FishingFish_Wrecker_05_Colour_05_Moon.BP_FishingFish_Wrecker_05_Colour_05_Moon_C
// 0x0000 (0x0990 - 0x0990)
class ABP_FishingFish_Wrecker_05_Colour_05_Moon_C : public ABP_FishingFish_Wrecker_05_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass BP_FishingFish_Wrecker_05_Colour_05_Moon.BP_FishingFish_Wrecker_05_Colour_05_Moon_C"));
return ptr;
}
void UserConstructionScript();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
3c562a4243e222e2a5d2afd6f33ac1002b5d77d5 | e49020bee62e9a7006b7a603588aff026ac19402 | /clang/lib/Basic/IdentifierTable.cpp | 621bcc265020d77a202936efaba490ba1a2832a7 | [
"NCSA"
] | permissive | angopher/llvm | 10d540f4d38fd184506d9096fb02a288af8a1aa1 | 163def217817c90fb982a6daf384744d8472b92b | refs/heads/master | 2020-06-10T09:59:52.274700 | 2018-05-10T23:14:40 | 2018-05-10T23:14:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,406 | cpp | //===- IdentifierTable.cpp - Hash table for identifier lookup -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the IdentifierInfo, IdentifierVisitor, and
// IdentifierTable interfaces.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TokenKinds.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstdio>
#include <cstring>
#include <string>
using namespace clang;
//===----------------------------------------------------------------------===//
// IdentifierInfo Implementation
//===----------------------------------------------------------------------===//
IdentifierInfo::IdentifierInfo() {
TokenID = tok::identifier;
ObjCOrBuiltinID = 0;
HasMacro = false;
HadMacro = false;
IsExtension = false;
IsFutureCompatKeyword = false;
IsPoisoned = false;
IsCPPOperatorKeyword = false;
NeedsHandleIdentifier = false;
IsFromAST = false;
ChangedAfterLoad = false;
FEChangedAfterLoad = false;
RevertedTokenID = false;
OutOfDate = false;
IsModulesImport = false;
}
//===----------------------------------------------------------------------===//
// IdentifierTable Implementation
//===----------------------------------------------------------------------===//
IdentifierIterator::~IdentifierIterator() = default;
IdentifierInfoLookup::~IdentifierInfoLookup() = default;
namespace {
/// A simple identifier lookup iterator that represents an
/// empty sequence of identifiers.
class EmptyLookupIterator : public IdentifierIterator
{
public:
StringRef Next() override { return StringRef(); }
};
} // namespace
IdentifierIterator *IdentifierInfoLookup::getIdentifiers() {
return new EmptyLookupIterator();
}
IdentifierTable::IdentifierTable(IdentifierInfoLookup *ExternalLookup)
: HashTable(8192), // Start with space for 8K identifiers.
ExternalLookup(ExternalLookup) {}
IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
IdentifierInfoLookup *ExternalLookup)
: IdentifierTable(ExternalLookup) {
// Populate the identifier table with info about keywords for the current
// language.
AddKeywords(LangOpts);
}
//===----------------------------------------------------------------------===//
// Language Keyword Implementation
//===----------------------------------------------------------------------===//
// Constants for TokenKinds.def
namespace {
enum {
KEYC99 = 0x1,
KEYCXX = 0x2,
KEYCXX11 = 0x4,
KEYGNU = 0x8,
KEYMS = 0x10,
BOOLSUPPORT = 0x20,
KEYALTIVEC = 0x40,
KEYNOCXX = 0x80,
KEYBORLAND = 0x100,
KEYOPENCL = 0x200,
KEYC11 = 0x400,
KEYARC = 0x800,
KEYNOMS18 = 0x01000,
KEYNOOPENCL = 0x02000,
WCHARSUPPORT = 0x04000,
HALFSUPPORT = 0x08000,
CHAR8SUPPORT = 0x10000,
KEYCONCEPTS = 0x20000,
KEYOBJC2 = 0x40000,
KEYZVECTOR = 0x80000,
KEYCOROUTINES = 0x100000,
KEYMODULES = 0x200000,
KEYCXX2A = 0x400000,
KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX2A,
KEYALL = (0x7fffff & ~KEYNOMS18 &
~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to exclude.
};
/// How a keyword is treated in the selected standard.
enum KeywordStatus {
KS_Disabled, // Disabled
KS_Extension, // Is an extension
KS_Enabled, // Enabled
KS_Future // Is a keyword in future standard
};
} // namespace
/// Translates flags as specified in TokenKinds.def into keyword status
/// in the given language standard.
static KeywordStatus getKeywordStatus(const LangOptions &LangOpts,
unsigned Flags) {
if (Flags == KEYALL) return KS_Enabled;
if (LangOpts.CPlusPlus && (Flags & KEYCXX)) return KS_Enabled;
if (LangOpts.CPlusPlus11 && (Flags & KEYCXX11)) return KS_Enabled;
if (LangOpts.CPlusPlus2a && (Flags & KEYCXX2A)) return KS_Enabled;
if (LangOpts.C99 && (Flags & KEYC99)) return KS_Enabled;
if (LangOpts.GNUKeywords && (Flags & KEYGNU)) return KS_Extension;
if (LangOpts.MicrosoftExt && (Flags & KEYMS)) return KS_Extension;
if (LangOpts.Borland && (Flags & KEYBORLAND)) return KS_Extension;
if (LangOpts.Bool && (Flags & BOOLSUPPORT)) return KS_Enabled;
if (LangOpts.Half && (Flags & HALFSUPPORT)) return KS_Enabled;
if (LangOpts.WChar && (Flags & WCHARSUPPORT)) return KS_Enabled;
if (LangOpts.Char8 && (Flags & CHAR8SUPPORT)) return KS_Enabled;
if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) return KS_Enabled;
if (LangOpts.OpenCL && (Flags & KEYOPENCL)) return KS_Enabled;
if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) return KS_Enabled;
if (LangOpts.C11 && (Flags & KEYC11)) return KS_Enabled;
// We treat bridge casts as objective-C keywords so we can warn on them
// in non-arc mode.
if (LangOpts.ObjC2 && (Flags & KEYARC)) return KS_Enabled;
if (LangOpts.ObjC2 && (Flags & KEYOBJC2)) return KS_Enabled;
if (LangOpts.ConceptsTS && (Flags & KEYCONCEPTS)) return KS_Enabled;
if (LangOpts.CoroutinesTS && (Flags & KEYCOROUTINES)) return KS_Enabled;
if (LangOpts.ModulesTS && (Flags & KEYMODULES)) return KS_Enabled;
if (LangOpts.CPlusPlus && (Flags & KEYALLCXX)) return KS_Future;
return KS_Disabled;
}
/// AddKeyword - This method is used to associate a token ID with specific
/// identifiers because they are language keywords. This causes the lexer to
/// automatically map matching identifiers to specialized token codes.
static void AddKeyword(StringRef Keyword,
tok::TokenKind TokenCode, unsigned Flags,
const LangOptions &LangOpts, IdentifierTable &Table) {
KeywordStatus AddResult = getKeywordStatus(LangOpts, Flags);
// Don't add this keyword under MSVCCompat.
if (LangOpts.MSVCCompat && (Flags & KEYNOMS18) &&
!LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
return;
// Don't add this keyword under OpenCL.
if (LangOpts.OpenCL && (Flags & KEYNOOPENCL))
return;
// Don't add this keyword if disabled in this language.
if (AddResult == KS_Disabled) return;
IdentifierInfo &Info =
Table.get(Keyword, AddResult == KS_Future ? tok::identifier : TokenCode);
Info.setIsExtensionToken(AddResult == KS_Extension);
Info.setIsFutureCompatKeyword(AddResult == KS_Future);
}
/// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
/// representations.
static void AddCXXOperatorKeyword(StringRef Keyword,
tok::TokenKind TokenCode,
IdentifierTable &Table) {
IdentifierInfo &Info = Table.get(Keyword, TokenCode);
Info.setIsCPlusPlusOperatorKeyword();
}
/// AddObjCKeyword - Register an Objective-C \@keyword like "class" "selector"
/// or "property".
static void AddObjCKeyword(StringRef Name,
tok::ObjCKeywordKind ObjCID,
IdentifierTable &Table) {
Table.get(Name).setObjCKeywordID(ObjCID);
}
/// AddKeywords - Add all keywords to the symbol table.
///
void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
// Add keywords and tokens for the current language.
#define KEYWORD(NAME, FLAGS) \
AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \
FLAGS, LangOpts, *this);
#define ALIAS(NAME, TOK, FLAGS) \
AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \
FLAGS, LangOpts, *this);
#define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
if (LangOpts.CXXOperatorNames) \
AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this);
#define OBJC1_AT_KEYWORD(NAME) \
if (LangOpts.ObjC1) \
AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
#define OBJC2_AT_KEYWORD(NAME) \
if (LangOpts.ObjC2) \
AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
#define TESTING_KEYWORD(NAME, FLAGS)
#include "clang/Basic/TokenKinds.def"
if (LangOpts.ParseUnknownAnytype)
AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
LangOpts, *this);
if (LangOpts.DeclSpecKeyword)
AddKeyword("__declspec", tok::kw___declspec, KEYALL, LangOpts, *this);
// Add the '_experimental_modules_import' contextual keyword.
get("import").setModulesImport(true);
}
/// Checks if the specified token kind represents a keyword in the
/// specified language.
/// \returns Status of the keyword in the language.
static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts,
tok::TokenKind K) {
switch (K) {
#define KEYWORD(NAME, FLAGS) \
case tok::kw_##NAME: return getKeywordStatus(LangOpts, FLAGS);
#include "clang/Basic/TokenKinds.def"
default: return KS_Disabled;
}
}
/// Returns true if the identifier represents a keyword in the
/// specified language.
bool IdentifierInfo::isKeyword(const LangOptions &LangOpts) const {
switch (getTokenKwStatus(LangOpts, getTokenID())) {
case KS_Enabled:
case KS_Extension:
return true;
default:
return false;
}
}
/// Returns true if the identifier represents a C++ keyword in the
/// specified language.
bool IdentifierInfo::isCPlusPlusKeyword(const LangOptions &LangOpts) const {
if (!LangOpts.CPlusPlus || !isKeyword(LangOpts))
return false;
// This is a C++ keyword if this identifier is not a keyword when checked
// using LangOptions without C++ support.
LangOptions LangOptsNoCPP = LangOpts;
LangOptsNoCPP.CPlusPlus = false;
LangOptsNoCPP.CPlusPlus11 = false;
LangOptsNoCPP.CPlusPlus2a = false;
return !isKeyword(LangOptsNoCPP);
}
tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
// We use a perfect hash function here involving the length of the keyword,
// the first and third character. For preprocessor ID's there are no
// collisions (if there were, the switch below would complain about duplicate
// case values). Note that this depends on 'if' being null terminated.
#define HASH(LEN, FIRST, THIRD) \
(LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
#define CASE(LEN, FIRST, THIRD, NAME) \
case HASH(LEN, FIRST, THIRD): \
return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
unsigned Len = getLength();
if (Len < 2) return tok::pp_not_keyword;
const char *Name = getNameStart();
switch (HASH(Len, Name[0], Name[2])) {
default: return tok::pp_not_keyword;
CASE( 2, 'i', '\0', if);
CASE( 4, 'e', 'i', elif);
CASE( 4, 'e', 's', else);
CASE( 4, 'l', 'n', line);
CASE( 4, 's', 'c', sccs);
CASE( 5, 'e', 'd', endif);
CASE( 5, 'e', 'r', error);
CASE( 5, 'i', 'e', ident);
CASE( 5, 'i', 'd', ifdef);
CASE( 5, 'u', 'd', undef);
CASE( 6, 'a', 's', assert);
CASE( 6, 'd', 'f', define);
CASE( 6, 'i', 'n', ifndef);
CASE( 6, 'i', 'p', import);
CASE( 6, 'p', 'a', pragma);
CASE( 7, 'd', 'f', defined);
CASE( 7, 'i', 'c', include);
CASE( 7, 'w', 'r', warning);
CASE( 8, 'u', 'a', unassert);
CASE(12, 'i', 'c', include_next);
CASE(14, '_', 'p', __public_macro);
CASE(15, '_', 'p', __private_macro);
CASE(16, '_', 'i', __include_macros);
#undef CASE
#undef HASH
}
}
//===----------------------------------------------------------------------===//
// Stats Implementation
//===----------------------------------------------------------------------===//
/// PrintStats - Print statistics about how well the identifier table is doing
/// at hashing identifiers.
void IdentifierTable::PrintStats() const {
unsigned NumBuckets = HashTable.getNumBuckets();
unsigned NumIdentifiers = HashTable.getNumItems();
unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
unsigned AverageIdentifierSize = 0;
unsigned MaxIdentifierLength = 0;
// TODO: Figure out maximum times an identifier had to probe for -stats.
for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
unsigned IdLen = I->getKeyLength();
AverageIdentifierSize += IdLen;
if (MaxIdentifierLength < IdLen)
MaxIdentifierLength = IdLen;
}
fprintf(stderr, "\n*** Identifier Table Stats:\n");
fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers);
fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
NumIdentifiers/(double)NumBuckets);
fprintf(stderr, "Ave identifier length: %f\n",
(AverageIdentifierSize/(double)NumIdentifiers));
fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
// Compute statistics about the memory allocated for identifiers.
HashTable.getAllocator().PrintStats();
}
//===----------------------------------------------------------------------===//
// SelectorTable Implementation
//===----------------------------------------------------------------------===//
unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
}
namespace clang {
/// MultiKeywordSelector - One of these variable length records is kept for each
/// selector containing more than one keyword. We use a folding set
/// to unique aggregate names (keyword selectors in ObjC parlance). Access to
/// this class is provided strictly through Selector.
class MultiKeywordSelector
: public DeclarationNameExtra, public llvm::FoldingSetNode {
MultiKeywordSelector(unsigned nKeys) {
ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
}
public:
// Constructor for keyword selectors.
MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) {
assert((nKeys > 1) && "not a multi-keyword selector");
ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
// Fill in the trailing keyword array.
IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1);
for (unsigned i = 0; i != nKeys; ++i)
KeyInfo[i] = IIV[i];
}
// getName - Derive the full selector name and return it.
std::string getName() const;
unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; }
using keyword_iterator = IdentifierInfo *const *;
keyword_iterator keyword_begin() const {
return reinterpret_cast<keyword_iterator>(this+1);
}
keyword_iterator keyword_end() const {
return keyword_begin()+getNumArgs();
}
IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
return keyword_begin()[i];
}
static void Profile(llvm::FoldingSetNodeID &ID,
keyword_iterator ArgTys, unsigned NumArgs) {
ID.AddInteger(NumArgs);
for (unsigned i = 0; i != NumArgs; ++i)
ID.AddPointer(ArgTys[i]);
}
void Profile(llvm::FoldingSetNodeID &ID) {
Profile(ID, keyword_begin(), getNumArgs());
}
};
} // namespace clang.
unsigned Selector::getNumArgs() const {
unsigned IIF = getIdentifierInfoFlag();
if (IIF <= ZeroArg)
return 0;
if (IIF == OneArg)
return 1;
// We point to a MultiKeywordSelector.
MultiKeywordSelector *SI = getMultiKeywordSelector();
return SI->getNumArgs();
}
IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
if (getIdentifierInfoFlag() < MultiArg) {
assert(argIndex == 0 && "illegal keyword index");
return getAsIdentifierInfo();
}
// We point to a MultiKeywordSelector.
MultiKeywordSelector *SI = getMultiKeywordSelector();
return SI->getIdentifierInfoForSlot(argIndex);
}
StringRef Selector::getNameForSlot(unsigned int argIndex) const {
IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
return II? II->getName() : StringRef();
}
std::string MultiKeywordSelector::getName() const {
SmallString<256> Str;
llvm::raw_svector_ostream OS(Str);
for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
if (*I)
OS << (*I)->getName();
OS << ':';
}
return OS.str();
}
std::string Selector::getAsString() const {
if (InfoPtr == 0)
return "<null selector>";
if (getIdentifierInfoFlag() < MultiArg) {
IdentifierInfo *II = getAsIdentifierInfo();
if (getNumArgs() == 0) {
assert(II && "If the number of arguments is 0 then II is guaranteed to "
"not be null.");
return II->getName();
}
if (!II)
return ":";
return II->getName().str() + ":";
}
// We have a multiple keyword selector.
return getMultiKeywordSelector()->getName();
}
void Selector::print(llvm::raw_ostream &OS) const {
OS << getAsString();
}
/// Interpreting the given string using the normal CamelCase
/// conventions, determine whether the given string starts with the
/// given "word", which is assumed to end in a lowercase letter.
static bool startsWithWord(StringRef name, StringRef word) {
if (name.size() < word.size()) return false;
return ((name.size() == word.size() || !isLowercase(name[word.size()])) &&
name.startswith(word));
}
ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
if (!first) return OMF_None;
StringRef name = first->getName();
if (sel.isUnarySelector()) {
if (name == "autorelease") return OMF_autorelease;
if (name == "dealloc") return OMF_dealloc;
if (name == "finalize") return OMF_finalize;
if (name == "release") return OMF_release;
if (name == "retain") return OMF_retain;
if (name == "retainCount") return OMF_retainCount;
if (name == "self") return OMF_self;
if (name == "initialize") return OMF_initialize;
}
if (name == "performSelector" || name == "performSelectorInBackground" ||
name == "performSelectorOnMainThread")
return OMF_performSelector;
// The other method families may begin with a prefix of underscores.
while (!name.empty() && name.front() == '_')
name = name.substr(1);
if (name.empty()) return OMF_None;
switch (name.front()) {
case 'a':
if (startsWithWord(name, "alloc")) return OMF_alloc;
break;
case 'c':
if (startsWithWord(name, "copy")) return OMF_copy;
break;
case 'i':
if (startsWithWord(name, "init")) return OMF_init;
break;
case 'm':
if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
break;
case 'n':
if (startsWithWord(name, "new")) return OMF_new;
break;
default:
break;
}
return OMF_None;
}
ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) {
IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
if (!first) return OIT_None;
StringRef name = first->getName();
if (name.empty()) return OIT_None;
switch (name.front()) {
case 'a':
if (startsWithWord(name, "array")) return OIT_Array;
break;
case 'd':
if (startsWithWord(name, "default")) return OIT_ReturnsSelf;
if (startsWithWord(name, "dictionary")) return OIT_Dictionary;
break;
case 's':
if (startsWithWord(name, "shared")) return OIT_ReturnsSelf;
if (startsWithWord(name, "standard")) return OIT_Singleton;
break;
case 'i':
if (startsWithWord(name, "init")) return OIT_Init;
default:
break;
}
return OIT_None;
}
ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) {
IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
if (!first) return SFF_None;
StringRef name = first->getName();
switch (name.front()) {
case 'a':
if (name == "appendFormat") return SFF_NSString;
break;
case 'i':
if (name == "initWithFormat") return SFF_NSString;
break;
case 'l':
if (name == "localizedStringWithFormat") return SFF_NSString;
break;
case 's':
if (name == "stringByAppendingFormat" ||
name == "stringWithFormat") return SFF_NSString;
break;
}
return SFF_None;
}
namespace {
struct SelectorTableImpl {
llvm::FoldingSet<MultiKeywordSelector> Table;
llvm::BumpPtrAllocator Allocator;
};
} // namespace
static SelectorTableImpl &getSelectorTableImpl(void *P) {
return *static_cast<SelectorTableImpl*>(P);
}
SmallString<64>
SelectorTable::constructSetterName(StringRef Name) {
SmallString<64> SetterName("set");
SetterName += Name;
SetterName[3] = toUppercase(SetterName[3]);
return SetterName;
}
Selector
SelectorTable::constructSetterSelector(IdentifierTable &Idents,
SelectorTable &SelTable,
const IdentifierInfo *Name) {
IdentifierInfo *SetterName =
&Idents.get(constructSetterName(Name->getName()));
return SelTable.getUnarySelector(SetterName);
}
size_t SelectorTable::getTotalMemory() const {
SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
return SelTabImpl.Allocator.getTotalMemory();
}
Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
if (nKeys < 2)
return Selector(IIV[0], nKeys);
SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
// Unique selector, to guarantee there is one per name.
llvm::FoldingSetNodeID ID;
MultiKeywordSelector::Profile(ID, IIV, nKeys);
void *InsertPos = nullptr;
if (MultiKeywordSelector *SI =
SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
return Selector(SI);
// MultiKeywordSelector objects are not allocated with new because they have a
// variable size array (for parameter types) at the end of them.
unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
MultiKeywordSelector *SI =
(MultiKeywordSelector *)SelTabImpl.Allocator.Allocate(
Size, alignof(MultiKeywordSelector));
new (SI) MultiKeywordSelector(nKeys, IIV);
SelTabImpl.Table.InsertNode(SI, InsertPos);
return Selector(SI);
}
SelectorTable::SelectorTable() {
Impl = new SelectorTableImpl();
}
SelectorTable::~SelectorTable() {
delete &getSelectorTableImpl(Impl);
}
const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
switch (Operator) {
case OO_None:
case NUM_OVERLOADED_OPERATORS:
return nullptr;
#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
case OO_##Name: return Spelling;
#include "clang/Basic/OperatorKinds.def"
}
llvm_unreachable("Invalid OverloadedOperatorKind!");
}
StringRef clang::getNullabilitySpelling(NullabilityKind kind,
bool isContextSensitive) {
switch (kind) {
case NullabilityKind::NonNull:
return isContextSensitive ? "nonnull" : "_Nonnull";
case NullabilityKind::Nullable:
return isContextSensitive ? "nullable" : "_Nullable";
case NullabilityKind::Unspecified:
return isContextSensitive ? "null_unspecified" : "_Null_unspecified";
}
llvm_unreachable("Unknown nullability kind.");
}
| [
"[email protected]"
] | |
da31735876bffe91848fabb58d01bca37453a174 | fcb11ed067ca203932f930facb608e4a07824112 | /series5.cpp | cb814ccf6b5cbbefc393b33f4d1027f8ca52fbf2 | [] | no_license | debjyotigorai/Cpp | 8891a7cdb813ae52a67667a04c80658f1374281f | 19f35c3e64b480471cac0658713cb32d9213aa04 | refs/heads/master | 2021-06-28T01:31:01.889120 | 2019-02-06T16:08:53 | 2019-02-06T16:08:53 | 100,121,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 455 | cpp | //1 - x^2 + x^3 - x^4 + ...
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
long long int i, x, sum=1, n;
cout << "Enter the value of x : ";
cin >> x;
cout << "Enter the range : ";
cin >> n;
cout << "1";
for (i=2; i<=n; i++)
{
int z=pow(-1,i+1);
if (z<0)
cout << " - ";
else
cout << " + ";
if (i==n)
cout << x << "^5 ";
else
cout << x << "^" << i;
sum+=(z)*(pow(x,i));
}
cout << " = " << sum;
}
| [
"[email protected]"
] | |
b807966f3409def6e402e0f4154383a68f8e5e97 | b21b07fc237a764474eb9995783c1b714356bf5f | /src/Xyz/SimplexNoise.cpp | d605c33842509507b55cb3da1b68390f4969d9a0 | [
"BSD-2-Clause"
] | permissive | jebreimo/Xyz | a26b7d93fbb112ebf6c13369c16313db82b68550 | 2f3a6773345c28ad2925e24e89cab296561b42c5 | refs/heads/master | 2023-08-31T03:10:18.086392 | 2023-08-20T14:46:15 | 2023-08-20T14:46:15 | 48,961,224 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,995 | cpp | //****************************************************************************
// Copyright © 2022 Jan Erik Breimo. All rights reserved.
// Created by Jan Erik Breimo on 2022-05-07.
//
// This file is distributed under the BSD License.
// License text is included with the source distribution.
//****************************************************************************
#include "Xyz/SimplexNoise.hpp"
#include <algorithm>
// Copied (and slightly adapted)
// from https://gist.github.com/Flafla2/f0260a861be0ebdeef76
namespace
{
// Hash lookup table as defined by Ken SimplexNoise. This is a randomly
// arranged array of all numbers from 0-255 inclusive.
uint8_t PERMUTATION[256] = {
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233,
7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10,
23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252,
219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87,
174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48,
27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230,
220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25,
63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,
200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186,
3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126,
255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189,
28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70,
221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98,
108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228,
251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51,
145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236,
205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66,
215, 61, 156, 180
};
double gradient(int hash, double x, double y, double z)
{
switch (hash & 0xF)
{
case 0x0: return x + y;
case 0x1: return -x + y;
case 0x2: return x - y;
case 0x3: return -x - y;
case 0x4: return x + z;
case 0x5: return -x + z;
case 0x6: return x - z;
case 0x7: return -x - z;
case 0x8: return y + z;
case 0x9: return -y + z;
case 0xA: return y - z;
case 0xB: return -y - z;
case 0xC: return y + x;
case 0xD: return -y + z;
case 0xE: return y - x;
case 0xF: return -y - z;
default: return 0;
}
}
double fade(double t)
{
// Fade function as defined by Ken SimplexNoise. This eases coordinate
// values so that they will "ease" towards integral values.
// This ends up smoothing the final output.
return t * t * t * (t * (t * 6 - 15) + 10); // 6t^5 - 15t^4 + 10t^3
}
double lerp(double a, double b, double x)
{
return a + x * (b - a);
}
}
SimplexNoise::SimplexNoise()
{
std::copy(std::begin(PERMUTATION), std::end(PERMUTATION),
permutation_);
std::copy(std::begin(PERMUTATION), std::end(PERMUTATION),
permutation_ + 256);
}
double SimplexNoise::simplex(double x, double y, double z)
{
// Calculate the "unit cube" that the point asked will be located in.
// The left bound is ( |_x_|,|_y_|,|_z_| ) and the right bound is that
// plus 1. Next we calculate the location (from 0.0 to 1.0) in that cube.
// We also fade the location to smooth the result.
int xi = int(x) & 255;
int yi = int(y) & 255;
int zi = int(z) & 255;
double xf = x - int(x);
double yf = y - int(y);
double zf = z - int(z);
double u = fade(xf);
double v = fade(yf);
double w = fade(zf);
int aaa, aba, aab, abb, baa, bba, bab, bbb;
aaa = permutation_[permutation_[permutation_[xi] + yi] + zi];
aba = permutation_[permutation_[permutation_[xi] + ++yi] + zi];
aab = permutation_[permutation_[permutation_[xi] + yi] + ++zi];
abb = permutation_[permutation_[permutation_[xi] + ++yi] + ++zi];
baa = permutation_[permutation_[permutation_[++xi] + yi] + zi];
bba = permutation_[permutation_[permutation_[++xi] + ++yi] + zi];
bab = permutation_[permutation_[permutation_[++xi] + yi] + ++zi];
bbb = permutation_[permutation_[permutation_[++xi] + ++yi] + ++zi];
double x1, x2, y1, y2;
// The gradient function calculates the dot product between a pseudorandom
// gradient vector and the vector from the input coordinate to the 8
// surrounding points in its unit cube.
x1 = lerp(gradient(aaa, xf, yf, zf),
gradient(baa, xf - 1, yf, zf),
u);
// This is all then lerped together as a sort of weighted average based on
// the faded (u,v,w) values we made earlier.
x2 = lerp(gradient(aba, xf, yf - 1, zf),
gradient(bba, xf - 1, yf - 1, zf),
u);
y1 = lerp(x1, x2, v);
x1 = lerp(gradient(aab, xf, yf, zf - 1),
gradient(bab, xf - 1, yf, zf - 1),
u);
x2 = lerp(gradient(abb, xf, yf - 1, zf - 1),
gradient(bbb, xf - 1, yf - 1, zf - 1),
u);
y2 = lerp(x1, x2, v);
// For convenience, we reduce it to 0 - 1 (theoretical min/max before
// is -1 - 1)
return (lerp(y1, y2, w) + 1) / 2;
}
double SimplexNoise::simplex(double x, double y, double z,
int octaves, double persistence)
{
double total = 0;
double frequency = 1;
double amplitude = 1;
double max_value = 0;
for (int i = 0; i < octaves; i++)
{
total += simplex(x * frequency, y * frequency, z * frequency)
* amplitude;
max_value += amplitude;
amplitude *= persistence;
frequency *= 2;
}
return total / max_value;
}
| [
"[email protected]"
] | |
a4b0f42c09efa2ae00be3b45fa8c4aee80eac3e7 | 575731c1155e321e7b22d8373ad5876b292b0b2f | /examples/native/ios/Pods/boost-for-react-native/boost/metaparse/v1/impl/push_back_c.hpp | c6868c0dc16cb49fd78c00b976ceed9edb14fad6 | [
"BSL-1.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Nozbe/zacs | 802a84ffd47413a1687a573edda519156ca317c7 | c3d455426bc7dfb83e09fdf20781c2632a205c04 | refs/heads/master | 2023-06-12T20:53:31.482746 | 2023-06-07T07:06:49 | 2023-06-07T07:06:49 | 201,777,469 | 432 | 10 | MIT | 2023-01-24T13:29:34 | 2019-08-11T14:47:50 | JavaScript | UTF-8 | C++ | false | false | 1,027 | hpp | #ifndef BOOST_METAPARSE_V1_PUSH_BACK_C_HPP
#define BOOST_METAPARSE_V1_PUSH_BACK_C_HPP
// Copyright Abel Sinkovics ([email protected]) 2013.
// 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)
#include <boost/metaparse/config.hpp>
#include <boost/metaparse/v1/fwd/string.hpp>
#include <boost/metaparse/v1/impl/update_c.hpp>
#include <boost/metaparse/v1/impl/size.hpp>
namespace boost
{
namespace metaparse
{
namespace v1
{
namespace impl
{
template <class S, char C>
struct push_back_c;
#ifdef BOOST_METAPARSE_VARIADIC_STRING
template <char... Cs, char C>
struct push_back_c<string<Cs...>, C> : string<Cs..., C> {};
#else
template <class S, char C>
struct push_back_c :
update_c<typename S::type, size<typename S::type>::type::value, C>
{};
#endif
}
}
}
}
#endif
| [
"[email protected]"
] | |
e5da24000808179faf59b1240f2745fd73190189 | 129136fed2665b6554223cb95407b1bbb7c421e2 | /Programming/1-2_sem/Qsort_opt/Qsort_opt.cpp | 61fe73c950928a8237e6ccb996816d7ad125f5f5 | [] | no_license | PotapovaSofia/DIHT-MIPT | e28f62c3ef91137d86ee8585ad4daefb1930a890 | aef75ac5154d22ce0e424b3874bf15bae779fbf0 | refs/heads/master | 2016-09-05T16:44:46.501488 | 2016-02-20T21:46:23 | 2016-02-20T21:46:23 | 32,089,336 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,077 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void generation(int* Arr, int n)
{
int i;
srand(time(NULL));
for ( i=0;i<n;++i)
{
Arr[i] = rand()%100 - 50;
printf("%d ", Arr[i]);
}
printf("\n");
}
int cmp_(void* a, void* b){
return (*(int*)a - *(int*)b);
}
void swap(void* a, void* b, size_t size)
{
char* x = (char*)(malloc(size));
memcpy(x, a, size);
memcpy(a, b, size);
memcpy(b, x, size);
free(x);
}
void QuickSort ( void* Arr, int first, int last, size_t size, int(*cmp)(void*, void*))
{
if ((last - first) > 10)
{
int i, j;
i = first;
j = last;
int key = (rand() % last + first) % last;
char *buf = (char*)malloc(size);
memcpy(buf, (char*)Arr + key*size, size);
do {
while (cmp((char*)Arr + i*size, buf) < 0) i++;
while (cmp((char*)Arr + j*size, buf) > 0) j--;
if(i <= j) {
if (i < j) swap((char*)Arr + i*size, (char*)Arr + j*size, size);
i++;
j--;
}
} while (i <= j);
if (i < last)
QuickSort(Arr, i, last, size, cmp);
if (first < j)
QuickSort(Arr, first,j, size, cmp);
}
}
void InsertSort(void* a, int n, size_t size, int(*cmp)(void*, void*))
{
int i;
for (i = 1; i < n; ++i)
{
char* key = (char*)(malloc(size));
memcpy(key, (char*)a + i* size, size);
int j = i - 1;
while ((j >= 0) && (cmp((char*)a + j * size, key) > 0))
{
swap((char*)a + j*size, (char*)a + (j + 1) * size, size);
j--;
}
memcpy((char*)a + (j + 1) * size, key, size);
}
}
int main()
{
int i, n;
printf("Number: ");
scanf("%d", &n);
printf ("\n");
int* Arr = (int*)(malloc(sizeof(int)*n));
generation(Arr, n);
int(*p)(void*, void*);
p = cmp_;
QuickSort(Arr, 0, n - 1, sizeof(int), p);
InsertSort(Arr, n, sizeof(int), p);
for (i = 0; i < n; ++i)
{
printf("%d ", Arr[i]);
}
free(Arr);
return 0;
}
| [
"[email protected]"
] | |
288230e9c8d07e65f331be84dae3541bd8429c30 | c26b2d68eab6ce8a7bcabaa61a0edcf067362aea | /vz03/src/herbivora.h | bb867b5ce4aa6e64988ea2e29cc49c33f213e8af | [] | no_license | reiva5/oop | b810f4c75f209eef631c2cf2cd26dfad284cd236 | 465c6075f2d2f16221c482bae9dbb4117c4a6398 | refs/heads/master | 2020-12-10T04:28:46.077254 | 2017-03-15T06:36:02 | 2017-03-15T06:36:02 | 83,626,249 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 419 | h | #ifndef HERBIVORA_H
#define HREBIVORA_H
#include "pemakan.h"
/** @class Herbivora
* Kelas Herbivora menyimpan informasi makanan berupa tumbuhan
*/
class Herbivora: public Pemakan {
public:
/** @brief Setter tumbuhan
* @param n Jumlah tumbuhan yang diinginkan
*/
void SetAmount(int n);
/** @brief Getter tumbuhan
* @return tumbuhan
*/
int GetAmount();
protected:
int tumbuhan;
};
#endif | [
"[email protected]"
] | |
4c77e1da3e9e85add1f524b0e0252ea9224f9fd9 | d1e81fa4e8a54b5d5e0e4f85adb79971a8d3b4dd | /TFTTest/TftTest1/UTFT.cpp | 5854898716af44b286f7a598c26aa16e0cbbacfa | [] | no_license | SimonBlasen/Arduino | 8fd753d7c5075765a52b7d2b54e78a69c77886d9 | 623ecd8869231549871795730fa2c96452493d17 | refs/heads/master | 2023-07-06T23:21:55.518542 | 2023-07-02T13:08:47 | 2023-07-02T13:08:47 | 99,805,226 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,687 | cpp | /*
UTFT.cpp - Arduino/chipKit library support for Color TFT LCD Boards
Copyright (C)2010-2014 Henning Karlsen. All right reserved
This library is the continuation of my ITDB02_Graph, ITDB02_Graph16
and RGB_GLCD libraries for Arduino and chipKit. As the number of
supported display modules and controllers started to increase I felt
it was time to make a single, universal library as it will be much
easier to maintain in the future.
Basic functionality of this library was origianlly based on the
demo-code provided by ITead studio (for the ITDB02 modules) and
NKC Electronics (for the RGB GLCD module/shield).
This library supports a number of 8bit, 16bit and serial graphic
displays, and will work with both Arduino and chipKit boards. For a
full list of tested display modules and controllers, see the
document UTFT_Supported_display_modules_&_controllers.pdf.
When using 8bit and 16bit display modules there are some
requirements you must adhere to. These requirements can be found
in the document UTFT_Requirements.pdf.
There are no special requirements when using serdial displays.
You can always find the latest version of the library at
http://electronics.henningkarlsen.com/
http://www.buydisplay.com
If you make any modifications or improvements to the code, I would
appreciate that you share the code with me so that I might include
it in the next release. I can be contacted through
http://electronics.henningkarlsen.com/contact.php.
This library is free software; you can redistribute it and/or
modify it under the terms of the CC BY-NC-SA 3.0 license.
Please see the included documents for further information.
Commercial use of this library requires you to buy a license that
will allow commercial use. This includes using the library,
modified or not, as a tool to sell products.
The license applies to all part of the library including the
examples and tools supplied with the library.
*/
#include "UTFT.h"
#include <pins_arduino.h>
// Include hardware-specific functions for the correct MCU
#if defined(__AVR__)
#include <avr/pgmspace.h>
#include "hardware/avr/HW_AVR.h"
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#include "hardware/avr/HW_ATmega1280.h"
#elif defined(__AVR_ATmega328P__)
#include "hardware/avr/HW_ATmega328P.h"
#elif defined(__AVR_ATmega32U4__)
#include "hardware/avr/HW_ATmega32U4.h"
#elif defined(__AVR_ATmega168__)
#error "ATmega168 MCUs are not supported because they have too little flash memory!"
#elif defined(__AVR_ATmega1284P__)
#include "hardware/avr/HW_ATmega1284P.h"
#else
#error "Unsupported AVR MCU!"
#endif
#elif defined(__PIC32MX__)
#include "hardware/pic32/HW_PIC32.h"
#if defined(__32MX320F128H__)
#pragma message("Compiling for chipKIT UNO32 (PIC32MX320F128H)")
#include "hardware/pic32/HW_PIC32MX320F128H.h"
#elif defined(__32MX340F512H__)
#pragma message("Compiling for chipKIT uC32 (PIC32MX340F512H)")
#include "hardware/pic32/HW_PIC32MX340F512H.h"
#elif defined(__32MX795F512L__)
#pragma message("Compiling for chipKIT MAX32 (PIC32MX795F512L)")
#include "hardware/pic32/HW_PIC32MX795F512L.h"
#else
#error "Unsupported PIC32 MCU!"
#endif
#elif defined(__arm__)
#include "hardware/arm/HW_ARM.h"
#if defined(__SAM3X8E__)
#pragma message("Compiling for Arduino Due (AT91SAM3X8E)...")
#include "hardware/arm/HW_SAM3X8E.h"
#elif defined(__MK20DX128__) || defined(__MK20DX256__)
#pragma message("Compiling for Teensy 3.x (MK20DX128VLH7 / MK20DX256VLH7)...")
#include "hardware/arm/HW_MX20DX256.h"
#else
#error "Unsupported ARM MCU!"
#endif
#endif
#include "memorysaver.h"
UTFT::UTFT()
{
}
UTFT::UTFT(byte model, int RS, int WR, int CS, int RST, int SER)
{
word dsx[] = {239, 239, 239, 239, 239, 239, 175, 175, 239, 127, 127, 239, 271, 479, 239, 239, 239, 0, 0, 239, 479, 319, 239, 175, 127, 239, 239, 319, 319, 799, 127, 127, 239, 239, 319, 319, 319, 319, 127};
word dsy[] = {319, 399, 319, 319, 319, 319, 219, 219, 399, 159, 127, 319, 479, 799, 319, 319, 319, 0, 0, 319, 799, 479, 319, 219, 159, 319, 319, 479, 479, 479, 159, 159, 319, 319, 479, 239, 239, 239, 159};
byte dtm[] = {16, 16, 16, 8, 8, 16, 8, SERIAL_4PIN, 16, SERIAL_5PIN, SERIAL_5PIN, 16, 16, 16, 8, 16, LATCHED_16, 0, 0, 8, 16, 16, 16, 8, SERIAL_5PIN, SERIAL_5PIN, SERIAL_4PIN, 16, 16, 16, SERIAL_5PIN, SERIAL_5PIN, 8, 16, 16, 16, SERIAL_5PIN, SERIAL_4PIN, SERIAL_5PIN};
disp_x_size = dsx[model];
disp_y_size = dsy[model];
display_transfer_mode = dtm[model];
display_model = model;
__p1 = RS;
__p2 = WR;
__p3 = CS;
__p4 = RST;
__p5 = SER;
if (display_transfer_mode == SERIAL_4PIN)
{
display_transfer_mode=1;
display_serial_mode=SERIAL_4PIN;
}
if (display_transfer_mode == SERIAL_5PIN)
{
display_transfer_mode=1;
display_serial_mode=SERIAL_5PIN;
}
if (display_transfer_mode!=1)
{
_set_direction_registers(display_transfer_mode);
P_RS = portOutputRegister(digitalPinToPort(RS));
B_RS = digitalPinToBitMask(RS);
P_WR = portOutputRegister(digitalPinToPort(WR));
B_WR = digitalPinToBitMask(WR);
P_CS = portOutputRegister(digitalPinToPort(CS));
B_CS = digitalPinToBitMask(CS);
P_RST = portOutputRegister(digitalPinToPort(RST));
B_RST = digitalPinToBitMask(RST);
if (display_transfer_mode==LATCHED_16)
{
P_ALE = portOutputRegister(digitalPinToPort(SER));
B_ALE = digitalPinToBitMask(SER);
cbi(P_ALE, B_ALE);
pinMode(8,OUTPUT);
digitalWrite(8, LOW);
}
}
else
{
P_SDA = portOutputRegister(digitalPinToPort(RS));
B_SDA = digitalPinToBitMask(RS);
P_SCL = portOutputRegister(digitalPinToPort(WR));
B_SCL = digitalPinToBitMask(WR);
P_CS = portOutputRegister(digitalPinToPort(CS));
B_CS = digitalPinToBitMask(CS);
if (RST != NOTINUSE)
{
P_RST = portOutputRegister(digitalPinToPort(RST));
B_RST = digitalPinToBitMask(RST);
}
if (display_serial_mode!=SERIAL_4PIN)
{
P_RS = portOutputRegister(digitalPinToPort(SER));
B_RS = digitalPinToBitMask(SER);
}
}
}
void UTFT::LCD_Write_COM(char VL)
{
if (display_transfer_mode!=1)
{
cbi(P_RS, B_RS);
LCD_Writ_Bus(0x00,VL,display_transfer_mode);
}
else
LCD_Writ_Bus(0x00,VL,display_transfer_mode);
}
void UTFT::LCD_Write_DATA(char VH,char VL)
{
if (display_transfer_mode!=1)
{ if(display_transfer_mode==16)
{sbi(P_RS, B_RS);
LCD_Writ_Bus(VH,VL,display_transfer_mode);
}
else if(display_transfer_mode==8)
{sbi(P_RS, B_RS);
LCD_Writ_Bus(0x00,VH,display_transfer_mode);
LCD_Writ_Bus(0x00,VL,display_transfer_mode);
}
}
else
{
LCD_Writ_Bus(0x01,VH,display_transfer_mode);
LCD_Writ_Bus(0x01,VL,display_transfer_mode);
}
}
void UTFT::LCD_Write_DATA(char VL)
{
if (display_transfer_mode!=1)
{
sbi(P_RS, B_RS);
LCD_Writ_Bus(0x00,VL,display_transfer_mode);
}
else
LCD_Writ_Bus(0x01,VL,display_transfer_mode);
}
void UTFT::LCD_Write_COM_DATA(char com1,int dat1)
{
LCD_Write_COM(com1);
LCD_Write_DATA(dat1>>8,dat1);
}
void UTFT::InitLCD(byte orientation)
{
orient=orientation;
_hw_special_init();
pinMode(__p1,OUTPUT);
pinMode(__p2,OUTPUT);
pinMode(__p3,OUTPUT);
if (__p4 != NOTINUSE)
pinMode(__p4,OUTPUT);
if ((display_transfer_mode==LATCHED_16) or ((display_transfer_mode==1) and (display_serial_mode==SERIAL_5PIN)))
pinMode(__p5,OUTPUT);
if (display_transfer_mode!=1)
_set_direction_registers(display_transfer_mode);
sbi(P_RST, B_RST);
delay(5);
cbi(P_RST, B_RST);
delay(15);
sbi(P_RST, B_RST);
delay(15);
cbi(P_CS, B_CS);
switch(display_model)
{
/*#ifndef DISABLE_HX8347A
#include "tft_drivers/hx8347a/initlcd.h"
#endif
#ifndef DISABLE_ILI9327
#include "tft_drivers/ili9327/initlcd.h"
#endif
#ifndef DISABLE_SSD1289
#include "tft_drivers/ssd1289/initlcd.h"
#endif
#ifndef DISABLE_ILI9325C
#include "tft_drivers/ili9325c/initlcd.h"
#endif
#ifndef DISABLE_ILI9325D
#include "tft_drivers/ili9325d/default/initlcd.h"
#endif
#ifndef DISABLE_ILI9325D_ALT
#include "tft_drivers/ili9325d/alt/initlcd.h"
#endif
#ifndef DISABLE_HX8340B_8
#include "tft_drivers/hx8340b/8/initlcd.h"
#endif
#ifndef DISABLE_HX8340B_S
#include "tft_drivers/hx8340b/s/initlcd.h"
#endif
#ifndef DISABLE_ST7735
#include "tft_drivers/st7735/std/initlcd.h"
#endif
#ifndef DISABLE_ST7735_ALT
#include "tft_drivers/st7735/alt/initlcd.h"
#endif
#ifndef DISABLE_PCF8833
#include "tft_drivers/pcf8833/initlcd.h"
#endif
#ifndef DISABLE_S1D19122
#include "tft_drivers/s1d19122/initlcd.h"
#endif
#ifndef DISABLE_HX8352A
#include "tft_drivers/hx8352a/initlcd.h"
#endif*/
#ifndef DISABLE_SSD1963_480
#include "tft_drivers/ssd1963/480/initlcd.h"
#endif
#ifndef DISABLE_SSD1963_800
#include "tft_drivers/ssd1963/800/initlcd.h"
#endif
#ifndef DISABLE_SSD1963_800_ALT
#include "tft_drivers/ssd1963/800alt/initlcd.h"
#endif
/*#ifndef DISABLE_S6D1121
#include "tft_drivers/s6d1121/initlcd.h"
#endif
#ifndef DISABLE_ILI9481
#include "tft_drivers/ili9481/initlcd.h"
#endif
#ifndef DISABLE_S6D0164
#include "tft_drivers/s6d0164/initlcd.h"
#endif
#ifndef DISABLE_ST7735S
#include "tft_drivers/st7735s/initlcd.h"
#endif*/
#ifndef DISABLE_ILI9341_S4P
#include "tft_drivers/ili9341/s4p/initlcd.h"
#endif
#ifndef DISABLE_ILI9341_S5P
#include "tft_drivers/ili9341/s5p/initlcd.h"
#endif
/*#ifndef DISABLE_R61581
#include "tft_drivers/r61581/initlcd.h"
#endif
#ifndef DISABLE_ILI9486
#include "tft_drivers/ili9486/initlcd.h"
#endif
#ifndef DISABLE_CPLD
#include "tft_drivers/cpld/initlcd.h"
#endif
#ifndef DISABLE_HX8353C
#include "tft_drivers/hx8353c/initlcd.h"
#endif*/
#ifndef DISABLE_ILI9341_8
#include "tft_drivers/ili9341/8B/initlcd.h"
#endif
#ifndef DISABLE_ILI9341_16
#include "tft_drivers/ili9341/16B/initlcd.h"
#endif
#ifndef DISABLE_ILI9488_16
#include "tft_drivers/ili9488/16B/initlcd.h"
#endif
#ifndef DISABLE_ILI9342_16
#include "tft_drivers/ili9342/16B/initlcd.h"
#endif
#ifndef DISABLE_ILI9342_S4P
#include "tft_drivers/ili9342/s4p/initlcd.h"
#endif
#ifndef DISABLE_ILI9342_S5P
#include "tft_drivers/ili9342/s5p/initlcd.h"
#endif
#ifndef DISABLE_ILI9163_S5P
#include "tft_drivers/ili9163/s5p/initlcd.h"
#endif
}
sbi (P_CS, B_CS);
setColor(255, 255, 255);
setBackColor(0, 0, 0);
cfont.font=0;
_transparent = false;
}
void UTFT::setXY(word x1, word y1, word x2, word y2)
{
if (orient==LANDSCAPE)
{
swap(word, x1, y1);
swap(word, x2, y2)
y1=disp_y_size-y1;
y2=disp_y_size-y2;
swap(word, y1, y2)
}
switch(display_model)
{
/*#ifndef DISABLE_HX8347A
#include "tft_drivers/hx8347a/setxy.h"
#endif
#ifndef DISABLE_HX8352A
#include "tft_drivers/hx8352a/setxy.h"
#endif
#ifndef DISABLE_ILI9327
#include "tft_drivers/ili9327/setxy.h"
#endif
#ifndef DISABLE_SSD1289
#include "tft_drivers/ssd1289/setxy.h"
#endif
#ifndef DISABLE_ILI9325C
#include "tft_drivers/ili9325c/setxy.h"
#endif
#ifndef DISABLE_ILI9325D
#include "tft_drivers/ili9325d/default/setxy.h"
#endif
#ifndef DISABLE_ILI9325D_ALT
#include "tft_drivers/ili9325d/alt/setxy.h"
#endif
#ifndef DISABLE_HX8340B_8
#include "tft_drivers/hx8340b/8/setxy.h"
#endif
#ifndef DISABLE_HX8340B_S
#include "tft_drivers/hx8340b/s/setxy.h"
#endif
#ifndef DISABLE_ST7735
#include "tft_drivers/st7735/std/setxy.h"
#endif
#ifndef DISABLE_ST7735_ALT
#include "tft_drivers/st7735/alt/setxy.h"
#endif
#ifndef DISABLE_S1D19122
#include "tft_drivers/s1d19122/setxy.h"
#endif*/
#ifndef DISABLE_PCF8833
#include "tft_drivers/pcf8833/setxy.h"
#endif
#ifndef DISABLE_SSD1963_480
#include "tft_drivers/ssd1963/480/setxy.h"
#endif
#ifndef DISABLE_SSD1963_800
#include "tft_drivers/ssd1963/800/setxy.h"
#endif
#ifndef DISABLE_SSD1963_800_ALT
#include "tft_drivers/ssd1963/800alt/setxy.h"
#endif
#ifndef DISABLE_S6D1121
#include "tft_drivers/s6d1121/setxy.h"
#endif
#ifndef DISABLE_ILI9481
#include "tft_drivers/ili9481/setxy.h"
#endif
#ifndef DISABLE_S6D0164
#include "tft_drivers/s6d0164/setxy.h"
#endif
#ifndef DISABLE_ST7735S
#include "tft_drivers/st7735s/setxy.h"
#endif
#ifndef DISABLE_ILI9341_S4P
#include "tft_drivers/ili9341/s4p/setxy.h"
#endif
#ifndef DISABLE_ILI9341_S5P
#include "tft_drivers/ili9341/s5p/setxy.h"
#endif
#ifndef DISABLE_R61581
#include "tft_drivers/r61581/setxy.h"
#endif
#ifndef DISABLE_ILI9486
#include "tft_drivers/ili9486/setxy.h"
#endif
#ifndef DISABLE_CPLD
#include "tft_drivers/cpld/setxy.h"
#endif
#ifndef DISABLE_HX8353C
#include "tft_drivers/hx8353c/setxy.h"
#endif
#ifndef DISABLE_ILI9341_8
#include "tft_drivers/ili9341/8B/setxy.h"
#endif
#ifndef DISABLE_ILI9341_16
#include "tft_drivers/ili9341/16B/setxy.h"
#endif
#ifndef DISABLE_ILI9488_16
#include "tft_drivers/ili9488/16B/setxy.h"
#endif
#ifndef DISABLE_ILI9342_16
#include "tft_drivers/ili9342/16B/setxy.h"
#endif
#ifndef DISABLE_ILI9342_S4P
#include "tft_drivers/ili9342/s4p/setxy.h"
#endif
#ifndef DISABLE_ILI9342_S5P
#include "tft_drivers/ili9342/s5p/setxy.h"
#endif
#ifndef DISABLE_ILI9163_S5P
#include "tft_drivers/ili9163/s5p/setxy.h"
#endif
}
}
void UTFT::clrXY()
{
if (orient==PORTRAIT)
setXY(0,0,disp_x_size,disp_y_size);
else
setXY(0,0,disp_y_size,disp_x_size);
}
void UTFT::drawRect(int x1, int y1, int x2, int y2)
{
if (x1>x2)
{
swap(int, x1, x2);
}
if (y1>y2)
{
swap(int, y1, y2);
}
drawHLine(x1, y1, x2-x1);
drawHLine(x1, y2, x2-x1);
drawVLine(x1, y1, y2-y1);
drawVLine(x2, y1, y2-y1);
}
void UTFT::drawRoundRect(int x1, int y1, int x2, int y2)
{
if (x1>x2)
{
swap(int, x1, x2);
}
if (y1>y2)
{
swap(int, y1, y2);
}
if ((x2-x1)>4 && (y2-y1)>4)
{
drawPixel(x1+1,y1+1);
drawPixel(x2-1,y1+1);
drawPixel(x1+1,y2-1);
drawPixel(x2-1,y2-1);
drawHLine(x1+2, y1, x2-x1-4);
drawHLine(x1+2, y2, x2-x1-4);
drawVLine(x1, y1+2, y2-y1-4);
drawVLine(x2, y1+2, y2-y1-4);
}
}
void UTFT::fillRect(int x1, int y1, int x2, int y2)
{
if (x1>x2)
{
swap(int, x1, x2);
}
if (y1>y2)
{
swap(int, y1, y2);
}
if (display_transfer_mode==16)
{
cbi(P_CS, B_CS);
setXY(x1, y1, x2, y2);
sbi(P_RS, B_RS);
_fast_fill_16(fch,fcl,((long(x2-x1)+1)*(long(y2-y1)+1)));
sbi(P_CS, B_CS);
}
else if ((display_transfer_mode==8) and (fch==fcl))
{
cbi(P_CS, B_CS);
setXY(x1, y1, x2, y2);
sbi(P_RS, B_RS);
_fast_fill_8(fch,((long(x2-x1)+1)*(long(y2-y1)+1)));
sbi(P_CS, B_CS);
}
else
{
if (orient==PORTRAIT)
{
for (int i=0; i<((y2-y1)/2)+1; i++)
{
drawHLine(x1, y1+i, x2-x1);
drawHLine(x1, y2-i, x2-x1);
}
}
else
{
for (int i=0; i<((x2-x1)/2)+1; i++)
{
drawVLine(x1+i, y1, y2-y1);
drawVLine(x2-i, y1, y2-y1);
}
}
}
}
void UTFT::fillRoundRect(int x1, int y1, int x2, int y2)
{
if (x1>x2)
{
swap(int, x1, x2);
}
if (y1>y2)
{
swap(int, y1, y2);
}
if ((x2-x1)>4 && (y2-y1)>4)
{
for (int i=0; i<((y2-y1)/2)+1; i++)
{
switch(i)
{
case 0:
drawHLine(x1+2, y1+i, x2-x1-4);
drawHLine(x1+2, y2-i, x2-x1-4);
break;
case 1:
drawHLine(x1+1, y1+i, x2-x1-2);
drawHLine(x1+1, y2-i, x2-x1-2);
break;
default:
drawHLine(x1, y1+i, x2-x1);
drawHLine(x1, y2-i, x2-x1);
}
}
}
}
void UTFT::drawCircle(int x, int y, int radius)
{
int f = 1 - radius;
int ddF_x = 1;
int ddF_y = -2 * radius;
int x1 = 0;
int y1 = radius;
cbi(P_CS, B_CS);
setXY(x, y + radius, x, y + radius);
LCD_Write_DATA(fch,fcl);
setXY(x, y - radius, x, y - radius);
LCD_Write_DATA(fch,fcl);
setXY(x + radius, y, x + radius, y);
LCD_Write_DATA(fch,fcl);
setXY(x - radius, y, x - radius, y);
LCD_Write_DATA(fch,fcl);
while(x1 < y1)
{
if(f >= 0)
{
y1--;
ddF_y += 2;
f += ddF_y;
}
x1++;
ddF_x += 2;
f += ddF_x;
setXY(x + x1, y + y1, x + x1, y + y1);
LCD_Write_DATA(fch,fcl);
setXY(x - x1, y + y1, x - x1, y + y1);
LCD_Write_DATA(fch,fcl);
setXY(x + x1, y - y1, x + x1, y - y1);
LCD_Write_DATA(fch,fcl);
setXY(x - x1, y - y1, x - x1, y - y1);
LCD_Write_DATA(fch,fcl);
setXY(x + y1, y + x1, x + y1, y + x1);
LCD_Write_DATA(fch,fcl);
setXY(x - y1, y + x1, x - y1, y + x1);
LCD_Write_DATA(fch,fcl);
setXY(x + y1, y - x1, x + y1, y - x1);
LCD_Write_DATA(fch,fcl);
setXY(x - y1, y - x1, x - y1, y - x1);
LCD_Write_DATA(fch,fcl);
}
sbi(P_CS, B_CS);
clrXY();
}
void UTFT::fillCircle(int x, int y, int radius)
{
for(int y1=-radius; y1<=0; y1++)
for(int x1=-radius; x1<=0; x1++)
if(x1*x1+y1*y1 <= radius*radius)
{
drawHLine(x+x1, y+y1, 2*(-x1));
drawHLine(x+x1, y-y1, 2*(-x1));
break;
}
}
void UTFT::clrScr()
{
long i;
cbi(P_CS, B_CS);
clrXY();
if (display_transfer_mode!=1)
sbi(P_RS, B_RS);
if (display_transfer_mode==16)
_fast_fill_16(0,0,((disp_x_size+1)*(disp_y_size+1)));
else if (display_transfer_mode==8)
_fast_fill_8(0,((disp_x_size+1)*(disp_y_size+1)));
else
{
for (i=0; i<((disp_x_size+1)*(disp_y_size+1)); i++)
{
if (display_transfer_mode!=1)
LCD_Writ_Bus(0,0,display_transfer_mode);
else
{
LCD_Writ_Bus(1,0,display_transfer_mode);
LCD_Writ_Bus(1,0,display_transfer_mode);
}
}
}
sbi(P_CS, B_CS);
}
void UTFT::fillScr(byte r, byte g, byte b)
{
word color = ((r&248)<<8 | (g&252)<<3 | (b&248)>>3);
fillScr(color);
}
void UTFT::fillScr(word color)
{
long i;
char ch, cl;
ch=byte(color>>8);
cl=byte(color & 0xFF);
cbi(P_CS, B_CS);
clrXY();
if (display_transfer_mode!=1)
sbi(P_RS, B_RS);
if (display_transfer_mode==16)
_fast_fill_16(ch,cl,((disp_x_size+1)*(disp_y_size+1)));
else if ((display_transfer_mode==8) and (ch==cl))
_fast_fill_8(ch,((disp_x_size+1)*(disp_y_size+1)));
else
{
for (i=0; i<((disp_x_size+1)*(disp_y_size+1)); i++)
{
if (display_transfer_mode!=1)
{ if(display_transfer_mode==16)
{
LCD_Writ_Bus(ch,cl,display_transfer_mode);
}
else
{
LCD_Writ_Bus(0x00,ch,display_transfer_mode);
LCD_Writ_Bus(0x00,cl,display_transfer_mode);
}
}
else
{
LCD_Writ_Bus(1,ch,display_transfer_mode);
LCD_Writ_Bus(1,cl,display_transfer_mode);
}
}
}
sbi(P_CS, B_CS);
}
void UTFT::setColor(byte r, byte g, byte b)
{
fch=((r&248)|g>>5);
fcl=((g&28)<<3|b>>3);
// fch=((r&0x1f<<3)|(g&0x3f>>3));
// fcl=((g&0x3f)<<5|(b&0x1f));
}
void UTFT::setColor(word color)
{
fch=byte(color>>8);
fcl=byte(color & 0xFF);
}
word UTFT::getColor()
{
return (fch<<8) | fcl;
}
void UTFT::setBackColor(byte r, byte g, byte b)
{
bch=((r&248)|g>>5);
bcl=((g&28)<<3|b>>3);
_transparent=false;
}
void UTFT::setBackColor(uint32_t color)
{
if (color==VGA_TRANSPARENT)
_transparent=true;
else
{
bch=byte(color>>8);
bcl=byte(color & 0xFF);
_transparent=false;
}
}
word UTFT::getBackColor()
{
return (bch<<8) | bcl;
}
void UTFT::setPixel(word color)
{
LCD_Write_DATA((color>>8),(color&0xFF)); // rrrrrggggggbbbbb
}
void UTFT::drawPixel(int x, int y)
{
cbi(P_CS, B_CS);
setXY(x, y, x, y);
setPixel((fch<<8)|fcl);
sbi(P_CS, B_CS);
clrXY();
}
void UTFT::drawLine(int x1, int y1, int x2, int y2)
{
if (y1==y2)
drawHLine(x1, y1, x2-x1);
else if (x1==x2)
drawVLine(x1, y1, y2-y1);
else
{
unsigned int dx = (x2 > x1 ? x2 - x1 : x1 - x2);
short xstep = x2 > x1 ? 1 : -1;
unsigned int dy = (y2 > y1 ? y2 - y1 : y1 - y2);
short ystep = y2 > y1 ? 1 : -1;
int col = x1, row = y1;
cbi(P_CS, B_CS);
if (dx < dy)
{
int t = - (dy >> 1);
while (true)
{
setXY (col, row, col, row);
LCD_Write_DATA (fch, fcl);
if (row == y2)
return;
row += ystep;
t += dx;
if (t >= 0)
{
col += xstep;
t -= dy;
}
}
}
else
{
int t = - (dx >> 1);
while (true)
{
setXY (col, row, col, row);
LCD_Write_DATA (fch, fcl);
if (col == x2)
return;
col += xstep;
t += dy;
if (t >= 0)
{
row += ystep;
t -= dx;
}
}
}
sbi(P_CS, B_CS);
}
clrXY();
}
void UTFT::drawHLine(int x, int y, int l)
{
if (l<0)
{
l = -l;
x -= l;
}
cbi(P_CS, B_CS);
setXY(x, y, x+l, y);
if (display_transfer_mode == 16)
{
sbi(P_RS, B_RS);
_fast_fill_16(fch,fcl,l);
}
else if ((display_transfer_mode==8) and (fch==fcl))
{
sbi(P_RS, B_RS);
_fast_fill_8(fch,l);
}
else
{
for (int i=0; i<l+1; i++)
{
LCD_Write_DATA(fch, fcl);
}
}
sbi(P_CS, B_CS);
clrXY();
}
void UTFT::drawVLine(int x, int y, int l)
{
if (l<0)
{
l = -l;
y -= l;
}
cbi(P_CS, B_CS);
setXY(x, y, x, y+l);
if (display_transfer_mode == 16)
{
sbi(P_RS, B_RS);
_fast_fill_16(fch,fcl,l);
}
else if ((display_transfer_mode==8) and (fch==fcl))
{
sbi(P_RS, B_RS);
_fast_fill_8(fch,l);
}
else
{
for (int i=0; i<l+1; i++)
{
LCD_Write_DATA(fch, fcl);
}
}
sbi(P_CS, B_CS);
clrXY();
}
void UTFT::printChar(byte c, int x, int y)
{
byte i,ch;
word j;
word temp;
cbi(P_CS, B_CS);
if (!_transparent)
{
if (orient==PORTRAIT)
{
setXY(x,y,x+cfont.x_size-1,y+cfont.y_size-1);
temp=((c-cfont.offset)*((cfont.x_size/8)*cfont.y_size))+4;
for(j=0;j<((cfont.x_size/8)*cfont.y_size);j++)
{
ch=pgm_read_byte(&cfont.font[temp]);
for(i=0;i<8;i++)
{
if((ch&(1<<(7-i)))!=0)
{
setPixel((fch<<8)|fcl);
}
else
{
setPixel((bch<<8)|bcl);
}
}
temp++;
}
}
else
{
temp=((c-cfont.offset)*((cfont.x_size/8)*cfont.y_size))+4;
for(j=0;j<((cfont.x_size/8)*cfont.y_size);j+=(cfont.x_size/8))
{
setXY(x,y+(j/(cfont.x_size/8)),x+cfont.x_size-1,y+(j/(cfont.x_size/8)));
for (int zz=(cfont.x_size/8)-1; zz>=0; zz--)
{
ch=pgm_read_byte(&cfont.font[temp+zz]);
for(i=0;i<8;i++)
{
if((ch&(1<<i))!=0)
{
setPixel((fch<<8)|fcl);
}
else
{
setPixel((bch<<8)|bcl);
}
}
}
temp+=(cfont.x_size/8);
}
}
}
else
{
temp=((c-cfont.offset)*((cfont.x_size/8)*cfont.y_size))+4;
for(j=0;j<cfont.y_size;j++)
{
for (int zz=0; zz<(cfont.x_size/8); zz++)
{
ch=pgm_read_byte(&cfont.font[temp+zz]);
for(i=0;i<8;i++)
{
setXY(x+i+(zz*8),y+j,x+i+(zz*8)+1,y+j+1);
if((ch&(1<<(7-i)))!=0)
{
setPixel((fch<<8)|fcl);
}
}
}
temp+=(cfont.x_size/8);
}
}
sbi(P_CS, B_CS);
clrXY();
}
void UTFT::rotateChar(byte c, int x, int y, int pos, int deg)
{
byte i,j,ch;
word temp;
int newx,newy;
double radian;
radian=deg*0.0175;
cbi(P_CS, B_CS);
temp=((c-cfont.offset)*((cfont.x_size/8)*cfont.y_size))+4;
for(j=0;j<cfont.y_size;j++)
{
for (int zz=0; zz<(cfont.x_size/8); zz++)
{
ch=pgm_read_byte(&cfont.font[temp+zz]);
for(i=0;i<8;i++)
{
newx=x+(((i+(zz*8)+(pos*cfont.x_size))*cos(radian))-((j)*sin(radian)));
newy=y+(((j)*cos(radian))+((i+(zz*8)+(pos*cfont.x_size))*sin(radian)));
setXY(newx,newy,newx+1,newy+1);
if((ch&(1<<(7-i)))!=0)
{
setPixel((fch<<8)|fcl);
}
else
{
if (!_transparent)
setPixel((bch<<8)|bcl);
}
}
}
temp+=(cfont.x_size/8);
}
sbi(P_CS, B_CS);
clrXY();
}
void UTFT::print(char *st, int x, int y, int deg)
{
int stl, i;
stl = strlen(st);
if (orient==PORTRAIT)
{
if (x==RIGHT)
x=(disp_x_size+1)-(stl*cfont.x_size);
if (x==CENTER)
x=((disp_x_size+1)-(stl*cfont.x_size))/2;
}
else
{
if (x==RIGHT)
x=(disp_y_size+1)-(stl*cfont.x_size);
if (x==CENTER)
x=((disp_y_size+1)-(stl*cfont.x_size))/2;
}
for (i=0; i<stl; i++)
if (deg==0)
printChar(*st++, x + (i*(cfont.x_size)), y);
else
rotateChar(*st++, x, y, i, deg);
}
void UTFT::print(String st, int x, int y, int deg)
{
char buf[st.length()+1];
st.toCharArray(buf, st.length()+1);
print(buf, x, y, deg);
}
void UTFT::printNumI(long num, int x, int y, int length, char filler)
{
char buf[25];
char st[27];
boolean neg=false;
int c=0, f=0;
if (num==0)
{
if (length!=0)
{
for (c=0; c<(length-1); c++)
st[c]=filler;
st[c]=48;
st[c+1]=0;
}
else
{
st[0]=48;
st[1]=0;
}
}
else
{
if (num<0)
{
neg=true;
num=-num;
}
while (num>0)
{
buf[c]=48+(num % 10);
c++;
num=(num-(num % 10))/10;
}
buf[c]=0;
if (neg)
{
st[0]=45;
}
if (length>(c+neg))
{
for (int i=0; i<(length-c-neg); i++)
{
st[i+neg]=filler;
f++;
}
}
for (int i=0; i<c; i++)
{
st[i+neg+f]=buf[c-i-1];
}
st[c+neg+f]=0;
}
print(st,x,y);
}
void UTFT::printNumF(double num, byte dec, int x, int y, char divider, int length, char filler)
{
char st[27];
boolean neg=false;
if (dec<1)
dec=1;
else if (dec>5)
dec=5;
if (num<0)
neg = true;
_convert_float(st, num, length, dec);
if (divider != '.')
{
for (int i=0; i<sizeof(st); i++)
if (st[i]=='.')
st[i]=divider;
}
if (filler != ' ')
{
if (neg)
{
st[0]='-';
for (int i=1; i<sizeof(st); i++)
if ((st[i]==' ') || (st[i]=='-'))
st[i]=filler;
}
else
{
for (int i=0; i<sizeof(st); i++)
if (st[i]==' ')
st[i]=filler;
}
}
print(st,x,y);
}
void UTFT::setFont(uint8_t* font)
{
cfont.font=font;
cfont.x_size=font[0];//fontbyte(0);
cfont.y_size=font[1];//fontbyte(1);
cfont.offset=font[2];//fontbyte(2);
cfont.numchars=font[3];//fontbyte(3);
}
uint8_t* UTFT::getFont()
{
return cfont.font;
}
uint8_t UTFT::getFontXsize()
{
return cfont.x_size;
}
uint8_t UTFT::getFontYsize()
{
return cfont.y_size;
}
/*void UTFT::drawBitmap(int x, int y, int sx, int sy, bitmapdatatype data, int scale)
{
unsigned int col;
int tx, ty, tc, tsx, tsy;
if (scale==1)
{
if (orient==PORTRAIT)
{
cbi(P_CS, B_CS);
setXY(x, y, x+sx-1, y+sy-1);
for (tc=0; tc<(sx*sy); tc++)
{
col=pgm_read_word(&data[tc]);
LCD_Write_DATA(col>>8,col & 0xff);
}
sbi(P_CS, B_CS);
}
else
{
cbi(P_CS, B_CS);
for (ty=0; ty<sy; ty++)
{
setXY(x, y+ty, x+sx-1, y+ty);
for (tx=sx-1; tx>=0; tx--)
{
col=pgm_read_word(&data[(ty*sx)+tx]);
LCD_Write_DATA(col>>8,col & 0xff);
}
}
sbi(P_CS, B_CS);
}
}
else
{
if (orient==PORTRAIT)
{
cbi(P_CS, B_CS);
for (ty=0; ty<sy; ty++)
{
setXY(x, y+(ty*scale), x+((sx*scale)-1), y+(ty*scale)+scale);
for (tsy=0; tsy<scale; tsy++)
for (tx=0; tx<sx; tx++)
{
col=pgm_read_word(&data[(ty*sx)+tx]);
for (tsx=0; tsx<scale; tsx++)
LCD_Write_DATA(col>>8,col & 0xff);
}
}
sbi(P_CS, B_CS);
}
else
{
cbi(P_CS, B_CS);
for (ty=0; ty<sy; ty++)
{
for (tsy=0; tsy<scale; tsy++)
{
setXY(x, y+(ty*scale)+tsy, x+((sx*scale)-1), y+(ty*scale)+tsy);
for (tx=sx-1; tx>=0; tx--)
{
col=pgm_read_word(&data[(ty*sx)+tx]);
for (tsx=0; tsx<scale; tsx++)
LCD_Write_DATA(col>>8,col & 0xff);
}
}
}
sbi(P_CS, B_CS);
}
}
clrXY();
}
void UTFT::drawBitmap(int x, int y, int sx, int sy, bitmapdatatype data, int deg, int rox, int roy)
{
unsigned int col;
int tx, ty, newx, newy;
double radian;
radian=deg*0.0175;
if (deg==0)
drawBitmap(x, y, sx, sy, data);
else
{
cbi(P_CS, B_CS);
for (ty=0; ty<sy; ty++)
for (tx=0; tx<sx; tx++)
{
col=pgm_read_word(&data[(ty*sx)+tx]);
newx=x+rox+(((tx-rox)*cos(radian))-((ty-roy)*sin(radian)));
newy=y+roy+(((ty-roy)*cos(radian))+((tx-rox)*sin(radian)));
setXY(newx, newy, newx, newy);
LCD_Write_DATA(col>>8,col & 0xff);
}
sbi(P_CS, B_CS);
}
clrXY();
}*/
void UTFT::lcdOff()
{
cbi(P_CS, B_CS);
switch (display_model)
{
case PCF8833:
LCD_Write_COM(0x28);
break;
case CPLD:
LCD_Write_COM_DATA(0x01,0x0000);
LCD_Write_COM(0x0F);
break;
}
sbi(P_CS, B_CS);
}
void UTFT::lcdOn()
{
cbi(P_CS, B_CS);
switch (display_model)
{
case PCF8833:
LCD_Write_COM(0x29);
break;
case CPLD:
LCD_Write_COM_DATA(0x01,0x0010);
LCD_Write_COM(0x0F);
break;
}
sbi(P_CS, B_CS);
}
void UTFT::setContrast(char c)
{
cbi(P_CS, B_CS);
switch (display_model)
{
case PCF8833:
if (c>64) c=64;
LCD_Write_COM(0x25);
LCD_Write_DATA(c);
break;
}
sbi(P_CS, B_CS);
}
int UTFT::getDisplayXSize()
{
if (orient==PORTRAIT)
return disp_x_size+1;
else
return disp_y_size+1;
}
int UTFT::getDisplayYSize()
{
if (orient==PORTRAIT)
return disp_y_size+1;
else
return disp_x_size+1;
}
void UTFT::setBrightness(byte br)
{
cbi(P_CS, B_CS);
switch (display_model)
{
case CPLD:
if (br>16) br=16;
LCD_Write_COM_DATA(0x01,br);
LCD_Write_COM(0x0F);
break;
}
sbi(P_CS, B_CS);
}
void UTFT::setDisplayPage(byte page)
{
cbi(P_CS, B_CS);
switch (display_model)
{
case CPLD:
if (page>7) page=7;
LCD_Write_COM_DATA(0x04,page);
LCD_Write_COM(0x0F);
break;
}
sbi(P_CS, B_CS);
}
void UTFT::setWritePage(byte page)
{
cbi(P_CS, B_CS);
switch (display_model)
{
case CPLD:
if (page>7) page=7;
LCD_Write_COM_DATA(0x05,page);
LCD_Write_COM(0x0F);
break;
}
sbi(P_CS, B_CS);
}
| [
"[email protected]"
] | |
37a17f5aada19a69bd57c79199f40ec689d1616f | 4ddb183621a8587f45c12216d0227d36dfb430ff | /MBDGeneralFW/MBDTechInfo.m/src/MBDNoteModifyDlg.cpp | a936ad957930efba2ddfc947cf25662e1c5142a8 | [] | no_license | 0000duck/good-idea | 7cdd05c55483faefb96ef9b2efaa7b7eb2f22512 | 876b9c8bb67fa4a7dc62d89683d4fd9d28a94cae | refs/heads/master | 2021-05-29T02:46:02.336920 | 2013-07-22T17:53:06 | 2013-07-22T17:53:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,085 | cpp | // COPYRIGHT Dassault Systemes 2010
//===================================================================
//
// MBDNoteModifyDlg.cpp
// The dialog : MBDNoteModifyDlg
//
//===================================================================
//
// Usage notes:
//
//===================================================================
//
// Mar 2010 Creation: Code generated by the CAA wizard ev5adm
//===================================================================
#include "MBDNoteModifyDlg.h"
#include "CATApplicationFrame.h"
#include "CATDlgGridConstraints.h"
#include "CATMsgCatalog.h"
#ifdef MBDNoteModifyDlg_ParameterEditorInclude
#include "CATIParameterEditorFactory.h"
#include "CATIParameterEditor.h"
#include "CATICkeParm.h"
#endif
//-------------------------------------------------------------------------
// Constructor
//-------------------------------------------------------------------------
MBDNoteModifyDlg::MBDNoteModifyDlg() :
CATDlgDialog ((CATApplicationFrame::GetApplicationFrame())->GetMainWindow(),
//CAA2 WIZARD CONSTRUCTOR DECLARATION SECTION
"MBDNoteModifyDlg",CATDlgWndModal|CATDlgWndPointerLocation|CATDlgWndBtnOKCancel|CATDlgGridLayout
//END CAA2 WIZARD CONSTRUCTOR DECLARATION SECTION
)
{
//CAA2 WIZARD CONSTRUCTOR INITIALIZATION SECTION
_MBDModifyNameEditor = NULL;
_MBDModifyValueEditor = NULL;
//END CAA2 WIZARD CONSTRUCTOR INITIALIZATION SECTION
}
//-------------------------------------------------------------------------
// Destructor
//-------------------------------------------------------------------------
MBDNoteModifyDlg::~MBDNoteModifyDlg()
{
// Do not delete the control elements of your dialog:
// this is done automatically
// --------------------------------------------------
//CAA2 WIZARD DESTRUCTOR DECLARATION SECTION
_MBDModifyNameEditor = NULL;
_MBDModifyValueEditor = NULL;
//END CAA2 WIZARD DESTRUCTOR DECLARATION SECTION
}
void MBDNoteModifyDlg::Build()
{
// TODO: This call builds your dialog from the layout declaration file
// -------------------------------------------------------------------
//CAA2 WIZARD WIDGET CONSTRUCTION SECTION
_MBDModifyNameEditor = new CATDlgEditor(this, "MBDModifyNameEditor", CATDlgEdtReadOnly);
_MBDModifyNameEditor -> SetVisibleTextWidth(5);
_MBDModifyNameEditor -> SetGridConstraints(0, 0, 1, 1, CATGRID_4SIDES);
_MBDModifyValueEditor = new CATDlgEditor(this, "MBDModifyValueEditor");
_MBDModifyValueEditor -> SetGridConstraints(0, 1, 1, 1, CATGRID_4SIDES);
//END CAA2 WIZARD WIDGET CONSTRUCTION SECTION
int oHeight = 0,oWidth = 0;
PrtService::GetWindowMaxSize(&oHeight,&oWidth );
_MBDModifyValueEditor -> SetVisibleTextWidth(int (0.065*oWidth));
//CAA2 WIZARD CALLBACK DECLARATION SECTION
//END CAA2 WIZARD CALLBACK DECLARATION SECTION
}
CATDlgEditor* MBDNoteModifyDlg::GetMBDNoteModifyNameEditor()
{
return _MBDModifyNameEditor;
}
CATDlgEditor* MBDNoteModifyDlg::GetMBDNoteModifyValueEditor()
{
return _MBDModifyValueEditor;
}
| [
"zhangwy0916@e6631ee2-bc36-6fc4-7263-08c298121e4e"
] | zhangwy0916@e6631ee2-bc36-6fc4-7263-08c298121e4e |
9b83294b2fb573490cadd874fd3157c93a47fcac | c689037be8a029aa95bf5fe1c4aef2912f194f31 | /LaboratoryDevices/SelectDevicesWidget.h | 1278c022880d40441eb5570eadcee42586655303 | [] | no_license | oscilo/LabDev | b6933d65562af9d210f809e00a0cfcc09c37833b | 8ae22a5658f85f2854b30b47e6aebc75d1cb02e4 | refs/heads/master | 2020-05-31T03:27:28.118419 | 2017-03-15T22:44:28 | 2017-03-15T22:44:28 | 30,373,361 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,663 | h | #ifndef SELECTDEVICESWIDGET_H
#define SELECTDEVICESWIDGET_H
#include "globals.h"
#include "structures.h"
class CheckDeviceLayout : public QHBoxLayout {
Q_OBJECT
public:
CheckDeviceLayout(const DeviceInfo &di, QWidget *parent = 0) : QHBoxLayout(parent), curDI(di) {
check = new QCheckBox(di.name, parent);
spin = new QSpinBox(parent);
spin->setRange(1, 5);
spin->hide();
connect(check, SIGNAL(clicked(bool)), spin, SLOT(setVisible(bool)));
connect(check, SIGNAL(clicked(bool)), this, SLOT(OnOffSlot(bool)));
connect(spin, SIGNAL(valueChanged(int)), this, SLOT(CountChanged(int)));
this->addWidget(check, 1);
this->addWidget(spin);
}
~CheckDeviceLayout() {
}
QList<DeviceInfo>& GetDeviceList() {
return devices;
}
signals:
void UpdateDevices();
public slots:
void Clear() {
spin->setValue(1);
spin->hide();
check->setChecked(false);
}
void CheckSelectionList(const QList<DeviceInfo> &existingSelection) {
QList<DeviceInfo> newDevices;
foreach(DeviceInfo di, existingSelection) {
if(di.id == curDI.id) {
di.order = newDevices.size();
newDevices << di;
}
}
if(0 == newDevices.size())
Clear();
else {
check->setChecked(true);
spin->show();
spin->setValue(newDevices.size());
devices = newDevices;
}
}
private slots:
void OnOffSlot(bool action) {
if(action)
emit CountChanged(spin->value());
else
emit CountChanged(0);
}
void CountChanged(int count) {
int oldSize = devices.size();
if(oldSize == count)
return;
if(oldSize < count) {
int flag = count - oldSize;
while(flag) {
DeviceInfo di = curDI;
di.order = devices.size();
di.uuid = QUuid::createUuid();
devices << di;
flag--;
}
}
else {
int flag = oldSize - count;
while(flag) {
devices.removeLast();
flag--;
}
}
emit UpdateDevices();
}
private:
DeviceInfo curDI;
QList<DeviceInfo> devices;
QCheckBox *check;
QSpinBox *spin;
};
class SelectDevicesWidget : public QGroupBox {
Q_OBJECT
public:
SelectDevicesWidget(QWidget *parent = 0);
~SelectDevicesWidget();
void SetDevicesList(const QList<DeviceInfo>&);
DBRecordList GetSelectedDevices();
signals:
void SelectionUpdated(const QList<DeviceInfo>&);
void CheckSelectionList(const QList<DeviceInfo>&);
public slots:
void Clear();
void SetExistingSelection(const QList<DeviceInfo>&);
private slots:
void UpdateSelectedDevices();
private:
void FillWidget();
void AddCheckLayoutAtPosition(const DeviceInfo &, int row, int column);
QList<DeviceInfo> totalDevices;
QList<DeviceInfo> selectedDevices;
QList<CheckDeviceLayout*> checkLayouts;
QGridLayout *layout;
};
#endif | [
"[email protected]"
] | |
d5b10fd840e59b756c211cab4d2eb6bb258e3e76 | ef15a4a77b6e1fbb3220a5047885ba7568a80b74 | /src/core/Core/SignalToStop.hpp | b66f5a6ec1be9ca38fff701986ce19cd9dde6921 | [] | no_license | el-bart/ACARM-ng | 22ad5a40dc90a2239206f18dacbd4329ff8377de | de277af4b1c54e52ad96cbe4e1f574bae01b507d | refs/heads/master | 2020-12-27T09:24:14.591095 | 2014-01-28T19:24:34 | 2014-01-28T19:24:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 843 | hpp | /*
* SignalToStop.hpp
*
*/
#ifndef INCLUDE_CORE_SIGNALTOSTOP_HPP_FILE
#define INCLUDE_CORE_SIGNALTOSTOP_HPP_FILE
/* public header */
#include "System/SignalRegistrator.hpp"
#include "Logger/Node.hpp"
#include "Core/WorkThreads.hpp"
namespace Core
{
/** \brief handles given signal's registration and unregistration.
*
* when given signal is received system is triggered to stop.
*/
class SignalToStop: public System::SignalRegistrator
{
public:
/** \brief registers handle for signal.
* \param signum signal number to be handled.
* \param wt main system threads. if NULL, signal is ignored.
*/
SignalToStop(int signum, WorkThreads *wt);
/** \brief unregisters signal handle.
*/
~SignalToStop(void);
private:
int signum_;
Logger::Node log_;
}; // class SignalToStop
} // namespace Core
#endif
| [
"[email protected]"
] | |
9db88d488c6ffd2b10d44ee4753ddf7f6822594e | 81bb77804b2481a92c0d48ad2f76e5b79d29e9ec | /src/base58.h | 458f045ad5289379066b5ccc631231dae4dcac16 | [
"MIT"
] | permissive | AndrewJEON/qtum | a5216a67c25e818b11266366f37d0b7bcf5a573f | 5373115c4550a9dbd99f360dd50cc4f67722dc91 | refs/heads/master | 2021-06-11T16:50:00.126511 | 2017-03-14T17:12:40 | 2017-03-14T17:12:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,741 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
/**
* Why base-58 instead of standard base-64 encoding?
* - Don't want 0OIl characters that look the same in some fonts and
* could be used to create visually identical looking data.
* - A string with non-alphanumeric characters is not as easily accepted as input.
* - E-mail usually won't line-break if there's no punctuation to break at.
* - Double-clicking selects the whole string as one word if it's all alphanumeric.
*/
#ifndef QUANTUM_BASE58_H
#define QUANTUM_BASE58_H
#include "chainparams.h"
#include "key.h"
#include "pubkey.h"
#include "script/script.h"
#include "script/standard.h"
#include "support/allocators/zeroafterfree.h"
#include <string>
#include <vector>
/**
* Encode a byte sequence as a base58-encoded string.
* pbegin and pend cannot be NULL, unless both are.
*/
std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend);
/**
* Encode a byte vector as a base58-encoded string
*/
std::string EncodeBase58(const std::vector<unsigned char>& vch);
/**
* Decode a base58-encoded string (psz) into a byte vector (vchRet).
* return true if decoding is successful.
* psz cannot be NULL.
*/
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet);
/**
* Decode a base58-encoded string (str) into a byte vector (vchRet).
* return true if decoding is successful.
*/
bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet);
/**
* Encode a byte vector into a base58-encoded string, including checksum
*/
std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn);
/**
* Decode a base58-encoded string (psz) that includes a checksum into a byte
* vector (vchRet), return true if decoding is successful
*/
inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet);
/**
* Decode a base58-encoded string (str) that includes a checksum into a byte
* vector (vchRet), return true if decoding is successful
*/
inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet);
/**
* Base class for all base58-encoded data
*/
class CBase58Data
{
protected:
//! the version byte(s)
std::vector<unsigned char> vchVersion;
//! the actually encoded data
typedef std::vector<unsigned char, zero_after_free_allocator<unsigned char> > vector_uchar;
vector_uchar vchData;
CBase58Data();
void SetData(const std::vector<unsigned char> &vchVersionIn, const void* pdata, size_t nSize);
void SetData(const std::vector<unsigned char> &vchVersionIn, const unsigned char *pbegin, const unsigned char *pend);
public:
bool SetString(const char* psz, unsigned int nVersionBytes = 1);
bool SetString(const std::string& str);
std::string ToString() const;
int CompareTo(const CBase58Data& b58) const;
bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; }
bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; }
bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; }
bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; }
bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; }
};
/** base58-encoded Quantum addresses.
* Public-key-hash-addresses have version 0 (or 111 testnet).
* The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
* Script-hash-addresses have version 5 (or 196 testnet).
* The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
*/
class CQuantumAddress : public CBase58Data {
public:
bool Set(const CKeyID &id);
bool Set(const CScriptID &id);
bool Set(const CTxDestination &dest);
bool IsValid() const;
bool IsValid(const CChainParams ¶ms) const;
CQuantumAddress() {}
CQuantumAddress(const CTxDestination &dest) { Set(dest); }
CQuantumAddress(const std::string& strAddress) { SetString(strAddress); }
CQuantumAddress(const char* pszAddress) { SetString(pszAddress); }
CTxDestination Get() const;
bool GetKeyID(CKeyID &keyID) const;
bool IsScript() const;
};
/**
* A base58-encoded secret key
*/
class CQuantumSecret : public CBase58Data
{
public:
void SetKey(const CKey& vchSecret);
CKey GetKey();
bool IsValid() const;
bool SetString(const char* pszSecret);
bool SetString(const std::string& strSecret);
CQuantumSecret(const CKey& vchSecret) { SetKey(vchSecret); }
CQuantumSecret() {}
};
template<typename K, int Size, CChainParams::Base58Type Type> class CQuantumExtKeyBase : public CBase58Data
{
public:
void SetKey(const K &key) {
unsigned char vch[Size];
key.Encode(vch);
SetData(Params().Base58Prefix(Type), vch, vch+Size);
}
K GetKey() {
K ret;
if (vchData.size() == Size) {
//if base58 encouded data not holds a ext key, return a !IsValid() key
ret.Decode(&vchData[0]);
}
return ret;
}
CQuantumExtKeyBase(const K &key) {
SetKey(key);
}
CQuantumExtKeyBase(const std::string& strBase58c) {
SetString(strBase58c.c_str(), Params().Base58Prefix(Type).size());
}
CQuantumExtKeyBase() {}
};
typedef CQuantumExtKeyBase<CExtKey, BIP32_EXTKEY_SIZE, CChainParams::EXT_SECRET_KEY> CQuantumExtKey;
typedef CQuantumExtKeyBase<CExtPubKey, BIP32_EXTKEY_SIZE, CChainParams::EXT_PUBLIC_KEY> CQuantumExtPubKey;
#endif // QUANTUM_BASE58_H
| [
"[email protected]"
] | |
a98e9f476dd86e348da9401f20f3a06c021ea80e | 8e4a2a7152e4b25641d72e930de8842732bcf53a | /OpenSeesCpp/eigen3/linearFunctionai.cpp | 48b55e4dcfecc4b8ffb1ebbb720b2ff0b2316df4 | [] | no_license | Mengsen-W/OpenSeesFiles | 9b9e8865a2b802047e419c5155aff5c20ac05937 | cda268d37cd17280dc18ada8c7f1b30af0b2bd6b | refs/heads/master | 2021-12-23T23:21:28.369076 | 2021-12-22T13:14:53 | 2021-12-22T13:14:53 | 239,237,550 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,450 | cpp | /*
* @Author: Mengsen.Wang
* @Date: 2020-07-17 09:49:15
* @Last Modified by: Mengsen.Wang
* @Last Modified time: 2020-07-17 10:47:16
*/
#include <ctime>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Dense>
#include <iostream>
#define MATRIX_SIZE 1000
int main() {
Eigen::MatrixXd A;
Eigen::MatrixXd B;
Eigen::MatrixXd X;
A = Eigen::MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE);
B = Eigen::MatrixXd::Random(MATRIX_SIZE, 1);
X = Eigen::MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE);
clock_t time_stt = clock();
std::cout << "----- QR decomposition colPivHouseholder -----" << std::endl;
X = A.colPivHouseholderQr().solve(B);
std::cout << "time use in QR colPivHouseholderQr decomposition is "
<< (1000) * (clock() - time_stt) /
static_cast<double>(CLOCKS_PER_SEC)
<< "ms" << std::endl;
time_stt = clock();
std::cout << "----- QR decomposition fullPivHouseholder -----" << std::endl;
X = A.fullPivHouseholderQr().solve(B);
std::cout << "time use in QR fullPivHouseholder decomposition is "
<< (1000) * (clock() - time_stt) /
static_cast<double>(CLOCKS_PER_SEC)
<< "ms" << std::endl;
time_stt = clock();
std::cout << "----- llt decomposition -----" << std::endl;
X = A.llt().solve(B);
std::cout << "time use in llt decomposition is "
<< (1000) * (clock() - time_stt) /
static_cast<double>(CLOCKS_PER_SEC)
<< "ms" << std::endl;
time_stt = clock();
std::cout << "----- ldlt decomposition -----" << std::endl;
X = A.ldlt().solve(B);
std::cout << "time use in ldlt decomposition is "
<< (1000) * (clock() - time_stt) /
static_cast<double>(CLOCKS_PER_SEC)
<< "ms" << std::endl;
time_stt = clock();
std::cout << "----- partialPivLu decomposition -----" << std::endl;
X = A.partialPivLu().solve(B);
std::cout << "time use in partialPivLu decomposition is "
<< (1000) * (clock() - time_stt) /
static_cast<double>(CLOCKS_PER_SEC)
<< "ms" << std::endl;
time_stt = clock();
std::cout << "----- fullPivLu decomposition -----" << std::endl;
X = A.fullPivLu().solve(B);
std::cout << "time use in fullPivLu decomposition is "
<< (1000) * (clock() - time_stt) /
static_cast<double>(CLOCKS_PER_SEC)
<< "ms" << std::endl;
return 0;
}
| [
"[email protected]"
] | |
e96e3af0be76106444fb057262c722e6095061a3 | d4baaa6748dda226b88a1afb2fba2b6c6f54a3cc | /QuestionAnswer_1/source/user.h | a61b280ceaa5b68c731d18c6ba2624a705a5fe11 | [] | no_license | zhangjiuchao/ProgramDesign | 8343363e9ebd4ad8bc2beb051c36f450cda653fe | 175c286b2ed2eca3c386f7aaf7ec13404989a95f | refs/heads/master | 2020-06-30T18:34:16.947478 | 2016-08-26T15:20:53 | 2016-08-26T15:20:53 | 66,571,078 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,026 | h | #ifndef USER_H
#define USER_H
//#include <iostream>
#include <QString>
#include <QList>
#include "questinfor.h"
#include <QTextStream>
class user
{
public:
user(QString str1="",QString str2="",QString str3="");
bool AddFocus(QString focusID);
void AddQuest(QString title,QString content);
void AddAnswer(QString);
void eraseQuest(QString question_id);
void eraseFocus(QString eraseID);
bool changePassword(QString str1,QString str2,QString str3);
bool isFocus(QString id);
friend QTextStream& operator<<(QTextStream& os,const user* host);
friend QTextStream& operator>>(QTextStream& is,user* host);
QList<QString> getFocusList();
QList<QString> getMyQuestion();
QList<QString> get_question_my_anwser();
QString getID();
QString getName();
QString getPassword();
private:
QString ID;
QString userName;
QString Password;
QList<QString> focusList;
QList<QString> myQuestion;
QList<QString> question_my_answer;
};
#endif // USER_H
| [
"[email protected]"
] | |
29ada50980d562e467d8267b9d3af643f6559c76 | 3ff49c066ddaf7e97ed2631760d438c6a1a452c5 | /src/ast/ASTAbstractVisitor.h | 479f96b3bd7bc0b42631a05748bb30fce6d49deb | [] | no_license | rudo-rov/CppSOM | 26321838d058ec188ab72bfd70dca5c12184df1d | 0fff035f9a5989014fb6ed214b41e7bdf088b904 | refs/heads/main | 2023-05-05T14:15:42.562364 | 2021-05-24T12:24:19 | 2021-05-24T12:24:19 | 342,613,612 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,222 | h | #pragma once
#include <any>
namespace som {
// Forward declaration of AST nodes to resolve circular reference
struct Class;
struct Method;
struct Block;
struct NestedBlock;
struct UnaryPattern;
struct BinaryPattern;
struct KeywordPattern;
struct Keyword;
struct KeywordWithArgs;
struct UnarySelector;
struct BinarySelector;
struct BinaryOperand;
struct KeywordSelector;
struct UnaryMessage;
struct BinaryMessage;
struct KeywordMessage;
struct Formula;
struct LiteralInteger;
struct LiteralDouble;
struct LiteralArray;
struct LiteralString;
struct Assignation;
struct Evaluation;
struct Variable;
struct NestedTerm;
struct Result;
class CAstAbstractVisitor {
public:
virtual std::any visit(Method* method) = 0;
virtual std::any visit(Class* classNode) = 0;
virtual std::any visit(Block* block) = 0;
virtual std::any visit(NestedBlock* nestedBlock) = 0;
virtual std::any visit(UnaryPattern* unaryPattern) = 0;
virtual std::any visit(BinaryPattern* binaryPattern) = 0;
virtual std::any visit(KeywordPattern* keywordPattern) = 0;
virtual std::any visit(Keyword* keyword) = 0;
virtual std::any visit(KeywordWithArgs* keyword) = 0;
virtual std::any visit(UnarySelector* unarySelector) = 0;
virtual std::any visit(BinarySelector* binarySelector) = 0;
virtual std::any visit(KeywordSelector* keywordSelector) = 0;
virtual std::any visit(UnaryMessage* unaryMessage) = 0;
virtual std::any visit(BinaryMessage* binaryMessage) = 0;
virtual std::any visit(BinaryOperand* binaryOperand) = 0;
virtual std::any visit(KeywordMessage* keywordMessage) = 0;
virtual std::any visit(Formula* formula) = 0;
virtual std::any visit(LiteralInteger* litInteger) = 0;
virtual std::any visit(LiteralString* litString) = 0;
virtual std::any visit(LiteralArray* litArray) = 0;
virtual std::any visit(LiteralDouble* litDouble) = 0;
virtual std::any visit(Assignation* assignation) = 0;
virtual std::any visit(Evaluation* evaluation) = 0;
virtual std::any visit(Result* result) = 0;
virtual std::any visit(Variable* variable) = 0;
virtual std::any visit(NestedTerm* nestedTerm) = 0;
};
}
| [
"[email protected]"
] | |
7ffec586c8dd2e09f767a0afadaac569716c3b06 | 8ac181aa59bbc34aa457ed90273b56763269859d | /Codeforces/668-DIV2/B.cpp | 9e90460de64ad73d97dd3b9bc8d34ae89d8b3dbc | [] | no_license | mohitmp9107/Competitive-Programming- | d8a85d37ad6eccb1c70e065f592f46961bdb21cf | d42ef49bfcd80ebfc87a75b544cf9d7d5afcc968 | refs/heads/master | 2021-07-11T11:09:14.808893 | 2020-10-03T08:15:36 | 2020-10-03T08:15:36 | 206,331,473 | 0 | 4 | null | 2020-10-03T08:15:38 | 2019-09-04T13:54:46 | C++ | UTF-8 | C++ | false | false | 1,304 | cpp | #include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template < typename T > using oset = tree < T, null_type, less < T >, rb_tree_tag, tree_order_statistics_node_update >;
// find_by_order(k) (k+1)th largest element
// order_of_key(k) no of elements <=k
typedef long long ll;
typedef long double ld;
#define endl '\n'
#define rep(i,n) for(ll i = 0; i < (n); ++i)
#define repA(i, a, n) for(ll i = a; i <= (n); ++i)
#define repD(i, a, n) for(ll i = a; i >= (n); --i)
#define trav(a, x) for(auto& a : x)
#define all(x) x.begin(), x.end()
#define sz(x) (ll)(x).size()
#define ff first
#define ss second
#define pb push_back
typedef vector<ll> vll;
typedef vector<pair<ll,ll>> vpl;
const ld PI = 4*atan((ld)1);
const ll INF = LLONG_MAX;
const ll mod = 1e9+7;
int main()
{
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
ll tt=1;
cin >> tt;
repA(qq,1,tt){
ll n; cin >> n;
vll a(n);
ll ans = INF;
rep(i,n){
cin >> a[i];
if(i)a[i]+=a[i-1];
}
rep(i,n){
ans = min(ans,a[i]);
}
cout<< -ans << endl;
}
}
| [
"[email protected]"
] | |
181a9dfd827524c75789617744e569536f5485aa | 8c8ea797b0821400c3176add36dd59f866b8ac3d | /AOJ/aoj0025.cpp | c2403359a69322f0b035d629e82f658fe2bce624 | [] | no_license | fushime2/competitive | d3d6d8e095842a97d4cad9ca1246ee120d21789f | b2a0f5957d8ae758330f5450306b629006651ad5 | refs/heads/master | 2021-01-21T16:00:57.337828 | 2017-05-20T06:45:46 | 2017-05-20T06:45:46 | 78,257,409 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 594 | cpp | #include <iostream>
#include <map>
#include <vector>
using namespace std;
#define N 4
int main(void)
{
ios::sync_with_stdio(false);
int a[N], b[N];
int hit, blow;
while(cin >> a[0] >> a[1] >> a[2] >> a[3], !cin.eof()) {
for(int i=0; i<N; i++) cin >> b[i];
hit = blow = 0;
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
if(a[i] == b[j]) {
if(i == j) hit++;
else blow++;
}
}
}
cout << hit << " " << blow << endl;
}
return 0;
}
| [
"[email protected]"
] | |
4a76cac30b1bc4bf6696ab84973927450e320812 | 99ecca1944396fb67de3e64663d464d17c558e8f | /super_template.cpp | 2055f142955090c02af6cc83a611f4302d75b2ba | [] | no_license | fedepousa/codejam-practicas | c1cb88eb3d6c7ec39d33b92038f02616984c2f86 | dff985d02a83d2d196ec70453d0b57d4a2f68acc | refs/heads/master | 2020-12-25T19:03:56.651996 | 2011-05-10T13:38:48 | 2011-05-10T13:38:48 | 32,286,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,579 | cpp | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string.h>
using namespace std;
#define forn(i, n) for(int i = 0; i < (int)(n); i++)
#define ford(i, n) for(int i = (int)(n) - 1; i >= 0; i--)
#define forab(i, a, b) for (int i = (int)(a); i <= (int)(b); i++)
#define forit(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end(); i++)
#define sz(a) (int)(a).size()
#define pb push_back
#define mp make_pair
#define fs first
#define sc second
#define last(a) int(a.size() - 1)
#define all(a) a.begin(), a.end()
#define zero(a) memset(a, 0, sizeof(a))
#define seta(a,x) memset (a, x, sizeof (a))
#define I (int)
typedef long long int64;//NOTES:int64
typedef unsigned long long uint64;//NOTES:uint64
const double pi=acos(-1.0);//NOTES:pi
const double eps=1e-11;//NOTES:eps
template<class T> inline T sqr(T x){return x*x;}//NOTES:sqr
//Numberic Functions
template<class T> inline T gcd(T a,T b)//NOTES:gcd(
{if(a<0)return gcd(-a,b);if(b<0)return gcd(a,-b);return (b==0)?a:gcd(b,a%b);}
template<class T> inline T lcm(T a,T b)//NOTES:lcm(
{if(a<0)return lcm(-a,b);if(b<0)return lcm(a,-b);return a*(b/gcd(a,b));}
template<class T> inline T euclide(T a,T b,T &x,T &y)//NOTES:euclide(
{if(a<0){T d=euclide(-a,b,x,y);x=-x;return d;}
if(b<0){T d=euclide(a,-b,x,y);y=-y;return d;}
if(b==0){x=1;y=0;return a;}else{T d=euclide(b,a%b,x,y);T t=x;x=y;y=t-(a/b)*y;return d;}}
template<class T> inline vector<pair<T,int> > factorize(T n)//NOTES:factorize(
{vector<pair<T,int> > R;for (T i=2;n>1;){if (n%i==0){int C=0;for (;n%i==0;C++,n/=i);R.push_back(make_pair(i,C));}
i++;if (i>n/i) i=n;}if (n>1) R.push_back(make_pair(n,1));return R;}
template<class T> inline bool isPrimeNumber(T n)//NOTES:isPrimeNumber(
{if(n<=1)return false;for (T i=2;i*i<=n;i++) if (n%i==0) return false;return true;}
template<class T> inline T eularFunction(T n)//NOTES:eularFunction(
{vector<pair<T,int> > R=factorize(n);T r=n;for (int i=0;i<R.size();i++)r=r/R[i].first*(R[i].first-1);return r;}
//Matrix Operations
const int MaxMatrixSize=40;//NOTES:MaxMatrixSize
template<class T> inline void showMatrix(int n,T A[MaxMatrixSize][MaxMatrixSize])//NOTES:showMatrix(
{for (int i=0;i<n;i++){for (int j=0;j<n;j++)cout<<A[i][j];cout<<endl;}}
template<class T> inline T checkMod(T n,T m) {return (n%m+m)%m;}//NOTES:checkMod(
template<class T> inline void identityMatrix(int n,T A[MaxMatrixSize][MaxMatrixSize])//NOTES:identityMatrix(
{for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=(i==j)?1:0;}
template<class T> inline void addMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:addMatrix(
{for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=A[i][j]+B[i][j];}
template<class T> inline void subMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:subMatrix(
{for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=A[i][j]-B[i][j];}
template<class T> inline void mulMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T _A[MaxMatrixSize][MaxMatrixSize],T _B[MaxMatrixSize][MaxMatrixSize])//NOTES:mulMatrix(
{ T A[MaxMatrixSize][MaxMatrixSize],B[MaxMatrixSize][MaxMatrixSize];
for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=_A[i][j],B[i][j]=_B[i][j],C[i][j]=0;
for (int i=0;i<n;i++) for (int j=0;j<n;j++) for (int k=0;k<n;k++) C[i][j]+=A[i][k]*B[k][j];}
template<class T> inline void addModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:addModMatrix(
{for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=checkMod(A[i][j]+B[i][j],m);}
template<class T> inline void subModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:subModMatrix(
{for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=checkMod(A[i][j]-B[i][j],m);}
template<class T> inline T multiplyMod(T a,T b,T m) {return (T)((((int64)(a)*(int64)(b)%(int64)(m))+(int64)(m))%(int64)(m));}//NOTES:multiplyMod(
template<class T> inline void mulModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T _A[MaxMatrixSize][MaxMatrixSize],T _B[MaxMatrixSize][MaxMatrixSize])//NOTES:mulModMatrix(
{ T A[MaxMatrixSize][MaxMatrixSize],B[MaxMatrixSize][MaxMatrixSize];
for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=_A[i][j],B[i][j]=_B[i][j],C[i][j]=0;
for (int i=0;i<n;i++) for (int j=0;j<n;j++) for (int k=0;k<n;k++) C[i][j]=(C[i][j]+multiplyMod(A[i][k],B[k][j],m))%m;}
template<class T> inline T powerMod(T p,int e,T m)//NOTES:powerMod(
{if(e==0)return 1%m;else if(e%2==0){T t=powerMod(p,e/2,m);return multiplyMod(t,t,m);}else return multiplyMod(powerMod(p,e-1,m),p,m);}
//Point&Line
double dist(double x1,double y1,double x2,double y2){return sqrt(sqr(x1-x2)+sqr(y1-y2));}//NOTES:dist(
double distR(double x1,double y1,double x2,double y2){return sqr(x1-x2)+sqr(y1-y2);}//NOTES:distR(
template<class T> T cross(T x0,T y0,T x1,T y1,T x2,T y2){return (x1-x0)*(y2-y0)-(x2-x0)*(y1-y0);}//NOTES:cross(
int crossOper(double x0,double y0,double x1,double y1,double x2,double y2)//NOTES:crossOper(
{double t=(x1-x0)*(y2-y0)-(x2-x0)*(y1-y0);if (fabs(t)<=eps) return 0;return (t<0)?-1:1;}
bool isIntersect(double x1,double y1,double x2,double y2,double x3,double y3,double x4,double y4)//NOTES:isIntersect(
{return crossOper(x1,y1,x2,y2,x3,y3)*crossOper(x1,y1,x2,y2,x4,y4)<0 && crossOper(x3,y3,x4,y4,x1,y1)*crossOper(x3,y3,x4,y4,x2,y2)<0;}
bool isMiddle(double s,double m,double t){return fabs(s-m)<=eps || fabs(t-m)<=eps || (s<m)!=(t<m);}//NOTES:isMiddle(
//Translator
bool isUpperCase(char c){return c>='A' && c<='Z';}//NOTES:isUpperCase(
bool isLowerCase(char c){return c>='a' && c<='z';}//NOTES:isLowerCase(
bool isLetter(char c){return c>='A' && c<='Z' || c>='a' && c<='z';}//NOTES:isLetter(
bool isDigit(char c){return c>='0' && c<='9';}//NOTES:isDigit(
char toLowerCase(char c){return (isUpperCase(c))?(c+32):c;}//NOTES:toLowerCase(
char toUpperCase(char c){return (isLowerCase(c))?(c-32):c;}//NOTES:toUpperCase(
template<class T> string toString(T n){ostringstream ost;ost<<n;ost.flush();return ost.str();}//NOTES:toString(
int toInt(string s){int r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toInt(
int64 toInt64(string s){int64 r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toInt64(
double toDouble(string s){double r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toDouble(
template<class T> void stoa(string s,int &n,T A[]){n=0;istringstream sin(s);for(T v;sin>>v;A[n++]=v);}//NOTES:stoa(
template<class T> void atos(int n,T A[],string &s){ostringstream sout;for(int i=0;i<n;i++){if(i>0)sout<<' ';sout<<A[i];}s=sout.str();}//NOTES:atos(
template<class T> void atov(int n,T A[],vector<T> &vi){vi.clear();for (int i=0;i<n;i++) vi.push_back(A[i]);}//NOTES:atov(
template<class T> void vtoa(vector<T> vi,int &n,T A[]){n=vi.size();for (int i=0;i<n;i++)A[i]=vi[i];}//NOTES:vtoa(
template<class T> void stov(string s,vector<T> &vi){vi.clear();istringstream sin(s);for(T v;sin>>v;vi.push_bakc(v));}//NOTES:stov(
template<class T> void vtos(vector<T> vi,string &s){ostringstream sout;for (int i=0;i<vi.size();i++){if(i>0)sout<<' ';sout<<vi[i];}s=sout.str();}//NOTES:vtos(
//Fraction
template<class T> struct Fraction{T a,b;Fraction(T a=0,T b=1);string toString();};//NOTES:Fraction
template<class T> Fraction<T>::Fraction(T a,T b){T d=gcd(a,b);a/=d;b/=d;if (b<0) a=-a,b=-b;this->a=a;this->b=b;}
template<class T> string Fraction<T>::toString(){ostringstream sout;sout<<a<<"/"<<b;return sout.str();}
template<class T> Fraction<T> operator+(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b+q.a*p.b,p.b*q.b);}
template<class T> Fraction<T> operator-(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b-q.a*p.b,p.b*q.b);}
template<class T> Fraction<T> operator*(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.a,p.b*q.b);}
template<class T> Fraction<T> operator/(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b,p.b*q.a);}
typedef vector<int> vint;
typedef struct _nodo{
vint adjs;
int color;
_nodo(){color=0;}
} nodo;
#define p(a) cout << a << endl
int main()
{
}
| [
"nicovaras22@132d8716-348d-89a7-68be-e1c8d3029e1a"
] | nicovaras22@132d8716-348d-89a7-68be-e1c8d3029e1a |
69721892a768fac6808ee60dfd9672acacbdc19b | b33a9177edaaf6bf185ef20bf87d36eada719d4f | /qtdeclarative/src/qml/jsruntime/qv4profiling_p.h | 6c54fc9bbdf19a1654d96b536ae8d0244adb9e27 | [
"Qt-LGPL-exception-1.1",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"LGPL-3.0-only",
"GPL-3.0-only",
"LGPL-2.1-or-later",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"GFDL-1.3-only",
"LicenseRef-scancode-digia-qt-preview",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-generic-exception"
] | permissive | wgnet/wds_qt | ab8c093b8c6eead9adf4057d843e00f04915d987 | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | refs/heads/master | 2021-04-02T11:07:10.181067 | 2020-06-02T10:29:03 | 2020-06-02T10:34:19 | 248,267,925 | 1 | 0 | Apache-2.0 | 2020-04-30T12:16:53 | 2020-03-18T15:20:38 | null | UTF-8 | C++ | false | false | 6,825 | h | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QV4PROFILING_H
#define QV4PROFILING_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include "qv4global_p.h"
#include "qv4engine_p.h"
#include "qv4function_p.h"
#include <QElapsedTimer>
QT_BEGIN_NAMESPACE
namespace QV4 {
namespace Profiling {
enum Features {
FeatureFunctionCall,
FeatureMemoryAllocation
};
enum MemoryType {
HeapPage,
LargeItem,
SmallItem
};
struct FunctionCallProperties {
qint64 start;
qint64 end;
QString name;
QString file;
int line;
int column;
};
struct MemoryAllocationProperties {
qint64 timestamp;
qint64 size;
MemoryType type;
};
class FunctionCall {
public:
FunctionCall() : m_function(0), m_start(0), m_end(0)
{ Q_ASSERT_X(false, Q_FUNC_INFO, "Cannot construct a function call without function"); }
FunctionCall(Function *function, qint64 start, qint64 end) :
m_function(function), m_start(start), m_end(end)
{ m_function->compilationUnit->addref(); }
FunctionCall(const FunctionCall &other) :
m_function(other.m_function), m_start(other.m_start), m_end(other.m_end)
{ m_function->compilationUnit->addref(); }
~FunctionCall()
{ m_function->compilationUnit->release(); }
FunctionCall &operator=(const FunctionCall &other) {
if (&other != this) {
if (m_function)
m_function->compilationUnit->release();
m_function = other.m_function;
m_start = other.m_start;
m_end = other.m_end;
m_function->compilationUnit->addref();
}
return *this;
}
FunctionCallProperties resolve() const;
private:
friend bool operator<(const FunctionCall &call1, const FunctionCall &call2);
Function *m_function;
qint64 m_start;
qint64 m_end;
};
#define Q_V4_PROFILE_ALLOC(engine, size, type)\
(engine->profiler &&\
(engine->profiler->featuresEnabled & (1 << Profiling::FeatureMemoryAllocation)) ?\
engine->profiler->trackAlloc(size, type) : size)
#define Q_V4_PROFILE_DEALLOC(engine, pointer, size, type) \
(engine->profiler &&\
(engine->profiler->featuresEnabled & (1 << Profiling::FeatureMemoryAllocation)) ?\
engine->profiler->trackDealloc(pointer, size, type) : pointer)
#define Q_V4_PROFILE(engine, function)\
(engine->profiler &&\
(engine->profiler->featuresEnabled & (1 << Profiling::FeatureFunctionCall)) ?\
Profiling::FunctionCallProfiler::profileCall(engine->profiler, engine, function) :\
function->code(engine, function->codeData))
class Q_QML_EXPORT Profiler : public QObject {
Q_OBJECT
Q_DISABLE_COPY(Profiler)
public:
Profiler(QV4::ExecutionEngine *engine);
size_t trackAlloc(size_t size, MemoryType type)
{
MemoryAllocationProperties allocation = {m_timer.nsecsElapsed(), (qint64)size, type};
m_memory_data.append(allocation);
return size;
}
void *trackDealloc(void *pointer, size_t size, MemoryType type)
{
MemoryAllocationProperties allocation = {m_timer.nsecsElapsed(), -(qint64)size, type};
m_memory_data.append(allocation);
return pointer;
}
quint64 featuresEnabled;
public slots:
void stopProfiling();
void startProfiling(quint64 features);
void reportData();
void setTimer(const QElapsedTimer &timer) { m_timer = timer; }
signals:
void dataReady(const QVector<QV4::Profiling::FunctionCallProperties> &,
const QVector<QV4::Profiling::MemoryAllocationProperties> &);
private:
QV4::ExecutionEngine *m_engine;
QElapsedTimer m_timer;
QVector<FunctionCall> m_data;
QVector<MemoryAllocationProperties> m_memory_data;
friend class FunctionCallProfiler;
};
class FunctionCallProfiler {
Q_DISABLE_COPY(FunctionCallProfiler)
public:
// It's enough to ref() the function in the destructor as it will probably not disappear while
// it's executing ...
FunctionCallProfiler(Profiler *profiler, Function *function) :
profiler(profiler), function(function), startTime(profiler->m_timer.nsecsElapsed())
{}
~FunctionCallProfiler()
{
profiler->m_data.append(FunctionCall(function, startTime, profiler->m_timer.nsecsElapsed()));
}
static ReturnedValue profileCall(Profiler *profiler, ExecutionEngine *engine, Function *function)
{
FunctionCallProfiler callProfiler(profiler, function);
return function->code(engine, function->codeData);
}
Profiler *profiler;
Function *function;
qint64 startTime;
};
} // namespace Profiling
} // namespace QV4
Q_DECLARE_TYPEINFO(QV4::Profiling::MemoryAllocationProperties, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(QV4::Profiling::FunctionCallProperties, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(QV4::Profiling::FunctionCall, Q_MOVABLE_TYPE);
QT_END_NAMESPACE
Q_DECLARE_METATYPE(QVector<QV4::Profiling::FunctionCallProperties>)
Q_DECLARE_METATYPE(QVector<QV4::Profiling::MemoryAllocationProperties>)
#endif // QV4PROFILING_H
| [
"[email protected]"
] | |
72a8c8e1d5a24677d25f802676368885cde7f460 | c712c82341b30aad4678f6fbc758d6d20bd84c37 | /CAC_Source_1.7884/RecusalBookDialog.h | 43ecb8655aa472f0ac07fe40bdad7923e117ad1a | [] | no_license | governmentbg/EPEP_2019_d2 | ab547c729021e1d625181e264bdf287703dcb46c | 5e68240f15805c485505438b27de12bab56df91e | refs/heads/master | 2022-12-26T10:00:41.766991 | 2020-09-28T13:55:30 | 2020-09-28T13:55:30 | 292,803,726 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 358 | h | class TRecusalBookDialog : public TFloatDialog
{
public:
TRecusalBookDialog(TWindow* parent, TRecusalBookGroup *group, int resId = IDD_RECUSAL_BOOK);
protected:
TCharListFace *types;
TCharAutoListFace *compositions;
TDateFace *minDate;
TDateFace *maxDate;
TLongFace *autogen;
TCheckFace *filtered;
TCheckFace *recujed;
virtual bool IsValid();
};
| [
"[email protected]"
] | |
76e76978aa547bdd62a466f226aa7723fe14facb | 9484781e2faf0889182bc9fc9071d2a81e15e341 | /Ground.cpp | 3eaa89f1d1492713517daa9c1a3a76cd8cc0b333 | [] | no_license | Tubbz-alt/trip-to-mars | 0e34a7a608d8868a16f1748e327ada85b6310300 | 2122bb58f63abad0a2e6d0e814f7d0f2c323c98f | refs/heads/master | 2021-05-28T23:14:41.708327 | 2015-03-27T19:11:12 | 2015-03-27T19:11:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,582 | cpp | #include "Ground.h"
/*---------------------------------------------------------------------------*/
Ground::Ground(int Xground, int Zground, float MaxHigh, float SoftCoef)
{
int i,j;
xground = Xground;
zground = Zground;
maxhigh = MaxHigh;
softcoef = SoftCoef;
map = new float* [xground];
for(i=0; i<xground; i++)
map[i] = new float [zground];
if( !USEFROMFILE )
{
for(i=0; i<xground; i++)
for(j=0; j<zground; j++)
map[i][j]=-1.0;
map[0][0]=xrand(0.0, maxhigh); // 1er rnd bug
map[0][0]=xrand(0.0, maxhigh);
map[xground-1][0]=xrand(0.0, maxhigh);
map[0][zground-1]=xrand(0.0, maxhigh);
map[xground-1][zground-1]=xrand(0.0, maxhigh);
map[0][0]=0.;
map[xground-1][0]=0.;
map[0][zground-1]=0.;
map[xground-1][zground-1]=0.;
buildground();
lissage(LISSAGEDEGRE);
HighCut(HIGHCUT);
}
else
{
loadheightmap();
lissage(LISSAGEDEGRE);
}
}
/*---------------------------------------------------------------------------*/
Ground::~Ground()
{
for(int i=0; i<xground; i++)
delete [] map[i];
delete [] map;
}
/*---------------------------------------------------------------------------*/
void Ground::loadheightmap()
{
int i, j;
set_color_depth(8);
//heightmap = load_bitmap("mountainheight513.bmp", NULL);
heightmap = load_bitmap("canyonheight2.bmp", NULL);
if ( !heightmap ) { allegro_message("No Highmap Found \n"); exit(1); }
for(j=0; j<zground; j++)
for(i=0; i<xground; i++)
map[i][j] = float( (unsigned char)getpixel(heightmap, i, j) );
destroy_bitmap(heightmap);
}
/*---------------------------------------------------------------------------*/
void Ground::buildground()
{
buildsubground(0, 0, xground-1, zground-1);
}
/*---------------------------------------------------------------------------*/
void Ground::buildsubground(int x1, int z1, int x2, int z2)
{
int xm = (x1+x2)/2;
int zm = (z1+z2)/2;
int dl = MIN(x2-x1,z2-z1);
int variance;
float scaledrnd;
variance = random(dl);
variance = 2*variance - dl;
scaledrnd = float(variance) * softcoef;
if((xm!=x1)||(zm!=z1))
{
// altitude new points
map[x1][zm] = (map[x1][zm]==-1.0) ? ((map[x1][z1]+map[x1][z2])/float(2))+scaledrnd : map[x1][zm];
map[xm][z1] = (map[xm][z1]==-1.0) ? ((map[x1][z1]+map[x2][z1])/float(2))+scaledrnd : map[xm][z1];
map[xm][z2] = (map[xm][z2]==-1.0) ? ((map[x1][z2]+map[x2][z2])/float(2))+scaledrnd : map[xm][z2];
map[x2][zm] = (map[x2][zm]==-1.0) ? ((map[x2][z1]+map[x2][z2])/float(2))+scaledrnd : map[x2][zm];
map[xm][zm] = (map[xm][zm]==-1.0) ?((map[x1][z1]+map[x2][z1]+map[x1][z2]+map[x2][z2])/float(4))+scaledrnd :
map[xm][zm];
// hauteur clipping
map[x1][zm] = (map[x1][zm]<0.0) ? 0.0 : map[x1][zm];
map[xm][z1] = (map[xm][z1]<0.0) ? 0.0 : map[xm][z1];
map[xm][z2] = (map[xm][z2]<0.0) ? 0.0 : map[xm][z2];
map[x2][zm] = (map[x2][zm]<0.0) ? 0.0 : map[x2][zm];
map[xm][zm] = (map[xm][zm]<0.0) ? 0.0 : map[xm][zm];
map[x1][zm] = (map[x1][zm]>maxhigh) ? maxhigh : map[x1][zm];
map[xm][z1] = (map[xm][z1]>maxhigh) ? maxhigh : map[xm][z1];
map[xm][z2] = (map[xm][z2]>maxhigh) ? maxhigh : map[xm][z2];
map[x2][zm] = (map[x2][zm]>maxhigh) ? maxhigh : map[x2][zm];
map[xm][zm] = (map[xm][zm]>maxhigh) ? maxhigh : map[xm][zm];
// rec (!ordre>)
buildsubground(x1,z1,xm,zm);
buildsubground(xm,z1,x2,zm);
buildsubground(x1,zm,xm,z2);
buildsubground(xm,zm,x2,z2);
}
}
/*---------------------------------------------------------------------------*/
void Ground::lissage(int degre)
{
int i, j, k;
for(k=0; k<degre; k++)
for(i=1; i<xground-1; i++)
for(j=1; j<zground-1; j++)
{
if(map[i][j]!=0)
{
map[i][j]=(map[i-1][j-1]+map[i-1][j]+map[i-1][j+1]+map[i][j-1]+
map[i][j+1]+map[i+1][j-1]+map[i+1][j]+map[i+1][j+1])/8.;
}
}
}
/*---------------------------------------------------------------------------*/
void Ground::HighCut(int highcut)
{
int i, j;
for(i=0; i<xground; i++)
for(j=0; j<zground; j++)
map[i][j] = (map[i][j]<(float)highcut) ? 0.0 : map[i][j];
}
/*---------------------------------------------------------------------------*/
float Ground::xrand(float xl, float xh)
{
#if defined(LINUX)
return (xl + (xh - xl) * drand48() );
#else
return (xl + (xh - xl) * rand() / 32767.0 );
#endif
}
int Ground::random(int rndmax)
{
return ( rand() % (rndmax+1) );
}
| [
"anthony.prieur@4cb61479-95d8-4551-e4b5-d013f55dcc39"
] | anthony.prieur@4cb61479-95d8-4551-e4b5-d013f55dcc39 |
7256649c1b45655ea0cc7a7affc81c5f3fe54265 | adbc979313cbc1f0d42c79ac4206d42a8adb3234 | /Source Code/李沿橙 2017-10-23/source/李沿橙/bus/bus.cpp | 0e0ba6ecc02f0bc9722cb827d7c4ccb465cb67b0 | [] | no_license | UnnamedOrange/Contests | a7982c21e575d1342d28c57681a3c98f8afda6c0 | d593d56921d2cde0c473b3abedb419bef4cf3ba4 | refs/heads/master | 2018-10-22T02:26:51.952067 | 2018-07-21T09:32:29 | 2018-07-21T09:32:29 | 112,301,400 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,218 | cpp | #pragma G++ optimize("O3")
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <bitset>
using std::cin;
using std::cout;
using std::endl;
typedef int INT;
inline INT readIn()
{
INT a = 0;
bool minus = false;
char ch = getchar();
while (!(ch == '-' || ch >= '0' && ch <= '9')) ch = getchar();
if (ch == '-')
{
minus = true;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
a *= 10;
a += ch;
a -= '0';
ch = getchar();
}
if (minus) a = -a;
return a;
}
inline void printOut(INT x)
{
if (!x)
{
putchar('0');
}
else
{
char buffer[12];
INT length = 0;
bool minus = x < 0;
if (minus) x = -x;
while (x)
{
buffer[length++] = x % 10 + '0';
x /= 10;
}
if (minus) buffer[length++] = '-';
do
{
putchar(buffer[--length]);
} while (length);
}
putchar(' ');
}
const INT maxn = INT(1e6) + 5;
INT n, maxc;
INT c[maxn];
INT v[maxn];
struct stack : public std::vector<INT>
{
INT back2()
{
return std::vector<INT>::operator[](std::vector<INT>::size() - 2);
}
};
#define RunInstance(x) delete new x
struct cheat1
{
static const INT maxN = 5005;
INT f[maxN];
cheat1() : f()
{
f[0] = 0;
for (int i = 1; i <= n; i++)
{
f[i] = -1;
for (int j = 0; j < i; j++)
{
if ((i - j) % c[j] || f[j] == -1) continue;
INT t = f[j] + (i - j) / c[j] * v[j];
if (f[i] == -1 || f[i] > t) f[i] = t;
}
printOut(f[i]);
}
putchar('\n');
}
};
struct cheat2
{
cheat2()
{
INT cnt = v[0];
INT sum = 0;
for (int i = 1; i <= n; i++)
{
printOut(sum += cnt);
cnt = std::min(cnt, v[i]);
}
}
};
struct work
{
INT f[maxn];
stack q[11][10];
INT y(INT s)
{
return c[s] * f[s] - s * v[s];
}
INT x(INT s)
{
return v[s];
}
INT y(INT i, INT j)
{
return y(i) - y(j);
}
INT x(INT i, INT j)
{
return x(j) - x(i);
}
double slope(INT i, INT j)
{
INT x2 = x(i, j);
if (!x2) return 1e100;
return double(y(i, j)) / x2;
}
INT dp(INT i, INT j)
{
return f[j] + (i - j) / c[j] * v[j];
}
work() : f()
{
f[0] = 0;
q[c[0]][0].push_back(0);
for (int i = 1; i <= n; i++)
{
INT& ans = f[i];
ans = -1;
for (int j = 1; j <= maxc; j++)
{
stack& s = q[j][i % j];
if (s.empty()) continue;
while (s.size() > 1 &&
dp(i, s.back()) >= dp(i, s.back2()))
s.pop_back();
INT k = s.back();
INT t = dp(i, k);
if (ans == -1 || ans > t)
ans = t;
}
printOut(ans);
if (i != n && f[i] != -1)
{
stack& s = q[c[i]][i % c[i]];
while (s.size() && v[s.back()] >= v[i]) s.pop_back();
while (s.size() > 1 && slope(i, s.back()) >= slope(s.back(), s.back2()))
s.pop_back();
s.push_back(i);
}
}
}
};
void run()
{
n = readIn();
maxc = readIn();
for (int i = 0; i < n; i++)
{
c[i] = readIn();
v[i] = readIn();
}
//if (n <= 5000)
// RunInstance(cheat1);
//else if (maxc == 1)
// RunInstance(cheat2);
//else
RunInstance(work);
}
int main()
{
#ifndef JUDGE
freopen("bus.in", "r", stdin);
freopen("bus.out", "w", stdout);
#endif
run();
return 0;
}
| [
"[email protected]"
] | |
e063d1a76d7610f8d626233ecb551423c89f987c | 3dbe2d0454979091d3f1f23c3bda6f8371efe8be | /arm_compute/runtime/CL/ICLGEMMKernelSelection.h | 69b941109d33bf329ad9fe1ab326458b98ddd52e | [
"MIT",
"LicenseRef-scancode-dco-1.1"
] | permissive | alexjung/ComputeLibrary | 399339e097a34cf28f64ac23b3ccb371e121a4c9 | a9d47c17791ebce45427ea6331bd6e35f7d721f4 | refs/heads/master | 2022-11-25T22:34:48.281986 | 2020-07-30T14:38:20 | 2020-07-30T14:38:20 | 283,794,492 | 0 | 0 | MIT | 2020-07-30T14:16:27 | 2020-07-30T14:16:26 | null | UTF-8 | C++ | false | false | 2,579 | h | /*
* Copyright (c) 2020 ARM Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef ARM_COMPUTE_ICLGEMMKERNELSELECTION_H
#define ARM_COMPUTE_ICLGEMMKERNELSELECTION_H
#include "arm_compute/core/GPUTarget.h"
#include "arm_compute/core/Types.h"
#include "arm_compute/runtime/CL/CLTypes.h"
namespace arm_compute
{
namespace cl_gemm
{
/** Basic interface for the GEMM kernel selection */
class ICLGEMMKernelSelection
{
public:
/** Constructor
*
* @param[in] arch GPU target
*/
ICLGEMMKernelSelection(GPUTarget arch)
: _target(arch)
{
}
/** Default Move Constructor. */
ICLGEMMKernelSelection(ICLGEMMKernelSelection &&) = default;
/** Default move assignment operator */
ICLGEMMKernelSelection &operator=(ICLGEMMKernelSelection &&) = default;
/** Virtual destructor */
virtual ~ICLGEMMKernelSelection() = default;
/** Given the input parameters passed through @ref CLGEMMKernelSelectionParams, this method returns the @ref CLGEMMKernelType to use
*
* @param[in] params Input parameters used by the function to return the OpenCL GEMM's kernel
*
* @return @ref CLGEMMKernelType
*/
virtual CLGEMMKernelType select_kernel(const CLGEMMKernelSelectionParams ¶ms) = 0;
protected:
GPUTarget _target; /**< GPU target could be used to call a dedicated heuristic for each GPU IP for a given GPU architecture */
};
} // namespace cl_gemm
} // namespace arm_compute
#endif /*ARM_COMPUTE_ICLGEMMKERNELSELECTION_H */
| [
"[email protected]"
] | |
7a8ee6e89234f511f0c9621e346ef8e385c5868b | 9d4ad6d7f3122f8d32a4a713f06b81ecb7a47c6e | /headers/boost/1.31.0/boost/python/slice_nil.hpp | b77d06cb2248fb3ab7dd61b1ea1fd671d6904430 | [] | no_license | metashell/headers | 226d6d55eb659134a2ae2aa022b56b893bff1b30 | ceb6da74d7ca582791f33906992a5908fcaca617 | refs/heads/master | 2021-01-20T23:26:51.811362 | 2018-08-25T07:06:19 | 2018-08-25T07:06:19 | 13,360,747 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 913 | hpp | // Copyright David Abrahams 2002. Permission to copy, use,
// modify, sell and distribute this software is granted provided this
// copyright notice appears in all copies. This software is provided
// "as is" without express or implied warranty, and with no claim as
// to its suitability for any purpose.
#ifndef SLICE_NIL_DWA2002620_HPP
# define SLICE_NIL_DWA2002620_HPP
# include <boost/python/detail/prefix.hpp>
namespace boost { namespace python { namespace api {
class object;
enum slice_nil
{
# ifndef _ // Watch out for GNU gettext users, who #define _(x)
_
# endif
};
template <class T>
struct slice_bound
{
typedef object type;
};
template <>
struct slice_bound<slice_nil>
{
typedef slice_nil type;
};
}
using api::slice_nil;
# ifndef _ // Watch out for GNU gettext users, who #define _(x)
using api::_;
# endif
}} // namespace boost::python
#endif // SLICE_NIL_DWA2002620_HPP
| [
"[email protected]"
] | |
d0037625ad2d3affbd5873f079c58a7a0a50304d | 2db92f5aed1f3a18de6bfad1818ae662137692b2 | /Default.h | c4b0f2e11e1a84c2feeb019b64a2b3af6fc57ca5 | [] | no_license | Gelya-Cyber/Restoraunt | ec0bea4e6cf43543f78e266df8dae2700da192b9 | 3d0fb719568f84467b0966cd24b3e1e6af08e085 | refs/heads/master | 2022-11-13T00:05:21.289599 | 2020-06-18T12:21:22 | 2020-06-18T12:21:22 | 273,228,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,936 | h | /*********************************************************************
Rhapsody : 9.0
Login : raxma
Component : DefaultComponent
Configuration : DefaultConfig
Model Element : Default
//! Generated Date : Thu, 18, Jun 2020
File Path : DefaultComponent\DefaultConfig\Default.h
*********************************************************************/
#ifndef Default_H
#define Default_H
//## auto_generated
#include <oxf\oxf.h>
//## auto_generated
#include <oxf\event.h>
//## auto_generated
class Authorization_Form;
//## auto_generated
class CancelReservation_Form;
//## auto_generated
class Database;
//## auto_generated
class Main_Form;
//## auto_generated
class MenuAdd_Form;
//## auto_generated
class MenuDelete_Form;
//## auto_generated
class MenuEdit_Form;
//## auto_generated
class Menu_Form;
//## auto_generated
class OrderAdd_Form;
//## auto_generated
class OrderDelete_Form;
//## auto_generated
class OrderEdit_Form;
//## auto_generated
class Order_Form;
//## auto_generated
class Reservation_Form;
//## auto_generated
class Table_Form;
//## auto_generated
class WaiterAdd_Form;
//## auto_generated
class WaiterDelete_Form;
//## auto_generated
class WaiterEdit_Form;
//## auto_generated
class Waiter_Form;
//#[ ignore
#define Enter_Password_Default_id 18601
//#]
//## package Default
//## event Enter_Password()
class Enter_Password : public OMEvent {
//// Constructors and destructors ////
public :
//## auto_generated
Enter_Password();
//// Framework operations ////
//## statechart_method
virtual bool isTypeOf(const short id) const;
};
#endif
/*********************************************************************
File Path : DefaultComponent\DefaultConfig\Default.h
*********************************************************************/
| [
"[email protected]"
] | |
2816114820980efb09a736075066c1ae8208251b | 7052b9b0e0aea3524dd990bb97eacf3f492e1941 | /CC3000/examples/wlan_mag/wlan_mag.ino | 8e918bddd32ce336dcb8a9f51e0344cdf2d1d7e5 | [
"BSD-2-Clause"
] | permissive | pscholl/Adafruit_CC3000_Library | 64a1d03152ed465d61244286077686f8eed5693c | 1a571ff1a9ca7c482a497e6c94201c38ba09dc4d | refs/heads/master | 2021-01-24T20:02:10.598462 | 2015-06-23T11:35:58 | 2015-06-23T11:35:58 | 19,730,591 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,638 | ino |
/* ATTENTION: need to include Wire and I2CDev libs for
* jNode sensors (LSM9DS0, MPL115A2, VCNL4010, SHT21X)
*
* With this sample we've used 99% of available memory!
*/
#include <Wire.h>
#include <I2Cdev.h>
#include <LSM9DS0.h>
#include <Adafruit_CC3000.h>
#include <SPI.h>
#include "utility/debug.h"
#include "utility/socket.h"
unsigned long time=0;
// These are the interrupt and control pins
// DO NOT CHANGE!!!!
#define ADAFRUIT_CC3000_IRQ 11
#define ADAFRUIT_CC3000_VBAT 13
#define ADAFRUIT_CC3000_CS 10
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,
ADAFRUIT_CC3000_IRQ,
ADAFRUIT_CC3000_VBAT,
SPI_CLOCK_DIVIDER);
#define WLAN_SSID "fsr_mobi" // cannot be longer than 32 characters!
#define WLAN_PASS "woh0Roo2The7chai"
#define WLAN_SECURITY WLAN_SEC_WPA2 // Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define LISTEN_PORT 7 // What TCP port to listen on for connections
Adafruit_CC3000_Server quatServer(LISTEN_PORT);
LSM9DS0 sen;
void setup(void)
{
Wire.begin();
Serial.begin(115200);
/* Initialise the module */
//Serial.println(F("\nInitializing..."));
if (!cc3000.begin() || (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) )
{
Serial.println(F("Failed!"));
while(1);
}
while (!cc3000.checkDHCP())
{
delay(100); // ToDo: Insert a DHCP timeout!
}
/*********************************************************/
/* You can safely remove this to save some flash memory! */
/*********************************************************/
// Serial.println(F("\r\nNOTE: This sketch may cause problems with other sketches"));
// Serial.println(F("since the .disconnect() function is never called, so the"));
// Serial.println(F("AP may refuse connection requests from the CC3000 until a"));
// Serial.println(F("timeout period passes. This is normal behaviour since"));
// Serial.println(F("there isn't an obvious moment to disconnect with a server.\r\n"));
// Start listening for connections
displayConnectionDetails();
quatServer.begin();
sen.initialize();
sen.setGyroFullScale(2000);
sen.setGyroOutputDataRate(LSM9DS0_RATE_95);
sen.setGyroBandwidthCutOffMode(LSM9DS0_BW_HIGH);
sen.setGyroDataFilter(LSM9DS0_LOW_PASS);
sen.setAccRate(LSM9DS0_ACC_RATE_100);
sen.setAccFullScale(LSM9DS0_ACC_8G);
sen.setAccAntiAliasFilterBandwidth(LSM9DS0_ACC_FILTER_BW_50);
sen.setMagFullScale(LSM9DS0_MAG_4_GAUSS);
sen.setMagOutputRate(LSM9DS0_M_ODR_100);
}
#define p(x) client.print(x)
void loop(void)
{
// Try to get a client which is connected.
Adafruit_CC3000_ClientRef client = quatServer.available();
if (client) {
measurement_t m = sen.getMeasurement();
p(m.ax); p("\t"); // acceleration
p(m.ay); p("\t");
p(m.az); p("\t");
p(m.gx); p("\t"); // gyroscope
p(m.gy); p("\t");
p(m.gz); p("\t");
p(m.mx); p("\t"); // magnetometer
p(m.my); p("\t");
p(m.mz); p("\n");
}
}
/**************************************************************************/
/*!
@brief Tries to read the IP address and other connection details
*/
/**************************************************************************/
bool displayConnectionDetails(void)
{
// There is not enough space to include code for printing the full IP
// address, so we just print the last byte of it.
tNetappIpconfigRetArgs ipconfig;
netapp_ipconfig(&ipconfig);
Serial.println(ipconfig.aucIP[0]);
}
| [
"[email protected]"
] | |
df4686b64f23df1bd180ab71749f892557da3e90 | c50c4796cc416e78ef2c8883899d12f1d4e0a9e8 | /RPG/QuotesSettings.h | fcf5f16592a9e42f06884c6e6b893fd4d83f061d | [
"MIT"
] | permissive | kriskirov/RPG-Remote | 052b5c9eb24a1f61415def3cb3d72e0d30489a49 | f446f5461ad38267ed3a34dc80e8bd807ae29ef9 | refs/heads/master | 2021-01-20T01:19:10.416123 | 2017-05-09T11:37:42 | 2017-05-09T11:37:42 | 89,253,403 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 465 | h | #ifndef QUOTES_SETTINGS_H
#define QUOTES_SETTINGS_H
#include <string>
struct QuotesSettings{
QuotesSettings() = default;
QuotesSettings(
std::string attack,
std::string getAttacked,
std::string getAttackedWhileDead,
std::string dead
);
~QuotesSettings() = default;
QuotesSettings& operator=(const QuotesSettings& rhs) = default;
std::string mAttack;
std::string mGetAttacked;
std::string mGetAttackedWhileDead;
std::string mDead;
};
#endif | [
"[email protected]"
] | |
0ebecc26962b4a030a103e91a8befd0cfbb7a7ea | 95273e09057dea3ee4d8b2c7405c62c511d76e6c | /src/ESPectroBase_GpioEx.cpp | cf2412036d67e8a1d928b4cc1a1afd5715308196 | [] | no_license | alwint3r/EspX | a3af26c86f7bdace1adfe8f3ab5b50a8344bcc05 | eed8cb93a18a11a6b72be85326e2fef900427dd7 | refs/heads/master | 2020-05-29T08:40:33.140368 | 2017-01-07T19:04:28 | 2017-01-07T19:04:28 | 69,655,952 | 0 | 0 | null | 2016-09-30T10:02:22 | 2016-09-30T10:02:22 | null | UTF-8 | C++ | false | false | 979 | cpp | //
// Created by Andri Yadi on 8/1/16.
//
#include "ESPectroBase_GpioEx.h"
ESPectroBase_GpioEx::ESPectroBase_GpioEx(uint8_t address):
SX1508(address), i2cDeviceAddress_(address)
{
}
ESPectroBase_GpioEx::~ESPectroBase_GpioEx() {
}
byte ESPectroBase_GpioEx::begin(byte address, byte resetPin) {
byte addr = (address != ESPECTRO_BASE_GPIOEX_ADDRESS)? address: i2cDeviceAddress_;
byte res = SX1508::begin(addr, resetPin);
if (res) {
SX1508::pinMode(ESPECTRO_BASE_GPIOEX_LED_PIN, OUTPUT);
clock(INTERNAL_CLOCK_2MHZ, 4);
}
return res;
}
void ESPectroBase_GpioEx::turnOnLED() {
SX1508::digitalWrite(ESPECTRO_BASE_GPIOEX_LED_PIN, LOW);
}
void ESPectroBase_GpioEx::turnOffLED() {
SX1508::digitalWrite(ESPECTRO_BASE_GPIOEX_LED_PIN, HIGH);
}
void ESPectroBase_GpioEx::blinkLED(unsigned long tOn, unsigned long tOff, byte onIntensity, byte offIntensity) {
blink(ESPECTRO_BASE_GPIOEX_LED_PIN, tOn, tOff, onIntensity, offIntensity);
}
| [
"[email protected]"
] | |
abb4494d31f83c59e62840a3cbee255fc3dd0ca4 | 3011f9e4204f2988c983b8815187f56a6bf58ebd | /src/ys_library/ysglcpp/src/nownd/ysglbuffermanager_nownd.h | af34a97c2e372bd4ad528a98ad9a18d6f039d852 | [] | no_license | hvantil/AR-BoardGames | 9e80a0f2bb24f8bc06902785d104178a214d0d63 | 71b9620df66d80c583191b8c8e8b925a6df5ddc3 | refs/heads/master | 2020-03-17T01:36:47.674272 | 2018-05-13T18:11:16 | 2018-05-13T18:11:16 | 133,160,216 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,763 | h | /* ////////////////////////////////////////////////////////////
File Name: ysglbuffermanager_nownd.h
Copyright (c) 2017 Soji Yamakawa. All rights reserved.
http://www.ysflight.com
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
//////////////////////////////////////////////////////////// */
#ifndef YSGLBUFFERMANAGER_GL2_IS_INCLUDED
#define YSGLBUFFERMANAGER_GL2_IS_INCLUDED
/* { */
#include <ysclass.h>
#include <ysglbuffermanager.h>
class YsGLBufferManager::ActualBuffer
{
public:
};
/* } */
#endif
| [
"[email protected]"
] | |
753d6db593d2dbb3cbc3552a2e76c038af4365c9 | f5f750efbde0ccd95856820c975ec88ee6ace0f8 | /aws-cpp-sdk-apigateway/include/aws/apigateway/model/PutMethodRequest.h | b09c86623a5a17eb3cc9a9ae9099ed949c7e68f2 | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | csimmons0/aws-sdk-cpp | 578a4ae6e7899944f8850dc37accba5568b919eb | 1d0e1ddb51022a02700a9d1d3658abf628bb41c8 | refs/heads/develop | 2020-06-17T14:58:41.406919 | 2017-04-12T03:45:33 | 2017-04-12T03:45:33 | 74,995,798 | 0 | 0 | null | 2017-03-02T05:35:49 | 2016-11-28T17:12:34 | C++ | UTF-8 | C++ | false | false | 25,054 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/apigateway/APIGateway_EXPORTS.h>
#include <aws/apigateway/APIGatewayRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
namespace Aws
{
namespace APIGateway
{
namespace Model
{
/**
* <p>Request to add a method to an existing <a>Resource</a>
* resource.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/apigateway-2015-07-09/PutMethodRequest">AWS
* API Reference</a></p>
*/
class AWS_APIGATEWAY_API PutMethodRequest : public APIGatewayRequest
{
public:
PutMethodRequest();
Aws::String SerializePayload() const override;
/**
* <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p>
*/
inline const Aws::String& GetRestApiId() const{ return m_restApiId; }
/**
* <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p>
*/
inline void SetRestApiId(const Aws::String& value) { m_restApiIdHasBeenSet = true; m_restApiId = value; }
/**
* <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p>
*/
inline void SetRestApiId(Aws::String&& value) { m_restApiIdHasBeenSet = true; m_restApiId = value; }
/**
* <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p>
*/
inline void SetRestApiId(const char* value) { m_restApiIdHasBeenSet = true; m_restApiId.assign(value); }
/**
* <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p>
*/
inline PutMethodRequest& WithRestApiId(const Aws::String& value) { SetRestApiId(value); return *this;}
/**
* <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p>
*/
inline PutMethodRequest& WithRestApiId(Aws::String&& value) { SetRestApiId(value); return *this;}
/**
* <p>The <a>RestApi</a> identifier for the new <a>Method</a> resource.</p>
*/
inline PutMethodRequest& WithRestApiId(const char* value) { SetRestApiId(value); return *this;}
/**
* <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p>
*/
inline const Aws::String& GetResourceId() const{ return m_resourceId; }
/**
* <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p>
*/
inline void SetResourceId(const Aws::String& value) { m_resourceIdHasBeenSet = true; m_resourceId = value; }
/**
* <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p>
*/
inline void SetResourceId(Aws::String&& value) { m_resourceIdHasBeenSet = true; m_resourceId = value; }
/**
* <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p>
*/
inline void SetResourceId(const char* value) { m_resourceIdHasBeenSet = true; m_resourceId.assign(value); }
/**
* <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p>
*/
inline PutMethodRequest& WithResourceId(const Aws::String& value) { SetResourceId(value); return *this;}
/**
* <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p>
*/
inline PutMethodRequest& WithResourceId(Aws::String&& value) { SetResourceId(value); return *this;}
/**
* <p>The <a>Resource</a> identifier for the new <a>Method</a> resource.</p>
*/
inline PutMethodRequest& WithResourceId(const char* value) { SetResourceId(value); return *this;}
/**
* <p>Specifies the method request's HTTP method type.</p>
*/
inline const Aws::String& GetHttpMethod() const{ return m_httpMethod; }
/**
* <p>Specifies the method request's HTTP method type.</p>
*/
inline void SetHttpMethod(const Aws::String& value) { m_httpMethodHasBeenSet = true; m_httpMethod = value; }
/**
* <p>Specifies the method request's HTTP method type.</p>
*/
inline void SetHttpMethod(Aws::String&& value) { m_httpMethodHasBeenSet = true; m_httpMethod = value; }
/**
* <p>Specifies the method request's HTTP method type.</p>
*/
inline void SetHttpMethod(const char* value) { m_httpMethodHasBeenSet = true; m_httpMethod.assign(value); }
/**
* <p>Specifies the method request's HTTP method type.</p>
*/
inline PutMethodRequest& WithHttpMethod(const Aws::String& value) { SetHttpMethod(value); return *this;}
/**
* <p>Specifies the method request's HTTP method type.</p>
*/
inline PutMethodRequest& WithHttpMethod(Aws::String&& value) { SetHttpMethod(value); return *this;}
/**
* <p>Specifies the method request's HTTP method type.</p>
*/
inline PutMethodRequest& WithHttpMethod(const char* value) { SetHttpMethod(value); return *this;}
/**
* <p>Specifies the type of authorization used for the method.</p>
*/
inline const Aws::String& GetAuthorizationType() const{ return m_authorizationType; }
/**
* <p>Specifies the type of authorization used for the method.</p>
*/
inline void SetAuthorizationType(const Aws::String& value) { m_authorizationTypeHasBeenSet = true; m_authorizationType = value; }
/**
* <p>Specifies the type of authorization used for the method.</p>
*/
inline void SetAuthorizationType(Aws::String&& value) { m_authorizationTypeHasBeenSet = true; m_authorizationType = value; }
/**
* <p>Specifies the type of authorization used for the method.</p>
*/
inline void SetAuthorizationType(const char* value) { m_authorizationTypeHasBeenSet = true; m_authorizationType.assign(value); }
/**
* <p>Specifies the type of authorization used for the method.</p>
*/
inline PutMethodRequest& WithAuthorizationType(const Aws::String& value) { SetAuthorizationType(value); return *this;}
/**
* <p>Specifies the type of authorization used for the method.</p>
*/
inline PutMethodRequest& WithAuthorizationType(Aws::String&& value) { SetAuthorizationType(value); return *this;}
/**
* <p>Specifies the type of authorization used for the method.</p>
*/
inline PutMethodRequest& WithAuthorizationType(const char* value) { SetAuthorizationType(value); return *this;}
/**
* <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if
* the type is CUSTOM.</p>
*/
inline const Aws::String& GetAuthorizerId() const{ return m_authorizerId; }
/**
* <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if
* the type is CUSTOM.</p>
*/
inline void SetAuthorizerId(const Aws::String& value) { m_authorizerIdHasBeenSet = true; m_authorizerId = value; }
/**
* <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if
* the type is CUSTOM.</p>
*/
inline void SetAuthorizerId(Aws::String&& value) { m_authorizerIdHasBeenSet = true; m_authorizerId = value; }
/**
* <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if
* the type is CUSTOM.</p>
*/
inline void SetAuthorizerId(const char* value) { m_authorizerIdHasBeenSet = true; m_authorizerId.assign(value); }
/**
* <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if
* the type is CUSTOM.</p>
*/
inline PutMethodRequest& WithAuthorizerId(const Aws::String& value) { SetAuthorizerId(value); return *this;}
/**
* <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if
* the type is CUSTOM.</p>
*/
inline PutMethodRequest& WithAuthorizerId(Aws::String&& value) { SetAuthorizerId(value); return *this;}
/**
* <p>Specifies the identifier of an <a>Authorizer</a> to use on this Method, if
* the type is CUSTOM.</p>
*/
inline PutMethodRequest& WithAuthorizerId(const char* value) { SetAuthorizerId(value); return *this;}
/**
* <p>Specifies whether the method required a valid <a>ApiKey</a>.</p>
*/
inline bool GetApiKeyRequired() const{ return m_apiKeyRequired; }
/**
* <p>Specifies whether the method required a valid <a>ApiKey</a>.</p>
*/
inline void SetApiKeyRequired(bool value) { m_apiKeyRequiredHasBeenSet = true; m_apiKeyRequired = value; }
/**
* <p>Specifies whether the method required a valid <a>ApiKey</a>.</p>
*/
inline PutMethodRequest& WithApiKeyRequired(bool value) { SetApiKeyRequired(value); return *this;}
/**
* <p>A human-friendly operation identifier for the method. For example, you can
* assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET
* /pets</code> method in <a
* href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a>
* example.</p>
*/
inline const Aws::String& GetOperationName() const{ return m_operationName; }
/**
* <p>A human-friendly operation identifier for the method. For example, you can
* assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET
* /pets</code> method in <a
* href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a>
* example.</p>
*/
inline void SetOperationName(const Aws::String& value) { m_operationNameHasBeenSet = true; m_operationName = value; }
/**
* <p>A human-friendly operation identifier for the method. For example, you can
* assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET
* /pets</code> method in <a
* href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a>
* example.</p>
*/
inline void SetOperationName(Aws::String&& value) { m_operationNameHasBeenSet = true; m_operationName = value; }
/**
* <p>A human-friendly operation identifier for the method. For example, you can
* assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET
* /pets</code> method in <a
* href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a>
* example.</p>
*/
inline void SetOperationName(const char* value) { m_operationNameHasBeenSet = true; m_operationName.assign(value); }
/**
* <p>A human-friendly operation identifier for the method. For example, you can
* assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET
* /pets</code> method in <a
* href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a>
* example.</p>
*/
inline PutMethodRequest& WithOperationName(const Aws::String& value) { SetOperationName(value); return *this;}
/**
* <p>A human-friendly operation identifier for the method. For example, you can
* assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET
* /pets</code> method in <a
* href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a>
* example.</p>
*/
inline PutMethodRequest& WithOperationName(Aws::String&& value) { SetOperationName(value); return *this;}
/**
* <p>A human-friendly operation identifier for the method. For example, you can
* assign the <code>operationName</code> of <code>ListPets</code> for the <code>GET
* /pets</code> method in <a
* href="http://petstore-demo-endpoint.execute-api.com/petstore/pets">PetStore</a>
* example.</p>
*/
inline PutMethodRequest& WithOperationName(const char* value) { SetOperationName(value); return *this;}
/**
* <p>A key-value map defining required or optional method request parameters that
* can be accepted by Amazon API Gateway. A key defines a method request parameter
* name matching the pattern of <code>method.request.{location}.{name}</code>,
* where <code>location</code> is <code>querystring</code>, <code>path</code>, or
* <code>header</code> and <code>name</code> is a valid and unique parameter name.
* The value associated with the key is a Boolean flag indicating whether the
* parameter is required (<code>true</code>) or optional (<code>false</code>). The
* method request parameter names defined here are available in <a>Integration</a>
* to be mapped to integration request parameters or body-mapping templates.</p>
*/
inline const Aws::Map<Aws::String, bool>& GetRequestParameters() const{ return m_requestParameters; }
/**
* <p>A key-value map defining required or optional method request parameters that
* can be accepted by Amazon API Gateway. A key defines a method request parameter
* name matching the pattern of <code>method.request.{location}.{name}</code>,
* where <code>location</code> is <code>querystring</code>, <code>path</code>, or
* <code>header</code> and <code>name</code> is a valid and unique parameter name.
* The value associated with the key is a Boolean flag indicating whether the
* parameter is required (<code>true</code>) or optional (<code>false</code>). The
* method request parameter names defined here are available in <a>Integration</a>
* to be mapped to integration request parameters or body-mapping templates.</p>
*/
inline void SetRequestParameters(const Aws::Map<Aws::String, bool>& value) { m_requestParametersHasBeenSet = true; m_requestParameters = value; }
/**
* <p>A key-value map defining required or optional method request parameters that
* can be accepted by Amazon API Gateway. A key defines a method request parameter
* name matching the pattern of <code>method.request.{location}.{name}</code>,
* where <code>location</code> is <code>querystring</code>, <code>path</code>, or
* <code>header</code> and <code>name</code> is a valid and unique parameter name.
* The value associated with the key is a Boolean flag indicating whether the
* parameter is required (<code>true</code>) or optional (<code>false</code>). The
* method request parameter names defined here are available in <a>Integration</a>
* to be mapped to integration request parameters or body-mapping templates.</p>
*/
inline void SetRequestParameters(Aws::Map<Aws::String, bool>&& value) { m_requestParametersHasBeenSet = true; m_requestParameters = value; }
/**
* <p>A key-value map defining required or optional method request parameters that
* can be accepted by Amazon API Gateway. A key defines a method request parameter
* name matching the pattern of <code>method.request.{location}.{name}</code>,
* where <code>location</code> is <code>querystring</code>, <code>path</code>, or
* <code>header</code> and <code>name</code> is a valid and unique parameter name.
* The value associated with the key is a Boolean flag indicating whether the
* parameter is required (<code>true</code>) or optional (<code>false</code>). The
* method request parameter names defined here are available in <a>Integration</a>
* to be mapped to integration request parameters or body-mapping templates.</p>
*/
inline PutMethodRequest& WithRequestParameters(const Aws::Map<Aws::String, bool>& value) { SetRequestParameters(value); return *this;}
/**
* <p>A key-value map defining required or optional method request parameters that
* can be accepted by Amazon API Gateway. A key defines a method request parameter
* name matching the pattern of <code>method.request.{location}.{name}</code>,
* where <code>location</code> is <code>querystring</code>, <code>path</code>, or
* <code>header</code> and <code>name</code> is a valid and unique parameter name.
* The value associated with the key is a Boolean flag indicating whether the
* parameter is required (<code>true</code>) or optional (<code>false</code>). The
* method request parameter names defined here are available in <a>Integration</a>
* to be mapped to integration request parameters or body-mapping templates.</p>
*/
inline PutMethodRequest& WithRequestParameters(Aws::Map<Aws::String, bool>&& value) { SetRequestParameters(value); return *this;}
/**
* <p>A key-value map defining required or optional method request parameters that
* can be accepted by Amazon API Gateway. A key defines a method request parameter
* name matching the pattern of <code>method.request.{location}.{name}</code>,
* where <code>location</code> is <code>querystring</code>, <code>path</code>, or
* <code>header</code> and <code>name</code> is a valid and unique parameter name.
* The value associated with the key is a Boolean flag indicating whether the
* parameter is required (<code>true</code>) or optional (<code>false</code>). The
* method request parameter names defined here are available in <a>Integration</a>
* to be mapped to integration request parameters or body-mapping templates.</p>
*/
inline PutMethodRequest& AddRequestParameters(const Aws::String& key, bool value) { m_requestParametersHasBeenSet = true; m_requestParameters[key] = value; return *this; }
/**
* <p>A key-value map defining required or optional method request parameters that
* can be accepted by Amazon API Gateway. A key defines a method request parameter
* name matching the pattern of <code>method.request.{location}.{name}</code>,
* where <code>location</code> is <code>querystring</code>, <code>path</code>, or
* <code>header</code> and <code>name</code> is a valid and unique parameter name.
* The value associated with the key is a Boolean flag indicating whether the
* parameter is required (<code>true</code>) or optional (<code>false</code>). The
* method request parameter names defined here are available in <a>Integration</a>
* to be mapped to integration request parameters or body-mapping templates.</p>
*/
inline PutMethodRequest& AddRequestParameters(Aws::String&& key, bool value) { m_requestParametersHasBeenSet = true; m_requestParameters[key] = value; return *this; }
/**
* <p>A key-value map defining required or optional method request parameters that
* can be accepted by Amazon API Gateway. A key defines a method request parameter
* name matching the pattern of <code>method.request.{location}.{name}</code>,
* where <code>location</code> is <code>querystring</code>, <code>path</code>, or
* <code>header</code> and <code>name</code> is a valid and unique parameter name.
* The value associated with the key is a Boolean flag indicating whether the
* parameter is required (<code>true</code>) or optional (<code>false</code>). The
* method request parameter names defined here are available in <a>Integration</a>
* to be mapped to integration request parameters or body-mapping templates.</p>
*/
inline PutMethodRequest& AddRequestParameters(const char* key, bool value) { m_requestParametersHasBeenSet = true; m_requestParameters[key] = value; return *this; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline const Aws::Map<Aws::String, Aws::String>& GetRequestModels() const{ return m_requestModels; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline void SetRequestModels(const Aws::Map<Aws::String, Aws::String>& value) { m_requestModelsHasBeenSet = true; m_requestModels = value; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline void SetRequestModels(Aws::Map<Aws::String, Aws::String>&& value) { m_requestModelsHasBeenSet = true; m_requestModels = value; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& WithRequestModels(const Aws::Map<Aws::String, Aws::String>& value) { SetRequestModels(value); return *this;}
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& WithRequestModels(Aws::Map<Aws::String, Aws::String>&& value) { SetRequestModels(value); return *this;}
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& AddRequestModels(const Aws::String& key, const Aws::String& value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& AddRequestModels(Aws::String&& key, const Aws::String& value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& AddRequestModels(const Aws::String& key, Aws::String&& value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& AddRequestModels(Aws::String&& key, Aws::String&& value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& AddRequestModels(const char* key, Aws::String&& value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& AddRequestModels(Aws::String&& key, const char* value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; }
/**
* <p>Specifies the <a>Model</a> resources used for the request's content type.
* Request models are represented as a key/value map, with a content type as the
* key and a <a>Model</a> name as the value.</p>
*/
inline PutMethodRequest& AddRequestModels(const char* key, const char* value) { m_requestModelsHasBeenSet = true; m_requestModels[key] = value; return *this; }
private:
Aws::String m_restApiId;
bool m_restApiIdHasBeenSet;
Aws::String m_resourceId;
bool m_resourceIdHasBeenSet;
Aws::String m_httpMethod;
bool m_httpMethodHasBeenSet;
Aws::String m_authorizationType;
bool m_authorizationTypeHasBeenSet;
Aws::String m_authorizerId;
bool m_authorizerIdHasBeenSet;
bool m_apiKeyRequired;
bool m_apiKeyRequiredHasBeenSet;
Aws::String m_operationName;
bool m_operationNameHasBeenSet;
Aws::Map<Aws::String, bool> m_requestParameters;
bool m_requestParametersHasBeenSet;
Aws::Map<Aws::String, Aws::String> m_requestModels;
bool m_requestModelsHasBeenSet;
};
} // namespace Model
} // namespace APIGateway
} // namespace Aws
| [
"[email protected]"
] | |
1b1db33275ca9020ab39e1df49702ad2e1dfa7d8 | e1c8e3767bac2d7d2bb83e56aa46bfad6286f734 | /games/anarchy/fireDepartment.h | 6856c29f0c39dee9a08ac9c174999225c4c62dfb | [
"MIT"
] | permissive | joeykuhn/Joueur.cpp | df2709357aae71be84100bf8c39f859ffe965a86 | 9b3f9d9a37f79aad958f179cb89c4f08706387b8 | refs/heads/master | 2021-01-24T09:19:20.206407 | 2016-09-27T23:04:41 | 2016-09-27T23:04:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,872 | h | // Generated by Creer at 01:31AM on December 23, 2015 UTC, git hash: '1b69e788060071d644dd7b8745dca107577844e1'
// Can put out fires completely.
#ifndef JOUEUR_ANARCHY_FIREDEPARTMENT_H
#define JOUEUR_ANARCHY_FIREDEPARTMENT_H
#include "anarchy.h"
#include "building.h"
// <<-- Creer-Merge: includes -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// you can add addtional #includes(s) here.
// <<-- /Creer-Merge: includes -->>
/// <summary>
/// Can put out fires completely.
/// </summary>
class Anarchy::FireDepartment : public Anarchy::Building
{
friend Anarchy::GameManager;
protected:
virtual void deltaUpdateField(const std::string& fieldName, boost::property_tree::ptree& delta);
FireDepartment() {};
~FireDepartment() {};
public:
/// <summary>
/// The amount of fire removed from a building when bribed to extinguish a building.
/// </summary>
int fireExtinguished;
// <<-- Creer-Merge: fields -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// you can add addtional fields(s) here. None of them will be tracked or updated by the server.
// <<-- /Creer-Merge: fields -->>
/// <summary>
/// Bribes this FireDepartment to extinguish the some of the fire in a building.
/// </summary>
/// <param name="building">The Building you want to extinguish.</param>
/// <returns>true if the bribe worked, false otherwise</returns>
bool extinguish(Anarchy::Building* building);
// <<-- Creer-Merge: methods -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// you can add addtional method(s) here.
// <<-- /Creer-Merge: methods -->>
};
#endif
| [
"[email protected]"
] | |
60e5fb32350ab045ec71c799a0a5c28e815d2ca9 | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE122_Heap_Based_Buffer_Overflow/s04/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82_goodG2B.cpp | c33c8d71ef39b59ac89102c07f1b01680ea08a75 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 1,351 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82_goodG2B.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806.label.xml
Template File: sources-sink-82_goodG2B.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Initialize data as a large string
* GoodSource: Initialize data as a small string
* Sinks: loop
* BadSink : Copy data to string using a loop
* Flow Variant: 82 Data flow: data passed in a parameter to a virtual method called via a pointer
*
* */
#ifndef OMITGOOD
#include "std_testcase.h"
#include "CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82.h"
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82
{
void CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_wchar_t_loop_82_goodG2B::action(wchar_t * data)
{
{
wchar_t dest[50] = L"";
size_t i, dataLen;
dataLen = wcslen(data);
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
for (i = 0; i < dataLen; i++)
{
dest[i] = data[i];
}
dest[50-1] = L'\0'; /* Ensure the destination buffer is null terminated */
printWLine(data);
delete [] data;
}
}
}
#endif /* OMITGOOD */
| [
"[email protected]"
] | |
822c0cbe1df8c14a644ce9901565c54c578f3ffc | 4a887b7390deb04cf908571876e33a3c6bc63826 | /3_2DEngineWithGUI/Base.h | ca97adadb48fe9a86cf60458c1e07489b0e947f7 | [
"MIT"
] | permissive | dnjfdkanwjr/2DEngine | 504d2a97638346fdf283c0889f40f16574d0ca4a | 8908073192b6a80a84d155f07061003800e8d0ce | refs/heads/master | 2021-02-09T19:34:56.041713 | 2020-03-19T05:41:25 | 2020-03-19T05:41:25 | 244,318,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | h | #pragma once
#include <string>
namespace rp {
class Base
{
protected:
std::string name{};
bool state{};
public:
Base(std::string&& name);
virtual ~Base();
void SetName(std::string&& name)noexcept;
void SetName(std::string& name)noexcept;
void SetState(bool state)noexcept;
const std::string& GetName() const noexcept;
bool GetState() const noexcept;
};
}
| [
"[email protected]"
] | |
b4d0120da0bc869691692d0bb26876d0ff0995bf | 90e02ef236ec48414dcdb5bd08665c865605f984 | /src/cisst-saw/sawTrajectories/include/sawTrajectories/osaTrajectory.h | 8cb23c2f0b8f4d37ab48e3a23ee07f8097863e12 | [] | no_license | NicholasDascanio/dvrk_moveit | 3033ccda21d140a5feda0a7a42585c94784a1f13 | 4d23fa74f3663551791b958f96203f4196b1d765 | refs/heads/master | 2021-01-03T00:43:10.683504 | 2020-03-11T17:54:20 | 2020-03-11T17:54:20 | 239,836,095 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,035 | h | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ex: set filetype=cpp softtabstop=4 shiftwidth=4 tabstop=4 cindent expandtab: */
/*
$Id: osaTrajectory.h 4202 2013-05-17 15:39:06Z adeguet1 $
Author(s): Simon Leonard
Created on: 2012
(C) Copyright 2012-2014 Johns Hopkins University (JHU), All Rights
Reserved.
--- begin cisst license - do not edit ---
This software is provided "as is" under an open source license, with
no warranty. The complete license can be found in license.txt and
http://www.cisst.org/cisst/license.txt.
--- end cisst license ---
*/
#ifndef _osaTrajectory_h
#define _osaTrajectory_h
#include <cisstRobot/robFunction.h>
#include <cisstRobot/robManipulator.h>
#include <cisstVector/vctFrame4x4.h>
#include <cisstVector/vctDynamicVectorTypes.h>
#include <list>
#include <sawTrajectories/sawTrajectoriesExport.h>
class CISST_EXPORT osaTrajectory : public robManipulator{
public:
enum Errno
{
ESUCCESS,
EPENDING,
EEXPIRED,
EEMPTY,
EUNSUPPORTED,
ETRANSITION,
EINVALID
};
private:
double currenttime;
vctDynamicVector<double> q;
robFunction* function;
enum Space{ R3, RN, SO3, SE3 };
// segment base class
class Segment{
private:
osaTrajectory::Space inspace;
osaTrajectory::Space outspace;
protected:
double duration;
public:
Segment( osaTrajectory::Space is, osaTrajectory::Space os ) :
inspace( is ),
outspace( os ),
duration( -1.0 ){}
virtual ~Segment() {}
virtual osaTrajectory::Space InputSpace() const { return inspace; }
virtual osaTrajectory::Space OutputSpace() const { return outspace; }
};
std::list< osaTrajectory::Segment* > segments;
osaTrajectory::Errno LoadNextSegment();
// Inverse kinematics segment
class IKSegment : public Segment {
private:
vctFrame4x4<double> Rtstart; /**< start Cartesian position */
vctFrame4x4<double> Rtfinal; /**< final Carteisan position */
double v; /**< linear velocity */
double w; /**< angular velocity */
public:
IKSegment( const vctFrame4x4<double>& Rts,
const vctFrame4x4<double>& Rtf,
double v, double w);
//! Get segment start position (Cartesian pos 4x4 matrix)
vctFrame4x4<double> StateStart() const { return Rtstart; }
//! Get segment final position (Cartesian pos 4x4 matrix)
vctFrame4x4<double> StateFinal() const { return Rtfinal; }
//! Get segment linear velocity
double VelocityLinear() const { return v; }
//! Get segment angular velocity
double VelocityAngular() const { return w; }
}; // IK segment
// ZC: NOT USED ?
// Forward kinematics segment
class FKSegment : public Segment {
private:
vctDynamicVector<double> qstart;
vctDynamicVector<double> qfinal;
public:
FKSegment( const vctDynamicVector<double>& qs,
const vctDynamicVector<double>& qf,
double ) :
Segment( osaTrajectory::SE3, osaTrajectory::RN ),
qstart( qs ),
qfinal( qf ){}
//! Get segment start position (joint space ??? ZC)
vctDynamicVector<double> StateStart() const { return qstart; }
//! Get segment final position (joint space ??? ZC)
vctDynamicVector<double> StateFinal() const { return qfinal; }
}; // FK segment
// Joint segment
class RnSegment : public Segment {
private:
vctDynamicVector<double> qstart; /**< start joint position */
vctDynamicVector<double> qfinal; /**< final joint position */
vctDoubleVec vel; /**< joint velocity */
public:
RnSegment( const vctDynamicVector<double>& qs,
const vctDynamicVector<double>& qf,
double );
//! Get segment start position (joint space ??? ZC)
vctDynamicVector<double> StateStart() const { return qstart; }
//! Get segment final position (joint space ??? ZC)
vctDynamicVector<double> StateFinal() const { return qfinal; }
//! Get segment linear velocity
vctDoubleVec VelocityJoint() const { return vel; }
}; // Joint segment
double GetTime() const { return currenttime; }
void SetTime( double t ){ currenttime = t; }
osaTrajectory::Errno PostProcess();
public:
osaTrajectory( const std::string& robotfilename,
const vctFrame4x4<double>& Rtw0,
const vctDynamicVector<double>& qinit );
/**
* @brief Insert inverse kinematic segment
*
* @param Rt2
* @param vmax
* @param wmax
* @return osaTrajectory::Errno Error number
*/
osaTrajectory::Errno InsertIK( const vctFrame4x4<double>& Rt2,
double vmax,
double wmax );
osaTrajectory::Errno Insert( const vctFrame4x4<double>& Rt2, double dt );
osaTrajectory::Errno Evaluate( double t,
vctFrame4x4<double>& Rt,
vctDynamicVector<double>& q );
friend std::ostream& operator<<( std::ostream& os,
const osaTrajectory::Errno& e ){
switch( e ){
case osaTrajectory::ESUCCESS: os << "SUCCESS"; break;
case osaTrajectory::EPENDING: os << "EPENDING"; break;
case osaTrajectory::EEXPIRED: os << "EEXPIRED"; break;
case osaTrajectory::EEMPTY: os << "EEMPTY"; break;
case osaTrajectory::EUNSUPPORTED: os << "EUNSUPPORTED"; break;
case osaTrajectory::ETRANSITION: os << "ETRANSITION"; break;
case osaTrajectory::EINVALID: os << "EINVALID"; break;
}
return os;
}
};
#endif // _osaTrajectory_h
| [
"[email protected]"
] | |
bedd6b0597395d00f57558d719997af8cb55958f | 6c7cd2aecd2f055a34396cd555c3539d6bf521f1 | /sm_kinematics/src/Transformation.cpp | 1876fb255d4f7261f685e742d17a5c1e1a9e9a0b | [] | no_license | tsandy/Schweizer-Messer | 4dc3b100bd51eee78cdf9827db0143072dd7e5d3 | 77ba4c6c5668526f8dc8696375d44f5a85db0208 | refs/heads/master | 2021-01-21T00:01:20.531790 | 2013-03-22T10:35:17 | 2013-03-22T10:35:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,250 | cpp | #include <sm/kinematics/Transformation.hpp>
#include <sm/kinematics/quaternion_algebra.hpp>
#include <sm/kinematics/rotations.hpp>
#include <sm/random.hpp>
#include <sm/kinematics/UncertainHomogeneousPoint.hpp>
#include <sm/kinematics/UncertainTransformation.hpp>
#include <sm/kinematics/transformations.hpp>
namespace sm {
namespace kinematics {
Transformation::Transformation() :
_q_a_b(quatIdentity()), _t_a_b_a(0.0, 0.0, 0.0)
{
}
Transformation::Transformation(Eigen::Matrix4d const & T_a_b) :
_q_a_b( r2quat(T_a_b.topLeftCorner<3,3>()) ),
_t_a_b_a( T_a_b.topRightCorner<3,1>() )
{
}
Transformation::Transformation(const Eigen::Vector4d & q_a_b, const Eigen::Vector3d t_a_b_a) :
_q_a_b(q_a_b), _t_a_b_a(t_a_b_a)
{
_q_a_b.normalize();
}
Transformation::~Transformation(){}
/// @return the rotation matrix
Eigen::Matrix3d Transformation::C() const
{
return quat2r(_q_a_b);
}
/// @return the translation vector
const Eigen::Vector3d & Transformation::t() const
{
return _t_a_b_a;
}
const Eigen::Vector4d & Transformation::q() const
{
return _q_a_b;
}
Eigen::Matrix4d Transformation::T() const
{
Eigen::Matrix4d T_a_b;
// \todo...make this do less copying.
T_a_b.topLeftCorner<3,3>() = quat2r(_q_a_b);
T_a_b.topRightCorner<3,1>() = _t_a_b_a;
T_a_b.bottomLeftCorner<1,3>().setZero();
T_a_b(3,3) = 1.0;
return T_a_b;
}
Eigen::Matrix<double, 3,4> Transformation::T3x4() const
{
Eigen::Matrix<double, 3, 4> T3x4;
// \todo...make this do less copying.
T3x4.topLeftCorner<3,3>() = quat2r(_q_a_b);
T3x4.topRightCorner<3,1>() = _t_a_b_a;
return T3x4;
}
Transformation Transformation::inverse() const
{
// \todo Make this do less copying.
return Transformation(quatInv(_q_a_b), quatRotate(quatInv(_q_a_b),-_t_a_b_a));
}
void Transformation::checkTransformationIsValid( void ) const
{
// \todo.
}
Transformation Transformation::operator*(const Transformation & rhs) const
{
return Transformation(qplus(_q_a_b,rhs._q_a_b), quatRotate(_q_a_b,rhs._t_a_b_a) + _t_a_b_a);
}
Eigen::Vector3d Transformation::operator*(const Eigen::Vector3d & rhs) const
{
return quatRotate(_q_a_b, rhs) + _t_a_b_a;
}
Eigen::Vector4d Transformation::operator*(const Eigen::Vector4d & rhs) const
{
Eigen::Vector4d rval;
rval.head<3>() = quatRotate(_q_a_b, rhs.head<3>()) + rhs[3] * _t_a_b_a;
rval[3] = rhs[3];
return rval;
}
HomogeneousPoint Transformation::operator*(const HomogeneousPoint & rhs) const
{
Eigen::Vector4d rval = rhs.toHomogeneous();
rval.head<3>() = (quatRotate(_q_a_b, rhs.toHomogeneous().head<3>()) + rval[3] * _t_a_b_a).eval();
return HomogeneousPoint(rval);
}
void Transformation::setRandom()
{
_q_a_b = quatRandom();
_t_a_b_a = (Eigen::Vector3d::Random().array() - 0.5) * 100.0;
}
bool Transformation::isBinaryEqual(const Transformation & rhs) const
{
return _q_a_b == rhs._q_a_b && _t_a_b_a == rhs._t_a_b_a;
}
/// \brief The update step for this transformation from a minimal update.
void Transformation::oplus(const Eigen::Matrix<double,6,1> & dt)
{
_q_a_b = updateQuat( _q_a_b, dt.tail<3>() );
_t_a_b_a += dt.head<3>();
}
Eigen::Matrix<double,6,6> Transformation::S() const
{
Eigen::Matrix<double,6,6> S;
S.setIdentity();
S.topRightCorner<3,3>() = -crossMx(_t_a_b_a);
return S;
}
void Transformation::setIdentity()
{
_q_a_b = quatIdentity();
_t_a_b_a.setZero();
}
/// \brief Set this to a random transformation.
void Transformation::setRandom( double translationMaxMeters, double rotationMaxRadians)
{
// Create a random unit-length axis.
Eigen::Vector3d axis = Eigen::Vector3d::Random().array() - 0.5;
// Create a random rotation angle in radians.
double angle = sm::random::randLU(0.0, rotationMaxRadians);
// Now a random axis/angle.cp
axis.array() *= angle/axis.norm();
Eigen::Vector3d t;
t.setRandom();
t.array() -= 0.5;
t.array() *= sm::random::randLU(0.0, translationMaxMeters)/t.norm();
_q_a_b = axisAngle2quat(axis);
_t_a_b_a = t;
}
UncertainTransformation Transformation::operator*(const UncertainTransformation & UT_b_c) const
{
const Transformation & T_a_b = *this;
const Transformation & T_b_c = UT_b_c;
Transformation T_a_c = T_a_b * T_b_c;
UncertainTransformation::covariance_t T_a_b_boxtimes = boxTimes(T_a_b.T());
UncertainTransformation::covariance_t U_a_c = T_a_b_boxtimes * UT_b_c.U() * T_a_b_boxtimes.transpose();
return UncertainTransformation(T_a_c, U_a_c);
}
UncertainHomogeneousPoint Transformation::operator*(const UncertainHomogeneousPoint & p_1) const
{
const Transformation & T_0_1 = *this;
Eigen::Vector4d p_0 = T_0_1 * p_1.toHomogeneous();
Eigen::Matrix4d T01 = T_0_1.T();
UncertainHomogeneousPoint::covariance_t U = T01 * p_1.U4() * T01.transpose();
return UncertainHomogeneousPoint(p_0,U);
}
/// \brief rotate a point (do not translate)
Eigen::Vector3d Transformation::rotate(const Eigen::Vector3d & p) const
{
return quatRotate(_q_a_b, p);
}
/// \brief rotate a point (do not translate)
Eigen::Vector4d Transformation::rotate(const Eigen::Vector4d & p) const
{
Eigen::Vector4d rval = p;
rval.head<3>() = quatRotate(_q_a_b, rval.head<3>());
return rval;
}
UncertainVector3 Transformation::rotate(const UncertainVector3 & p) const
{
Eigen::Vector3d mean = rotate(p.mean());
Eigen::Matrix3d R = C();
Eigen::Matrix3d P = R * p.covariance() * R.transpose();
return UncertainVector3(mean, P);
}
} // namespace kinematics
} // namespace sm
| [
"[email protected]"
] | |
90e7de7b20078ef820c8452dca297570de5bbe97 | 959e014804f834564af221244cfb858a76f0907e | /src/NN/CellList/CellNNIteratorRuntime.hpp | b8c6d5c600658a200aad127391c7ee369464f09e | [] | no_license | rurban/openfpm_data_1.1.0 | 4626ab6fba2098c2d24f3634f3e2cf75c29eb18f | e8bb5c4ba150d13596b11daa40098612b7638c81 | refs/heads/master | 2023-06-24T16:29:45.223597 | 2019-06-05T15:23:18 | 2019-06-05T15:23:18 | 144,209,213 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,532 | hpp | /*
* CellNNIteratorRuntime.hpp
*
* Created on: Nov 18, 2016
* Author: i-bird
*/
#ifndef OPENFPM_DATA_SRC_NN_CELLLIST_CELLNNITERATORRUNTIME_HPP_
#define OPENFPM_DATA_SRC_NN_CELLLIST_CELLNNITERATORRUNTIME_HPP_
#include "util/mathutil.hpp"
#define FULL openfpm::math::pow(3,dim)
#define SYM openfpm::math::pow(3,dim)/2 + 1
#define CRS openfpm::math::pow(2,dim)
#define NO_CHECK 1
#define SAFE 2
#define RUNTIME -1
/*! \brief Iterator for the neighborhood of the cell structures
*
* In general you never create it directly but you get it from the CellList structures
*
* It iterate across all the element of the selected cell and the near cells
*
* \note to calculate quantities that involve a total reduction (like energies) use the CellIteratorSymRed
*
* \tparam dim dimensionality of the space where the cell live
* \tparam Cell cell type on which the iterator is working
* \tparam impl implementation specific options NO_CHECK do not do check on access, SAFE do check on access
*
*/
template<unsigned int dim, typename Cell,unsigned int impl>
class CellNNIterator<dim,Cell,RUNTIME,impl>
{
protected:
//! actual element id
const typename Cell::Mem_type_type::loc_index * start_id;
//! stop id to read the end of the cell
const typename Cell::Mem_type_type::loc_index * stop_id;
//! Actual NNc_id;
size_t NNc_id;
//! Size of the neighboring cells
size_t NNc_size;
//! Center cell, or cell for witch we are searching the NN-cell
const long int cell;
//! actual cell id = NNc[NNc_id]+cell stored for performance reason
size_t cell_id;
//! Cell list
Cell & cl;
//! NN cell id
const long int * NNc;
/*! \brief Select non-empty cell
*
*/
inline void selectValid()
{
while (start_id == stop_id)
{
NNc_id++;
// No more Cell
if (NNc_id >= NNc_size) return;
cell_id = NNc[NNc_id] + cell;
start_id = &cl.getStartId(cell_id);
stop_id = &cl.getStopId(cell_id);
}
}
private:
public:
/*! \brief
*
* Cell NN iterator
*
* \param cell Cell id
* \param NNc Cell neighborhood indexes (relative)
* \param NNc_size size of the neighborhood
* \param cl Cell structure
*
*/
inline CellNNIterator(size_t cell, const long int * NNc, size_t NNc_size, Cell & cl)
:NNc_id(0),NNc_size(NNc_size),cell(cell),cell_id(NNc[NNc_id] + cell),cl(cl),NNc(NNc)
{
start_id = &cl.getStartId(cell_id);
stop_id = &cl.getStopId(cell_id);
selectValid();
}
/*! \brief Check if there is the next element
*
* \return true if there is the next element
*
*/
inline bool isNext()
{
if (NNc_id >= NNc_size)
return false;
return true;
}
/*! \brief take the next element
*
* \return itself
*
*/
inline CellNNIterator & operator++()
{
start_id++;
selectValid();
return *this;
}
/*! \brief Get the value of the cell
*
* \return the next element object
*
*/
inline const typename Cell::Mem_type_type::loc_index & get()
{
return cl.get_lin(start_id);
}
};
/*! \brief Symmetric iterator for the neighborhood of the cell structures
*
* In general you never create it directly but you get it from the CellList structures
*
* It iterate across all the element of the selected cell and the near cells.
*
* \note if we query the neighborhood of p and q is the neighborhood of p
* when we will query the neighborhood of q p is not present. This is
* useful to implement formula like \f$ \sum_{q = neighborhood(p) and p <= q} \f$
*
* \tparam dim dimensionality of the space where the cell live
* \tparam Cell cell type on which the iterator is working
* \tparam NNc_size neighborhood size
* \tparam impl implementation specific options NO_CHECK do not do check on access, SAFE do check on access
*
*/
template<unsigned int dim, typename Cell,unsigned int impl>
class CellNNIteratorSym<dim,Cell,RUNTIME,impl> : public CellNNIterator<dim,Cell,RUNTIME,impl>
{
//! index of the particle p
size_t p;
//! Position of the particle p
const openfpm::vector<Point<dim,typename Cell::stype>> & v;
/*! Select the next valid element
*
*/
inline void selectValid()
{
if (this->NNc[this->NNc_id] == 0)
{
while (this->start_id < this->stop_id)
{
size_t q = this->cl.get_lin(this->start_id);
for (long int i = dim-1 ; i >= 0 ; i--)
{
if (v.template get<0>(p)[i] < v.template get<0>(q)[i])
return;
else if (v.template get<0>(p)[i] > v.template get<0>(q)[i])
goto next;
}
if (q >= p) return;
next:
this->start_id++;
}
CellNNIterator<dim,Cell,RUNTIME,impl>::selectValid();
}
else
{
CellNNIterator<dim,Cell,RUNTIME,impl>::selectValid();
}
}
public:
/*! \brief
*
* Cell NN iterator
*
* \param cell Cell id
* \param p index of the particle from which we are searching the neighborhood particles
* \param NNc Cell neighborhood indexes (relative)
* \param cl Cell structure
*
*/
inline CellNNIteratorSym(size_t cell,
size_t p,
const long int * NNc,
size_t NNc_size,
Cell & cl,
const openfpm::vector<Point<dim,typename Cell::stype>> & v)
:CellNNIterator<dim,Cell,RUNTIME,impl>(cell,NNc,NNc_size,cl),p(p),v(v)
{
if (this->NNc_id >= this->NNc_size)
return;
selectValid();
}
/*! \brief take the next element
*
* \return itself
*
*/
inline CellNNIteratorSym<dim,Cell,RUNTIME,impl> & operator++()
{
this->start_id++;
selectValid();
return *this;
}
};
#endif /* OPENFPM_DATA_SRC_NN_CELLLIST_CELLNNITERATORRUNTIME_HPP_ */
| [
"[email protected]"
] | |
a43f9f1dfb76961c6f5f3af11fd259bfd4d34983 | fc987ace8516d4d5dfcb5444ed7cb905008c6147 | /third_party/WebKit/Source/wtf/HashTraits.h | 68a18dd753fc4f94dcb94c71587b54a8c6724d89 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause"
] | permissive | nfschina/nfs-browser | 3c366cedbdbe995739717d9f61e451bcf7b565ce | b6670ba13beb8ab57003f3ba2c755dc368de3967 | refs/heads/master | 2022-10-28T01:18:08.229807 | 2020-09-07T11:45:28 | 2020-09-07T11:45:28 | 145,939,440 | 2 | 4 | BSD-3-Clause | 2022-10-13T14:59:54 | 2018-08-24T03:47:46 | null | UTF-8 | C++ | false | false | 15,939 | h | /*
* Copyright (C) 2005, 2006, 2007, 2008, 2011, 2012 Apple Inc. All rights
* reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef WTF_HashTraits_h
#define WTF_HashTraits_h
#include "wtf/Forward.h"
#include "wtf/HashFunctions.h"
#include "wtf/HashTableDeletedValueType.h"
#include "wtf/StdLibExtras.h"
#include "wtf/TypeTraits.h"
#include <limits>
#include <memory>
#include <string.h> // For memset.
#include <type_traits>
#include <utility>
namespace WTF {
template <bool isInteger, typename T>
struct GenericHashTraitsBase;
template <typename T>
struct HashTraits;
enum ShouldWeakPointersBeMarkedStrongly {
WeakPointersActStrong,
WeakPointersActWeak
};
template <typename T>
struct GenericHashTraitsBase<false, T> {
// The emptyValueIsZero flag is used to optimize allocation of empty hash
// tables with zeroed memory.
static const bool emptyValueIsZero = false;
// The hasIsEmptyValueFunction flag allows the hash table to automatically
// generate code to check for the empty value when it can be done with the
// equality operator, but allows custom functions for cases like String that
// need them.
static const bool hasIsEmptyValueFunction = false;
// The starting table size. Can be overridden when we know beforehand that a
// hash table will have at least N entries.
#if defined(MEMORY_SANITIZER_INITIAL_SIZE)
static const unsigned minimumTableSize = 1;
#else
static const unsigned minimumTableSize = 8;
#endif
// When a hash table backing store is traced, its elements will be
// traced if their class type has a trace method. However, weak-referenced
// elements should not be traced then, but handled by the weak processing
// phase that follows.
template <typename U = void>
struct IsTraceableInCollection {
static const bool value = IsTraceable<T>::value && !IsWeak<T>::value;
};
// The NeedsToForbidGCOnMove flag is used to make the hash table move
// operations safe when GC is enabled: if a move constructor invokes
// an allocation triggering the GC then it should be invoked within GC
// forbidden scope.
template <typename U = void>
struct NeedsToForbidGCOnMove {
// TODO(yutak): Consider using of std:::is_trivially_move_constructible
// when it is accessible.
static const bool value = !std::is_pod<T>::value;
};
static const WeakHandlingFlag weakHandlingFlag =
IsWeak<T>::value ? WeakHandlingInCollections
: NoWeakHandlingInCollections;
};
// Default integer traits disallow both 0 and -1 as keys (max value instead of
// -1 for unsigned).
template <typename T>
struct GenericHashTraitsBase<true, T> : GenericHashTraitsBase<false, T> {
static const bool emptyValueIsZero = true;
static void constructDeletedValue(T& slot, bool) {
slot = static_cast<T>(-1);
}
static bool isDeletedValue(T value) { return value == static_cast<T>(-1); }
};
template <typename T>
struct GenericHashTraits
: GenericHashTraitsBase<std::is_integral<T>::value, T> {
typedef T TraitType;
typedef T EmptyValueType;
static T emptyValue() { return T(); }
// Type for functions that do not take ownership, such as contains.
typedef const T& PeekInType;
typedef T* IteratorGetType;
typedef const T* IteratorConstGetType;
typedef T& IteratorReferenceType;
typedef const T& IteratorConstReferenceType;
static IteratorReferenceType getToReferenceConversion(IteratorGetType x) {
return *x;
}
static IteratorConstReferenceType getToReferenceConstConversion(
IteratorConstGetType x) {
return *x;
}
template <typename IncomingValueType>
static void store(IncomingValueType&& value, T& storage) {
storage = std::forward<IncomingValueType>(value);
}
// Type for return value of functions that do not transfer ownership, such
// as get.
// FIXME: We could change this type to const T& for better performance if we
// figured out a way to handle the return value from emptyValue, which is a
// temporary.
typedef T PeekOutType;
static const T& peek(const T& value) { return value; }
};
template <typename T>
struct HashTraits : GenericHashTraits<T> {};
template <typename T>
struct FloatHashTraits : GenericHashTraits<T> {
static T emptyValue() { return std::numeric_limits<T>::infinity(); }
static void constructDeletedValue(T& slot, bool) {
slot = -std::numeric_limits<T>::infinity();
}
static bool isDeletedValue(T value) {
return value == -std::numeric_limits<T>::infinity();
}
};
template <>
struct HashTraits<float> : FloatHashTraits<float> {};
template <>
struct HashTraits<double> : FloatHashTraits<double> {};
// Default unsigned traits disallow both 0 and max as keys -- use these traits
// to allow zero and disallow max - 1.
template <typename T>
struct UnsignedWithZeroKeyHashTraits : GenericHashTraits<T> {
static const bool emptyValueIsZero = false;
static T emptyValue() { return std::numeric_limits<T>::max(); }
static void constructDeletedValue(T& slot, bool) {
slot = std::numeric_limits<T>::max() - 1;
}
static bool isDeletedValue(T value) {
return value == std::numeric_limits<T>::max() - 1;
}
};
template <typename P>
struct HashTraits<P*> : GenericHashTraits<P*> {
static const bool emptyValueIsZero = true;
static void constructDeletedValue(P*& slot, bool) {
slot = reinterpret_cast<P*>(-1);
}
static bool isDeletedValue(P* value) {
return value == reinterpret_cast<P*>(-1);
}
};
template <typename T>
struct SimpleClassHashTraits : GenericHashTraits<T> {
static const bool emptyValueIsZero = true;
template <typename U = void>
struct NeedsToForbidGCOnMove {
static const bool value = false;
};
static void constructDeletedValue(T& slot, bool) {
new (NotNull, &slot) T(HashTableDeletedValue);
}
static bool isDeletedValue(const T& value) {
return value.isHashTableDeletedValue();
}
};
template <typename P>
struct HashTraits<RefPtr<P>> : SimpleClassHashTraits<RefPtr<P>> {
typedef std::nullptr_t EmptyValueType;
static EmptyValueType emptyValue() { return nullptr; }
static const bool hasIsEmptyValueFunction = true;
static bool isEmptyValue(const RefPtr<P>& value) { return !value; }
typedef RefPtrValuePeeker<P> PeekInType;
typedef RefPtr<P>* IteratorGetType;
typedef const RefPtr<P>* IteratorConstGetType;
typedef RefPtr<P>& IteratorReferenceType;
typedef const RefPtr<P>& IteratorConstReferenceType;
static IteratorReferenceType getToReferenceConversion(IteratorGetType x) {
return *x;
}
static IteratorConstReferenceType getToReferenceConstConversion(
IteratorConstGetType x) {
return *x;
}
static void store(PassRefPtr<P> value, RefPtr<P>& storage) {
storage = value;
}
typedef P* PeekOutType;
static PeekOutType peek(const RefPtr<P>& value) { return value.get(); }
static PeekOutType peek(std::nullptr_t) { return 0; }
};
template <typename T>
struct HashTraits<RawPtr<T>> : HashTraits<T*> {};
template <typename T>
struct HashTraits<std::unique_ptr<T>>
: SimpleClassHashTraits<std::unique_ptr<T>> {
using EmptyValueType = std::nullptr_t;
static EmptyValueType emptyValue() { return nullptr; }
static const bool hasIsEmptyValueFunction = true;
static bool isEmptyValue(const std::unique_ptr<T>& value) { return !value; }
using PeekInType = T*;
static void store(std::unique_ptr<T>&& value, std::unique_ptr<T>& storage) {
storage = std::move(value);
}
using PeekOutType = T*;
static PeekOutType peek(const std::unique_ptr<T>& value) {
return value.get();
}
static PeekOutType peek(std::nullptr_t) { return nullptr; }
static void constructDeletedValue(std::unique_ptr<T>& slot, bool) {
// Dirty trick: implant an invalid pointer to unique_ptr. Destructor isn't
// called for deleted buckets, so this is okay.
new (NotNull, &slot) std::unique_ptr<T>(reinterpret_cast<T*>(1u));
}
static bool isDeletedValue(const std::unique_ptr<T>& value) {
return value.get() == reinterpret_cast<T*>(1u);
}
};
template <>
struct HashTraits<String> : SimpleClassHashTraits<String> {
static const bool hasIsEmptyValueFunction = true;
static bool isEmptyValue(const String&);
};
// This struct template is an implementation detail of the
// isHashTraitsEmptyValue function, which selects either the emptyValue function
// or the isEmptyValue function to check for empty values.
template <typename Traits, bool hasEmptyValueFunction>
struct HashTraitsEmptyValueChecker;
template <typename Traits>
struct HashTraitsEmptyValueChecker<Traits, true> {
template <typename T>
static bool isEmptyValue(const T& value) {
return Traits::isEmptyValue(value);
}
};
template <typename Traits>
struct HashTraitsEmptyValueChecker<Traits, false> {
template <typename T>
static bool isEmptyValue(const T& value) {
return value == Traits::emptyValue();
}
};
template <typename Traits, typename T>
inline bool isHashTraitsEmptyValue(const T& value) {
return HashTraitsEmptyValueChecker<
Traits, Traits::hasIsEmptyValueFunction>::isEmptyValue(value);
}
template <typename FirstTraitsArg, typename SecondTraitsArg>
struct PairHashTraits
: GenericHashTraits<std::pair<typename FirstTraitsArg::TraitType,
typename SecondTraitsArg::TraitType>> {
typedef FirstTraitsArg FirstTraits;
typedef SecondTraitsArg SecondTraits;
typedef std::pair<typename FirstTraits::TraitType,
typename SecondTraits::TraitType>
TraitType;
typedef std::pair<typename FirstTraits::EmptyValueType,
typename SecondTraits::EmptyValueType>
EmptyValueType;
static const bool emptyValueIsZero =
FirstTraits::emptyValueIsZero && SecondTraits::emptyValueIsZero;
static EmptyValueType emptyValue() {
return std::make_pair(FirstTraits::emptyValue(),
SecondTraits::emptyValue());
}
static const bool hasIsEmptyValueFunction =
FirstTraits::hasIsEmptyValueFunction ||
SecondTraits::hasIsEmptyValueFunction;
static bool isEmptyValue(const TraitType& value) {
return isHashTraitsEmptyValue<FirstTraits>(value.first) &&
isHashTraitsEmptyValue<SecondTraits>(value.second);
}
static const unsigned minimumTableSize = FirstTraits::minimumTableSize;
static void constructDeletedValue(TraitType& slot, bool zeroValue) {
FirstTraits::constructDeletedValue(slot.first, zeroValue);
// For GC collections the memory for the backing is zeroed when it is
// allocated, and the constructors may take advantage of that,
// especially if a GC occurs during insertion of an entry into the
// table. This slot is being marked deleted, but If the slot is reused
// at a later point, the same assumptions around memory zeroing must
// hold as they did at the initial allocation. Therefore we zero the
// value part of the slot here for GC collections.
if (zeroValue)
memset(reinterpret_cast<void*>(&slot.second), 0, sizeof(slot.second));
}
static bool isDeletedValue(const TraitType& value) {
return FirstTraits::isDeletedValue(value.first);
}
};
template <typename First, typename Second>
struct HashTraits<std::pair<First, Second>>
: public PairHashTraits<HashTraits<First>, HashTraits<Second>> {};
template <typename KeyTypeArg, typename ValueTypeArg>
struct KeyValuePair {
typedef KeyTypeArg KeyType;
template <typename IncomingKeyType, typename IncomingValueType>
KeyValuePair(IncomingKeyType&& key, IncomingValueType&& value)
: key(std::forward<IncomingKeyType>(key)),
value(std::forward<IncomingValueType>(value)) {}
template <typename OtherKeyType, typename OtherValueType>
KeyValuePair(KeyValuePair<OtherKeyType, OtherValueType>&& other)
: key(std::move(other.key)), value(std::move(other.value)) {}
KeyTypeArg key;
ValueTypeArg value;
};
template <typename KeyTraitsArg, typename ValueTraitsArg>
struct KeyValuePairHashTraits
: GenericHashTraits<KeyValuePair<typename KeyTraitsArg::TraitType,
typename ValueTraitsArg::TraitType>> {
typedef KeyTraitsArg KeyTraits;
typedef ValueTraitsArg ValueTraits;
typedef KeyValuePair<typename KeyTraits::TraitType,
typename ValueTraits::TraitType>
TraitType;
typedef KeyValuePair<typename KeyTraits::EmptyValueType,
typename ValueTraits::EmptyValueType>
EmptyValueType;
static const bool emptyValueIsZero =
KeyTraits::emptyValueIsZero && ValueTraits::emptyValueIsZero;
static EmptyValueType emptyValue() {
return KeyValuePair<typename KeyTraits::EmptyValueType,
typename ValueTraits::EmptyValueType>(
KeyTraits::emptyValue(), ValueTraits::emptyValue());
}
template <typename U = void>
struct IsTraceableInCollection {
static const bool value = IsTraceableInCollectionTrait<KeyTraits>::value ||
IsTraceableInCollectionTrait<ValueTraits>::value;
};
template <typename U = void>
struct NeedsToForbidGCOnMove {
static const bool value =
KeyTraits::template NeedsToForbidGCOnMove<>::value ||
ValueTraits::template NeedsToForbidGCOnMove<>::value;
};
static const WeakHandlingFlag weakHandlingFlag =
(KeyTraits::weakHandlingFlag == WeakHandlingInCollections ||
ValueTraits::weakHandlingFlag == WeakHandlingInCollections)
? WeakHandlingInCollections
: NoWeakHandlingInCollections;
static const unsigned minimumTableSize = KeyTraits::minimumTableSize;
static void constructDeletedValue(TraitType& slot, bool zeroValue) {
KeyTraits::constructDeletedValue(slot.key, zeroValue);
// See similar code in this file for why we need to do this.
if (zeroValue)
memset(reinterpret_cast<void*>(&slot.value), 0, sizeof(slot.value));
}
static bool isDeletedValue(const TraitType& value) {
return KeyTraits::isDeletedValue(value.key);
}
};
template <typename Key, typename Value>
struct HashTraits<KeyValuePair<Key, Value>>
: public KeyValuePairHashTraits<HashTraits<Key>, HashTraits<Value>> {};
template <typename T>
struct NullableHashTraits : public HashTraits<T> {
static const bool emptyValueIsZero = false;
static T emptyValue() { return reinterpret_cast<T>(1); }
};
// This is for tracing inside collections that have special support for weak
// pointers. The trait has a trace method which returns true if there are weak
// pointers to things that have not (yet) been marked live. Returning true
// indicates that the entry in the collection may yet be removed by weak
// handling. Default implementation for non-weak types is to use the regular
// non-weak TraceTrait. Default implementation for types with weakness is to
// call traceInCollection on the type's trait.
template <WeakHandlingFlag weakHandlingFlag,
ShouldWeakPointersBeMarkedStrongly strongify,
typename T,
typename Traits>
struct TraceInCollectionTrait;
} // namespace WTF
using WTF::HashTraits;
using WTF::PairHashTraits;
using WTF::NullableHashTraits;
using WTF::SimpleClassHashTraits;
#endif // WTF_HashTraits_h
| [
"[email protected]"
] | |
4c76f75b20942941b0554679ea78f9c18c709f74 | c27df8ce4903389256023f71fc8004c6caf41d21 | /examples/common/15_tim_usonic/main.cpp | 6de553fd9ed6fd2a348a75f8890e2366befaf687 | [] | no_license | atu-guda/stm32oxc | be8f584e6978fa40482bbd5df4a23bd6b41329eb | 591b43246b8928329642b06bad8b9de6802e62ed | refs/heads/master | 2023-09-03T08:42:36.058233 | 2023-09-02T19:15:15 | 2023-09-02T19:15:15 | 34,165,176 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,877 | cpp | #include <oxc_auto.h>
#include <oxc_tim.h>
using namespace std;
using namespace SMLRL;
USE_DIE4LED_ERROR_HANDLER;
BOARD_DEFINE_LEDS;
BOARD_CONSOLE_DEFINES;
const char* common_help_string = "App to test US-014 ultrasonic sensor with timer" NL;
TIM_HandleTypeDef tim_h;
void init_usonic();
// --- local commands;
int cmd_test0( int argc, const char * const * argv );
CmdInfo CMDINFO_TEST0 { "test0", 'T', cmd_test0, " [n] - test sensor" };
const CmdInfo* global_cmds[] = {
DEBUG_CMDS,
&CMDINFO_TEST0,
nullptr
};
int main(void)
{
BOARD_PROLOG;
UVAR('t') = 1000;
UVAR('n') = 20;
BOARD_POST_INIT_BLINK;
pr( NL "##################### " PROJ_NAME NL );
srl.re_ps();
oxc_add_aux_tick_fun( led_task_nortos );
init_usonic();
delay_ms( 50 );
std_main_loop_nortos( &srl, nullptr );
return 0;
}
// TEST0
int cmd_test0( int argc, const char * const * argv )
{
int n = arg2long_d( 1, argc, argv, UVAR('n'), 0 );
uint32_t t_step = UVAR('t');
std_out << NL "Test0: n= " << n << " t= " << t_step << NL;
tim_print_cfg( TIM_EXA );
delay_ms( 10 );
uint32_t tm0 = HAL_GetTick();
break_flag = 0;
for( int i=0; i<n && !break_flag; ++i ) {
std_out << "[" << i << "] l= " << UVAR('l') << NL;
std_out.flush();
delay_ms_until_brk( &tm0, t_step );
}
return 0;
}
// ----------------------------- configs ----------------
void init_usonic()
{
// 5.8 mks approx 1mm 170000 = v_c/2 in mm/s, 998 or 846
tim_h.Init.Prescaler = calc_TIM_psc_for_cnt_freq( TIM_EXA, 170000 );
tim_h.Instance = TIM_EXA;
tim_h.Init.Period = 8500; // F approx 20Hz: for future motor PWM
tim_h.Init.ClockDivision = 0;
tim_h.Init.CounterMode = TIM_COUNTERMODE_UP;
tim_h.Init.RepetitionCounter = 0;
if( HAL_TIM_PWM_Init( &tim_h ) != HAL_OK ) {
UVAR('e') = 1; // like error
return;
}
TIM_ClockConfigTypeDef sClockSourceConfig;
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
HAL_TIM_ConfigClockSource( &tim_h, &sClockSourceConfig );
TIM_OC_InitTypeDef tim_oc_cfg;
tim_oc_cfg.OCMode = TIM_OCMODE_PWM1;
tim_oc_cfg.OCPolarity = TIM_OCPOLARITY_HIGH;
tim_oc_cfg.OCNPolarity = TIM_OCNPOLARITY_HIGH;
tim_oc_cfg.OCFastMode = TIM_OCFAST_DISABLE;
tim_oc_cfg.OCIdleState = TIM_OCIDLESTATE_RESET;
tim_oc_cfg.OCNIdleState = TIM_OCNIDLESTATE_RESET;
tim_oc_cfg.Pulse = 3; // 3 = approx 16 us
if( HAL_TIM_PWM_ConfigChannel( &tim_h, &tim_oc_cfg, TIM_CHANNEL_1 ) != HAL_OK ) {
UVAR('e') = 11;
return;
}
if( HAL_TIM_PWM_Start( &tim_h, TIM_CHANNEL_1 ) != HAL_OK ) {
UVAR('e') = 12;
return;
}
TIM_IC_InitTypeDef tim_ic_cfg;
// tim_ic_cfg.ICPolarity = TIM_ICPOLARITY_RISING;
tim_ic_cfg.ICPolarity = TIM_ICPOLARITY_BOTHEDGE; // rising - start, falling - stop
tim_ic_cfg.ICSelection = TIM_ICSELECTION_DIRECTTI;
tim_ic_cfg.ICPrescaler = TIM_ICPSC_DIV1;
tim_ic_cfg.ICFilter = 0; // 0 - 0x0F
if( HAL_TIM_IC_ConfigChannel( &tim_h, &tim_ic_cfg, TIM_CHANNEL_2 ) != HAL_OK ) {
UVAR('e') = 21;
return;
}
HAL_NVIC_SetPriority( TIM_EXA_IRQ, 7, 0 );
HAL_NVIC_EnableIRQ( TIM_EXA_IRQ );
if( HAL_TIM_IC_Start_IT( &tim_h, TIM_CHANNEL_2 ) != HAL_OK ) {
UVAR('e') = 23;
}
}
void TIM_EXA_IRQHANDLER(void)
{
HAL_TIM_IRQHandler( &tim_h );
}
void HAL_TIM_IC_CaptureCallback( TIM_HandleTypeDef *htim )
{
uint32_t cap2;
static uint32_t c_old = 0xFFFFFFFF;
if( htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2 ) {
cap2 = HAL_TIM_ReadCapturedValue( htim, TIM_CHANNEL_2 );
if( cap2 > c_old ) {
UVAR('l') = cap2 - c_old ;
leds.reset( BIT2 );
} else {
leds.set( BIT2 );
}
c_old = cap2;
UVAR('m') = cap2;
UVAR('z') = htim->Instance->CNT;
}
}
// vim: path=.,/usr/share/stm32cube/inc/,/usr/arm-none-eabi/include,/usr/share/stm32oxc/inc
| [
"[email protected]"
] | |
1a9621510a5890e6f3891087573b7d14d8e3f50b | 794decce384b8e0ba625e421cc35681b16eba577 | /tensorflow/core/data/service/snapshot/utils.h | 3ea632e5e304dbb17318c166b6eb6c58c530abb7 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | 911gt3/tensorflow | a6728e86100a2d5328280cfefcfa8e7c8de24c4c | 423ea74f41d5f605933a9d9834fe2420989fe406 | refs/heads/master | 2023-04-09T14:27:29.072195 | 2023-04-03T06:20:23 | 2023-04-03T06:22:54 | 258,948,634 | 0 | 0 | Apache-2.0 | 2020-04-26T05:36:59 | 2020-04-26T05:36:58 | null | UTF-8 | C++ | false | false | 1,592 | h | /* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_DATA_SERVICE_SNAPSHOT_UTILS_H_
#define TENSORFLOW_CORE_DATA_SERVICE_SNAPSHOT_UTILS_H_
#include <cstdint>
#include <vector>
#include "absl/strings/string_view.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/tsl/platform/status.h"
namespace tensorflow {
namespace data {
int64_t EstimatedSizeBytes(const std::vector<Tensor>& tensors);
// Returns a `Status` that indicates the snapshot stream assignment has changed
// and the worker should retry unless it's cancelled.
Status StreamAssignmentChanged(absl::string_view worker_address,
int64_t stream_index);
// Returns true if `status` indicates the snapshot stream assignment has changed
// returned by `StreamAssignmentChanged`.
bool IsStreamAssignmentChanged(const Status& status);
} // namespace data
} // namespace tensorflow
#endif // TENSORFLOW_CORE_DATA_SERVICE_SNAPSHOT_UTILS_H_
| [
"[email protected]"
] | |
8a5aab971b95db02883d20232314fe4fad3c19c2 | f12e53b806ba418a58f814ebc87c4446a422b2f5 | /solutions/uri/1789/1789.cpp | c14cdae8df69b14fd26b05dda0d6eeafcb2cf0b5 | [
"MIT"
] | permissive | biadelmont/playground | f775cd86109e30ed464d4d6eff13f9ded40627cb | 93c6248ec6cd25d75f0efbda1d50e0705bbd1e5a | refs/heads/master | 2021-05-06T15:49:43.253788 | 2017-11-07T13:00:31 | 2017-11-07T13:00:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 402 | cpp | #include <cstdio>
int main() {
int l, v, fastest;
while (scanf("%d", &l) != EOF) {
fastest = 0;
while (l--) {
scanf("%d", &v);
if (v > fastest) fastest = v;
}
if (fastest < 10) {
puts("1");
} else if (fastest < 20) {
puts("2");
} else {
puts("3");
}
}
return 0;
}
| [
"[email protected]"
] | |
ec6638730f6368f85bfaef8cb895edcd78f1e02b | 9228d266b854a8767b2c3dd9f51a6cc07a9daf5e | /Source/Lutefisk3D/2D/Drawable2D.cpp | 9758ce2b0dd619b2bf62df7bcda9da0ff5f72761 | [
"Apache-2.0",
"BSD-2-Clause",
"Zlib",
"MIT",
"LicenseRef-scancode-khronos",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Lutefisk3D/lutefisk3d | 9dfed84ab853134846ab9acf3c2fae419ec102f3 | d2132b82003427511df0167f613905191b006eb5 | refs/heads/master | 2021-10-19T03:58:00.025782 | 2019-02-17T18:14:49 | 2019-02-17T18:14:49 | 37,516,913 | 3 | 1 | NOASSERTION | 2018-10-20T12:51:56 | 2015-06-16T08:10:08 | C++ | UTF-8 | C++ | false | false | 3,563 | cpp | //
// Copyright (c) 2008-2016 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "Drawable2D.h"
#include "Renderer2D.h"
#include "Lutefisk3D/Core/Context.h"
#include "Lutefisk3D/Graphics/Camera.h"
#include "Lutefisk3D/Graphics/Material.h"
#include "Lutefisk3D/Graphics/Texture2D.h"
#include "Lutefisk3D/Scene/Scene.h"
#include "Lutefisk3D/Container/HandleManager.h"
namespace Urho3D
{
const float PIXEL_SIZE = 0.01f;
Drawable2D::Drawable2D(Context* context) :
Drawable(context, DRAWABLE_GEOMETRY2D),
layer_(0),
orderInLayer_(0),
sourceBatchesDirty_(true)
{
}
Drawable2D::~Drawable2D()
{
if (renderer_)
renderer_->RemoveDrawable(this);
}
void Drawable2D::RegisterObject(Context* context)
{
URHO3D_ACCESSOR_ATTRIBUTE("Layer", GetLayer, SetLayer, int, 0, AM_DEFAULT);
URHO3D_ACCESSOR_ATTRIBUTE("Order in Layer", GetOrderInLayer, SetOrderInLayer, int, 0, AM_DEFAULT);
URHO3D_ATTRIBUTE("View Mask", int, viewMask_, DEFAULT_VIEWMASK, AM_DEFAULT);
}
/// Handle enabled/disabled state change.
void Drawable2D::OnSetEnabled()
{
bool enabled = IsEnabledEffective();
if (enabled && renderer_)
renderer_->AddDrawable(this);
else if (!enabled && renderer_)
renderer_->RemoveDrawable(this);
}
/// Set layer.
void Drawable2D::SetLayer(int layer)
{
if (layer == layer_)
return;
layer_ = layer;
OnDrawOrderChanged();
MarkNetworkUpdate();
}
/// Set order in layer.
void Drawable2D::SetOrderInLayer(int orderInLayer)
{
if (orderInLayer == orderInLayer_)
return;
orderInLayer_ = orderInLayer;
OnDrawOrderChanged();
MarkNetworkUpdate();
}
/// Return all source batches (called by Renderer2D).
const std::vector<SourceBatch2D>& Drawable2D::GetSourceBatches()
{
if (sourceBatchesDirty_)
UpdateSourceBatches();
return sourceBatch_;
}
/// Handle scene being assigned.
void Drawable2D::OnSceneSet(Scene* scene)
{
// Do not call Drawable::OnSceneSet(node), as 2D drawable components should not be added to the octree
// but are instead rendered through Renderer2D
if (scene)
{
renderer_ = scene->GetOrCreateComponent<Renderer2D>();
if (IsEnabledEffective())
renderer_->AddDrawable(this);
}
else
{
if (renderer_)
renderer_->RemoveDrawable(this);
}
}
/// Handle node transform being dirtied.
void Drawable2D::OnMarkedDirty(Node* node)
{
Drawable::OnMarkedDirty(node);
sourceBatchesDirty_ = true;
}
}
| [
"[email protected]"
] | |
0811a45932f781306c79c102a317affdaf89c095 | fae45a23a885b72cd27c0ad1b918ad754b5de9fd | /benchmarks/shenango/parsec/pkgs/tools/cmake/src/Source/cmSeparateArgumentsCommand.cxx | ea6f065af9c9f954ceb35d70187934ff3500acf4 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-other-permissive",
"MIT"
] | permissive | bitslab/CompilerInterrupts | 6678700651c7c83fd06451c94188716e37e258f0 | 053a105eaf176b85b4c0d5e796ac1d6ee02ad41b | refs/heads/main | 2023-06-24T18:09:43.148845 | 2021-07-26T17:32:28 | 2021-07-26T17:32:28 | 342,868,949 | 3 | 3 | MIT | 2021-07-19T15:38:30 | 2021-02-27T13:57:16 | C | UTF-8 | C++ | false | false | 1,314 | cxx | /*=========================================================================
Program: CMake - Cross-Platform Makefile Generator
Module: $RCSfile: cmSeparateArgumentsCommand.cxx,v $
Language: C++
Date: $Date: 2012/03/29 17:21:08 $
Version: $Revision: 1.1.1.1 $
Copyright (c) 2002 Kitware, Inc., Insight Consortium. All rights reserved.
See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "cmSeparateArgumentsCommand.h"
// cmSeparateArgumentsCommand
bool cmSeparateArgumentsCommand
::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
{
if(args.size() != 1 )
{
this->SetError("called with incorrect number of arguments");
return false;
}
const char* cacheValue = this->Makefile->GetDefinition(args[0].c_str());
if(!cacheValue)
{
return true;
}
std::string value = cacheValue;
cmSystemTools::ReplaceString(value," ", ";");
this->Makefile->AddDefinition(args[0].c_str(), value.c_str());
return true;
}
| [
"[email protected]"
] | |
16797e4979a0f00c0f5408ba087dd3da9615e2ee | 446641d5115aaa8371a767e7e0e0597797568e33 | /Quarter 3/Week 5/closingthefarm.cpp | a811cf8531272c1710d89f581bee2d89071e997d | [
"MIT"
] | permissive | nwatx/CS3-Independent-Study | b4faa3442507121eef32e233bfacd8a549b85acc | 16b91d4e0503d10d825ae800c46ea9233cd5e066 | refs/heads/master | 2023-04-16T02:14:43.959564 | 2021-04-23T19:43:21 | 2021-04-23T19:43:21 | 290,934,485 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,207 | cpp | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update
using namespace __gnu_pbds;
using namespace std;
#pragma GCC optimize("O3")
#pragma GCC optimization ("unroll-loops")
#pragma region
using ll = long long;
using db = long double; // or double, if TL is tight
using str = string; // yay python!
using pi = pair<int,int>;
using pl = pair<ll,ll>;
using pd = pair<db,db>;
using vi = vector<int>;
using vb = vector<bool>;
using vl = vector<ll>;
using vd = vector<db>;
using vs = vector<str>;
using vpi = vector<pi>;
using vpl = vector<pl>;
using vpd = vector<pd>;
#define tcT template<class T
#define tcTU tcT, class U
// ^ lol this makes everything look weird but I'll try it
tcT> using V = vector<T>;
tcT, size_t SZ> using AR = array<T,SZ>;
tcT> using PR = pair<T,T>;
// pairs
#define mp make_pair
#define f first
#define s second
// vectors
// oops size(x), rbegin(x), rend(x) need C++17
#define sz(x) (int)x.size()
#define bg(x) x.begin()
#define en(x) x.end()
#define all(x) bg(x), end(x)
#define rall(x) x.rbegin(), x.rend()
#define sor(x) sort(all(x))
#define rsz resize
#define ins insert
#define ft front()
#define bk back()
#define pb push_back
#define eb emplace_back
#define pf push_front
#define lb lower_bound
#define ub upper_bound
tcT> int lwb(V<T>& a, const T& b) { return int(lb(all(a),b)-bg(a)); }
// loops
#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)
const int MOD = 1e9+7; // 998244353;
const ll INF = 1e18; // not too close to LLONG_MAX
const char nl = '\n';
const db PI = acos((db)-1);
const int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1}; // for every grid problem!!
mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());
template<class T> using pqg = priority_queue<T,vector<T>,greater<T>>;
template<class T> using ost = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; //order statistic tree!
// bitwise ops
// also see https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
constexpr int pct(int x) { return __builtin_popcount(x); } // # of bits set
constexpr int bits(int x) { // assert(x >= 0); // make C++11 compatible until USACO updates ...
return x == 0 ? 0 : 31-__builtin_clz(x); } // floor(log2(x))
constexpr int p2(int x) { return 1<<x; }
constexpr int msk2(int x) { return p2(x)-1; }
ll cdiv(ll a, ll b) { return a/b+((a^b)>0&&a%b); } // divide a by b rounded up
ll fdiv(ll a, ll b) { return a/b-((a^b)<0&&a%b); } // divide a by b rounded down
tcT> bool ckmin(T& a, const T& b) {
return b < a ? a = b, 1 : 0; } // set a = min(a,b)
tcT> bool ckmax(T& a, const T& b) {
return a < b ? a = b, 1 : 0; }
tcTU> T fstTrue(T lo, T hi, U f) {
hi ++; assert(lo <= hi); // assuming f is increasing
while (lo < hi) { // find first index such that f is true
T mid = lo+(hi-lo)/2;
f(mid) ? hi = mid : lo = mid+1;
}
return lo;
}
tcTU> T lstTrue(T lo, T hi, U f) {
lo --; assert(lo <= hi); // assuming f is decreasing
while (lo < hi) { // find first index such that f is true
T mid = lo+(hi-lo+1)/2;
f(mid) ? lo = mid : hi = mid-1;
}
return lo;
}
tcT> void remDup(vector<T>& v) { // sort and remove duplicates
sort(all(v)); v.erase(unique(all(v)),end(v)); }
tcTU> void erase(T& t, const U& u) { // don't erase
auto it = t.find(u); assert(it != end(t));
t.erase(it); } // element that doesn't exist from (multi)set
// INPUT
#define tcTUU tcT, class ...U
tcT> void re(complex<T>& c);
tcTU> void re(pair<T,U>& p);
tcT> void re(V<T>& v);
tcT, size_t SZ> void re(AR<T,SZ>& a);
tcT> void re(T& x) { cin >> x; }
void re(double& d) { str t; re(t); d = stod(t); }
void re(long double& d) { str t; re(t); d = stold(t); }
tcTUU> void re(T& t, U&... u) { re(t); re(u...); }
tcT> void re(complex<T>& c) { T a,b; re(a,b); c = {a,b}; }
tcTU> void re(pair<T,U>& p) { re(p.f,p.s); }
tcT> void re(V<T>& x) { trav(a,x) re(a); }
tcT, size_t SZ> void re(AR<T,SZ>& x) { trav(a,x) re(a); }
tcT> void rv(int n, V<T>& x) { x.rsz(n); re(x); }
// TO_STRING
#define ts to_string
str ts(char c) { return str(1,c); }
str ts(const char* s) { return (str)s; }
str ts(str s) { return s; }
str ts(bool b) {
// #ifdef LOCAL
// return b ? "true" : "false";
// #else
return ts((int)b);
// #endif
}
tcT> str ts(complex<T> c) {
stringstream ss; ss << c; return ss.str(); }
str ts(V<bool> v) {
str res = "{"; F0R(i,sz(v)) res += char('0'+v[i]);
res += "}"; return res; }
template<size_t SZ> str ts(bitset<SZ> b) {
str res = ""; F0R(i,SZ) res += char('0'+b[i]);
return res; }
tcTU> str ts(pair<T,U> p);
tcT> str ts(T v) { // containers with begin(), end()
#ifdef LOCAL
bool fst = 1; str res = "{";
for (const auto& x: v) {
if (!fst) res += ", ";
fst = 0; res += ts(x);
}
res += "}"; return res;
#else
bool fst = 1; str res = "";
for (const auto& x: v) {
if (!fst) res += " ";
fst = 0; res += ts(x);
}
return res;
#endif
}
tcTU> str ts(pair<T,U> p) {
#ifdef LOCAL
return "("+ts(p.f)+", "+ts(p.s)+")";
#else
return ts(p.f)+" "+ts(p.s);
#endif
}
// OUTPUT
tcT> void pr(T x) { cout << ts(x); }
tcTUU> void pr(const T& t, const U&... u) {
pr(t); pr(u...); }
void ps() { pr("\n"); } // print w/ spaces
tcTUU> void ps(const T& t, const U&... u) {
pr(t); if (sizeof...(u)) pr(" "); ps(u...); }
// DEBUG
void DBG() { cerr << "]" << endl; }
tcTUU> void DBG(const T& t, const U&... u) {
cerr << ts(t); if (sizeof...(u)) cerr << ", ";
DBG(u...); }
#ifdef LOCAL // compile with -DLOCAL, chk -> fake assert
#define dbg(...) cerr << "Line(" << __LINE__ << ") -> [" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__)
#define chk(...) if (!(__VA_ARGS__)) cerr << "Line(" << __LINE__ << ") -> function(" \
<< __FUNCTION__ << ") -> CHK FAILED: (" << #__VA_ARGS__ << ")" << "\n", exit(0);
#else
#define dbg(...) 0
#define chk(...) 0
#endif
void setPrec() { cout << fixed << setprecision(15); }
void unsyncIO() { cin.tie(0)->sync_with_stdio(0); }
// FILE I/O
void setIn(str s) { freopen(s.c_str(),"r",stdin); }
void setOut(str s) { freopen(s.c_str(),"w",stdout); }
void setIO(str s = "") {
unsyncIO(); setPrec();
// cin.exceptions(cin.failbit);
// throws exception when do smth illegal
// ex. try to read letter into int
if (sz(s)) setIn(s+".in"), setOut(s+".out"); // for USACO
}
#pragma endregion
const int MX = 2e5+1;
// make sure to intialize ALL GLOBAL VARS between tcs!
struct UF {
vi e;
UF(int n) : e(n, -1) {}
bool sameSet(int a, int b) { return find(a) == find(b); }
int size(int x) { return -e[find(x)]; }
int find(int x) { return e[x] < 0 ? x : e[x] = find(e[x]); }
bool join(int a, int b) {
a = find(a), b = find(b);
if (a == b) return false;
if (e[a] > e[b]) swap(a, b);
e[a] += e[b]; e[b] = a;
return true;
}
};
int N, M;
bool A[MX];
bool vis[MX];
vi adj[MX];
int main() {
// clock_t start = clock();
setIO("closing");
re(N, M);
UF uf(N);
F0R(i, M) {
int a, b;
re(a, b);
a--; b--;
adj[a].pb(b);
adj[b].pb(a);
}
vi order(N);
F0R(i, N) {
int a;
re(a);
a--;
order[i] = a;
}
R0F(i, N) {
vis[i] = true;
trav(e, adj[i]) {
if(vis[i] && vis[e]) uf.join(i, e);
}
uf.size(order[i]) == N-i ? pr("YES\n"): pr("NO\n");
}
// cerr << "Total Time: " << (double)(clock() - start)/ CLOCKS_PER_SEC;
}
/* stuff you should look for
* int overflow, array bounds
* special cases (n=1?)
* do smth instead of nothing and stay organized
* WRITE STUFF DOWN
* DON'T GET STUCK ON ONE APPROACH
*/ | [
"[email protected]"
] | |
b54eacb64f1d68645984c5b1e71e92db1c534771 | 332515cb827e57f3359cfe0562c5b91d711752df | /Application_UWP_WinRT/Generated Files/winrt/impl/Windows.UI.Xaml.Printing.2.h | 5e5ea5bc06e58dbf3fb9e73050c826b0a0063b8c | [
"MIT"
] | permissive | GCourtney27/DX12-Simple-Xbox-Win32-Application | 7c1f09abbfb768a1d5c2ab0d7ee9621f66ad85d5 | 4f0bc4a52aa67c90376f05146f2ebea92db1ec57 | refs/heads/master | 2023-02-19T06:54:18.923600 | 2021-01-24T08:18:19 | 2021-01-24T08:18:19 | 312,744,674 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,542 | h | // WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.201113.7
#ifndef WINRT_Windows_UI_Xaml_Printing_2_H
#define WINRT_Windows_UI_Xaml_Printing_2_H
#include "winrt/impl/Windows.UI.Xaml.1.h"
#include "winrt/impl/Windows.UI.Xaml.Printing.1.h"
WINRT_EXPORT namespace winrt::Windows::UI::Xaml::Printing
{
struct AddPagesEventHandler : Windows::Foundation::IUnknown
{
AddPagesEventHandler(std::nullptr_t = nullptr) noexcept {}
AddPagesEventHandler(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IUnknown(ptr, take_ownership_from_abi) {}
template <typename L> AddPagesEventHandler(L lambda);
template <typename F> AddPagesEventHandler(F* function);
template <typename O, typename M> AddPagesEventHandler(O* object, M method);
template <typename O, typename M> AddPagesEventHandler(com_ptr<O>&& object, M method);
template <typename O, typename M> AddPagesEventHandler(weak_ref<O>&& object, M method);
auto operator()(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::Printing::AddPagesEventArgs const& e) const;
};
struct GetPreviewPageEventHandler : Windows::Foundation::IUnknown
{
GetPreviewPageEventHandler(std::nullptr_t = nullptr) noexcept {}
GetPreviewPageEventHandler(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IUnknown(ptr, take_ownership_from_abi) {}
template <typename L> GetPreviewPageEventHandler(L lambda);
template <typename F> GetPreviewPageEventHandler(F* function);
template <typename O, typename M> GetPreviewPageEventHandler(O* object, M method);
template <typename O, typename M> GetPreviewPageEventHandler(com_ptr<O>&& object, M method);
template <typename O, typename M> GetPreviewPageEventHandler(weak_ref<O>&& object, M method);
auto operator()(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::Printing::GetPreviewPageEventArgs const& e) const;
};
struct PaginateEventHandler : Windows::Foundation::IUnknown
{
PaginateEventHandler(std::nullptr_t = nullptr) noexcept {}
PaginateEventHandler(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IUnknown(ptr, take_ownership_from_abi) {}
template <typename L> PaginateEventHandler(L lambda);
template <typename F> PaginateEventHandler(F* function);
template <typename O, typename M> PaginateEventHandler(O* object, M method);
template <typename O, typename M> PaginateEventHandler(com_ptr<O>&& object, M method);
template <typename O, typename M> PaginateEventHandler(weak_ref<O>&& object, M method);
auto operator()(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::Printing::PaginateEventArgs const& e) const;
};
struct __declspec(empty_bases) AddPagesEventArgs : Windows::UI::Xaml::Printing::IAddPagesEventArgs
{
AddPagesEventArgs(std::nullptr_t) noexcept {}
AddPagesEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::UI::Xaml::Printing::IAddPagesEventArgs(ptr, take_ownership_from_abi) {}
AddPagesEventArgs();
};
struct __declspec(empty_bases) GetPreviewPageEventArgs : Windows::UI::Xaml::Printing::IGetPreviewPageEventArgs
{
GetPreviewPageEventArgs(std::nullptr_t) noexcept {}
GetPreviewPageEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::UI::Xaml::Printing::IGetPreviewPageEventArgs(ptr, take_ownership_from_abi) {}
GetPreviewPageEventArgs();
};
struct __declspec(empty_bases) PaginateEventArgs : Windows::UI::Xaml::Printing::IPaginateEventArgs
{
PaginateEventArgs(std::nullptr_t) noexcept {}
PaginateEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::UI::Xaml::Printing::IPaginateEventArgs(ptr, take_ownership_from_abi) {}
PaginateEventArgs();
};
struct __declspec(empty_bases) PrintDocument : Windows::UI::Xaml::Printing::IPrintDocument,
impl::base<PrintDocument, Windows::UI::Xaml::DependencyObject>,
impl::require<PrintDocument, Windows::UI::Xaml::IDependencyObject, Windows::UI::Xaml::IDependencyObject2>
{
PrintDocument(std::nullptr_t) noexcept {}
PrintDocument(void* ptr, take_ownership_from_abi_t) noexcept : Windows::UI::Xaml::Printing::IPrintDocument(ptr, take_ownership_from_abi) {}
PrintDocument();
[[nodiscard]] static auto DocumentSourceProperty();
};
}
#endif
| [
"[email protected]"
] | |
b8858cf97fd7aab067a4c9453ac9560d552b4104 | a15ca13cce9b7abd1ae3ddaa255eb452b4b6f557 | /examples/compressor/ex_compressor.cpp | c96a6a88579c9ff4a38c4e661534993681117c1f | [
"MIT"
] | permissive | jrepp/DaisySP | 1b0dd4981ed02b5a04f560ff80635e62ea1c45ee | cc68b240424538c498b5c01b73ae44038458da2b | refs/heads/master | 2021-02-26T20:39:35.093106 | 2020-03-06T21:32:20 | 2020-03-06T21:32:20 | 245,552,003 | 1 | 0 | null | 2020-03-07T02:06:45 | 2020-03-07T02:06:44 | null | UTF-8 | C++ | false | false | 2,155 | cpp | #include "daisysp.h"
#include "daisy_seed.h"
// Shortening long macro for sample rate
#ifndef SAMPLE_RATE
#define SAMPLE_RATE DSY_AUDIO_SAMPLE_RATE
#endif
// Interleaved audio definitions
#define LEFT (i)
#define RIGHT (i+1)
using namespace daisysp;
static daisy_handle seed;
static Compressor comp;
// Helper Modules
static AdEnv env;
static Oscillator osc_a, osc_b;
static Metro tick;
static void AudioCallback(float *in, float *out, size_t size)
{
float osc_a_out, osc_b_out, env_out, sig_out;
for (size_t i = 0; i < size; i += 2)
{
// When the metro ticks:
// trigger the envelope to start
if (tick.Process())
{
env.Trigger();
}
// Use envelope to control the amplitude of the oscillator.
env_out = env.Process();
osc_a.SetAmp(env_out);
osc_a_out = osc_a.Process();
osc_b_out = osc_b.Process();
// Compress the steady tone with the enveloped tone.
sig_out = comp.Process(osc_b_out, osc_a_out);
// Output
out[LEFT] = sig_out; // compressed
out[RIGHT] = osc_a_out; // key signal
}
}
int main(void)
{
// initialize seed hardware and daisysp modules
daisy_seed_init(&seed);
comp.Init(SAMPLE_RATE);
env.Init(SAMPLE_RATE);
osc_a.Init(SAMPLE_RATE);
osc_b.Init(SAMPLE_RATE);
// Set up metro to pulse every second
tick.Init(1.0f, SAMPLE_RATE);
// set compressor parameters
comp.SetThreshold(-64.0f);
comp.SetRatio(2.0f);
comp.SetAttack(0.005f);
comp.SetRelease(0.1250);
// set adenv parameters
env.SetTime(ADENV_SEG_ATTACK, 0.001);
env.SetTime(ADENV_SEG_DECAY, 0.50);
env.SetMin(0.0);
env.SetMax(0.25);
env.SetCurve(0); // linear
// Set parameters for oscillator
osc_a.SetWaveform(Oscillator::WAVE_TRI);
osc_a.SetFreq(110);
osc_a.SetAmp(0.25);
osc_b.SetWaveform(Oscillator::WAVE_TRI);
osc_b.SetFreq(220);
osc_b.SetAmp(0.25);
// define callback
dsy_audio_set_callback(DSY_AUDIO_INTERNAL, AudioCallback);
// start callback
dsy_audio_start(DSY_AUDIO_INTERNAL);
while(1) {}
}
| [
"[email protected]"
] | |
ff2bc2760f6a38329c29c8103fd9ac79b6d2a8e9 | b13299265bb464aa42a73ba16ab02de672328337 | /include/lemviewer.h | 851e5b135bcf37936c872b4d93f4dc8cbc7234bd | [] | no_license | jamie124/DCPU-Developer | 65f98b33bb9420f1597bd0d2ff166924df9848db | 83e5e952872a054a44badc188d9a91390eaccc4c | refs/heads/master | 2021-01-01T15:36:11.234309 | 2013-01-19T11:40:45 | 2013-01-19T11:40:45 | 4,083,735 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,417 | h | #ifndef _LEMVIEWER_H
#define _LEMVIEWER_H
#include <QGLWidget>
#include "constants.h"
#include "emulator.h"
#include <QMutex>
const int CHAR_WIDTH = 4;
const int CHAR_HEIGHT = 8;
const int COLUMNS = 32;
const int ROWS = 12;
const int WIDTH = COLUMNS * CHAR_WIDTH;
const int HEIGHT = ROWS * CHAR_HEIGHT;
// Size of pixel, scaled up to create 0x10c look
const int PIXEL_WIDTH = 3;
const int PIXEL_HEIGHT = 3;
const int REAL_WIDTH = WIDTH * PIXEL_WIDTH;
const int REAL_HEIGHT = HEIGHT * PIXEL_HEIGHT;
const word_t defaultPalette[] = {
0x000, 0x00a, 0x0a0, 0x0aa,
0xa00, 0xa0a, 0xa50, 0xaaa,
0x555, 0x55f, 0x5f5, 0x5ff,
0xf55, 0xf5f, 0xff5, 0xfff
};
const word_t defaultFont[] = {
0xb79e, 0x388e, 0x722c, 0x75f4, 0x19bb, 0x7f8f, 0x85f9, 0xb158, 0x242e, 0x2400, 0x082a, 0x0800, 0x0008, 0x0000, 0x0808, 0x0808,
0x00ff, 0x0000, 0x00f8, 0x0808, 0x08f8, 0x0000, 0x080f, 0x0000, 0x000f, 0x0808, 0x00ff, 0x0808, 0x08f8, 0x0808, 0x08ff, 0x0000,
0x080f, 0x0808, 0x08ff, 0x0808, 0x6633, 0x99cc, 0x9933, 0x66cc, 0xfef8, 0xe080, 0x7f1f, 0x0701, 0x0107, 0x1f7f, 0x80e0, 0xf8fe,
0x5500, 0xaa00, 0x55aa, 0x55aa, 0xffaa, 0xff55, 0x0f0f, 0x0f0f, 0xf0f0, 0xf0f0, 0x0000, 0xffff, 0xffff, 0x0000, 0xffff, 0xffff,
0x0000, 0x0000, 0x005f, 0x0000, 0x0300, 0x0300, 0x3e14, 0x3e00, 0x266b, 0x3200, 0x611c, 0x4300, 0x3629, 0x7650, 0x0002, 0x0100,
0x1c22, 0x4100, 0x4122, 0x1c00, 0x1408, 0x1400, 0x081c, 0x0800, 0x4020, 0x0000, 0x0808, 0x0800, 0x0040, 0x0000, 0x601c, 0x0300,
0x3e49, 0x3e00, 0x427f, 0x4000, 0x6259, 0x4600, 0x2249, 0x3600, 0x0f08, 0x7f00, 0x2745, 0x3900, 0x3e49, 0x3200, 0x6119, 0x0700,
0x3649, 0x3600, 0x2649, 0x3e00, 0x0024, 0x0000, 0x4024, 0x0000, 0x0814, 0x2200, 0x1414, 0x1400, 0x2214, 0x0800, 0x0259, 0x0600,
0x3e59, 0x5e00, 0x7e09, 0x7e00, 0x7f49, 0x3600, 0x3e41, 0x2200, 0x7f41, 0x3e00, 0x7f49, 0x4100, 0x7f09, 0x0100, 0x3e41, 0x7a00,
0x7f08, 0x7f00, 0x417f, 0x4100, 0x2040, 0x3f00, 0x7f08, 0x7700, 0x7f40, 0x4000, 0x7f06, 0x7f00, 0x7f01, 0x7e00, 0x3e41, 0x3e00,
0x7f09, 0x0600, 0x3e61, 0x7e00, 0x7f09, 0x7600, 0x2649, 0x3200, 0x017f, 0x0100, 0x3f40, 0x7f00, 0x1f60, 0x1f00, 0x7f30, 0x7f00,
0x7708, 0x7700, 0x0778, 0x0700, 0x7149, 0x4700, 0x007f, 0x4100, 0x031c, 0x6000, 0x417f, 0x0000, 0x0201, 0x0200, 0x8080, 0x8000,
0x0001, 0x0200, 0x2454, 0x7800, 0x7f44, 0x3800, 0x3844, 0x2800, 0x3844, 0x7f00, 0x3854, 0x5800, 0x087e, 0x0900, 0x4854, 0x3c00,
0x7f04, 0x7800, 0x047d, 0x0000, 0x2040, 0x3d00, 0x7f10, 0x6c00, 0x017f, 0x0000, 0x7c18, 0x7c00, 0x7c04, 0x7800, 0x3844, 0x3800,
0x7c14, 0x0800, 0x0814, 0x7c00, 0x7c04, 0x0800, 0x4854, 0x2400, 0x043e, 0x4400, 0x3c40, 0x7c00, 0x1c60, 0x1c00, 0x7c30, 0x7c00,
0x6c10, 0x6c00, 0x4c50, 0x3c00, 0x6454, 0x4c00, 0x0836, 0x4100, 0x0077, 0x0000, 0x4136, 0x0800, 0x0201, 0x0201, 0x0205, 0x0200
};
class LemViewer :
public QGLWidget
{
Q_OBJECT
public:
LemViewer(Emulator *emu, QWidget *parent = 0);
~LemViewer();
void queueChar(int c, int r);
void drawScreen();
void drawChar(int c, int r);
void drawLoop();
void updateChar(word_t key);
word_t getColour(word_t value);
void setScreenAddress(long ramAddress);
public slots:
void animate();
protected:
void paintEvent(QPaintEvent *event);
private:
int elapsed;
Emulator *emulator;
long screenAddress;
word_map memory;
word_t videoBuffer[WIDTH][HEIGHT];
//QMap<int, QMap<int, int>> videoBuffer;
QMap<int, QMap<int, bool> > cellQueue;
bool initialised;
};
#endif
| [
"[email protected]"
] | |
04f3bf59a6968978a904c83f0712ca5e0ffa488f | be8718f6882f2b4b124b245d10d1d05c2e09a901 | /Engine/Source/Shared/Import/Mdl/MdlNode.cpp | 124f9d419de8f8cb5e8219e2d627270585d87776 | [] | no_license | kolhammer/Psybrus | fd907a8e25b488327846d46853ca219c55cca81b | 21c794568eed41aaacb633cd87dedd5ce2793115 | refs/heads/master | 2016-09-05T08:58:04.427316 | 2012-03-19T11:33:32 | 2012-03-19T11:33:32 | 3,031,999 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,811 | cpp | /**************************************************************************
*
* File: MdlNode.cpp
* Author: Neil Richardson
* Ver/Date:
* Description:
* Model node.
*
*
*
*
**************************************************************************/
#include "MdlNode.h"
#include "MdlMesh.h"
#include "MdlMorph.h"
#include "MdlEntity.h"
#include "Base/BcDebug.h"
#include "Base/BcString.h"
//////////////////////////////////////////////////////////////////////////
// Ctor
MdlNode::MdlNode():
NodeType_( eNT_EMPTY ),
pParent_( NULL ),
pChild_( NULL ),
pNext_( NULL )
{
RelativeTransform_.identity();
AbsoluteTransform_.identity();
pNodeMeshObject_ = NULL;
pNodeSkinObject_ = NULL;
pNodeColMeshObject_ = NULL;
pNodeMorphObject_ = NULL;
pNodeEntityObject_ = NULL;
pNodeLightObject_ = NULL;
pNodeProjectorObject_ = NULL;
}
//////////////////////////////////////////////////////////////////////////
// Dtor
MdlNode::~MdlNode()
{
delete pNodeMeshObject_;
delete pNodeSkinObject_;
delete pNodeColMeshObject_;
delete pNodeMorphObject_;
delete pNodeEntityObject_;
delete pNodeLightObject_;
delete pNodeProjectorObject_;
///* NOTE: Memory corruption somewhere.
MdlNode* pNext = pChild_;
while( pNext != NULL )
{
MdlNode* pTheNext = pNext->pNext_;
delete pNext;
pNext = pTheNext;
}
}
//////////////////////////////////////////////////////////////////////////
// name
void MdlNode::name( const BcChar* Name )
{
BcStrCopy( Name_, Name );
}
const BcChar* MdlNode::name()
{
return Name_;
}
//////////////////////////////////////////////////////////////////////////
// parentNode
BcBool MdlNode::parentNode( MdlNode* pNode, const BcChar* ParentName )
{
BcBool bParented = BcFalse;
// Parent another node to this tree.
if( ParentName == NULL || BcStrCompare( ParentName, Name_ ) )
{
// Tell the node who its parent is.
pNode->pParent_ = this;
// If we have a child already we need our next to match.
if( pChild_ != NULL )
{
MdlNode* pParentNode = pChild_;
// Find the last node
while( pParentNode->pNext_ != NULL )
{
BcAssert( pParentNode != pParentNode->pNext_ );
pParentNode = pParentNode->pNext_;
}
//
pParentNode->pNext_ = pNode;
bParented = BcTrue;
}
else
{
pChild_ = pNode;
bParented = BcTrue;
}
}
else
{
// If we are not the destined parent pass it to next and child.
// Find the last node
MdlNode* pNextNode = pChild_;
while( pNextNode != NULL )
{
bParented |= pNextNode->parentNode( pNode, ParentName );
pNextNode = pNextNode->pNext_;
}
}
return bParented;
}
//////////////////////////////////////////////////////////////////////////
// makeRelativeTransform
void MdlNode::makeRelativeTransform( const BcMat4d& ParentAbsolute )
{
// Parent another node to this tree.
MdlNode* pNextNode = pChild_;
//
BcMat4d InverseParent = ParentAbsolute;
InverseParent.inverse();
RelativeTransform_ = AbsoluteTransform_ * InverseParent;
// For all the nodes parented to the same as us.
while( pNextNode != NULL )
{
pNextNode->makeRelativeTransform( AbsoluteTransform_ );
pNextNode = pNextNode->pNext_;
}
}
//////////////////////////////////////////////////////////////////////////
// makeAbsoluteTransform
void MdlNode::makeAbsoluteTransform( const BcMat4d& ParentAbsolute )
{
// Parent another node to this tree.
MdlNode* pNextNode = pChild_;
//
BcMat4d InverseParent = ParentAbsolute;
InverseParent.inverse();
AbsoluteTransform_ = ParentAbsolute * RelativeTransform_;
// For all the nodes parented to the same as us.
while( pNextNode != NULL )
{
pNextNode->makeAbsoluteTransform( AbsoluteTransform_ );
pNextNode = pNextNode->pNext_;
}
}
//////////////////////////////////////////////////////////////////////////
// flipTransform
void MdlNode::flipTransform( BcMat4d& Transform )
{
Transform.transpose();
Transform[0][2] = -Transform[0][2];
Transform[1][2] = -Transform[1][2];
Transform[2][0] = -Transform[2][0];
Transform[2][1] = -Transform[2][1];
Transform[2][3] = -Transform[2][3];
Transform.transpose();
}
//////////////////////////////////////////////////////////////////////////
// flipTransforms
void MdlNode::flipCoordinateSpace()
{
// Parent another node to this tree.
MdlNode* pNextNode = pChild_;
// Flip absolute and inverse bind pose transforms.
flipTransform( AbsoluteTransform_ );
flipTransform( InverseBindpose_ );
// If we've got a mesh, flip it's coordinate space.
if( type() & eNT_MESH )
{
pNodeMeshObject_->flipCoordinateSpace();
}
if( type() & eNT_SKIN )
{
pNodeSkinObject_->flipCoordinateSpace();
}
if( type() & eNT_MORPH )
{
pNodeMorphObject_->flipCoordinateSpace();
}
// For all the nodes parented to the same as us.
while( pNextNode != NULL )
{
pNextNode->flipCoordinateSpace();
pNextNode = pNextNode->pNext_;
}
}
//////////////////////////////////////////////////////////////////////////
// type
void MdlNode::type( BcU32 NodeType )
{
if( NodeType != eNT_COLMESH && NodeType != eNT_ENTITY )
{
BcAssert( ( NodeType_ & ~NodeType ) == 0 );
}
if( ( NodeType_ & NodeType ) == 0 )
{
NodeType_ |= NodeType;
switch( NodeType )
{
case eNT_EMPTY:
break;
case eNT_MESH:
pNodeMeshObject_ = new MdlMesh();
break;
case eNT_SKIN:
pNodeSkinObject_ = new MdlMesh();
break;
case eNT_COLMESH:
// Naughty.
//pNodeColMeshObject_ = new MdlMesh();
BcAssert( pNodeMeshObject_ != NULL );
break;
case eNT_MORPH:
pNodeMorphObject_ = new MdlMesh();
break;
case eNT_ENTITY:
pNodeEntityObject_ = new MdlEntity();
break;
case eNT_LIGHT:
pNodeLightObject_ = new MdlLight();
break;
case eNT_PROJECTOR:
pNodeProjectorObject_ = new MdlProjector();
break;
}
}
}
//////////////////////////////////////////////////////////////////////////
// countJoints
void MdlNode::countJoints( BcU32& iCount )
{
if( type() & eNT_JOINT )
{
iCount++;
}
MdlNode* pNextNode = pChild_;
while( pNextNode != NULL )
{
if( pNextNode->type() & eNT_JOINT )
{
pNextNode->countJoints( iCount );
}
pNextNode = pNextNode->pNext_;
}
}
//////////////////////////////////////////////////////////////////////////
//
void MdlNode::findAllAABBs()
{
MdlNode* pNextNode = pChild_;
// If our AABB is empty, calculate our bounds based on child nodes.
if( AABB_.isEmpty() )
{
while( pNextNode != NULL )
{
// Find our childs..
pNextNode->findAllAABBs();
// Add its AABB to ours.
if( pNextNode->AABB_.isEmpty() == BcFalse )
{
AABB_.expandBy( pNextNode->AABB_ );
}
//
pNextNode = pNextNode->pNext_;
}
// Transform our AABB
if( AABB_.isEmpty() == BcFalse )
{
AABB_ = AABB_.transform( AbsoluteTransform_ );
}
}
else
{
// Transform ours.
AABB_ = AABB_.transform( AbsoluteTransform_ );
}
} | [
"[email protected]"
] | |
ffb32c7bfa66792ff42c6982c642d1dd258c2f1d | 4a4109182be077240476da145c1ea0366a190b7c | /Plugins/QFireBase/qfirebase.cpp | f49d959a1e797a0219f5ae4bff27ccb231e15e97 | [] | no_license | devkitcc/SDMedic | 5f7c0a59856108b4d55bc3f051eca3d241073e4b | 14509964f5730923268e138ccdb2e99bc944d7b2 | refs/heads/master | 2021-05-08T01:36:28.333248 | 2017-10-22T17:14:38 | 2017-10-22T17:14:38 | 107,885,884 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 58 | cpp | #include "qfirebase.h"
QFireBase::QFireBase()
{
}
| [
"[email protected]"
] | |
278610710edb06f4e8cfd21ed070aaad83328446 | 2eac4cb30dd9fbbf73e35c294f8549107dbeee0e | /src/Adjacency.h | 1f071998066f9571840d8a5dad9345aec43f4c24 | [] | no_license | patrickmacarthur/OurAdventure | 9f720f8523eea467f8d101e44613a4d0f5a92183 | 2db5450af6601f924f8de614fb3b83ed42e98b29 | refs/heads/master | 2021-01-23T07:08:54.335142 | 2014-10-28T18:03:36 | 2014-10-28T18:03:36 | 2,129,865 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,575 | h | #ifndef ADJACENCY_H
#define ADJACENCY_H
/* Adjacency.h
*
* Author: Patrick MacArthur
*
* This file is part of the CS 516 Final Project
*/
#include <istream>
#include <ostream>
#include <map>
#include "Direction.h"
#include "Item.h"
class Feature;
class Map;
/*
* This class represents an adjacency between rooms.
*/
class Adjacency : public Item
{
public:
Adjacency();
// constructor
virtual ~Adjacency();
// destructor
virtual void addToMap( Map * map );
// Adds this item to the map
virtual Item * clone() const;
// dynamic copy
virtual Feature * getExit( const Direction & );
// Gets the exit in the given direction. Returns 0 if
// there is no feature in that direction.
virtual int getExitCount() const;
// Returns the number of exits.
const ID & getFeatureID() const;
// Returns the ID of the "source" feature.
virtual void input( std::istream & s, Map * );
// Inputs the adjacency in the format:
// featureId directionCount directionName featureId ...
virtual void printDescription( std::ostream & s );
// Outputs the adjacency list in a human-readable
// format
virtual void save( std::ostream & s );
// Saves the adjacency list to disk in same format
// input, except adds type tag in front
private:
std::map<Direction, Feature *> m_table;
ID m_featureID;
};
/* vim: set et sw=4 tw=65: */
#endif
| [
"[email protected]"
] | |
fde7c6cfbc63c7a0c1dd0d967b977e264112cbc1 | 618729b2291385cd51e395db1dbca933439312b4 | /os.cpp | 45d040c176383938996e8c33040817a91f08459f | [] | no_license | grih9/fluffyOS | bfe2bfc7de37366c57d34fa50d1421c344b6a682 | f3ed3efd5863d857d76065b04216aa3298a09e0c | refs/heads/master | 2023-04-11T07:23:10.383620 | 2021-04-18T15:49:27 | 2021-04-18T15:49:27 | 359,168,571 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,815 | cpp | #include <stdio.h>
#include "sys.h"
#include "rtos_api.h"
// Инициализация стеков
void InitializeStacks(int numStack)
{
char cushionSpace[100000];
cushionSpace[99999] = 1; // отключаем оптимизацию массивов
for (int i = 0; i <= MAX_TASK; ++i) {
if (!setjmp(InitStacks[i])) {
continue;
} else {
TaskQueue[RunningTask].entry();
break;
}
}
}
int StartOS(TTaskCall entry, int priority, char *name)
{
RunningTask = TaskHead = -1;
TaskCount = 0; //подсчет задач
FreeTask = 0; //ожидающие задачи
printf("StartOS!\n");
InitializeStacks(0); //инициализация стека
for (int i = 0; i < MAX_TASK; i++)
{
TaskQueue[i].next = i + 1; // номер массива на след элемент
TaskQueue[i].prev = i - 1; // пред элемент
TaskQueue[i].task_state = TASK_SUSPENDED; // пометка ожидания (неактивная задача)
TaskQueue[i].switch_count = 0; // ключ
TaskQueue[i].waiting_events = 0; // ожидание задачи
TaskQueue[i].working_events = 0; // сработавшие задачи
} // создание массива задач
TaskQueue[MAX_TASK - 1].next = 0; // присваиваем последнему элементу 0
TaskQueue[0].prev = MAX_TASK - 1; // присваиваем предпоследний
if (!setjmp(MainContext)) {
ActivateTask(entry, priority, name); // запускаем функцию активации задачи
}
return 0;
}
// Завершает работу системы(задача завершена)
void ShutdownOS()
{
printf("ShutdownOS!\n");
} | [
"[email protected]"
] | |
2afdee78415e6b3b8019099f55955075a2ac3d2b | 9a3558d9cc1070d75b6972abaf12339f3c43b672 | /libraries/helper/helper.hpp | 8dfa3d61682d662d17355285d1b50d766492c757 | [] | no_license | kurokis/Ublox | 32888bb69d5eeebc8eab9d6e47997c5d825d1e35 | a434a513ba68d25e7badce022e73b77ca3e2f2a3 | refs/heads/master | 2021-01-21T12:30:40.132612 | 2017-09-03T11:23:12 | 2017-09-03T11:23:12 | 102,074,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 845 | hpp | //
// helper.hpp
// GPS_READER
//
// Created by blue-i on 01/09/2017.
// Copyright © 2017 blue-i. All rights reserved.
//
#ifndef helper_hpp
#define helper_hpp
#include <stdio.h>
#include "string.h"
#include <iostream>
#include <stdio.h>
#include <unistd.h> //Used for UART
#include <fcntl.h> //Used for UART
#include <termios.h> //Used for UART
#include <sys/ioctl.h> //Used for UART
#include <sys/stat.h> //Used for fifo
#include <poll.h> //Pollin()
#define UBLOX_INITIAL_BAUD B9600
#define UBLOX_OPERATING_BAUD B57600
#define GPS_PORT "/dev/ttyUSB_Ublox"
void UART_Init(int b);
void UBloxTxBuffer(const char b[], int t);
void UART_Close();
void GPS_Init(void);
bool file_exist(const std::string& name);
bool pollin(void);
void Reader_sender(void);
void run(void);
#endif /* helper_hpp */
| [
"[email protected]"
] | |
9384681a8ebcae72126edc49a2f1a1bd6af8758e | e132d5b086464fe0651223df74f06ff16dfbdcff | /example/doc/http_examples.hpp | 4cd879ae33d50860d75cdddada4cbb427748f006 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | shibing/beast | fa1de3a19ecd1bf55120b92e4ebdf9cf99894f24 | c495f946c92c1175d30e1e8e60d412c3a30025b4 | refs/heads/develop | 2021-01-02T22:56:23.222703 | 2017-08-03T15:53:12 | 2017-08-03T15:53:12 | 99,427,713 | 1 | 0 | null | 2017-08-05T14:29:21 | 2017-08-05T14:29:21 | null | UTF-8 | C++ | false | false | 35,802 | hpp | //
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot 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)
//
// Official repository: https://github.com/boostorg/beast
//
#include <boost/beast.hpp>
#include <iostream>
/* This file contains the functions and classes found in the documentation
They are compiled and run as part of the unit tests, so you can copy
the code and use it in your own projects as a starting point for
building a network application.
*/
// The documentation assumes the boost::beast::http namespace
namespace boost {
namespace beast {
namespace http {
//------------------------------------------------------------------------------
//
// Example: Expect 100-continue
//
//------------------------------------------------------------------------------
//[example_http_send_expect_100_continue
/** Send a request with Expect: 100-continue
This function will send a request with the Expect: 100-continue
field by first sending the header, then waiting for a successful
response from the server before continuing to send the body. If
a non-successful server response is received, the function
returns immediately.
@param stream The remote HTTP server stream.
@param buffer The buffer used for reading.
@param req The request to send. This function modifies the object:
the Expect header field is inserted into the message if it does
not already exist, and set to "100-continue".
@param ec Set to the error, if any occurred.
*/
template<
class SyncStream,
class DynamicBuffer,
class Body, class Allocator>
void
send_expect_100_continue(
SyncStream& stream,
DynamicBuffer& buffer,
request<Body, basic_fields<Allocator>>& req,
error_code& ec)
{
static_assert(is_sync_stream<SyncStream>::value,
"SyncStream requirements not met");
static_assert(is_dynamic_buffer<DynamicBuffer>::value,
"DynamicBuffer requirements not met");
// Insert or replace the Expect field
req.set(field::expect, "100-continue");
// Create the serializer
request_serializer<Body, basic_fields<Allocator>> sr{req};
// Send just the header
write_header(stream, sr, ec);
if(ec)
return;
// Read the response from the server.
// A robust client could set a timeout here.
{
response<string_body> res;
read(stream, buffer, res, ec);
if(ec)
return;
if(res.result() != status::continue_)
{
// The server indicated that it will not
// accept the request, so skip sending the body.
return;
}
}
// Server is OK with the request, send the body
write(stream, sr, ec);
}
//]
//[example_http_receive_expect_100_continue
/** Receive a request, handling Expect: 100-continue if present.
This function will read a request from the specified stream.
If the request contains the Expect: 100-continue field, a
status response will be delivered.
@param stream The remote HTTP client stream.
@param buffer The buffer used for reading.
@param ec Set to the error, if any occurred.
*/
template<
class SyncStream,
class DynamicBuffer>
void
receive_expect_100_continue(
SyncStream& stream,
DynamicBuffer& buffer,
error_code& ec)
{
static_assert(is_sync_stream<SyncStream>::value,
"SyncStream requirements not met");
static_assert(is_dynamic_buffer<DynamicBuffer>::value,
"DynamicBuffer requirements not met");
// Declare a parser for a request with a string body
request_parser<string_body> parser;
// Read the header
read_header(stream, buffer, parser, ec);
if(ec)
return;
// Check for the Expect field value
if(parser.get()[field::expect] == "100-continue")
{
// send 100 response
response<empty_body> res;
res.version = 11;
res.result(status::continue_);
res.set(field::server, "test");
write(stream, res, ec);
if(ec)
return;
}
// Read the rest of the message.
//
// We use parser.base() to return a basic_parser&, to avoid an
// ambiguous function error (from boost::asio::read). Another
// solution is to qualify the call, e.g. `beast::http::read`
//
read(stream, buffer, parser.base(), ec);
}
//]
//------------------------------------------------------------------------------
//
// Example: Send Child Process Output
//
//------------------------------------------------------------------------------
//[example_http_send_cgi_response
/** Send the output of a child process as an HTTP response.
The output of the child process comes from a @b SyncReadStream. Data
will be sent continuously as it is produced, without the requirement
that the entire process output is buffered before being sent. The
response will use the chunked transfer encoding.
@param input A stream to read the child process output from.
@param output A stream to write the HTTP response to.
@param ec Set to the error, if any occurred.
*/
template<
class SyncReadStream,
class SyncWriteStream>
void
send_cgi_response(
SyncReadStream& input,
SyncWriteStream& output,
error_code& ec)
{
static_assert(is_sync_read_stream<SyncReadStream>::value,
"SyncReadStream requirements not met");
static_assert(is_sync_write_stream<SyncWriteStream>::value,
"SyncWriteStream requirements not met");
using boost::asio::buffer_cast;
using boost::asio::buffer_size;
// Set up the response. We use the buffer_body type,
// allowing serialization to use manually provided buffers.
response<buffer_body> res;
res.result(status::ok);
res.version = 11;
res.set(field::server, "Beast");
res.set(field::transfer_encoding, "chunked");
// No data yet, but we set more = true to indicate
// that it might be coming later. Otherwise the
// serializer::is_done would return true right after
// sending the header.
res.body.data = nullptr;
res.body.more = true;
// Create the serializer.
response_serializer<buffer_body, fields> sr{res};
// Send the header immediately.
write_header(output, sr, ec);
if(ec)
return;
// Alternate between reading from the child process
// and sending all the process output until there
// is no more output.
do
{
// Read a buffer from the child process
char buffer[2048];
auto bytes_transferred = input.read_some(
boost::asio::buffer(buffer, sizeof(buffer)), ec);
if(ec == boost::asio::error::eof)
{
ec = {};
// `nullptr` indicates there is no buffer
res.body.data = nullptr;
// `false` means no more data is coming
res.body.more = false;
}
else
{
if(ec)
return;
// Point to our buffer with the bytes that
// we received, and indicate that there may
// be some more data coming
res.body.data = buffer;
res.body.size = bytes_transferred;
res.body.more = true;
}
// Write everything in the body buffer
write(output, sr, ec);
// This error is returned by body_buffer during
// serialization when it is done sending the data
// provided and needs another buffer.
if(ec == error::need_buffer)
{
ec = {};
continue;
}
if(ec)
return;
}
while(! sr.is_done());
}
//]
//--------------------------------------------------------------------------
//
// Example: HEAD Request
//
//--------------------------------------------------------------------------
//[example_http_do_head_response
/** Handle a HEAD request for a resource.
*/
template<
class SyncStream,
class DynamicBuffer
>
void do_server_head(
SyncStream& stream,
DynamicBuffer& buffer,
error_code& ec)
{
static_assert(is_sync_stream<SyncStream>::value,
"SyncStream requirements not met");
static_assert(is_dynamic_buffer<DynamicBuffer>::value,
"DynamicBuffer requirments not met");
// We deliver this payload for all GET requests
static std::string const payload = "Hello, world!";
// Read the request
request<string_body> req;
read(stream, buffer, req, ec);
if(ec)
return;
// Set up the response, starting with the common fields
response<string_body> res;
res.version = 11;
res.set(field::server, "test");
// Now handle request-specific fields
switch(req.method())
{
case verb::head:
case verb::get:
{
// A HEAD request is handled by delivering the same
// set of headers that would be sent for a GET request,
// including the Content-Length, except for the body.
res.result(status::ok);
res.set(field::content_length, payload.size());
// For GET requests, we include the body
if(req.method() == verb::get)
{
// We deliver the same payload for GET requests
// regardless of the target. A real server might
// deliver a file based on the target.
res.body = payload;
}
break;
}
default:
{
// We return responses indicating an error if
// we do not recognize the request method.
res.result(status::bad_request);
res.set(field::content_type, "text/plain");
res.body = "Invalid request-method '" + req.method_string().to_string() + "'";
res.prepare_payload();
break;
}
}
// Send the response
write(stream, res, ec);
if(ec)
return;
}
//]
//[example_http_do_head_request
/** Send a HEAD request for a resource.
This function submits a HEAD request for the specified resource
and returns the response.
@param res The response. This is an output parameter.
@param stream The synchronous stream to use.
@param buffer The buffer to use.
@param target The request target.
@param ec Set to the error, if any occurred.
@throws std::invalid_argument if target is empty.
*/
template<
class SyncStream,
class DynamicBuffer
>
response<empty_body>
do_head_request(
SyncStream& stream,
DynamicBuffer& buffer,
string_view target,
error_code& ec)
{
// Do some type checking to be a good citizen
static_assert(is_sync_stream<SyncStream>::value,
"SyncStream requirements not met");
static_assert(is_dynamic_buffer<DynamicBuffer>::value,
"DynamicBuffer requirments not met");
// The interfaces we are using are low level and do not
// perform any checking of arguments; so we do it here.
if(target.empty())
throw std::invalid_argument("target may not be empty");
// Build the HEAD request for the target
request<empty_body> req;
req.version = 11;
req.method(verb::head);
req.target(target);
req.set(field::user_agent, "test");
// A client MUST send a Host header field in all HTTP/1.1 request messages.
// https://tools.ietf.org/html/rfc7230#section-5.4
req.set(field::host, "localhost");
// Now send it
write(stream, req, ec);
if(ec)
return {};
// Create a parser to read the response.
// Responses to HEAD requests MUST NOT include
// a body, so we use the `empty_body` type and
// only attempt to read the header.
parser<false, empty_body> p;
read_header(stream, buffer, p, ec);
if(ec)
return {};
// Transfer ownership of the response to the caller.
return p.release();
}
//]
//------------------------------------------------------------------------------
//
// Example: HTTP Relay
//
//------------------------------------------------------------------------------
//[example_http_relay
/** Relay an HTTP message.
This function efficiently relays an HTTP message from a downstream
client to an upstream server, or from an upstream server to a
downstream client. After the message header is read from the input,
a user provided transformation function is invoked which may change
the contents of the header before forwarding to the output. This may
be used to adjust fields such as Server, or proxy fields.
@param output The stream to write to.
@param input The stream to read from.
@param buffer The buffer to use for the input.
@param transform The header transformation to apply. The function will
be called with this signature:
@code
template<class Body>
void transform(message<
isRequest, Body, Fields>&, // The message to transform
error_code&); // Set to the error, if any
@endcode
@param ec Set to the error if any occurred.
@tparam isRequest `true` to relay a request.
@tparam Fields The type of fields to use for the message.
*/
template<
bool isRequest,
class SyncWriteStream,
class SyncReadStream,
class DynamicBuffer,
class Transform>
void
relay(
SyncWriteStream& output,
SyncReadStream& input,
DynamicBuffer& buffer,
error_code& ec,
Transform&& transform)
{
static_assert(is_sync_write_stream<SyncWriteStream>::value,
"SyncWriteStream requirements not met");
static_assert(is_sync_read_stream<SyncReadStream>::value,
"SyncReadStream requirements not met");
// A small buffer for relaying the body piece by piece
char buf[2048];
// Create a parser with a buffer body to read from the input.
parser<isRequest, buffer_body> p;
// Create a serializer from the message contained in the parser.
serializer<isRequest, buffer_body, fields> sr{p.get()};
// Read just the header from the input
read_header(input, buffer, p, ec);
if(ec)
return;
// Apply the caller's header tranformation
transform(p.get(), ec);
if(ec)
return;
// Send the transformed message to the output
write_header(output, sr, ec);
if(ec)
return;
// Loop over the input and transfer it to the output
do
{
if(! p.is_done())
{
// Set up the body for writing into our small buffer
p.get().body.data = buf;
p.get().body.size = sizeof(buf);
// Read as much as we can
read(input, buffer, p, ec);
// This error is returned when buffer_body uses up the buffer
if(ec == error::need_buffer)
ec = {};
if(ec)
return;
// Set up the body for reading.
// This is how much was parsed:
p.get().body.size = sizeof(buf) - p.get().body.size;
p.get().body.data = buf;
p.get().body.more = ! p.is_done();
}
else
{
p.get().body.data = nullptr;
p.get().body.size = 0;
}
// Write everything in the buffer (which might be empty)
write(output, sr, ec);
// This error is returned when buffer_body uses up the buffer
if(ec == error::need_buffer)
ec = {};
if(ec)
return;
}
while(! p.is_done() && ! sr.is_done());
}
//]
//------------------------------------------------------------------------------
//
// Example: Serialize to std::ostream
//
//------------------------------------------------------------------------------
//[example_http_write_ostream
// The detail namespace means "not public"
namespace detail {
// This helper is needed for C++11.
// When invoked with a buffer sequence, writes the buffers `to the std::ostream`.
template<class Serializer>
class write_ostream_helper
{
Serializer& sr_;
std::ostream& os_;
public:
write_ostream_helper(Serializer& sr, std::ostream& os)
: sr_(sr)
, os_(os)
{
}
// This function is called by the serializer
template<class ConstBufferSequence>
void
operator()(error_code& ec, ConstBufferSequence const& buffers) const
{
// These asio functions are needed to access a buffer's contents
using boost::asio::buffer_cast;
using boost::asio::buffer_size;
// Error codes must be cleared on success
ec = {};
// Keep a running total of how much we wrote
std::size_t bytes_transferred = 0;
// Loop over the buffer sequence
for(auto it = buffers.begin(); it != buffers.end(); ++ it)
{
// This is the next buffer in the sequence
boost::asio::const_buffer const buffer = *it;
// Write it to the std::ostream
os_.write(
buffer_cast<char const*>(buffer),
buffer_size(buffer));
// If the std::ostream fails, convert it to an error code
if(os_.fail())
{
ec = make_error_code(errc::io_error);
return;
}
// Adjust our running total
bytes_transferred += buffer_size(buffer);
}
// Inform the serializer of the amount we consumed
sr_.consume(bytes_transferred);
}
};
} // detail
/** Write a message to a `std::ostream`.
This function writes the serialized representation of the
HTTP/1 message to the sream.
@param os The `std::ostream` to write to.
@param msg The message to serialize.
@param ec Set to the error, if any occurred.
*/
template<
bool isRequest,
class Body,
class Fields>
void
write_ostream(
std::ostream& os,
message<isRequest, Body, Fields>& msg,
error_code& ec)
{
// Create the serializer instance
serializer<isRequest, Body, Fields> sr{msg};
// This lambda is used as the "visit" function
detail::write_ostream_helper<decltype(sr)> lambda{sr, os};
do
{
// In C++14 we could use a generic lambda but since we want
// to require only C++11, the lambda is written out by hand.
// This function call retrieves the next serialized buffers.
sr.next(ec, lambda);
if(ec)
return;
}
while(! sr.is_done());
}
//]
//------------------------------------------------------------------------------
//
// Example: Parse from std::istream
//
//------------------------------------------------------------------------------
//[example_http_read_istream
/** Read a message from a `std::istream`.
This function attempts to parse a complete HTTP/1 message from the stream.
@param is The `std::istream` to read from.
@param buffer The buffer to use.
@param msg The message to store the result.
@param ec Set to the error, if any occurred.
*/
template<
class Allocator,
bool isRequest,
class Body>
void
read_istream(
std::istream& is,
basic_flat_buffer<Allocator>& buffer,
message<isRequest, Body, fields>& msg,
error_code& ec)
{
// Create the message parser
//
// Arguments passed to the parser's constructor are
// forwarded to the message constructor. Here, we use
// a move construction in case the caller has constructed
// their message in a non-default way.
//
parser<isRequest, Body> p{std::move(msg)};
do
{
// Extract whatever characters are presently available in the istream
if(is.rdbuf()->in_avail() > 0)
{
// Get a mutable buffer sequence for writing
auto const mb = buffer.prepare(
static_cast<std::size_t>(is.rdbuf()->in_avail()));
// Now get everything we can from the istream
buffer.commit(static_cast<std::size_t>(is.readsome(
boost::asio::buffer_cast<char*>(mb),
boost::asio::buffer_size(mb))));
}
else if(buffer.size() == 0)
{
// Our buffer is empty and we need more characters,
// see if we've reached the end of file on the istream
if(! is.eof())
{
// Get a mutable buffer sequence for writing
auto const mb = buffer.prepare(1024);
// Try to get more from the istream. This might block.
is.read(
boost::asio::buffer_cast<char*>(mb),
boost::asio::buffer_size(mb));
// If an error occurs on the istream then return it to the caller.
if(is.fail() && ! is.eof())
{
// We'll just re-use io_error since std::istream has no error_code interface.
ec = make_error_code(errc::io_error);
return;
}
// Commit the characters we got to the buffer.
buffer.commit(static_cast<std::size_t>(is.gcount()));
}
else
{
// Inform the parser that we've reached the end of the istream.
p.put_eof(ec);
if(ec)
return;
break;
}
}
// Write the data to the parser
auto const bytes_used = p.put(buffer.data(), ec);
// This error means that the parser needs additional octets.
if(ec == error::need_more)
ec = {};
if(ec)
return;
// Consume the buffer octets that were actually parsed.
buffer.consume(bytes_used);
}
while(! p.is_done());
// Transfer ownership of the message container in the parser to the caller.
msg = p.release();
}
//]
//------------------------------------------------------------------------------
//
// Example: Deferred Body Type
//
//------------------------------------------------------------------------------
//[example_http_defer_body
/** Handle a form POST request, choosing a body type depending on the Content-Type.
This reads a request from the input stream. If the method is POST, and
the Content-Type is "application/x-www-form-urlencoded " or
"multipart/form-data", a `string_body` is used to receive and store
the message body. Otherwise, a `dynamic_body` is used to store the message
body. After the request is received, the handler will be invoked with the
request.
@param stream The stream to read from.
@param buffer The buffer to use for reading.
@param handler The handler to invoke when the request is complete.
The handler must be invokable with this signature:
@code
template<class Body>
void handler(request<Body>&& req);
@endcode
@throws system_error Thrown on failure.
*/
template<
class SyncReadStream,
class DynamicBuffer,
class Handler>
void
do_form_request(
SyncReadStream& stream,
DynamicBuffer& buffer,
Handler&& handler)
{
// Start with an empty_body parser
request_parser<empty_body> req0;
// Read just the header. Otherwise, the empty_body
// would generate an error if body octets were received.
read_header(stream, buffer, req0);
// Choose a body depending on the method verb
switch(req0.get().method())
{
case verb::post:
{
// If this is not a form upload then use a string_body
if( req0.get()[field::content_type] != "application/x-www-form-urlencoded" &&
req0.get()[field::content_type] != "multipart/form-data")
goto do_dynamic_body;
// Commit to string_body as the body type.
// As long as there are no body octets in the parser
// we are constructing from, no exception is thrown.
request_parser<string_body> req{std::move(req0)};
// Finish reading the message
read(stream, buffer, req);
// Call the handler. It can take ownership
// if desired, since we are calling release()
handler(req.release());
break;
}
do_dynamic_body:
default:
{
// Commit to dynamic_body as the body type.
// As long as there are no body octets in the parser
// we are constructing from, no exception is thrown.
request_parser<dynamic_body> req{std::move(req0)};
// Finish reading the message
read(stream, buffer, req);
// Call the handler. It can take ownership
// if desired, since we are calling release()
handler(req.release());
break;
}
}
}
//]
//------------------------------------------------------------------------------
//
// Example: Custom Parser
//
//------------------------------------------------------------------------------
//[example_http_custom_parser
template<bool isRequest>
class custom_parser
: public basic_parser<isRequest, custom_parser<isRequest>>
{
private:
// The friend declaration is needed,
// otherwise the callbacks must be made public.
friend class basic_parser<isRequest, custom_parser>;
/// Called after receiving the request-line (isRequest == true).
void
on_request_impl(
verb method, // The method verb, verb::unknown if no match
string_view method_str, // The method as a string
string_view target, // The request-target
int version, // The HTTP-version
error_code& ec); // The error returned to the caller, if any
/// Called after receiving the start-line (isRequest == false).
void
on_response_impl(
int code, // The status-code
string_view reason, // The obsolete reason-phrase
int version, // The HTTP-version
error_code& ec); // The error returned to the caller, if any
/// Called after receiving a header field.
void
on_field_impl(
field f, // The known-field enumeration constant
string_view name, // The field name string.
string_view value, // The field value
error_code& ec); // The error returned to the caller, if any
/// Called after the complete header is received.
void
on_header_impl(
error_code& ec); // The error returned to the caller, if any
/// Called just before processing the body, if a body exists.
void
on_body_init_impl(
boost::optional<
std::uint64_t> const&
content_length, // Content length if known, else `boost::none`
error_code& ec); // The error returned to the caller, if any
/// Called for each piece of the body, if a body exists.
//!
//! This is used when there is no chunked transfer coding.
//!
//! The function returns the number of bytes consumed from the
//! input buffer. Any input octets not consumed will be will be
//! presented on subsequent calls.
//!
std::size_t
on_body_impl(
string_view s, // A portion of the body
error_code& ec); // The error returned to the caller, if any
/// Called for each chunk header.
void
on_chunk_header_impl(
std::uint64_t size, // The size of the upcoming chunk,
// or zero for the last chunk
string_view extension, // The chunk extensions (may be empty)
error_code& ec); // The error returned to the caller, if any
/// Called to deliver the chunk body.
//!
//! This is used when there is a chunked transfer coding. The
//! implementation will automatically remove the encoding before
//! calling this function.
//!
//! The function returns the number of bytes consumed from the
//! input buffer. Any input octets not consumed will be will be
//! presented on subsequent calls.
//!
std::size_t
on_chunk_body_impl(
std::uint64_t remain, // The number of bytes remaining in the chunk,
// including what is being passed here.
// or zero for the last chunk
string_view body, // The next piece of the chunk body
error_code& ec); // The error returned to the caller, if any
/// Called when the complete message is parsed.
void
on_finish_impl(error_code& ec);
public:
custom_parser() = default;
};
//]
// Definitions are not part of the docs but necessary to link
template<bool isRequest>
void custom_parser<isRequest>::
on_request_impl(verb method, string_view method_str,
string_view path, int version, error_code& ec)
{
boost::ignore_unused(method, method_str, path, version);
ec = {};
}
template<bool isRequest>
void custom_parser<isRequest>::
on_response_impl(
int status,
string_view reason,
int version,
error_code& ec)
{
boost::ignore_unused(status, reason, version);
ec = {};
}
template<bool isRequest>
void custom_parser<isRequest>::
on_field_impl(
field f,
string_view name,
string_view value,
error_code& ec)
{
boost::ignore_unused(f, name, value);
ec = {};
}
template<bool isRequest>
void custom_parser<isRequest>::
on_header_impl(error_code& ec)
{
ec = {};
}
template<bool isRequest>
void custom_parser<isRequest>::
on_body_init_impl(
boost::optional<std::uint64_t> const& content_length,
error_code& ec)
{
boost::ignore_unused(content_length);
ec = {};
}
template<bool isRequest>
std::size_t custom_parser<isRequest>::
on_body_impl(string_view body, error_code& ec)
{
boost::ignore_unused(body);
ec = {};
return body.size();
}
template<bool isRequest>
void custom_parser<isRequest>::
on_chunk_header_impl(
std::uint64_t size,
string_view extension,
error_code& ec)
{
boost::ignore_unused(size, extension);
ec = {};
}
template<bool isRequest>
std::size_t custom_parser<isRequest>::
on_chunk_body_impl(
std::uint64_t remain,
string_view body,
error_code& ec)
{
boost::ignore_unused(remain);
ec = {};
return body.size();
}
template<bool isRequest>
void custom_parser<isRequest>::
on_finish_impl(error_code& ec)
{
ec = {};
}
//------------------------------------------------------------------------------
//
// Example: Incremental Read
//
//------------------------------------------------------------------------------
//[example_incremental_read
/* This function reads a message using a fixed size buffer to hold
portions of the body, and prints the body contents to a `std::ostream`.
*/
template<
bool isRequest,
class SyncReadStream,
class DynamicBuffer>
void
read_and_print_body(
std::ostream& os,
SyncReadStream& stream,
DynamicBuffer& buffer,
error_code& ec)
{
parser<isRequest, buffer_body> p;
read_header(stream, buffer, p, ec);
if(ec)
return;
while(! p.is_done())
{
char buf[512];
p.get().body.data = buf;
p.get().body.size = sizeof(buf);
read(stream, buffer, p, ec);
if(ec == error::need_buffer)
ec.assign(0, ec.category());
if(ec)
return;
os.write(buf, sizeof(buf) - p.get().body.size);
}
}
//]
//------------------------------------------------------------------------------
//
// Example: Expect 100-continue
//
//------------------------------------------------------------------------------
//[example_chunk_parsing
/** Read a message with a chunked body and print the chunks and extensions
*/
template<
bool isRequest,
class SyncReadStream,
class DynamicBuffer>
void
print_chunked_body(
std::ostream& os,
SyncReadStream& stream,
DynamicBuffer& buffer,
error_code& ec)
{
// Declare the parser with an empty body since
// we plan on capturing the chunks ourselves.
parser<isRequest, empty_body> p;
// First read the complete header
read_header(stream, buffer, p, ec);
if(ec)
return;
// This container will hold the extensions for each chunk
chunk_extensions ce;
// This string will hold the body of each chunk
std::string chunk;
// Declare our chunk header callback This is invoked
// after each chunk header and also after the last chunk.
auto header_cb =
[&](std::uint64_t size, // Size of the chunk, or zero for the last chunk
string_view extensions, // The raw chunk-extensions string. Already validated.
error_code& ev) // We can set this to indicate an error
{
// Parse the chunk extensions so we can access them easily
ce.parse(extensions, ev);
if(ev)
return;
// See if the chunk is too big
if(size > (std::numeric_limits<std::size_t>::max)())
{
ev = error::body_limit;
return;
}
// Make sure we have enough storage, and
// reset the container for the upcoming chunk
chunk.reserve(static_cast<std::size_t>(size));
chunk.clear();
};
// Set the callback. The function requires a non-const reference so we
// use a local variable, since temporaries can only bind to const refs.
p.on_chunk_header(header_cb);
// Declare the chunk body callback. This is called one or
// more times for each piece of a chunk body.
auto body_cb =
[&](std::uint64_t remain, // The number of bytes left in this chunk
string_view body, // A buffer holding chunk body data
error_code& ec) // We can set this to indicate an error
{
// If this is the last piece of the chunk body,
// set the error so that the call to `read` returns
// and we can process the chunk.
if(remain == body.size())
ec = error::end_of_chunk;
// Append this piece to our container
chunk.append(body.data(), body.size());
// The return value informs the parser of how much of the body we
// consumed. We will indicate that we consumed everything passed in.
return body.size();
};
p.on_chunk_body(body_cb);
while(! p.is_done())
{
// Read as much as we can. When we reach the end of the chunk, the chunk
// body callback will make the read return with the end_of_chunk error.
read(stream, buffer, p, ec);
if(! ec)
continue;
else if(ec != error::end_of_chunk)
return;
else
ec.assign(0, ec.category());
// We got a whole chunk, print the extensions:
for(auto const& extension : ce)
{
os << "Extension: " << extension.first;
if(! extension.second.empty())
os << " = " << extension.second << std::endl;
else
os << std::endl;
}
// Now print the chunk body
os << "Chunk Body: " << chunk << std::endl;
}
// Get a reference to the parsed message, this is for convenience
auto const& msg = p.get();
// Check each field promised in the "Trailer" header and output it
for(auto const& name : token_list{msg[field::trailer]})
{
// Find the trailer field
auto it = msg.find(name);
if(it == msg.end())
{
// Oops! They promised the field but failed to deliver it
os << "Missing Trailer: " << name << std::endl;
continue;
}
os << it->name() << ": " << it->value() << std::endl;
}
}
//]
} // http
} // beast
} // boost
| [
"[email protected]"
] | |
8788db759d2467f2e5ce1f3747107a50c10284ea | c102d77e7e363d043e017360d329c93b9285a6be | /Sources/Samples/AI/UnitPathManager.h | 4c85b601bbdd834052649cd9ee5cd19276a8484b | [
"MIT"
] | permissive | jdelezenne/Sonata | b7b1faee54ea9dbd273eab53a7dedbf106373110 | fb1b1b64a78874a0ab2809995be4b6f14f9e4d56 | refs/heads/master | 2020-07-15T22:32:47.094973 | 2019-09-01T11:07:03 | 2019-09-01T11:07:03 | 205,662,360 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,466 | h | /*=============================================================================
UnitPathManager.h
Project: Sonata Engine
Copyright �by7
Julien Delezenne
=============================================================================*/
#ifndef _SE_UNITPATHMANAGER_H_
#define _SE_UNITPATHMANAGER_H_
#include "Common.h"
#include "World.h"
extern int8 TileUnitCosts[TileType_Count][UnitType_Count];
enum PathfinderType
{
PathfinderType_AStar
};
class UnitPathMap : public AI::AStarPathfinderMap
{
public:
UnitPathMap();
virtual int GetNeighbourCount(AI::PathfinderNode* node);
virtual AI::PathfinderNodeID GetNeighbour(AI::PathfinderNode* node, int neighbour);
virtual void SetAStarFlags(AI::PathfinderNodeID node, uint32 flags);
virtual uint32 GetAStarFlags(AI::PathfinderNodeID node);
virtual void InitializeNeighbour(AI::AStarPathfinderNode* parent, AI::AStarPathfinderNode* child);
AI::PathfinderNodeID CellToPathfinderNodeID(Cell* cell);
Cell* PathfinderNodeIDToCell(AI::PathfinderNodeID node);
void Initialize(Map* map);
Map* GetMap() const { return _Map; }
protected:
Map* _Map;
};
class UnitPathGoal : public AI::AStarPathfinderGoal
{
public:
UnitPathGoal();
virtual void SetDestinationNode(AI::PathfinderNodeID node);
virtual bool IsNodeValid(AI::PathfinderNodeID node);
virtual real32 GetHeuristic(AI::AStarPathfinderNode* node);
virtual real32 GetCost(AI::AStarPathfinderNode* nodeA, AI::AStarPathfinderNode* nodeB);
virtual bool IsSearchFinished(AI::AStarPathfinderNode* node);
void Initialize(UnitPathMap* map, Unit* unit);
protected:
AI::PathfinderNodeID _DestinationNode;
UnitPathMap* _Map;
Unit* _Unit;
};
template <class T>
class RefComparer : public IComparer<T>
{
public:
virtual int Compare(const T& x, const T& y) const
{
if (*x < *y)
return -1;
else if (*x > *y)
return 1;
else
return 0;
}
};
class PriorityQueueStorage : public AI::AStarPathfinderStorage
{
public:
PriorityQueueStorage();
virtual ~PriorityQueueStorage();
virtual void Reset();
virtual void AddToOpenList(AI::AStarPathfinderNode* node, AI::AStarPathfinderMap* map);
virtual void AddToClosedList(AI::AStarPathfinderNode* node, AI::AStarPathfinderMap* map);
virtual void RemoveFromOpenList(AI::AStarPathfinderNode* node);
virtual void RemoveFromClosedList(AI::AStarPathfinderNode* node);
virtual AI::AStarPathfinderNode* FindInOpenList(AI::PathfinderNodeID node);
virtual AI::AStarPathfinderNode* FindInClosedList(AI::PathfinderNodeID node);
virtual AI::AStarPathfinderNode* RemoveBestOpenNode();
protected:
typedef PriorityQueue< AI::AStarPathfinderNode*, RefComparer<AI::AStarPathfinderNode*> > OpenList;
OpenList _OpenList;
typedef Array<AI::AStarPathfinderNode*> ClosedList;
ClosedList _ClosedList;
};
class UnitPathStorage : public PriorityQueueStorage
{
public:
UnitPathStorage();
virtual AI::AStarPathfinderNode* CreateNode(AI::PathfinderNodeID node);
virtual void DestroyNode(AI::AStarPathfinderNode* node);
};
class UnitPathManager
{
public:
UnitPathManager();
virtual ~UnitPathManager();
void Initialize(PathfinderType type);
bool HasPath(Unit* unit, Cell* source, Cell* destination);
bool FindPath(Unit* unit, Cell* source, Cell* destination, UnitPath* path);
protected:
AI::PathfinderNode* FindPath(Unit* unit, Cell* source, Cell* destination);
protected:
AI::AStarPathfinder* _Pathfinder;
PriorityQueueStorage* _Storage;
UnitPathGoal* _Goal;
UnitPathMap* _Map;
};
#endif
| [
"[email protected]"
] | |
7ecd5b686db5d4f94963cc57cea17c44445fa086 | 98b2ee5a57d66c957f8b924e0c99e28be9ce51d8 | /leetcode/137_SingleNumberII/Solution.cpp | 77d278e1cf5fa2ca6ca6d730127876fab384baa2 | [] | no_license | sauleddy/C_plus | c990aeecedcb547fc3afcbf387d2b51aa94d08cc | 69d6a112d1dd9ac2d99c4b630bb6769b09032252 | refs/heads/master | 2021-01-19T04:49:07.240672 | 2017-06-07T05:51:10 | 2017-06-07T05:51:10 | 87,397,291 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 671 | cpp | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Solution.cpp
* Author: eddy
*
* Created on May 10, 2017, 5:21 PM
*/
#include "Solution.h"
Solution::Solution() {
}
Solution::Solution(const Solution& orig) {
}
Solution::~Solution() {
}
int Solution::singleNumber(vector<int>& nums) {
int res = 0;
for (int i = 0; i < 32; ++i) {
int sum = 0;
for (int j = 0; j < nums.size(); ++j) {
sum += (nums[j] >> i) & 1;
}
res |= (sum % 3) << i;
}
return res;
}
| [
"[email protected]"
] | |
4954df9038975808ebc26d8174fd0b0356d08d0f | 1196266a7aa8230db1b86dcdd7efff85a43ff812 | /VST3_SDK/public.sdk/source/vst/vstcomponent.cpp | b69241908afb1eea9822d9ea88beec28081ef010 | [
"Unlicense"
] | permissive | fedden/RenderMan | c97547b9b5b3bddf1de6d9111e5eae6434e438ee | e81510d8b564a100899f4fed8c3049c8812cba8d | refs/heads/master | 2021-12-11T18:41:02.477036 | 2021-07-20T18:25:36 | 2021-07-20T18:25:36 | 82,790,125 | 344 | 45 | Unlicense | 2021-08-06T23:08:22 | 2017-02-22T10:09:32 | C++ | UTF-8 | C++ | false | false | 7,112 | cpp | //-----------------------------------------------------------------------------
// Project : VST SDK
//
// Category : Helpers
// Filename : public.sdk/source/vst/vstcomponent.cpp
// Created by : Steinberg, 04/2005
// Description : Basic VST Plug-in Implementation
//
//-----------------------------------------------------------------------------
// LICENSE
// (c) 2017, Steinberg Media Technologies GmbH, All Rights Reserved
//-----------------------------------------------------------------------------
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the Steinberg Media Technologies 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#include "vstcomponent.h"
namespace Steinberg {
namespace Vst {
//------------------------------------------------------------------------
// Component Implementation
//------------------------------------------------------------------------
Component::Component ()
: audioInputs (kAudio, kInput)
, audioOutputs (kAudio, kOutput)
, eventInputs (kEvent, kInput)
, eventOutputs (kEvent, kOutput)
{}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::initialize (FUnknown* context)
{
return ComponentBase::initialize (context);
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::terminate ()
{
// remove all buses
removeAllBusses ();
return ComponentBase::terminate ();
}
//------------------------------------------------------------------------
BusList* Component::getBusList (MediaType type, BusDirection dir)
{
if (type == kAudio)
return dir == kInput ? &audioInputs : &audioOutputs;
else if (type == kEvent)
return dir == kInput ? &eventInputs : &eventOutputs;
return 0;
}
//------------------------------------------------------------------------
tresult Component::removeAudioBusses ()
{
audioInputs.clear ();
audioOutputs.clear ();
return kResultOk;
}
//------------------------------------------------------------------------
tresult Component::removeEventBusses ()
{
eventInputs.clear ();
eventOutputs.clear ();
return kResultOk;
}
//------------------------------------------------------------------------
tresult Component::removeAllBusses ()
{
removeAudioBusses ();
removeEventBusses ();
return kResultOk;
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::getControllerClassId (TUID classID)
{
if (controllerClass.isValid ())
{
controllerClass.toTUID (classID);
return kResultTrue;
}
return kResultFalse;
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::setIoMode (IoMode /*mode*/)
{
return kNotImplemented;
}
//------------------------------------------------------------------------
int32 PLUGIN_API Component::getBusCount (MediaType type, BusDirection dir)
{
BusList* busList = getBusList (type, dir);
return busList ? static_cast<int32> (busList->size ()) : 0;
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::getBusInfo (MediaType type, BusDirection dir, int32 index, BusInfo& info)
{
if (index < 0)
return kInvalidArgument;
BusList* busList = getBusList (type, dir);
if (busList == 0)
return kInvalidArgument;
if (index >= static_cast<int32> (busList->size ()))
return kInvalidArgument;
Bus* bus = busList->at (index);
info.mediaType = type;
info.direction = dir;
if (bus->getInfo (info))
return kResultTrue;
return kResultFalse;
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::getRoutingInfo (RoutingInfo& /*inInfo*/, RoutingInfo& /*outInfo*/)
{
return kNotImplemented;
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::activateBus (MediaType type, BusDirection dir, int32 index, TBool state)
{
if (index < 0)
return kInvalidArgument;
BusList* busList = getBusList (type, dir);
if (busList == 0)
return kInvalidArgument;
if (index >= static_cast<int32> (busList->size ()))
return kInvalidArgument;
Bus* bus = busList->at (index);
bus->setActive (state);
return kResultTrue;
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::setActive (TBool /*state*/)
{
return kResultOk;
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::setState (IBStream* /*state*/)
{
return kNotImplemented;
}
//------------------------------------------------------------------------
tresult PLUGIN_API Component::getState (IBStream* /*state*/)
{
return kNotImplemented;
}
//------------------------------------------------------------------------
tresult Component::renameBus (MediaType type, BusDirection dir, int32 index, const String128 newName)
{
if (index < 0)
return kInvalidArgument;
BusList* busList = getBusList (type, dir);
if (busList == 0)
return kInvalidArgument;
if (index >= static_cast<int32> (busList->size ()))
return kInvalidArgument;
Bus* bus = busList->at (index);
bus->setName (newName);
return kResultTrue;
}
//------------------------------------------------------------------------
// Helpers Implementation
//------------------------------------------------------------------------
tresult getSpeakerChannelIndex (SpeakerArrangement arrangement, uint64 speaker, int32& channel)
{
channel = SpeakerArr::getSpeakerIndex (speaker, arrangement);
return channel < 0 ? kResultFalse : kResultTrue;
}
} // namespace Vst
} // namespace Steinberg
| [
"[email protected]"
] |